text
stringlengths 15
59.8k
| meta
dict |
---|---|
Q: WordPress: Getting title tag in PHP variable I am using Yoast SEO for SEO on the website. In my header file I have added
<title><?php wp_title( '|', true, 'right' ); ?></title>
I have also added <?php wp_head(); ?> in header.
Also enabled Force rewrite titles but still the title tag which I have added in page while editing it, in SEO Snippet is not displaying on webpage.
I have not added support for add_theme_support( 'title-tag' ); - Adding it and removing title tag from head also won't make any difference
So my question here is how I can grab the title tag Added in snippet and at list echo it out in page. On API for Yoast they have listed some hooks and filters but their are no examples.
Can get it by wpseo_title?
A: Make sure to add add_theme_support( 'title-tag' ); in functions.php and remove any <title></title> tags from header.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52592742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: php streaming wav in firefox vs chrome I have a hidden audio element in a page, and i'm setting the source dynamically. im setting it as a php page with a GET request that finds the file based on the GET parameter.
However, the audio element is taking the wav file just fine in Chrome but not in firefox. Here is the query and html
<html>
<audio id = "play_wav" controls>
<span id = "set_source">set source</span>
<script>
$('#set_source').on('click', function(){
$('#play_wav').attr('src', 'get_wav.php?fname=playme.wav');
document.getElementById('play_wav').play();
});
</script>
</html>
and here's get_wav.php
if(isset($_GET['fname])){
$fname = $_GET['fname'];
readfile($fname);
}
So this is working to play streaming audio in chrome but not in firefox. The source is still being set it's just not loading. Any suggestions?
A: First off, you should not store the audio files in the same directory as your php files because its easy to protect from someone loading your PHP files by using the basename() function to isolate the filename else you must make further checks its not a php or system file path thats been passed to the $_GET['fname'] parameter, you should also put a .htaccess in the media folder with deny from all in it, this will stop direct access and if you want to be able to stream with seek-able functionality then you need to handle the HTTP_RANGE headers.
<?php
if(!empty($_GET['fname'])){
$file_name = './wav_files/'.basename($_GET['fname']);
stream($file_name, 'audio/wav');
}
/**
* Streamable file handler
*
* @param String $file_location
* @param Header|String $content_type
* @return content
*/
function stream($file, $content_type = 'application/octet-stream') {
// Make sure the files exists
if (!file_exists($file)) {
header("HTTP/1.1 404 Not Found");
exit;
}
// Get file size
$filesize = sprintf("%u", filesize($file));
// Handle 'Range' header
if(isset($_SERVER['HTTP_RANGE'])){
$range = $_SERVER['HTTP_RANGE'];
}elseif($apache = apache_request_headers()){
$headers = array();
foreach ($apache as $header => $val){
$headers[strtolower($header)] = $val;
}
if(isset($headers['range'])){
$range = $headers['range'];
}
else $range = FALSE;
} else $range = FALSE;
//Is range
if($range){
$partial = true;
list($param, $range) = explode('=',$range);
// Bad request - range unit is not 'bytes'
if(strtolower(trim($param)) != 'bytes'){
header("HTTP/1.1 400 Invalid Request");
exit;
}
// Get range values
$range = explode(',',$range);
$range = explode('-',$range[0]);
// Deal with range values
if ($range[0] === ''){
$end = $filesize - 1;
$start = $end - intval($range[0]);
} else if ($range[1] === '') {
$start = intval($range[0]);
$end = $filesize - 1;
}else{
// Both numbers present, return specific range
$start = intval($range[0]);
$end = intval($range[1]);
if ($end >= $filesize || (!$start && (!$end || $end == ($filesize - 1)))) $partial = false;
}
$length = $end - $start + 1;
}
// No range requested
else {
$partial = false;
$length = $filesize;
}
// Send standard headers
header("Content-Type: $content_type");
header("Content-Length: $length");
header('Accept-Ranges: bytes');
// send extra headers for range handling...
if ($partial) {
header('HTTP/1.1 206 Partial Content');
header("Content-Range: bytes $start-$end/$filesize");
if (!$fp = fopen($file, 'rb')) { // Error out if we can't read the file
header("HTTP/1.1 500 Internal Server Error");
exit;
}
if ($start) fseek($fp,$start);
while($length){
set_time_limit(0);
$read = ($length > 8192) ? 8192 : $length;
$length -= $read;
print(fread($fp,$read));
}
fclose($fp);
}
//just send the whole file
else readfile($file);
exit;
}
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23400288",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: thymeleaf get first 3 objects Could you please help me.
I want to display my first 3 objects from product, I don't how it must be.
I try to use thymeleaf sequence, but it don't work. Maybe somebody can hint me how it could be done.
HTML:
<th:block th:each="product:${products}">
<a th:class="production_Page" th:href="@{'product/'+${product.id}}"> <p
th:text="${product.productName}"/></a>
<a th:class="production_Page"
th:href="@{'productDelete/'+${product.id}}">Delete</a>
<a th:class="production_Page"
th:href="@{'productEdit/'+${product.id}}">Edit</a>
<img th:class="productImage" th:src="${product.pathImage}"/>
<br/>
</th:block>
Controller:
@GetMapping("/products")
public String seeAllProductsIntoAList(Model model){
model.addAttribute("products", productService.findAll());
model.addAttribute("categories", categoryService.findAll());
return "/productView/products";
}
It would be great if somebody can hint me with this issue.
Thank you.
A: Since products is list of Product, you have to iterate over that list. On thymeleaf you can use th:each attribute to do iteration. So for your case you can use something as below. Give it a try.
<th:each="product,iterStat: ${products}" th:if="${iterStat.index} <3">
I am not entirely sure but based on your question you wanted only first three objects. For this you can use status variable that are defined in th:each. More detail you can find here.
A: Here's the way you do it with the #{numbers} context object.
<th:block th:each="i: ${#numbers.sequence(0, 2)}" th:with="product=${products[i]}">
<a th:class="production_Page" th:href="@{'product/'+${product.id}}">
<p th:text="${product.productName}"/>
</a>
<a th:class="production_Page" th:href="@{'productDelete/'+${product.id}}">Delete</a>
<a th:class="production_Page" th:href="@{'productEdit/'+${product.id}}">Edit</a>
<img th:class="productImage" th:src="${product.pathImage}"/>
<br/>
</th:block>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53526117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Codeigniter Email class inside a model Is it possible to use the Codeigniter Email class within a Model?
I have been trying to but it refuses to load the mail object. In general, are libraries allowed to be loaded into models?
Code
<?php
class ClubInvitation extends DataMapper {
var $table = "club_invitations";
var $has_one = array("club");
public function __construct($id){
parent::__construct($id);
$this->load->library('email');
}
public function inviteEmailToClub($email, $club, $message){
$invite = new ClubInvitation();
$invite->email = $email;
$invite->code = random_string('unique', null);
//$invite->save($club);
$club->ClubAdmin->limit(1);
$mainClubAdmin = $club->ClubAdmin->get()->User->get();
$data['club'] = $club;
$data['message'] = $message;
$data['club_leader'] = $mainClubAdmin;
$data['invite_code'] = $invite->code;
$email_body = $this->WBLayout->emailTemplate('invited_to_club', $data);
$this->email->from($mainClubAdmin->User->getAccount()->email, $club->name);
$this->email->to($email);
$this->email->subject($club->name.' has invited you to join');
$this->email->message($email_body);
$this->email->send();
}
}
A: Normally, libraries are loaded in controller and accessed from there, not from models. You could just return the array of data from your model to controller and use email library from controller itself. If thats not feasible for you, then try doing:
public function __construct($id){
parent::__construct($id);
}
public function inviteEmailToClub($email, $club, $message){
$CI =& get_instance();
$CI->load->library('email');
.....
$CI->email->from($mainClubAdmin->User->getAccount()->email, $club->name);
....
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19828289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PostgreSQL 1 to many trigger procedure I wrote this query in PostgreSQL:
CREATE OR REPLACE FUNCTION pippo() RETURNS TRIGGER AS $$
BEGIN
CHECK (NOT EXISTS (SELECT * FROM padre WHERE cod_fis NOT IN (SELECT padre FROM paternita)));
END;
$$ LANGUAGE plpgsql;
It returns:
Syntax error at or near CHECK.
I wrote this code because I have to realize a 1..n link between two tables.
A: You can't use CHECK here. CHECK is for table and column constraints.
Two further notes:
*
*If this is supposed to be a statement level constraint trigger, I'm guessing you're actually looking for IF ... THEN RAISE EXCEPTION 'message'; END IF;
(If not, you may want to expand and clarify what you're trying to do.)
*The function should return NEW, OLD or NULL.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27235269",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Php, Mysql can't retrieve column data for each row I'm trying to give each modal form a unique id based on results retrieved from my database so that different data will be passed onto the php form processor. I have 1 table that is placed in a form which has the unique value for each row being "mapid"
However, each row also has a modal which I've placed another form in but the only value I'm getting is the first row of the sql query. Please help.
$sql = "SELECT mapid, location, DATE_FORMAT(date,'%d/%m/%y') AS date, status FROM maps ORDER BY status DESC, date DESC ";
$result = $mysqli->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo
'
<form action="map.php" method="post">
<tr>
<td> '. $row["mapid"].' </td>
<td> '. $row["location"].' </td>
<td> ' . ($row["status"]=='0' ? 'Last Done' : (($row["status"]=='1') ? 'Started' : 'Done')).' </td>
<td> '.$row["date"].' </td>
<td> ' .
(($row["status"]=='0') ?
'<input type="hidden" name="mapid" value="'. $row["mapid"].'"/>
<input type="hidden" name="start" value="start"/>
<button class="btn btn-primary" name="getmap" type="submit">Start</button>'
: (($row["status"]=='1') ?
'<input type="hidden" name="mapid" value="'. $row["mapid"].'"/>
<input type="hidden" name="resume" value="resume"/>
<button class="btn btn-danger" type="submit" name="getmap" value="'. $row["mapid"].'">Resume</button>'
: (($row["status"]=='2') ?
'<input type="hidden" name="mapid" value="'. $row["mapid"].'"/>
<input type="hidden" name="process" value="process"/>
<button class="btn btn-primary" type="submit" name="getmap">Process</button>'
: ''))) . '
</td>
</form>
<td>
<button class="btn btn-primary" data-toggle="modal" data-target="#assign['. $row["mapid"].']">Assign</button>
</td>
<div class="modal fade" id="assign['. $row["mapid"].']" tabindex="-1" role="dialog" aria-labelledby="assignLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<form action="work/allocate.php" method="post">
<div class="modal-header">
<h5 class="modal-title" id="assignLabel">Assign Map</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<input type="hidden" name="mapid">
<p> Assign <strong>Map '. $row["mapid"].' - '. $row["location"].' </strong> to:</p>
<input class="form-control" id="name" name="name" type="text" >
</div>
<div class="modal-footer">
<button class="btn btn-primary" name="assigned" id="assigned" type="submit">Assign</button>
</div>
</form>
</tr>
</div>
</div>
</div>
'
A: Just needed to give the modal a unique id by adding ['. $row["mapid"].'] next to #assign.
<td>
<button class="btn btn-primary" data-toggle="modal" data-target="#assign['. $row["mapid"].']" value"">Assign</button>
</td>
<div class="modal fade" id="assign['. $row["mapid"].']" tabindex="-1" role="dialog" aria-labelledby="assignLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50207733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: AKS - Kube State metrics Supported versions I am using AKS and recently upgraded to AKS 1.24.6.
How to determine what version of kube state metrics supports what AKS version?
I am looking at this https://github.com/kubernetes/kube-state-metrics
I am unable to understand the matrix given between Kube state metrics and Client-Go version.
A: According to the matrix, you can either use v2.5.0 or v2.6.0.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74266550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Return result when count is below given value in spring mongodb I am relatively new to mongodb and spring data.
I am looking for a way to perform operation below in thread-safe manner. In implementation below, it is possible that result set will exceed 1000 after if statement is executed and just before result is queried.
How do I perform such operation atomically?
if (mongoTemplate.count(myQuery, Document.class) > 1000) {
throw new ResultSetTooLargeException()
}
return mongoTemplate.find(myQuery, Document::class.java)
A: You cannot do it atomically but you can use limit which reduces it.
return mongoTemplate.find(myQuery.limit(1000), Document::class.java)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70027146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Slick2d locating an x and y through pixel colour I am trying to make holdable items for my slick2d game, I figured a good way to do this would be to have a hand on the player, to do this i have 1 pixel a unique colour, allowing me to locate that colour, and the x +y.
It worked perfectly until i tried to scale up the image and i get this crazy out of bounds exeception.
this is my code to find the x and y:
public int[] getLocation(Image i, Color c){
Image scaled = i.getScaledCopy(getWidth(), getHeight());
for(int x = 0; x < scaled.getWidth(); x++){
for(int y = 0; y < scaled.getHeight(); y++){
if(scaled.getColor(x, y).r == c.r && scaled.getColor(x, y).g == c.g && scaled.getColor(x, y).b == c.b){
int[] xy = {x,y};
return xy;
}
}
}
return null;
}
and this is how i use it
float x = (float) (getLocation(walkLeft.getCurrentFrame(), new Color(1, 1, 1))[0] + getX());
float y = (float) (getLocation(walkLeft.getCurrentFrame(), new Color(1, 1, 1))[1] + getY());
g.fillRect(x, y, 2, 2);
the exception is:
java.lang.ArrayIndexOutOfBoundsException: 16384
and it leads me back to this line:
if(i.getColor(x, y).r == c.r && i.getColor(x, y).g == c.g && i.getColor(x, y).b == c.b){
in the getLocation method..
I have a feeling its dead easy, yet its stumped me. Thanks to anyone to responds.
A: The loop(s) in getLocation loop over the dimensions of a 2x scaled copy of the Image, but then attempt to access the pixels of the original. Given the original is half the size, when you are half-way through the loop you will be out of bounds of the image dimensions. Either:
*
*Don't scale the Image
*If you must scale the Image, check the pixel value of the scaled image rather than the original.
As an aside, the code posted contains redundant calls...a) in getLocation if you are going to scale, consider scaling the image once rather than placing that code within the loop itself b) no need to call getLocation twice with the same parameters. Call it once and just use the returned array
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39301242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: I have a .mp4 video how i can add water mark I have .mp4 video and i want to generate new video from that with watermarked on proper place.
Is there possibilities where i can create function and pass video it will return me Water marked video.
A: try this :
This code is add a text or string ON the video and after saving video you will play on any player.
Most Advantage of this code is Provide video with sound. And all things in one code(that is text and image).
#import <AVFoundation/AVFoundation.h>
-(void)MixVideoWithText
{
AVURLAsset* videoAsset = [[AVURLAsset alloc]initWithURL:url options:nil];
AVMutableComposition* mixComposition = [AVMutableComposition composition];
AVMutableCompositionTrack *compositionVideoTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeVideo preferredTrackID:kCMPersistentTrackID_Invalid];
AVAssetTrack *clipVideoTrack = [[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
AVMutableCompositionTrack *compositionAudioTrack = [mixComposition addMutableTrackWithMediaType:AVMediaTypeAudio preferredTrackID:kCMPersistentTrackID_Invalid];
AVAssetTrack *clipAudioTrack = [[videoAsset tracksWithMediaType:AVMediaTypeAudio] objectAtIndex:0];
//If you need audio as well add the Asset Track for audio here
[compositionVideoTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:clipVideoTrack atTime:kCMTimeZero error:nil];
[compositionAudioTrack insertTimeRange:CMTimeRangeMake(kCMTimeZero, videoAsset.duration) ofTrack:clipAudioTrack atTime:kCMTimeZero error:nil];
[compositionVideoTrack setPreferredTransform:[[[videoAsset tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0] preferredTransform]];
CGSize sizeOfVideo=[videoAsset naturalSize];
//TextLayer defines the text they want to add in Video
//Text of watermark
CATextLayer *textOfvideo=[[CATextLayer alloc] init];
textOfvideo.string=[NSString stringWithFormat:@"%@",text];//text is shows the text that you want add in video.
[textOfvideo setFont:(__bridge CFTypeRef)([UIFont fontWithName:[NSString stringWithFormat:@"%@",fontUsed] size:13])];//fontUsed is the name of font
[textOfvideo setFrame:CGRectMake(0, 0, sizeOfVideo.width, sizeOfVideo.height/6)];
[textOfvideo setAlignmentMode:kCAAlignmentCenter];
[textOfvideo setForegroundColor:[selectedColour CGColor]];
//Image of watermark
UIImage *myImage=[UIImage imageNamed:@"one.png"];
CALayer layerCa = [CALayer layer];
layerCa.contents = (id)myImage.CGImage;
layerCa.frame = CGRectMake(0, 0, sizeOfVideo.width, sizeOfVideo.height);
layerCa.opacity = 1.0;
CALayer *optionalLayer=[CALayer layer];
[optionalL addSublayer:textOfvideo];
optionalL.frame=CGRectMake(0, 0, sizeOfVideo.width, sizeOfVideo.height);
[optionalL setMasksToBounds:YES];
CALayer *parentLayer=[CALayer layer];
CALayer *videoLayer=[CALayer layer];
parentLayer.frame=CGRectMake(0, 0, sizeOfVideo.width, sizeOfVideo.height);
videoLayer.frame=CGRectMake(0, 0, sizeOfVideo.width, sizeOfVideo.height);
[parentLayer addSublayer:videoLayer];
[parentLayer addSublayer:optionalLayer];
[parentLayer addSublayer:layerCa];
AVMutableVideoComposition *videoComposition=[AVMutableVideoComposition videoComposition] ;
videoComposition.frameDuration=CMTimeMake(1, 30);
videoComposition.renderSize=sizeOfVideo;
videoComposition.animationTool=[AVVideoCompositionCoreAnimationTool videoCompositionCoreAnimationToolWithPostProcessingAsVideoLayer:videoLayer inLayer:parentLayer];
AVMutableVideoCompositionInstruction *instruction = [AVMutableVideoCompositionInstruction videoCompositionInstruction];
instruction.timeRange = CMTimeRangeMake(kCMTimeZero, [mixComposition duration]);
AVAssetTrack *videoTrack = [[mixComposition tracksWithMediaType:AVMediaTypeVideo] objectAtIndex:0];
AVMutableVideoCompositionLayerInstruction* layerInstruction = [AVMutableVideoCompositionLayerInstruction videoCompositionLayerInstructionWithAssetTrack:videoTrack];
instruction.layerInstructions = [NSArray arrayWithObject:layerInstruction];
videoComposition.instructions = [NSArray arrayWithObject: instruction];
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd_HH-mm-ss"];
NSString *destinationPath = [documentsDirectory stringByAppendingFormat:@"/utput_%@.mov", [dateFormatter stringFromDate:[NSDate date]]];
AVAssetExportSession *exportSession = [[AVAssetExportSession alloc] initWithAsset:mixComposition presetName:AVAssetExportPresetMediumQuality];
exportSession.videoComposition=videoComposition;
exportSession.outputURL = [NSURL fileURLWithPath:destinationPath];
exportSession.outputFileType = AVFileTypeQuickTimeMovie;
[exportSession exportAsynchronouslyWithCompletionHandler:^{
switch (exportSession.status)
{
case AVAssetExportSessionStatusCompleted:
NSLog(@"Export OK");
if (UIVideoAtPathIsCompatibleWithSavedPhotosAlbum(destinationPath)) {
UISaveVideoAtPathToSavedPhotosAlbum(destinationPath, self, @selector(video:didFinishSavingWithError:contextInfo:), nil);
}
break;
case AVAssetExportSessionStatusFailed:
NSLog (@"AVAssetExportSessionStatusFailed: %@", exportSession.error);
break;
case AVAssetExportSessionStatusCancelled:
NSLog(@"Export Cancelled");
break;
}
}];
}
Shows the error they will come after saving video.
-(void) video: (NSString *) videoPath didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
if(error)
NSLog(@"Finished saving video with error: %@", error);
}
From :https://stackoverflow.com/a/22016800/3901620
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41056975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to send a single-image in MediaPipe Javascript? Can you explain me how to send a single-image in MediaPipe Hand with Javascript? (from an uploaded image)
I used the Mediapipe Hand python-solution with a single-image like in the jupyther/google collab demo
I would like to do the same operation in javascript but I can't find any solution
Thanks !
| {
"language": "en",
"url": "https://stackoverflow.com/questions/75128024",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I create a top 3 chart list in google sheet I have a column in google sheet that has random numbers from 1 to 20.
I want to create a chart that shows the top 3 numbers that occurred in that column.
Example:
Lucky numbers:
so on....
TIA
A: Let's assume the answer to my questions was 'yes', you want the three numbers that occur most often and how often they occur.
I've tried a couple of ways of doing this. One way is to sort the numbers and use FREQUENCY to get the frequencies. Then you could use a query like this to get the top 3
=query(A1:B20,"select A,B order by B desc limit 3")
Another way is to get the mode, then the mode excluding the most frequent, then the mode excluding both of the previous ones etc.
=ArrayFormula(mode(if(iserror(match(A$2:A$20,F$1:F1,0)),A$2:A$20)))
starting in F2 - you don't need to sort them.
Then you can just use COUNTIF to get how many times they occur.
Then just put them into a chart.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/42106654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Write to a unique attribute of a non unique div folks!
I have two variables:
var day = $(this).text();
var day_id = $(this).data('num');
I have HTML inputs with unique ID:
<input class="update_day" data-id="88" type="text" value="5" name="day">
<input class="update_day" data-id="89 type="text" value="5" name="day">
<input class="update_day" data-id="90" type="text" value="5" name="day">
etc...
I need to update a SPECIFIC input (stored in variable "day_id") with certain data (stored in "day")
It is supposed to look like this:
$(".update_day WHERE data-id= day_id).val(day);
Thank you in advance! Sorry for the newbee question. I have honestly been trying to solve it myself.
A: Try
$(".update_day[data-id='90']").val(day);
if value is stored in variable day_id
$(".update_day[data-id='" + day_id + "']").val(day);
Attribute equals selector
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20624732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: SSIS 2012 SP1 "Value of null is not valid for stream" error on designer components I have just migrated a project from SSIS 2005 to SSIS 2012
Apart from the project, I had a custom pipeline component, which was also migrated to .NET 4.0, and installed in SQL Server DTS directory and the GAC, as usual.
After the migration, when I tried to open and configure the migrated component I got the error: "Value of null is not valid for stream".
The error only happened in "SSDT for BI" of VS 2012. When I tried to open and use the component in SQL Server Data Tools (VS 2010, not 2012, shell) it work without flaws.
So, this is a problem exclusive to SQL Server 2012 SP1 and SSDT for BI for VS2012
A: This problem affects SQL Server 2012 SSIS, and, in some occasssions, it doesn't even allow to open SSIS packages.
This error is solved with a Microsoft patch which can be downloaded from this page:
Micsosoft KB 2832017
Particularly, to solve the problem in VS, as VS is a 32 bit application, you only have to install the x86 download.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/15807861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Add controller for "plugin::users-permissions.user" [strapi v4] I can create a controller for created contentType, ex: api::restaurant.restaurant.
https://docs.strapi.io/developer-docs/latest/development/backend-customization/controllers.html
But for built-in plugins, ex: plugin::users-permissions.user, I don't know where to put the controller.
Strapi Version: 4.0.2
| {
"language": "en",
"url": "https://stackoverflow.com/questions/70617882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to access in the template, reactive form, an array in an array I'm a beginner in programming and i try to understand what i'm doing wrong. :)
I've create a reactive Form that contains an array of string that contains a string an an array of string.
it looks like this:
And the json file looks like this:
public dbData: any = {
'ITEMS':[
{
'NAME': 'Farine',
'QUANTITY': ['140', '60']
}]
};
I arrive to create the FormGroup correctly:
When i submit it looks correct:
But i don't arrive to display it in the template correctly :(
page.ts:
export class Form2Page implements OnInit, OnDestroy {
itemsForm: FormGroup;
constructor(private formBuilder: FormBuilder) {}
ngOnInit() {
this.initForm();
}
initForm() {
this.itemsForm = new FormGroup({
'items': new FormArray([])
});
console.log('From initForm', this.itemsForm);
}
onFormSubmit() {
console.log('Submit : ', this.itemsForm.value);
}
onAddItems() {
const control = new FormGroup({ name: new FormControl(''),
quantity: new FormArray([])});
(<FormArray>this.itemsForm.get('items')).push(control);
console.log('Add From', this.itemsForm);
}
Page.html
<ion-content>
<div>
{{dbData.ITEMS[0].QUANTITY[1]}}
</div>
<form [formGroup]="itemsForm" (ngSubmit)="onFormSubmit()">
<ion-button type="button" (click)="onAddItems()">New Item</ion-button>
<div formArrayName="items">
<div *ngFor="let itemsCtrl of itemsForm.get('items').controls; let i=index">
<h4>ITEMS</h4>
<div [formGroupName]="i">
<ion-label>Name :
<input type="text" formControlName="name">
</ion-label>
<br>
<div formArrayName="quantity">
<div *ngFor="let quantityCtrl of itemsForm.get('items').controls.get('quantity').controls; let j = index">
<ion-label>Quantity :
<input type="text" [formControlName]="j">
</ion-label>
<br>
</div>
</div>
</div>
</div>
</div>
<ion-button type="submit">Submit</ion-button>
</form>
</ion-content>
Thanks for your help :)
A: I haven't implemented in Ionic. But you can use the exact same thing in Ionic too:
import { Component } from '@angular/core';
import { FormBuilder, FormGroup, FormArray, FormControl } from '@angular/forms';
export interface Data {
ITEMS: Array<Item>;
}
export interface Item {
NAME: string;
QUANTITY: Array<string>;
}
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
dbData: Data = {
'ITEMS': [
{
'NAME': 'Farine',
'QUANTITY': ['140', '60']
}]
};
itemsForm: FormGroup;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.itemsForm = new FormGroup({
'ITEMS': this.formBuilder.array(this.dbData.ITEMS.map(item => this.createItem(item)))
});
}
onFormSubmit() {
console.log('Submit : ', this.itemsForm.value);
}
onAddItems() {
(<FormArray>this.itemsForm.get('ITEMS')).push(this.createItem({ NAME: '', QUANTITY: [] }));
}
addQuantity(i) {
(<FormArray>(<FormArray>this.itemsForm.get('ITEMS')).at(i).get('QUANTITY')).push(this.formBuilder.control(''));
}
private createItem(item: Item) {
return this.formBuilder.group({
NAME: [item.NAME],
QUANTITY: this.formBuilder.array(item.QUANTITY.map(item => this.formBuilder.control(item)))
});
}
}
And in the template:
<pre>{{ itemsForm.value | json }}</pre>
<form [formGroup]="itemsForm" (ngSubmit)="onFormSubmit()">
<button type="button" (click)="onAddItems()">New Item</button>
<div formArrayName="ITEMS">
<div *ngFor="let itemsCtrl of itemsForm.get('ITEMS').controls; let i=index">
<h4>ITEMS</h4>
<div [formGroupName]="i">
<label>Name :
<input type="text" formControlName="NAME">
</label>
<br>
<div formArrayName="QUANTITY">
<div
*ngFor="let item of itemsCtrl.get('QUANTITY').controls; let j = index">
<label>Quantity :
<input type="text" [formControlName]="j">
</label>
<br>
</div>
<button (click)="addQuantity(i)">Add Quantity</button>
</div>
</div>
</div>
</div>
<button type="submit">Submit</button>
</form>
Here's a Working Sample StackBlitz for your ref.
A: There are multiple issues in your code
please see the fixed code here
*
*You need to add controls/form to array, just having any empty form array is not enough
*For loading data into your form, you need to refactor a little bit, because you need to loop through your items and add control/form to your array
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56853641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Azure event hubs metrics not appearing when deploying with terraform When deploying with some other components (of a data pipeline) like function app and cosmosdb, metrics graphs on azure event hubs portal are not appearing instead graphs show "Resource not found".
But when I deploy the same terraform code for event hubs namespace without other components, metric graphs appears. Here is terraform code:
locals {
ip_rule_map = flatten([
for cidr in ["182.191.83.208"] : [
{
action = "Allow"
ip_mask = cidr
}
]
])
}
resource "azurerm_eventhub_namespace" "avro-ingestion" {
name = "test-eh"
location = "Central US"
resource_group_name = "test-rg"
sku = "Standard"
capacity = 1
network_rulesets = false ? [{
default_action = "Deny"
ip_rule = local.ip_rule_map
virtual_network_rule = []
trusted_service_access_enabled = true
}] : [
{
default_action = "Allow"
ip_rule = local.ip_rule_map
virtual_network_rule = []
trusted_service_access_enabled = true
}
]
tags = {
Name = "avro-ingestion"
Purpose = "data-ingestion-infra-deployment"
CreatedBy = "emumba"
}
}
resource "azurerm_eventhub_namespace_authorization_rule" "user_managed" {
name = "UserManagedSharedAccessKey"
namespace_name = azurerm_eventhub_namespace.avro-ingestion.name
resource_group_name = "test-rg"
listen = true
send = true
manage = true
}
resource "null_resource" "schema-registry" {
depends_on = [
azurerm_eventhub_namespace.avro-ingestion
]
provisioner "local-exec" {
interpreter = ["/bin/bash", "-c"]
command = "az eventhubs namespace schema-registry create --name test-schema-group --namespace-name test-eh --resource-group test-rg --schema-compatibility Backward --schema-type Avro"
}
}
resource "azurerm_eventhub" "thunder" {
name = "test"
namespace_name = azurerm_eventhub_namespace.avro-ingestion.name
resource_group_name = "test-rg"
partition_count = 2
message_retention = 1
}
resource "azurerm_eventhub_consumer_group" "function-app-cg" {
name = "fApp-cons-group"
namespace_name = azurerm_eventhub_namespace.avro-ingestion.name
eventhub_name = azurerm_eventhub.thunder.name
resource_group_name = "test-rg"
}
main.tf file where I am calling all modules along with event hubs namespace module:
resource "random_string" "random_Sacc1" {
length = 4
special = false
upper = false
min_lower = 1
min_numeric = 1
}
resource "random_string" "random_Sacc2" {
length = 2
special = false
upper = false
min_lower = 1
min_numeric = 1
}
module "azure-resource-group" {
source = "../../modules/resource-group"
region = var.region
res_group_name = var.res_group_name
}
module "azure-virtual-network" {
depends_on = [
module.azure-resource-group
]
source = "../../modules/virtual-network"
rg_name = module.azure-resource-group.name
rg_location = module.azure-resource-group.location
vn_name = var.vn_name
vn_cidrs = var.vn_cidrs
subnets = var.subnets
subnet_cidrs = var.subnet_cidrs
pub_nsg_name = var.pub_nsg_name
private_nsg_name = var.private_nsg_name
internet_ip_cidr_list = var.internet_ip_cidr_list
}
module "azure-ad-app-registration" {
depends_on = [
module.azure-resource-group
]
source = "../../modules/app-role-assignment"
app-display-name = var.app-display-name
rg_name = module.azure-resource-group.name
}
module "azure-eventhubs" {
source = "../../modules/event-hubs"
ns_name = var.eventhub_namespace_name
eventhub_name = var.eventhub_name
cons_group_name = var.cons_group_name
rg_name = module.azure-resource-group.name
rg_location = module.azure-resource-group.location
enable_private_access = var.enable_private_access
cidr_list = var.public_cidr_list
vnet_id_dns = module.azure-virtual-network.vnet-id
private_ep_subnet = module.azure-virtual-network.private-subent1-id
dns_zone_name = var.dns_zone_name_private_ep
schema_group_name = var.eventhub_schema_group_name
}
module "azure-storage-account" {
depends_on = [
module.azure-virtual-network
]
source = "../../modules/storage-account"
storage_acc_name = "${var.storage_acc_name}${random_string.random_Sacc1.id}"
rg_name = module.azure-resource-group.name
rg_location = module.azure-resource-group.location
enable_private_access = var.enable_private_access
cidr_list = var.public_cidr_list
vnet_id_dns = module.azure-virtual-network.vnet-id
private_ep_subnet = module.azure-virtual-network.private-subent1-id
dns_zone_name = var.dns_zone_name_private_ep
}
module "azure-cosmos-db" {
source = "../../modules/cosmos-db"
acc_name = var.cosmos_acc_name
db_name = var.cosmos_db_name
rg_name = module.azure-resource-group.name
rg_location = module.azure-resource-group.location
cosmos_db_container_name = var.cosmos_db_container_name
enable_private_access = var.enable_private_access
cidr_list = var.public_cidr_list
vnet_id_dns = module.azure-virtual-network.vnet-id
private_ep_subnet = module.azure-virtual-network.private-subent1-id
dns_zone_name = var.dns_zone_name_private_ep
synapse_link = var.enable_synapse_link
}
# module "fApp-azure-storage-account" {
# source = "../../modules/storage-account"
# storage_acc_name = "${var.storage_acc_fApp_name}${random_string.random_Sacc2.id}"
# rg_name = module.azure-resource-group.name
# rg_location = module.azure-resource-group.location
# enable_private_access = var.enable_private_access
# cidr_list = var.public_cidr_list
# private_ep_subnet = element(module.azure-virtual-network.subnet_id_list, 1)
# dns_zone_name = var.dns_zone_name_private_ep
# }
module "data-ingestion-fApp" {
depends_on = [
module.azure-cosmos-db,
module.azure-eventhubs,
module.azure-storage-account
]
source = "../../modules/function-app"
rg_name = module.azure-resource-group.name
rg_location = module.azure-resource-group.location
application_insight_name = var.application_insight_name
fApp_service_plan_name = var.fApp_service_plan_name
fApp_name = var.fApp_name
fApp-storage_acc_name = "${var.storage_acc_fApp_name}${random_string.random_Sacc2.id}"
enable_private_access = var.enable_private_access
vnet_id_dns = module.azure-virtual-network.vnet-id
private_ep_subnet = module.azure-virtual-network.private-subent1-id
integration_vnet_name = module.azure-virtual-network.vnet-name
integration_subnet_name = module.azure-virtual-network.private-subent2-name
func_configurations = { "AZURE_CLIENT_ID" = module.azure-ad-app-registration.client_id
"AZURE_CLIENT_SECRET" = module.azure-ad-app-registration.client_secret,
"AZURE_TENANT_ID" = module.azure-ad-app-registration.tenant_id,
"EVENTHUB_NAME" = var.eventhub_name,
"EVENTHUB_FULLY_QUALIFIED_NAMESPACE" = "${var.eventhub_namespace_name}.servicebus.windows.net",
"SCHEMA_GROUP_NAME" = var.eventhub_schema_group_name,
"OUTPUT_CONTAINER" = var.storage_acc_container_name,
"OUTPUT_PATH" = var.storage_acc_container_path,
"COSMOS_DB_URI" = module.azure-cosmos-db.cosmos_account_uri,
"COSMOS_DB_PRIMARY_KEY" = module.azure-cosmos-db.cosmos_account_primary_key,
"COSMOS_DB_NAME" = var.cosmos_db_name,
"COSMOS_DB_CONTAINER_NAME" = var.cosmos_db_container_name,
"a10devops_namespace_connection" = module.azure-eventhubs.eventhub_conn_str,
"a10devops_storage_connection" = module.azure-storage-account.storage_account_conn_str }
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/73931319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Tool Tip to show entire GridView row I want to create a tooltip feature that will display all of a user data that is being displayed in a gridview.
Expected Result: A GridView displays Last_Name,First_Name,Telephone,Cell_Phone. I want a tool tip to display with a mousehover over that users row of information and display all of the data in that tooltip. The data is only generated when a users uses my search box feature so it can't be a static tooltip string. I"m using a sqldatasource to fill in the gridview which i'm not sure how to call. The only thing I can find is by making the gridview a label which I don't want to do. Any guidance would be much appreciated.
<asp:GridView ID="GridView2" runat="server" AutoGenerateColumns="False" CellPadding="4" DataSourceID="SqlDataSource1" GridLines="None" HorizontalAlign="Center" AllowPaging="True" AllowSorting="True" ForeColor="#333333">
<AlternatingRowStyle BackColor="White" ForeColor="#284775" />
<Columns>
<asp:BoundField DataField="Last_Name" HeaderText="Last_Name" SortExpression="Last_Name" />
<asp:BoundField DataField="First_Name" HeaderText="First_Name" SortExpression="First_Name" />
<asp:BoundField DataField="Middle_Int" HeaderText="Middle_Int" SortExpression="Middle_Int" />
<asp:BoundField DataField="Telephone" HeaderText="Work Telephone" SortExpression="Telephone" />
<asp:BoundField DataField="Cell_Phone" HeaderText="Work Cell" SortExpression="Cell_Phone" />
</Columns>
</asp:GridView>
SQLDataSource Connection:
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:myconnection %>" SelectCommand="SELECT [Last_Name], [First_Name], [Middle_Int], [Rank], [Telephone], [Cell_Phone], [Unit], [UserName] FROM [Person_Search] WHERE (([Middle_Int] LIKE '%' + @Middle_Int + '%') OR ([Cell_Phone] LIKE '%' + @Cell_Phone + '%') OR ([First_Name] LIKE '%' + @First_Name + '%') OR ([Telephone] LIKE '%' + @Telephone + '%') OR ([Unit] = @Unit) OR ([Last_Name] LIKE '%' + @Last_Name + '%') OR ([UserName] LIKE '%' + @UserName + '%'))">
<SelectParameters>
<asp:ControlParameter ControlID="TextBox1" Name="Middle_Int" PropertyName="Text" />
<asp:ControlParameter ControlID="TextBox1" Name="Cell_Phone" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="TextBox1" Name="First_Name" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="TextBox1" Name="Telephone" PropertyName="Text" Type="String" />
<asp:ControlParameter ControlID="TextBox1" Name="Last_Name" PropertyName="Text" Type="String" />
</SelectParameters>
</asp:SqlDataSource>
Label Control View Code:
<asp:TemplateField HeaderText="Logid">
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("cityid") %>' ToolTip='<%# Bind("cityName") %>' ></asp:Label>
</ItemTemplate>
A: You can use the RowDataBound event to add the ToolTip property to a GridViewRow.
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
//check if the row is d datarow
if (e.Row.RowType == DataControlRowType.DataRow)
{
//cast the row back to a datarowview
DataRowView row = e.Row.DataItem as DataRowView;
StringBuilder tooltip = new StringBuilder();
//add the data to the tooltip stringbuilder
tooltip.Append(row["Last_Name"] + ", ");
tooltip.Append(row["First_Name"] + ", ");
tooltip.Append(row["Middle_Int"] + ", ");
tooltip.Append(row["Telephone"] + ", ");
tooltip.Append(row["Cell_Phone"]);
//add the tooltip attribute to the row
e.Row.Attributes.Add("ToolTip", tooltip.ToString());
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52520965",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Filter List Debug I'm having trouble debugging this procedure I built. I have over 2 thousand workbooks I'm trying to filter through.
I'm feeding this function a dictionary with its key being the file path & name and the item being a 9 digit part number and the revision number. Based on the folder path and part number, I'm trying to filter out the older revision numbers.
The error message I am recieving is:
Run-time error '10':
This array is fixed or temporarily locked
The debugger is stoping at the line: For Each VKey02 In DUnsorted.Keys. The debug counting variables k1 and k2 end with the values 39 and 1 respectively at the crash.
Any suggestions on how to solve this issue will be appreciated.
Note: I have enabled the "Microsoft Scripting Runtime" reference for this code to work as intended.
Option Explicit
Function HighestRev(ByVal DUnsorted As Scripting.Dictionary) As Scripting.Dictionary
Dim DSorted As Scripting.Dictionary
'Keys
Dim VKey01 As Variant
Dim VKey02 As Variant
Dim SKey01 As String
Dim SKey02 As String
'Items
Dim SItem01 As String
Dim SItem02 As String
'SKUs
Dim LSKU01 As Long
Dim LSKU02 As Long
'Revs
Dim IRev01 As Long
Dim IRev02 As Long
'File Name
Dim SName01 As String
Dim SName02 As String
'File Path
Dim SPath01 As String
Dim SPath02 As String
'Debug Variables
Dim k1 As Integer
Dim k2 As Integer
'Initializing
Set DSorted = DUnsorted
'Looping Through
k1 = 0
For Each VKey01 In DUnsorted.Keys
k1 = k1 + 1: k2 = 1 '<-- Debug
If VKey01 = "[A Particular File]" Then
Debug.Print "1 - " & VKey01
Debug.Print k1 & " - " & k2
End If
SKey01 = VKey01
If Not DSorted.Exists(SKey01) Then GoTo SkipKey01
SItem01 = DUnsorted(SKey01)
LSKU01 = Split(SItem01, "-")(0)
IRev01 = Split(SItem01, "-")(1)
SName01 = Split(SKey01, "\")(UBound(Split(SKey01, "\")))
SPath01 = Left(SKey01, Len(SKey01) - Len(SName01))
For Each VKey02 In DUnsorted.Keys
k2 = k2 + 1 '<-- Debug
If VKey02 = "[A Particular File]" Then
Debug.Print "2 - " & VKey02
Debug.Print k1 & " - " & k2
End If
SKey02 = VKey02
If Not DSorted.Exists(SKey02) Then GoTo SkipKey02
SItem02 = DUnsorted(SKey02)
LSKU02 = Split(SItem02, "-")(0)
IRev02 = Split(SItem02, "-")(1)
SName02 = Split(SKey02, "\")(UBound(Split(SKey02, "\")))
SPath02 = Left(SKey02, Len(SKey02) - Len(SName02))
'Identifying Match
If SKey01 <> SKey02 Then
If LSKU01 = LSKU02 Then
If UBound(Split(SPath01, SPath02)) > 0 Or UBound(Split(SPath02, SPath01)) > 0 Then
'Eliminating Older Revision
If IRev01 > IRev02 Then
DSorted.Remove (SKey02)
ElseIf IRev01 < IRev02 Then
DSorted.Remove (SKey01)
Else '<-- Last Modified Priority
DSorted.Remove (OlderDate(SKey01, SKey02))
End If
If Not DSorted.Exists(SKey01) Then GoTo SkipKey01
End If
End If
End If
SkipKey02:
Next VKey02
SkipKey01:
Next VKey01
End Function
A: Well the error actually followed one of the workbooks. I'm still puzzled with where in the workbook path and file name it's giving me the issue, but the code itself is now working.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59953483",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: R: Creating a function using dplyr functions I have a data frame with three variables of interest:
*
*survival time
*grouping factor
*event indicator (dead: yes or no)
I want to calculate incidence rate for each group. I do this daily, so it would be great to have a function doing this instead of a long script.
I've tried the following, but doesn't work.
library(survival)
data(lung) # example data
lung$death <- ifelse(lung$status==1, 0, 1) # event indicator: 0 = survived; 1 = dead.
# Function
func <- function(data_frame, group, survival_time, event) {
library(epitools)
table <- data_frame %>%
filter_(!is.na(.$group)) %>%
group_by_(.$group) %>%
summarise_(pt = round(sum(as.numeric(.$survival_time)/365.25)),
events = sum(.$event)) %>%
do(pois.exact(.$events, pt = .$pt/1000, conf.level = 0.95)) %>%
ungroup() %>%
transmute_(Category = c(levels(as.factor(.$group))),
Events = x,
Person_years = pt*1000,
Incidence_Rate = paste(format(round(rate, 2), nsmall=2), " (",
format(round(lower, 2), nsmall=2), " to ",
format(round(upper, 2), nsmall=2), ")",
sep=""))
return(table)
}
func(lung, sex, time, death)
**Error: incorrect length (0), expecting: 228 In addition: Warning message:
In is.na(.$group) : is.na() applied to non-(list or vector) of type 'NULL'**
Any ideas? I've read the post about NSE and SE in dplyr, but thought I applied the recommendations correctly?
A: Here is a part of the solution
data_frame = lung
group = "sex"
survival_time = "time"
event = "death"
data_frame %>%
filter_(paste("!is.na(", group, ")")) %>%
group_by_(group) %>%
summarise_(
pt = paste("round(sum(as.numeric(", survival_time, ") / 365.25))"),
events = paste("sum(", event, ")")
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35709492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Easy pattern detection for 3D reconstruction Im currently working on a 3d reconstruction/pose estimation project. To be more specific i have implemented a method which is able to estimate the pose, given horizontal and vertical line correspondences.
In order to have this method work, i need to create an easily detected pattern (the reference view) in which every single line detected (in others shots-view) can be distinguished from the others in such way i can tell which line is detected with respect to the reference view.
The problem is that i have hard time thinking of a pattern both good looking and functional. What i have come up so far is the pattern above in which given the color of the region, the line is detected, i can tell whether the line is vertical or horizontal and given the color of the line i can discrete the line to tell its coordinates in the reference pattern. Unfortunatly i find myself lost in all these detection methods and i lack the experience of working in such tasks, are there any methods relative to my task ?
Any help or idea is greatly appreciated.
PS: it is worth mentioning that the camera is already calibrated and i need this method to work in case the patter is partially occluded.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44373101",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating a normal class with injections from Spring Well, I have a normal class (LovHelper) that is responsible for doing some utils tasks. When i say normal class is because LovHelper.java don't have @Component, @Service or @Repository annotation.
Inside of this "normal class" i wanna inject a bean from spring, but the bean is always null. Look my Class LovHelper.java bellow:
package br.com.odontonew.helper;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import br.com.odontonew.bean.Lov;
import br.com.odontonew.dao.BasicDAO;
public class LovHelper {
@Autowired
private BasicDAO dao;
private static LovHelper instance;
private LovHelper(){
}
public static LovHelper getInstance(){
if (instance == null)
instance = new LovHelper();
return instance;
}
public Lov getLovByCodigo(Class lovClass, String codigo){
Map<String,Object> map = new HashMap<String,Object>();
map.put("codigo", codigo);
List<Lov> lovs = (List<Lov>)dao.findByQuery("SELECT c FROM "+lovClass.getName()+" c WHERE c.codigo = :codigo", map);
if (lovs.size() == 1)
return lovs.get(0);
else
return null;
}
/*Getters and Setters*/
public BasicDAO getDao() {
return dao;
}
public void setDao(BasicDAO dao) {
this.dao = dao;
}
}
So, in another class i just call: LovHelper.getInstance().getLovByCodigo(param1, param2). But i always get a NullPointerException because the bean "dao" within LovHelper is NULL.
After think a little i decided to change my LovHelper.java (using singleton pattern) to a Bean for Spring inject, then I put @Component annotation and remove all singleton pattern the was developed.
And in another class i inject "lovHelper" and use like this: lovHelper.getLovByCodigo(param1, param2). This second solution works fine, but the first not.
Finally, my doubt is: Why the original code (as posted) don't works.
A: Spring will only handle injection dependencies to a class that is constructed by the container. When you call getInstance(), you are allocating the object itself... there is no opportunity there for Spring to inject the dependencies that you have @Autowired.
Your second solution works because Spring is aware of your LovHelper class; it handles constructing it and injecting it into your other class.
If you don't want to mark the class with@Component, you can declare the class as a bean directly in your XML configuration. If you don't want to have it be a singleton, you can set it with prototype scope.
If you really need to manage the class yourself, you could consider looking at @Configurable. I believe it is intended to solve this problem but it requires aspects and I have not played with it myself.
A: Your helper should be context aware, but you can make it static:
@Component
public class LovHelper {
private static LovHelper instance;
@PostConstruct
void init() {
instance = this;
}
// do stuff
In this case static instance will keep reference to Spring aware bean.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18364754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ways to convert a PDF file into byte array..(for flushing out using outputstream())
*
*Is there any other way to convert a file (PDF) into byte array other than using FileInputStream or toByteArray(InputStream input)..
*Is there any method to convert it directly. I found Files.readAllBytes in java.nio.file.* package but it gives ClassNotFoundException in my RAD. I am having Java 8 JDK in my system.
*Is java.nio.file.* package not available in Java 8?
*My requirement is that i should not to stream the file using InputStram.
A: Seems like you're loading the whole content of your file into a byte[] directly in memory, then writing this in the OutputStream. The problem with this approach is that if you load files of 1 or 2 GBs entirely in memory then you will encounter with OutOfMemoryError quickly. To avoid this, you should read the data from InputStream in small chunks and write these chunks in the output stream. Here's an example for file downloading:
BufferedInputStream bis = new BufferedInputStream(
new FileInputStream(new File("/path/to/folder", "file.pdf")));
ServletOutputStream outStream = response.getOutputStream();
//to make it easier to change to 8 or 16 KBs
//make some tests to determine the best performance for your case
int FILE_CHUNK_SIZE = 1024 * 4;
byte[] chunk = new byte[FILE_CHUNK_SIZE];
int bytesRead = 0;
while ((bytesRead = bis.read(chunk)) != -1) {
outStream.write(chunk, 0, bytesRead);
}
bis.close();
outStream.flush();
outStream.close();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/26723322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java Thread creation process flow I was reading section ThreadPools section 6.2.3 java concurrency in practice by Brian Goetz. A statement I came across is
"Reusing an existing thread instead of creating a new one amortizes thread creation and teardown costs."
1) I wanted to get some metrics involved in the java thread creation process which as we know will involve the creation/allocation of a stack and the program counter register to the created thread. Is there a tool/utility/visual vm tracer/jmx bean that I can use for the same which can give me some indicators on memory and time usage for thread creation. Can some one guide me to the same ?
2) Is there a text which can guide me to the whole process of java thread creation in detail which should cover the respective OS calls to windows ?
Why is creating a Thread said to be expensive? has given me some information, but I wanted to study the internals of java thread creation in detail
Thanks
A: Concerning your second question:
2) Is there a text which can guide me to the whole process of java
thread creation in detail which should cover the respective OS calls
to windows ?
This guide, though slightly off topic is great: http://blog.jamesdbloom.com/JVMInternals.html
And the following book The Java Virtual Machine Specification, Java SE 7 Edition (google book link) explains the JVM internals in depth and as such would be my best bet (disclaimer: I had only skimmed through the visible parts)
If that is not good enough, you could always download the source code for the open jdk (7) and crawl through the code...
An excerpt from the open jdk code is this (openjdk\hotspot\src\share\vm\runtime\thread.cpp - c'tor):
// Base class for all threads: VMThread, WatcherThread, ConcurrentMarkSweepThread,
// JavaThread
Thread::Thread() {
// stack and get_thread
set_stack_base(NULL);
set_stack_size(0);
set_self_raw_id(0);
set_lgrp_id(-1);
// allocated data structures
set_osthread(NULL);
set_resource_area(new ResourceArea());
set_handle_area(new HandleArea(NULL));
set_active_handles(NULL);
set_free_handle_block(NULL);
set_last_handle_mark(NULL);
// This initial value ==> never claimed.
_oops_do_parity = 0;
// the handle mark links itself to last_handle_mark
new HandleMark(this);
// plain initialization
debug_only(_owned_locks = NULL;)
debug_only(_allow_allocation_count = 0;)
NOT_PRODUCT(_allow_safepoint_count = 0;)
NOT_PRODUCT(_skip_gcalot = false;)
CHECK_UNHANDLED_OOPS_ONLY(_gc_locked_out_count = 0;)
_jvmti_env_iteration_count = 0;
set_allocated_bytes(0);
_vm_operation_started_count = 0;
_vm_operation_completed_count = 0;
_current_pending_monitor = NULL;
_current_pending_monitor_is_from_java = true;
_current_waiting_monitor = NULL;
_num_nested_signal = 0;
omFreeList = NULL ;
omFreeCount = 0 ;
omFreeProvision = 32 ;
omInUseList = NULL ;
omInUseCount = 0 ;
_SR_lock = new Monitor(Mutex::suspend_resume, "SR_lock", true);
_suspend_flags = 0;
// thread-specific hashCode stream generator state - Marsaglia shift-xor form
_hashStateX = os::random() ;
_hashStateY = 842502087 ;
_hashStateZ = 0x8767 ; // (int)(3579807591LL & 0xffff) ;
_hashStateW = 273326509 ;
_OnTrap = 0 ;
_schedctl = NULL ;
_Stalled = 0 ;
_TypeTag = 0x2BAD ;
// Many of the following fields are effectively final - immutable
// Note that nascent threads can't use the Native Monitor-Mutex
// construct until the _MutexEvent is initialized ...
// CONSIDER: instead of using a fixed set of purpose-dedicated ParkEvents
// we might instead use a stack of ParkEvents that we could provision on-demand.
// The stack would act as a cache to avoid calls to ParkEvent::Allocate()
// and ::Release()
_ParkEvent = ParkEvent::Allocate (this) ;
_SleepEvent = ParkEvent::Allocate (this) ;
_MutexEvent = ParkEvent::Allocate (this) ;
_MuxEvent = ParkEvent::Allocate (this) ;
#ifdef CHECK_UNHANDLED_OOPS
if (CheckUnhandledOops) {
_unhandled_oops = new UnhandledOops(this);
}
#endif // CHECK_UNHANDLED_OOPS
#ifdef ASSERT
if (UseBiasedLocking) {
assert((((uintptr_t) this) & (markOopDesc::biased_lock_alignment - 1)) == 0, "forced alignment of thread object failed");
assert(this == _real_malloc_address ||
this == (void*) align_size_up((intptr_t) _real_malloc_address, markOopDesc::biased_lock_alignment),
"bug in forced alignment of thread objects");
}
#endif /* ASSERT */
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20653149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I add double-quotes to each item in my input string? I'm trying to concatenate a string into an object, with the format of "[email protected],[email protected],[email protected]". However, the parameter is expecting every value in the string to be surrounded by quotes, such as ""[email protected]","[email protected]","[email protected]"". The error is "Property validation failed", and it is expecting a System.String. How do I go about resolving this?
The exact lines of code are...
$existingconfig = get-mailboxjunkemailconfiguration $_.address
$existingconfig.trustedsendersanddomains += $_.approved_senders
where $_.approved_senders = "[email protected],[email protected],[email protected]"
A: Using Get-MailboxJunkEmailConfiguration -Identity BSmith | Get-Memeber shows that the TrustedSendersAndDomains property is a multiValuedProperty string, i.e. an Array. You can try changing the value of the $_.approved_senders into an array with -Split
$existingconfig = get-mailboxjunkemailconfiguration $_.address
$existingconfig.trustedsendersanddomains += ($_.approved_senders -Split ",")
| {
"language": "en",
"url": "https://stackoverflow.com/questions/25791825",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get XML Node while using tsql I would like to know, if anyone can help how to get NODE name o XML variable using TSQL.
<ROOT>
<IDS>
<ID>
<NAME>bla1</NAME>
<AGE>25</AGE>
</ID>
<ID>
<NAME>bla2</NAME>
<AGE>26</AGE>
</ID>
</IDS>
</ROOT>
After my query, I should be able to get the nodes names: NAME, AGE
My SQL server is MSSQL 2005.
A: This would give you the node names for the children of the first ID node:
DECLARE @x xml
SET @x = '<ROOT>
<IDS>
<ID>
<NAME>bla1</NAME>
<AGE>25</AGE>
</ID>
<ID>
<NAME>bla2</NAME>
<AGE>26</AGE>
</ID>
</IDS>
</ROOT>'
SELECT T.c.value('local-name(.)', 'varchar(50)')
FROM @x.nodes('/ROOT/IDS/ID[1]/*') T(c)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4393808",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OLS Regression Results R-squared value ca r2_squared by scikitlearn I followed a tutorial online and used OLS to build the model (from statsmodel!) The OLS analysis result gave me an amazing R^2 value (0.909). However, when I tried using the r2_score function by scikit-learn to evaluate the R^2 score, I only got 0.68.
Can someone tell what the difference is here?
The dataset came from here: https://www.kaggle.com/harlfoxem/housesalesprediction
Attached is my code!
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error, accuracy_score, r2_score
import matplotlib.pyplot as plt
import seaborn as sns
import statsmodels.api as sm
df = pd.read_csv('kc_house_data.csv')
df = df.drop(['id','date'], axis = 1)
X = df.iloc[:, 1:]
y= df.iloc[:, 0]
X = sm.add_constant(X)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 1/3, random_state = 0)
reg_OLS = sm.OLS(endog=y_train, exog=X_train).fit()
reg_OLS.summary()
y_pred = reg_OLS.predict(X_test)
print(r2_score(y_test, y_pred))
Output from OLS Regression Results
OLS Regression Results
Dep. Variable: price R-squared (uncentered): 0.909
Model: OLS Adj. R-squared (uncentered): 0.909
Method: Least Squares F-statistic: 8491.
Date: Thu, 17 Mar 2022 Prob (F-statistic): 0.00
Time: 23:36:48 Log-Likelihood: -1.9598e+05
No. Observations: 14408 AIC: 3.920e+05
Df Residuals: 14391 BIC: 3.921e+05
Df Model: 17
Covariance Type: nonrobust
coef std err t P>|t| [0.025 0.975]
bedrooms -2.898e+04 2217.526 -13.068 0.000 -3.33e+04 -2.46e+04
bathrooms 3.621e+04 3845.397 9.416 0.000 2.87e+04 4.37e+04
sqft_living 100.2140 2.690 37.257 0.000 94.942 105.486
sqft_lot 0.2609 0.057 4.563 0.000 0.149 0.373
floors 1.201e+04 4187.373 2.867 0.004 3798.844 2.02e+04
waterfront 6.237e+05 2.01e+04 31.012 0.000 5.84e+05 6.63e+05
view 5.237e+04 2566.027 20.410 0.000 4.73e+04 5.74e+04
condition 2.844e+04 2774.191 10.250 0.000 2.3e+04 3.39e+04
grade 9.613e+04 2558.509 37.571 0.000 9.11e+04 1.01e+05
sqft_above 63.2770 2.638 23.985 0.000 58.106 68.448
sqft_basement 36.9370 3.127 11.813 0.000 30.808 43.066
yr_built -2529.7423 80.708 -31.344 0.000 -2687.940 -2371.544
yr_renovated 13.0704 4.307 3.035 0.002 4.629 21.512
zipcode -510.0820 21.216 -24.043 0.000 -551.667 -468.497
lat 6.084e+05 1.27e+04 47.725 0.000 5.83e+05 6.33e+05
long -2.076e+05 1.55e+04 -13.371 0.000 -2.38e+05 -1.77e+05
sqft_living15 33.6926 3.996 8.432 0.000 25.860 41.525
sqft_lot15 -0.4850 0.092 -5.275 0.000 -0.665 -0.305
Omnibus: 9620.580 Durbin-Watson: 1.997
Prob(Omnibus): 0.000 Jarque-Bera (JB): 363824.963
Skew: 2.694 Prob(JB): 0.00
Kurtosis: 27.021 Cond. No. 1.32e+17
Output from r2_score
0.6855578295481021
A: Your R2=0.909 is from the OLS on the train data, while the R2_score=0.68 is based on the correlation of the test data.
Try predicting the train data and use R2_score on the train and predicted train data.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71522298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: MysqL: Perform fulltext search over multiple columns and 100 % match I'd like to do a fulltext search over multiple columns in a MySQL database, only using 1 Input field to search for addresses.
So far my code works but I also get rows returned where not all search words are present.
SELECT *, ((1.3 * (MATCH (city) AGAINST ('+$search*' IN BOOLEAN MODE)))
+ (0.6 * (MATCH (name, zip, str) AGAINST ('+$search*' IN BOOLEAN MODE)))) AS relevance
FROM service
WHERE (MATCH (name, city, zip, str) AGAINST ('+$search*' IN BOOLEAN MODE))
HAVING relevance > 0 ORDER BY relevance DESC LIMIT 10
This could return sth like:
$search = "Anderson City ZIP"
1. Anderson, City, ZIP, street x
2. Anderson, City, ZIP, street y
3. Smith, City, ZIP, street x
So line 3 is wrong because it does not contain Anderson but Smith.
I already tried to add the + operator in the $search string (Anderson City ZIP --> +Anderson +City +ZIP) but then the result often does not show anything.
Is it possible to return only rows with 100 % match?
A: The plus sign is the good thing to do but you have to be sure that one of the strings you are searching for is not in more than 50% of the rows of your table.
Also consider using quotes to match the full expression: +"Anderson City ZIP"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28568228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Dynamic or Conditional display of Jenkins job's parameters (rather than their value population) Let's say I have two(or more) types of projects: app(Application) and svc (Service) and I have created a Jenkins job (common job) which have bunch of parameters. This common job might call another downstream/individual project type jobs (Trigger other project builds etc and pass respective parameters) but it's out of scope of this question.
For ex:
PROJ_TYPE (a choice parameter type with values: app, svc)
Param2 (of some type)
Param3 (of Cascading type i.e. it depends upon the value of parent parameter PROJ_TYPE).
Param4 (Lets say I want to show this parameter only when PROJ_TYPE is selected as "app")
Param5 (of some type)
Param6 (Lets say I want to show this parameter only when PROJ_TYPE is selected as "svc". This parameter can be of any type i.e. choice, dynamic, extended choice, etc )
If I have the above parameters in a Jenkins job, then Jenkins job will show / prompt all of the parameters when a user will try to build (i.e. Build with Parameters).
Is it possible in Jenkins to show parameter (Param4) only if PROJ_TYPE parameter was selected as app otherwise, I don't want to show this parameter at all -or somehow if it's possible to grey it out? i.e. in this case, the job will show only PROJ_TYPE, Param2, Param3, Param4 and Param5 (and will not show Param6 or it's disabled/greyed out).
Similarly, I want to show parameter (Param6) only if PROJ_TYPE parameter was selected as svc otherwise, I don't want to show this parameter at all -or somehow if it's possible to grey it out? i.e. in this case, the job will show only PROJ_TYPE, Param2, Param3, Param5 and Param6 (and will not show Param4 or it's disabled/greyed out).
A: I know this is an oldie, but I had been searching for something similar until I found Active Choices Plugin. It doesn't hide the parameters, but it's possible to write a Groovy script (either directly in the Active Choices Parameter or in Scriptler) to return different values. For example:
Groovy
if (MY_PARAM.equals("Foo")) {return ['NOT APPLICABLE']}
else if (MY_PARAM.equals("Bar")) {return ['This is the only choice']}
else if (MY_PARAM.equals("Baz")) {return ['Bazoo', 'Bazar', 'Bazinga']}
/Groovy
In this example MY_PARAM is a parameter in the Jenkins job. As long as you put 'MY_PARAM' in the Active Choices 'Referenced Parameters' field the script will re-evaluate the parameter any time it is changed and display the return value (or list of values) which match.
In this way, you can return a different list of choices (including a list of one or even zero choices) depending on the previous selections, but I haven't found a way to prevent the Parameter from appearing on the parameters page. It's possible for multiple Active Choice Parameters to reference the same Parameter, so the instant someone selects "App" or "Svc" all the irrelevant parameters will switch to 'Not Applicable' or whatever suits you. I have played with some HTML text color as well, but don't have code samples at hand to share.
Dirk
A: According to the description you may do this with Dynamic-Jenkins-Parameter plugin:
A Jenkins parameter plugin that allows for two select elements. The second select populates values depending upon the selection made for the first select.
Example provided on the wiki does exactly what you need (at least for one conditional case). I didn't try it by myself.
A: @derik It worked! for me
the second list is populating based on the choice of the first element.
I used Active Choice reactive parameter plugin,
the requirement was the first param will list my servers,
based on the fist selection, the second parm is to connect to selected server and list the backup.
so the list of available backup will the shown here to restore.
*
*enabled parameterized.
*Select Choice Parameter
Name: Server
Choices : Choose..
qa
staging
master
Description : Select the server from the list
*Add new parameter "Active Choice Reactive Parameter"
Name: Backup
Script: Groovy Script
def getbackupsqa = ("sshpass -f /opt/installer/pass.txt /usr/bin/ssh -p 22 -o StrictHostKeyChecking=no [email protected] ls /opt/jenkins/backup").execute()
if (Server.equals("Choose..")) {return ['Choose..'] }
else if (Server.equals("qa")) {return getbackupsqa.text.readLines()}
else if (Server.equals("staging")) {return ['Staging server not yet configured']}
else if (Server.equals("master")) {return ['Master server not yet configured']}
Description : Select the backup from the list
Referenced parameters : Server
The result as here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30513679",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "28"
} |
Q: R: Way to map over all entries in a sparse matrix I have a sparse matrix created from R's Matrix package. I would like to iterate over each entry in the matrix and perform an operation, saving the result in another sparse matrix with the same indexes as the original matrix.
For example, let's say I have sparse matrix A:
1 . 1
2 . .
. . 4
ColSums would look like:
3 . 5
RowSums would look like:
2
2
4
I would like to iterate over A and do this
(1,1) > 3*2
(2,1) > 2*3
(1,3) > 2*5
(3,3) > 4*5
Creating B:
6 . 10
6 . .
. . 20
How would I go about doing this in a vectorized way?
I would think the function foo would look like:
B=fooMap(A,fun)
And fun would look like:
fun(row,col) = RowSums(row) * ColSums(col)
What's fooMap?
EDIT:
I went with flodel's solution. It uses summary to convert the sparse matrix into an i,j,x data frame, then uses with & friends to perform an operation on that frame, and then turns the result back into a sparse matrix. With this technique, the with/within operator is fooMap; the sparse matrix just has to be converted into the i,j,x data frame first so that with/within can be used.
Here's a one-liner that solved this particular problem.
B = with(summary(A), sparseMatrix(i=i, j=j, x = rowSums(A)[i] * colSums(A)[j]))
A: Whenever I have element-wise operations on sparse matrices, I go back and forth between the matrix itself and its summary representation:
summ.B <- summary(A)
summ.B <- within(summ.B, x <- rowSums(A)[i]*colSums(A)[j])
B <- sparseMatrix(i = summ.B$i, j = summ.B$j, x = summ.B$x)
B
# 3 x 3 sparse Matrix of class "dgCMatrix"
#
# [1,] 6 . 10
# [2,] 6 . .
# [3,] . . 20
A: Here's an approach that works with sparse matrices at each step.
## Load library and create example sparse matrix
library(Matrix)
m <- sparseMatrix(i = c(1,2,1,3), j = c(1,1,3,3), x = c(1,2,1,4))
## Multiply each cell by its respective row and column sums.
Diagonal(x = rowSums(m)) %*% (1*(m!=0)) %*% Diagonal(x = colSums(m))
# 3 x 3 sparse Matrix of class "dgCMatrix"
#
# [1,] 6 . 10
# [2,] 6 . .
# [3,] . . 20
(The 1* in (1*(m!=0)) is being used to coerce the logical matrix of class "lgCMatrix" produced by m!=0 back to a numeric matrix class "dgCMatrix". A longer-winded (but perhaps clearer) alternative would to use as(m!=0, "dgCMatrix") in its place.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/12649082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cant Get Bootstrap Table To Resize Im trying to get a bootstrap table to resize so that the maximum content height is 200px and anything greater will scroll.
I have the css for the table set to:
table.jSpeeds tr:hover, table.jSpeeds tr td:hover{
cursor:pointer;
}
table.table-fixed thead {
width: 97%;
}
table.table-fixed tbody {
height: 230px;
overflow-y: auto;
width: 100%;
}
& HTML:
<table class="table table-striped jSpeeds table-fixed">
<thead>
<tr><th>Time</th><th>Speed</th></tr>
</thead>
<tbody>
<tr><td>TestRow</td><td>TestVal</td></tr>
</tbody>
</table>
However the table is still the height and width of the page. I was wondering if anyone could help.
Please see the JSBin example here
Thanks.
A: Use bootstrap's responsive-table. Wrap your <table> with this.
<div class="table-responsive fix-table-height">
// your table here
</div>
Then add the class fix-table-height on the wrapper so you could define the height of the wrapper. In your case you want 200px;. So you can do this :
.fix-table-height{
max-height:200px;
}
This is the output jsFiddle
A: You'll need to change your table's body and rows display to block. Do something like this:
table.jSpeeds tr:hover, table.jSpeeds tr td:hover{
cursor:pointer;
}
table.table-fixed thead {
width: 100%;
}
table.table-fixed tbody {
height: 230px;
overflow-y: auto;
}
table.table-fixed tbody,
table.table-fixed tr {
display: block;
width: 100%;
}
table.table-fixed th,
table.table-fixed td {
width: 300px;
}
EDIT
Since I was challenged to give a robust solution, here is comes:
table.jSpeeds tr:hover, table.jSpeeds tr td:hover{
cursor:pointer;
}
table.table-fixed thead {
width: 100%;
}
table.table-fixed tbody {
height: 230px;
overflow-y: auto;
}
table.table-fixed tbody,
table.table-fixed tr {
display: block;
width: 100%;
}
table.table-fixed th,
table.table-fixed td {
display: block;
float: left;
width: 50%;
}
Gist Link
A: just adjust your css to this:
tbody {
display: block;
overflow: auto;
height: 230px;
}
tbody tr {
display: table;
width: 100%;
table-layout: fixed;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/38667982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How might I add a watermark effect to an image in Android? I have an image with frames and I need to add a watermark effect. How might I do this?
A: I found great tutorial on Android Image Processing here.
public static Bitmap mark(Bitmap src, String watermark, Point location, Color color, int alpha, int size, boolean underline) {
int w = src.getWidth();
int h = src.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Paint paint = new Paint();
paint.setColor(color);
paint.setAlpha(alpha);
paint.setTextSize(size);
paint.setAntiAlias(true);
paint.setUnderlineText(underline);
canvas.drawText(watermark, location.x, location.y, paint);
return result;
}
Thanks to Pete Houston who shares such useful tutorial on basic image processing.
A: It seems you are looking for a waterrippleeffect as this one. Checkout the complete source code. Also check the screenshot how does the effect look like.
A: For others reference, if you want to add the logo of your application (which is in your drawable folder(s)) on top of image use following method:
private Bitmap addWaterMark(Bitmap src) {
int w = src.getWidth();
int h = src.getHeight();
Bitmap result = Bitmap.createBitmap(w, h, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Bitmap waterMark = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.logo);
canvas.drawBitmap(waterMark, 0, 0, null);
return result;
}
A: If someone is still searching for this, I found a good solution here
It adds a watermark to the bottom right portion and scales it according to the source image which was exactly what I was looking for.
/**
* Embeds an image watermark over a source image to produce
* a watermarked one.
* @param source The source image where watermark should be placed
* @param watermark Watermark image to place
* @param ratio A float value < 1 to give the ratio of watermark's height to image's height,
* try changing this from 0.20 to 0.60 to obtain right results
*/
public static Bitmap addWatermark(Bitmap source, Bitmap watermark, float ratio) {
Canvas canvas;
Paint paint;
Bitmap bmp;
Matrix matrix;
RectF r;
int width, height;
float scale;
width = source.getWidth();
height = source.getHeight();
// Create the new bitmap
bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
paint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DITHER_FLAG | Paint.FILTER_BITMAP_FLAG);
// Copy the original bitmap into the new one
canvas = new Canvas(bmp);
canvas.drawBitmap(source, 0, 0, paint);
// Scale the watermark to be approximately to the ratio given of the source image height
scale = (float) (((float) height * ratio) / (float) watermark.getHeight());
// Create the matrix
matrix = new Matrix();
matrix.postScale(scale, scale);
// Determine the post-scaled size of the watermark
r = new RectF(0, 0, watermark.getWidth(), watermark.getHeight());
matrix.mapRect(r);
// Move the watermark to the bottom right corner
matrix.postTranslate(width - r.width(), height - r.height());
// Draw the watermark
canvas.drawBitmap(watermark, matrix, paint);
return bmp;
}
And it is well commented which is what is a huge plus!
A: In Kotlin:
Note: Its just modified code of above answers
private fun mark(src: Bitmap, watermark: String): Bitmap {
val w = src.width
val h = src.height
val result = Bitmap.createBitmap(w, h, src.config)
val canvas = Canvas(result)
canvas.drawBitmap(src, 0f, 0f, null)
val paint = Paint()
paint.color = Color.RED
paint.textSize = 10f
paint.isAntiAlias = true
paint.isUnderlineText = true
canvas.drawText(watermark, 20f, 25f, paint)
return result
}
val imageBitmap = mark(yourBitmap, "Your Text")
binding.meetProofImageView.setImageBitmap(imageBitmap)
A: You can use androidWM to add a watermark into your image, even with invisible watermarks:
add dependence:
dependencies {
...
implementation 'com.huangyz0918:androidwm:0.2.3'
...
}
and java code:
WatermarkText watermarkText = new WatermarkText(“Hello World”)
.setPositionX(0.5)
.setPositionY(0.5)
.setTextAlpha(100)
.setTextColor(Color.WHITE)
.setTextFont(R.font.champagne)
.setTextShadow(0.1f, 5, 5, Color.BLUE);
WatermarkBuilder.create(this, backgroundBitmap)
.loadWatermarkText(watermarkText)
.getWatermark()
.setToImageView(backgroundView);
You can easily add an image type watermark or a text watermark like this, and the library size is smaller than 30Kb.
A: I tried a few libraries mentioned in other posts, like this, but unfortunately it is missing, and not downloadable now. So I followed AndroidLearner 's answer above, but after tweaking the code a little bit, for those of you who are having trouble rotating the watermark, and what values are valid for the various methods of Paint class, so that the text shows rotated at an angle(like most of the company watermarks do), you can use the below code.
Note that, w and h are the screen width and height respectively, which you can calculate easily, there are tons of ways you can find on stackoverflow only.
public static Bitmap waterMarkBitmap(Bitmap src, String watermark) {
int w = src.getWidth();
int h = src.getHeight();
Bitmap mutableBitmap = Utils.getMutableBitmap(src);
Bitmap result = Bitmap.createBitmap(w, h, mutableBitmap.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0f, 0f, null);
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(92f);
paint.setAntiAlias(true);
paint.setAlpha(70); // accepts value between 0 to 255, 0 means 100% transparent, 255 means 100% opaque.
paint.setUnderlineText(false);
canvas.rotate(45, w / 10f, h / 4f);
canvas.drawText(watermark, w / 10f, h / 4f, paint);
canvas.rotate(-45, w / 10f, h / 4f);
return result;
}
It rotates the text watermark by 45 degrees, and places it at the centre of the bitmap.
Also note that, in case you are not able to get watermark, it might be the case that the bitmap you are using as source is immutable. For this worst case scenario, you can use below method to create a mutable bitmap from an immutable one.
public static Bitmap getMutableBitmap(Bitmap immutableBitmap) {
if (immutableBitmap.isMutable()) {
return immutableBitmap;
}
Bitmap workingBitmap = Bitmap.createBitmap(immutableBitmap);
return workingBitmap.copy(Bitmap.Config.ARGB_8888, true);
}
I found above method inside here. I have tested using both the methods in my application, and it works perfectly after I added above tweaks. Try it and let me know if it works or not.
A: use framelayout. put two imageviews inside the framelayout and specify the position of the watermark imageview.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10679445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Request jenkins rest api using the authtoken got from by organization's SSO I have a webportal where user login using our organization's SSO, After logging in i get the authtoken for the logged in session.
And currently i have the Jenkins authentication setup using organization LDAP.
From our webportal we will be issuing some jenkins REST APIs. I can see jenkins support API token for the REST APIs.
1. All our jenkins users don't have the token generated
2. Even they do generate, we will have to map each users id with token , which would be very bad.
Is there any way to execute rest api with the auth token got from SSO login ?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59389488",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Character entry causing infinite loop in C Ok, so I've searched several places for an answer to this, and I found the answer to the same problem in C++, but it involved clearing cin and that stuff, and I'm not sure how to translate that to C. I apologize in advance if this was, in fact, answered somewhere else, and I just missed it. Also, keep in mind that I'm basically teaching myself C, and I don't know much beyond what you see in this code.
Basically, my problem is this: I am running a loop that asks for input and then uses a switch statement to choose what happens. The switch takes an int, and it works fine with any numerical entry. When you enter a char, however, it just loops infinitely, giving no chance to input anything else.
Assuming this is the same problem as it was in the C++ examples I looked up - and I'm not 100% sure it is - when I enter a char it gets added to the buffer, and never gets cleared, so each time it loops the invalid input gets used again. Clearing the buffer seemed simple enough in C++, but I was unable to find anything I could understand in C.
Here's my code, for reference:
int main()
{
while(1)
{
printf("(1-10) -> Run a program | (-1) -> Display menu | (0) -> Quit : ");
int quit = 0;
int select;
scanf("%d", &select);
switch(select)
{
case 1:
printf("%s", pgmRun);
helloWorld();
printf("%s", pgmEnd);
break;
//More cases here
case 0:
quit = 1;
break;
default:
printf("\n");
printf("Error: Invalid input\n");
printf("\n");
}
if(quit == 1)
break;
}
return 0;
}
Thanks in advance for your help, and sorry for such a lengthy post. I tend to be long-winded. :P
A: fflush(stdin) has undefined behavior. If you want to discard characters entered after the scanf() call, you can read and discard them.
You can use getchar() to clear the character.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23421014",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Wpf: Prism + MVVM: Changing Modules/Views I'm developing a WPF application using MVVM + Prism.
The Shell is devided into two regions: Menu + MainScreenArea.
The Menu includes navigation: Search Entity, Add Entity, Edit Entity. And Basically the mainScreenArea should load the appropriate module/View. If Search Entity is chosen in the Menu Region, The mainScreenArea should display the SearchEntity Module/View.
I still haven't coded it, but I think I will create A module for each purpose: SearchEntityModule, AddEntityModule and etc.
Then the MainWorkArea will change modules on demand by the corresponding click on Menu Region.
Now, how do I change between the modules in the MainScreenArea Region? Should I load the nameOfModule to eventAggregator from MenuRegion and and MainScreenArea will get the name of screen from the aggregator?
Anyways, I'm new to this, so if I'm going in the wrong direction, please post me your suggestion. Thanks!
A: The prism documentation has a whole section on navigation. The problem with this question is that there are a number of different ways to go when loading modules on demand. I have posted a link that I hope leads you in the right direction. If it does, please mark this as answered. thank you
http://msdn.microsoft.com/en-us/library/gg430861(v=pandp.40).aspx
A: As has been said, there are a number of ways of accomplishing this. For my case, I have a similar shell that has a nav region and a main region, and my functionality is broken into a number of modules. My modules all add their own navigation view to that nav region (in the initialise of the module add their own nav-view to the nav-region). In this way my shell has no knowledge of the individual modules and the commands they may expose.
When a command is clicked the nav view model it belongs to does something like this:
/// <summary>
/// switch to the view given as string parameter
/// </summary>
/// <param name="screenUri"></param>
private void NavigateToView(string screenUri)
{
// if there is no MainRegion then something is very wrong
if (this.regionManager.Regions.ContainsRegionWithName(RegionName.MainRegion))
{
// see if this view is already loaded into the region
var view = this.regionManager.Regions[RegionName.MainRegion].GetView(screenUri);
if (view == null)
{
// if not then load it now
switch (screenUri)
{
case "DriverStatsView":
this.regionManager.Regions[RegionName.MainRegion].Add(this.container.Resolve<IDriverStatsViewModel>().View, screenUri);
break;
case "TeamStatsView":
this.regionManager.Regions[RegionName.MainRegion].Add(this.container.Resolve<ITeamStatsViewModel>().View, screenUri);
break;
case "EngineStatsView":
this.regionManager.Regions[RegionName.MainRegion].Add(this.container.Resolve<IEngineStatsViewModel>().View, screenUri);
break;
default:
throw new Exception(string.Format("Unknown screenUri: {0}", screenUri));
}
// and retrieve it into our view variable
view = this.regionManager.Regions[RegionName.MainRegion].GetView(screenUri);
}
// make the view the active view
this.regionManager.Regions[RegionName.MainRegion].Activate(view);
}
}
So basically that module has 3 possible views it could place into the MainView, and the key steps are to add it to the region and to make it active.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/24176964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MySQL LEFT JOIN Query with WHERE clause Hope someone can help as I am having a hard time understanding how to query properly
I have a Member table and a Member_Card table. Member_Card has a column Member, so the card is associated to a member. Both tables have a LastModifiedDate column. A member can have none, one or several cards.
I need to return all members whose LastModifiedDate >= sinceDate (given date) OR whose card (if any) LastModifiedDate >= sinceDate.
Imagine sinceDate is 2013-01-01 00:00:00. I want to output something like this:
[{
"Id": "001O000000FsAs7IAF",
"LastModifiedDate": 2013-01-01 00:00:00,
"Member_Card": null
}, {
"Id": "001O000000FrpIXIAZ",
"LastModifiedDate": 2012-12-12 00:00:00,
"Member_Card": [{
"Id": "a00O0000002w8FGIAY",
"Member": "001O000000FhDSoIAN",
"LastModifiedDate": 2013-01-01 00:00:00
}, {
"Id": "a00O0000002uYMtIAM",
"Member": "001O000000FhDSoIAN",
"LastModifiedDate": 2012-12-12 00:00:00
}]
}, {
"Id": "001O000000FsAg7IAF",
"LastModifiedDate": 2013-01-01 00:00:00,
"Member_Card": [{
"Id": "a00O0000002w8FFIAY",
"Member": "001O000000FhDSoIAN",
"LastModifiedDate": 2012-12-12 00:00:00
}]
}]
The 1st is a member with a matching LastModifiedDate without cards. The 2nd is a member with a non-matching LastModifiedDate, but he has 2 cards associated, and 1 of them has a matching LastModifiedDate. The 3rd one is a member with a matching LastModifiedDate with a card.
Thanks to SO I got the following query:
SELECT member.*,card.* from member inner join (
SELECT distinct member.id as mid FROM Member
INNER JOIN Member_Card
ON Member_Card.Member = Member.id
and ( Member.LastModifiedDate >= sinceDate
OR Member_Card.LastModifiedDate >= sinceDate ) ) a on a.mid=member.id
inner join member_card card on card.member=a.mid
Which works fine but is missing the case where the member doesn't have any card associated.
I tried to change some INNER JOINs to LEFT JOINs but then it's ignoring the date comparison :-(
Can you help me with this one?
A: You want to move the date check to the where of the inner query.
Try something like:
SELECT member.*,card.*
FROM member
LEFT JOIN member_card card on card.member=member.id
WHERE member.id IN (
SELECT DISTINCT m.id FROM Member m
LEFT JOIN Member_Card mc ON (mc.Member = m.id)
WHERE ( m.LastModifiedDate >= sinceDate
OR mc.LastModifiedDate >= sinceDate )
)
A: Try this... (yet to be tested)
SELECT * FROM member m1
JOIN card c1 ON c1.member = m1.id
WHERE m1.id IN (
SELECT DISTINCT m.id from member m
JOIN card c ON c.member = m.id
WHERE (c.LastModifiedDate >=sinceDate OR m.LastModifiedDate >= sinceDate))
A: You can try like this,
SELECT o.status, o.date, c.name
FROM cliente c
LEFT JOIN orders o
ON c.id=o.id
WHERE o.date = '2/1/2015'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/18123218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: FileNotFoundException : /storage/emulated/0/xyz/a bc/abc_06-07-2017 06-12-121481589883.amr I am trying to upload file from my device storage to cloud but whenever I try to upload I am getting following excaption.
java.io.FileNotFoundException: /storage/emulated/0/xyz/a bc/abc_06-07-2017 06-12-121481589883.amr: open failed: ENOENT (No such file or directory)
Here is my code.
DropboxInstance objDropboxInstance = new DropboxInstance();
String filePath = intent.getExtras().getString("filePath");
// filePath is = /storage/emulated/0/xyz/a bc/abc_06-07-2017 06-12-121481589883.amr
StringBuilder sb = new StringBuilder();
InputStream is;
String name = "abc_06-07-2017 06-12-121481589883";
try {
File file = new File(filePath);
is = new FileInputStream(file);
long size = f.length();
objDropboxInstance.getDropBoxStorage(this).upload("/" + name, is, size, true);
}
catch(IOException ioe) {
ioe.printStackTrace();
}
I don't know what's happening. I think path is correct. But I am not getting why I am getting this error. Please suggest me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/44953920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DockerHub set tag alias in automated build I'm using Docker Hub's automated build system to build a docker image. That image comes in two flavors (Debian jessie and wheezy based). I like to have speaking tags for both of those (:jessie and :wheezy) but would also like to have a :latest tag pointing to the :jessie flavor.
For now I simply duplicated the jessie line in the automated build config:
But this seems to actually build the image twice. What I would need is a way to specify a tag alias, but I am not sure if that's possible. And if so how to do it.
A: It's currently not possible to have more than one docker tag name by build. Duplicating the build is the only solution.
A: You can use the tags regexp
Look at the last tag that gets created.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35792027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Date string not recognized in Safari My JavaScript code is working on on Chrome, IE, and Firefox, but when it gets to safari it doesn't work. I believe I have narrowed down the problem: When creating a 'new Date' in JavaScript, all other browsers recognize my string except safari.
HTML:
<form>
<input id="timeIn" value="1:00 AM"/>
<input id="dateIn" value="1/20/2012"/>
<input id="timeOut" value="2:00 AM"/>
<input id="dateOut" value="1/21/2012"/>
</form>
JavaScript:
function calcHours() {
// Build datetime objects and subtract
var timeIn = new Date($('#timeIn').val() + $('#dateIn').val());
if(!isValidDate(timeIn)) return -1;
var timeOut = new Date($('#timeOut').val() + $('#dateOut').val());
if(!isValidDate(timeOut)) return -1;
var hours = (timeOut - timeIn)/(1000*60*60);
return hours.toFixed(1);
}
function isValidDate(d) {
console.log(d);
if ( Object.prototype.toString.call(d) === "[object Date]" ) {
// it is a date
if ( isNaN( d.getTime() ) ) { // d.valueOf() could also work
// date is not valid
console.log("isn't valid");
return 0;
}
else {
// date is valid
console.log("is valid");
return 1;
}
}
else {
// not a date
console.log("isn't valid");
return 0;
}
}
var hours = calcHours();
console.log("Hours:", hours);
I have made a js fiddle: http://jsfiddle.net/mq72k/7/. If you open it up in chrome, it will work fine. If you open it up in Safari, it will say invalid date for the same inputs and not work at all. I have also tried varying the string a bit, adding spaces, different order ect.
Does any one have any ideas how to fix this cross browser compatibility issue?
A: Try using an external plugin to parse your dates, something like Datejs
A: Frankly, I'm surprised other browsers parse the string correctly, as the string you give to the date object is 1:00 AM1/20/2012. Put the date first and add a space in between.
var timeIn = new Date($('#dateIn').val() + ' ' + $('#timeIn').val());
var timeOut = new Date($('#dateOut').val() + ' ' + $('#timeOut').val());
http://jsfiddle.net/mq72k/8/
A: Javascript does not parse string dates very well at all, including ISO8601 formats. You must parse the string yourself. You especially should not expect a minor format like month/day/year to be parsed since it is used by a small minority of the global population.
Incidentally, this has nothing to do with jQuery.
Edit
To reliably parse m/d/y format:
function toDate(ds) {
var a = ds.split('/');
return new Date(+a[2], (a[0] - 1), +a[1]);
}
The above assumes a correct date string is supplied. To check that it's a valid date at the same time:
function toDate(ds) {
var a = ds.split('/');
var d = new Date(+a[2], (a[0] - 1), +a[1]);
if (d.getDate() == a[1] && d.getFullYear() == a[2]) {
return d;
} else {
return NaN; // or some other suitable value like null or undefined
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10333606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: jquery addClass and removeClass slow in IE 11 I'm creating an app to monitor nodes on a cluster and this is an example of the visual state. Each small box in the grid represents a node and currently, when hovering over one node, the rest in that respective rack (grid) fadeout.
Here is the link via photobucket since I can't insert images due to my minimal reputation:
visual state
In Chrome and Firefox, hovering in and out a single node will instantly fadein/out the rest of the nodes in the rack, but in IE 11 it has a noticeable lag. I know that IE's javascript engine is slower than Chrome and Firefox, but I'm throwing this out there to see if the SO community can pick apart my code and suggest better ways of doing this as I am not the greatest front end programmer. Thank you and here is snippets of my code:
from the django template (each node has id="matrix-box-<node #>"):
<tr>
<td id="visual-state"><b>visual state</b></td>
<td id="matrix" colspan=5>
{% for row in v.22 %}
{% if v.23 == "ca" %}
{% if forloop.counter0|divisibleby:4 %}
<div id="rack-{% widthratio forloop.counter0 4 1 %}-{{ k }}" title="rack-{% widthratio forloop.counter0 4 1 %}">
{% endif %}
{% elif v.23 == "cs" %}
{% if forloop.counter0|divisibleby:8 %}
<div id="rack-{% widthratio forloop.counter0 8 1 %}-{{ k }}" title="rack-{% widthratio forloop.counter0 8 1 %}">
{% endif %}
{% endif %}
<div class="row">
{% for elem in row %}
{% if elem.1 == "#49E20E" %}
<div class="node node-faded" id="matrix-box-{{ elem.0 }}-{{ k }}" style="background: #00DC00;" title="{{ elem.0 }}"></div>
{% elif elem.1 == "#0000CD" %}
<div class="node node-faded" id="matrix-box-{{ elem.0 }}-{{ k }}" style="background: #0000CD;" title="{{ elem.0 }}"></div>
{% elif elem.1 == "yellow" %}
<div class="node node-faded" id="matrix-box-{{ elem.0 }}-{{ k }}" style="background: yellow;" title="{{ elem.0 }}"></div>
{% elif elem.1 == "#E3170D" %}
<div class="node node-faded" id="matrix-box-{{ elem.0 }}-{{ k }}" style="background: #E31702;" title="{{ elem.0 }}"></div>
{% elif elem.1 == "brown" %}
<div class="node node-faded" id="matrix-box-{{ elem.0 }}-{{ k }}" style="background: #6E3737;" title="{{ elem.0 }}"></div>
{% elif elem.1 == "orange" %}
<div class="node node-faded" id="matrix-box-{{ elem.0 }}-{{ k }}" style="background:#DC7800;" title="{{ elem.0 }}"></div>
{% elif elem.1 == "black" %}
<div class="node node-faded" id="matrix-box-{{ elem.0 }}-{{ k }}" style="background: black;" title="{{ elem.0 }}"></div>
{% elif elem.1 == "#cccccf" %}
<div class="node node-faded" id="matrix-box-{{ elem.0 }}-{{ k }}" style="background: #CCCCCF;border: 1px solid #CCCCCF"></div>
{% endif %}
{% endfor %}
</div>
... other code
from css code:
.node {
width: 4px;
height: 4px;
float: left;
border: 1px solid #B0B0B0;
background: #cccccf;
margin: 0 !important;
cursor: pointer;
filter: alpha(opacity=100);
opacity: 1;
}
.faded .node-faded {
width: 4px;
height: 4px;
filter: alpha(opacity=50);
opacity: .5;
}
.active {
width: 4px;
height: 4px;
float: left;
border: 1px solid black;
background: #cccccf;
margin: 0 !important;
cursor: pointer;
filter: alpha(opacity=100);
opacity: 1;
}
from js code:
var node = null;
var node_id = null;
var rack = null;
var nodes = null;
$(document).ready(function(){
$('[id^=matrix-box]').on({
mouseenter: function(){
node = $(this);
rack = node.parent().parent();
rack.addClass('faded');
node.removeClass('node-faded').addClass('active');
},
mouseleave: function(){
node.removeClass('active').addClass('node-faded');
rack.removeClass('faded');
},
click: function(e){
...other code
Also, any constructive criticism (albeit helpful and not malicious) is always welcome. Thanks again!
A: As you gave no possibility to test, this is kind of a guessing game. What you do is the following:
$('[id^=matrix-box]').on({ mouseenter: function(){});
This adds a new event listener on each element with an id starting with matrix-box. Not the worst idea, but it can be slow if you have a lof of these items.
Here is demo to validate this: http://jsfiddle.net/k3mjmdzp/3/
A good idea to overcome performance issues is to use a delegated event listener.
Try to rewrite your code like this:
$(function () {
$('#matrix').on('mouseenter mouseleave click', '[id^=matrix-box]', function (event) {
console.log(event);
});
});
Here you have the demo: http://jsfiddle.net/k3mjmdzp/2/
This will leave your code with having only event listeners on $('#matrix') and not on each child node. This is also nice if you append new items via ajax later on.
You can check for event listeners on the event Listeners tab in chrome developer tools.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/27532447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is a type inference? Does it only exist in statically typed languages? And is it only there when the language is not strongly typed (i.e., does Java have one)? Also, where does it belong - in the compilation phase assuming it's a compiled language?
In general, are the rules when the type is ambiguous dictated by the language specification or left up to the implementation?
A: Type inference is a feature of some statically-typed languages. It is done by the compiler to assign types to entities that otherwise lack any type annotations. The compiler effectively just 'fills in' the static type information on behalf of the programmer.
Type inference tends to work more poorly in languages with many implicit coercions and ambiguities, so most type inferenced languages are functional languages with little in the way of coercions, overloading, etc.
Type inference is part of the language specification, for the example the F# spec goes into great detail about the type inference algorithm and rules, as this effectively determines 'what is a legal program'.
Though some (most?) languages support some limited forms of type inference (e.g. 'var' in C#), for the most part people use 'type inference' to refer to languages where the vast majority of types are inferred rather than explicit (e.g. in F#, function and method signatures, in addition to local variables, are typically inferred; contrast to C# where 'var' allows inference of local variables but method declarations require full type information).
A: A type inferencer determines what type a variable is from the context. It relies on strong typing to do so. For example, functional languages are very strongly, statically typed but completely rely on type inference.
C# and VB.Net are other examples of statically typed languages with type inference (they provide it to make generics usable, and it is required for queries in LINQ, specifically to support projections).
Dynamic languages do not infer type, it is discovered at runtime.
A: Type inferencing is a bit of a compromise found in some static languages. You can declare variables without specifying the type, provided that the type can be inferred at compile time. It doesn't offer the flexibility of latent typing, but you do get type safety and you don't have to write as much.
See the Wikipedia article.
A: A type inferencer is anything which deduces types statically, using a type inference algorithm. As such, it is not just a feature of static languages.
You may build a static analysis tool for dynamic languages, or those with unsafe or implicit type conversions, and type inference will be a major part of its job. However, type inference for languages with unsafe or dynamic type systems, or which include implicit conversions, can not be used to prove the type safety of a program in the general case.
As such type inference is used:
*
*to avoid type annotations in static languages,
*in optimizing compilers for dynamic languages (ie for Scheme, Self and Python),
*In bug checking tools, compilers and security analysis for dynamic languages.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/692088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Cannot download card from Hyperledger Composer Playground I'm trying to export my Network Admin card from the Playground UI, but the export icon is disabled. In addition, I see the following error in my Chrome console:
Error: The current identity, with the name 'admin' and the identifier 'ddae16d6f23947e9349627051b8ca5933cef53d2918f52295352d7dd24cdabcb', must be activated.
How do I export the Network Admin card from the Playground?
Here's the full Firefox log:
Establishing admin connection ...
main.d12285adf00f2401cf60.bundle.js:1:346887
@JS : ModelManager :addSystemModels() [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : Resolver :resolveRelationship() Failed to resolve relationship [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : IdentityManager :<ResourceManager>() Binding in the tx names and impl
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : EngineTransactions :createHistorianRecord() created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : Resolver :resolveRelationship() Failed to resolve relationship [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : EngineTransactions :createHistorianRecord() created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : Resolver :resolveRelationship() Failed to resolve relationship [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : EngineTransactions :createHistorianRecord() created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : ConnectionProfileManager:getConnectionManagerByTy Looking up a connection manager for type web
main.d12285adf00f2401cf60.bundle.js:1:848811
Establishing admin connection ...
main.d12285adf00f2401cf60.bundle.js:1:346887
@JS : ConnectionProfileManager:getConnectionManagerByTy Looking up a connection manager for type web
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : IdentityManager :validateIdentity() Error: The current identity, with the name 'admin' and the identifier 'ddae16d6f23947e9349627051b8ca5933cef53d2918f52295352d7dd24cdabcb', must be activated (ACTIVATION_REQUIRED)
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : Engine :query() Caught error, rethrowing [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : IdentityManager :validateIdentity() Error: The current identity, with the name 'admin' and the identifier 'ddae16d6f23947e9349627051b8ca5933cef53d2918f52295352d7dd24cdabcb', must be activated (ACTIVATION_REQUIRED)
main.d12285adf00f2401cf60.bundle.js:1:848759
@JS : IdentityManager :<ResourceManager>() Binding in the tx names and impl
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : EngineTransactions :createHistorianRecord() created historian record
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : ConnectionProfileManager:getConnectionManagerByTy Looking up a connection manager for type web
main.d12285adf00f2401cf60.bundle.js:1:848811
@JS : ModelManager :addSystemModels() [object Object]
main.d12285adf00f2401cf60.bundle.js:1:848811
connected
main.d12285adf00f2401cf60.bundle.js:1:61666
A: This is the answer I got on GitHub:
The reason that the export is greyed out is because you are using the
bluemix staged Playground that is in the 'web-connector' mode. In
order to meaningfully export a business network card, you will need to
create a connection to Hyperledger Fabric. The steps you outline above
will not create a business network in Hyperledger Fabric, but within a
web connector.
If you follow the developer tutorial
(https://hyperledger.github.io/composer/tutorials/developer-tutorial)
you will be taken through the process of creating a (local) Fabric,
from which you can connect Playground and export business network
cards.
A: You can create the admin card via composer-cli.
composer card create
-p connection.json
-u PeerAdmin -c [email protected]
-k 114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457_sk
-r PeerAdmin -r ChannelAdmin
Add connection.json file as following:
{
"name": "fabric-network",
"type": "hlfv1",
"mspID": "Org1MSP",
"peers": [
{
"requestURL": "grpc://localhost:7051",
"eventURL": "grpc://localhost:7053"
}
],
"ca": {
"url": "http://localhost:7054",
"name": "ca.org1.example.com"
},
"orderers": [
{
"url" : "grpc://localhost:7050"
}
],
"channel": "composerchannel",
"timeout": 300
}
The certificate file can be found in the signcerts subdirectory (fabric-tools/fabric-scripts/hlfv1/composer/crypto-config/peerOrganizations/org1.example.com/users/[email protected]/msp) and is named [email protected].
The private key file can be found in the keystore subdirectory. The name of the private key file is a long hexadecimal string, with a suffix of _sk, for example 114aab0e76bf0c78308f89efc4b8c9423e31568da0c340ca187a9b17aa9a4457_sk.
Step by step tutorial is available in Hyperledger Composer
Tutorials @ https://hyperledger.github.io/composer/tutorials/deploy-to-fabric-single-org.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48972830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Unable to call locally declared scope function via ng-click in a directive
*
*I have a directive (Just a button).
*This directive has an isolated scope.
*I want to update the object in my parent scope by clicking on the button.
*But the function is not being called.
This is the plunker.
I've tried defining the function in both the link function and the controller, and they didn't work
I know I am missing something very basic. Need some form of explanation on why this is happening. Have tried looking through a lot of the other questions but I still couldn't find a clear answer.
Thanks in advance!
A: You forget to scope.$apply()! See forked plunk: http://plnkr.co/edit/zo1GrfwyQ8T82TJiW16h?p=preview
You need to call $apply() every time an external source touches Angular values (in this case the "external source" is the browser event handled by on()).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/20678763",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: display the back and next button between half the height of image android i have a problem in xml layout for displaying next and back button besides the image and should be in middle of height of image.
pls see this url
http://screencast.com/t/zE47nb0rkFE
two buttons are above the image,it is left and right but not the middle height of image.
and it should be for every resolution size of screen.
my xml is
<?xml version="1.0" encoding="utf-8"?>
A: you can use scrollview in code like this ::
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<ScrollView android:id="@+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView
android:id="@+id/imv"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="55dip"
/>
<ImageView
android:id="@+id/imagegallery"
android:layout_width="70sp"
android:layout_height="70sp"
android:layout_alignParentRight="true"
android:layout_below="@id/imv"/>
<ProgressBar
android:id="@+id/Bar"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:layout_height="wrap_content"
android:layout_above="@id/imagegallery"
android:layout_below="@id/imv"
/>
<TextView android:layout_height="wrap_content"
android:id="@+id/textView1"
android:text="Art Gallery"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_below="@id/imv"
/>
<TextView android:layout_height="wrap_content"
android:id="@+id/textView2"
android:textColor="#00C000"
android:textSize="20dip"
android:text=" "
android:layout_width="wrap_content"
android:layout_toLeftOf="@id/imagegallery"
android:layout_alignParentLeft="true"
android:layout_below="@id/textView1"
/>
<TextView android:layout_height="wrap_content"
android:id="@+id/textopeningnow"
android:text="Opening Now"
android:textColor="#000000"
android:layout_width="wrap_content"
android:layout_below="@id/textView2"
/>
<TextView android:layout_height="wrap_content"
android:id="@+id/diosas"
android:textSize="20dip"
android:text="Diosas/Godesses"
android:textColor="#00C000"
android:layout_width="wrap_content"
android:layout_below="@id/textopeningnow"
/>
<Button
android:id="@+id/back"
android:layout_height="wrap_content"
android:layout_width="25dip"
android:layout_centerVertical="true"
android:background="@drawable/leftarrow"/>
<Button
android:id="@+id/next"
android:layout_height="wrap_content"
android:layout_width="25dip"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:background="@drawable/rightarrow"/>
<ImageView android:id="@+id/imageLoader"
android:layout_width="wrap_content"
android:layout_height="200dip"
android:layout_toLeftOf="@id/next"
android:layout_toRightOf="@id/back"
android:layout_below="@id/diosas"
/>
<TextView
android:id="@+id/artistname"
android:textColor="#000000"
android:text=" "
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:layout_below="@id/imageLoader"
android:layout_centerInParent="true"
/>
</LinearLayout>
</ScrollView>
</RelativeLayout>
A: I'd enclose your image in a separate RelativeLayout, and add the buttons to it. It's way too hard to try to achieve what you want with just a global relative layout.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7452754",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is it possible to pass an argument to a Svelte component that specifies a particular file to import? I'm building a photography site. The user can click on links to various photo album components, e.g. an album of black and white portraits, an album of black and white architecture, etc.
The displayed contents (i.e., image file paths and corresponding image captions) for each album are detailed in a json file that is imported at the top of the album component, e.g. import {images} from './albums/bwportraits.js';, import {images} from './album/bwarchitecture.js';, etc.
Apart from the album-specific imports, the rest of each album component is identical. I would like a generic <Album /> component but be able to pass the json file to import as a prop, i.e. <Album album = "bwportraits" />, <Album album = "bwarchitecture" /> and the import within the <Album /> to be something equivalent to (the non-valid) import {images} from './albums/{album}';.
That is, I would like to dynamically specify which file to import. This does not appear possible - or, at least, I do not know how to do this.
It would, of course, be possible to import every album json file into the <Album /> component; they are reasonably small and the performance hit would be negligible. But this feels a little unclean to me. Is there a 'cleaner' workaround that anyone can suggest?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/68977680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: meaning of "Bird titi = new Swan();" I currently read a java book and I am stuck at an example including this line :
Bird titi = new Swan();
where Swan is a subclass of Bird.
I could explain this as follow:
when java executes this line, it stores memory for the value titi, and the memory stored can contain an information for an object of type Bird. next, the second part of the line call the Swan constructor without any argument, which initializes the titi value.
if I am right, I can't explain why a Swan instance can be stored in a Bird type because Swan, as a subclass, contains more information than Bird.
so I think I am something wrong. where?
and, extra-question : in which case this type of statement is useful?
thank you
A: You may have a method that only takes an instance of Bird. Since Swan is a Bird, you can use an instance of Swan and treat it as Bird.
That's the beauty of polymorphism. It allows you to change out the implementation of the class' internals without breaking the rest of your code.
A: Where it is calling new Swan(), it is creating a new Swan object in memory.
When the Swan object is assigned to the Bird variable (possible because a Swan is a sub type of Bird) the Bird variable simply has a pointer to the Swan in memory. Because titi is a verb, this object can now be accessed / treated like a bird for static time type checking and functionality... though it is always a Swan, and can be cast to a Swan to extended Swan functionality.
A: Bird titi = new Swan();
is actually known as: programming to superclass but sometimes programming to interfaces
means:
titi is a Bird, pointing to a Swan reference... note that this is only valid because of inheritance... which means in this case that Swan is a class that extends the Bird class
why: it allows modifications in the code... you can latter decide not to use a Swan but an Owl so
Bird titi = new Swan(); will be replaced with Bird titi = new Owl(); and everything will work fine
programming to interfaces is more elegant because you can do:
IFly titi = new Swan();
which is valid if the Swan implemtents the interface IFly, so it is:
titi is something that can fly, pointing to a Swan ref.
A: Bird titi = new Swan();
It's all about Polymorphism.
A Parent class/Interface type can hold it's Child class's Object.
Here Bird is Parent class/Interface and Swan is Child.
The same example is below :
List list = new ArrayList();
Here List is Parent Interafce and ArrayList it's Child class.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/45636124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
} |
Q: Using python generics and inheritance I need to implement a bunch classes, that all need to do the same modification to the parent class. As a skilled C++ programmer, I would look for a template class. But this needs to be implemented in Python. Here I am a rookie. I found the "Generic" and has constructed this example to show the core in my problem. The real program is somewhat more complicated(using ReportLab to generate PDF documents). I need to subclass to benefit from the class framework, which leads me into trying to implement a Generic using inheritance.
The problem is that cannot understand how I can pass argument to the "super" class, which here I try to make a Generic.
First attempt:
super().__init__(*argv, **kwargs)
Second attempt:
super(G, self).__init__(*argv, **kwargs)
Third attempt:
T.__init__(*argv, **kwargs)
Here is the complete example:
from typing import Generic, TypeVar
class A():
def __init__(self, i : int):
self.i = i
def draw():
print(self.i)
class C():
def __init__(self, s : str):
self.s = s
def draw():
print(self.s)
T = TypeVar('T')
class G(Generic[T]):
def __init__(self, *argv, **kwargs):
super().__init__(*argv, **kwargs)
def draw():
# Here is some special going to happen
super().draw()
gA = G[A](5)
gB = G[B]('Hello')
gA.draw()
gB.draw()
The output that I get:
Traceback (most recent call last):
File "<string>", line 34, in <module>
File "/usr/lib/python3.8/typing.py", line 729, in __call__
result = self.__origin__(*args, **kwargs)
File "<string>", line 28, in __init__
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
A: You have understood Python generics wrong. A Generic, say Generic[T], makes the TypeVar T act as whatever you provide the instance with.
I found this page to be very useful with learning Generics.
A: typing.Generic is specifically for type annotations; Python provides no runtime concept equivalent to either:
*
*Template classes, or
*Function overloads by parameter count/type
The latter has extremely limited support from functools.singledispatch, but it only handles the type of one argument, and the runtime type-checking is fairly slow.
That said, you don't need a template-based class or a polymorphic inheritance hierarchy here; Python is perfectly happy to call draw on anything that provides a method of that actual name. The code you're writing here can just do:
a = A(5)
b = B('Hello')
a.draw()
b.draw()
with no use of G needed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72522954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: disable component functionality based on page I a navigation where the menu items are hidden until you get to a certain point on the page then they show.
This works great on the homepage, because it is a relatively long page. But, some of my other pages are short and do not go past the height of the viewport. So when the page loads there are no navigation menu options and it shows the navigation is blank.
Is there a way in react to say disable a component conditionally according to what layout or page you are on?
Example: In Jekyll you can create an if statement and hide a class or section using somehting like {% if page.layout == 'home' %}hide{% endif %}. Is there an equivalent/similar method when using react?
Code:
import React from 'react';
import { Collapse, Navbar, NavbarToggler, NavbarBrand, Nav, NavItem, NavLink } from 'reactstrap';
export default class Example extends React.Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.state = {
isOpen: false,
isTop: true,
width: 0,
height: 0
};
this.updateWindowDimensions = this.updateWindowDimensions.bind(this);
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
componentDidMount() {
this.updateWindowDimensions();
window.addEventListener('resize', this.updateWindowDimensions);
document.addEventListener('scroll', () => {
const isTop = window.scrollY < window.innerHeight - 50;
if (isTop !== this.state.isTop) {
this.setState({ isTop })
}
});
}
componentWillUnmount() {
window.removeEventListener('resize', this.updateWindowDimensions);
}
updateWindowDimensions() {
this.setState({ width: window.innerWidth, height: window.innerHeight - 50 });
}
render() {
return (
<div>
<Navbar color="light" light expand="md">
<NavbarBrand href="/">Maryland <span>Brand</span></NavbarBrand>
<NavbarToggler onClick={this.toggle} />
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto" navbar>
<NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
<NavLink className="active" href="/">Our Brand</NavLink>
</NavItem>
<NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
<NavLink href="/">Logos</NavLink>
</NavItem>
<NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
<NavLink href="/">Color</NavLink>
</NavItem>
<NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
<NavLink href="/">Typography</NavLink>
</NavItem>
<NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
<NavLink href="/">Imagery</NavLink>
</NavItem>
<NavItem className={this.state.isTop ? 'hide' : 'show fadeIn'}>
<NavLink href="/">Editorial</NavLink>
</NavItem>
<NavItem>
<NavLink className="red bold uppercase show" href="/">Communicators Toolkit</NavLink>
</NavItem>
</Nav>
</Collapse>
</Navbar>
</div>
);
}
}
A: Gatsby comes with reach router, so you can use it to get location.pathname and then render something conditionally.
import React from 'react'
import { Location } from '@reach/router'
const HomepageOnly = () => (
<Location>
{({ location }) =>
location.pathname === '/' ? (
<p>This is the homepage</p>
) : (
<p>This is not</p>
)
}
</Location>
)
export default HomepageOnly
Codesandbox
| {
"language": "en",
"url": "https://stackoverflow.com/questions/56569223",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UIDocumentInteractionController working in iOS6 but not in iOS5 I am using UIDocumentInteractionController in MonoTouch and in the iOS6 Simulator and on iOS6 devices my code half works. However it does not work at all for iOS5 simulator/devices. Here is a sample class I made to test with in a sample project.
using System;
using MonoTouch.UIKit;
using MonoTouch.Foundation;
namespace DocumentThing
{
public class MyViewController : UIViewController
{
UIDocumentInteractionController documentInteractionController1;
UIDocumentInteractionController documentInteractionController2;
UIBarButtonItem leftButton;
UIBarButtonItem rightButton;
public MyViewController()
{
}
public override void ViewDidLoad()
{
View.BackgroundColor = UIColor.White;
leftButton = new UIBarButtonItem(UIBarButtonSystemItem.Action, null, null);
leftButton.Clicked += delegate(object sender, EventArgs e)
{
InvokeOnMainThread(delegate {
documentInteractionController1 = new UIDocumentInteractionController();
documentInteractionController1.Url = NSUrl.FromFilename(@"testpdf.pdf");
documentInteractionController1.PresentOpenInMenu(View.Frame, View, true);
});
};
NavigationItem.LeftBarButtonItem = leftButton;
rightButton = new UIBarButtonItem(UIBarButtonSystemItem.Action, null, null);
rightButton.Clicked += delegate(object sender, EventArgs e)
{
InvokeOnMainThread(delegate {
documentInteractionController2 = new UIDocumentInteractionController();
documentInteractionController2.Url = NSUrl.FromFilename(@"testpdf.pdf");
documentInteractionController2.PresentOptionsMenu(View.Frame, View, true);
});
};
NavigationItem.RightBarButtonItem = rightButton;
}
}
}
The PresentOptionsMenu works fine on iOS6 but not in iOS5, and the PresentOptionInMenu fails on both iOS5 and iOS6. Not sure if this is a bug with iOS5/6 SDKs/Simulators or if it is a bug in MonoTouch. I got no idea how to debug this issue further...
Suggestions?
A: Answering my own question...
Did you check if you have any thing to open a PDF on your device which has iOS5 on it? Don't forget iBooks is not installed by default and iOS does not think to use Safari as a PDF reader.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13448641",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Excel/Google Sheets Offset and Transpose formula question I have a query regarding the OFFSET and TRANSPOSE formulas. I have the following two sheets set up in Google Sheets (originally in Excel):
First sheet:
Formula in cell B2: =transpose('Form responses 1'!A2:BB2) (original)
=transpose(offset('Form responses 1'!A$2:BB$2,COLUMNS($A$2:A2)-1,0)) (current)
Formula in cell C2: =transpose('Form responses 1'!A3:BB3)
Formula in cell D2: =transpose('Form responses 1'!A4:BB4)
I would like the references to increase by row (vertically down) rather than by column (horizontally right) when I drag across to copy the formula.
Second sheet:
As you can see in the first sheet, I am trying to TRANSPOSE data from the second sheet using said formula. However when I go to drag the formula across (horizontally) it references the column when instead I need it to reference the row (if I drag it downwards it works fine but that is not what I need in this particular case).
I understand I need to implement a OFFSET function, something along the lines of: =transpose(offset('Form responses 1'!A$2:BB$2,COLUMNS($A$2:A2)-1,0))
I am unsure of what the last part would need to be, COLUMNS($A$2:A2)-1,0, what should I change this to to get the desire result?
If I have not explained thoroughly enough please let me know, thanks.
A: Use arrayformula and you won't have to drag anything. Try:
=arrayformula(transpose('Form responses 1'!A$1:BB$4))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/52150261",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Exception Safety example guarantee correct? I discuss the Exception Safety Guaratees and devised an example that I think provides the Strong Guarantee:
template<typename E, typename LT>
void strongSort(vector<E*> &data, LT lt) // works on pointers
{
vector<E*> temp { data }; // bad_alloc? but 'data' not changed.
sort(temp.begin(), temp.end(), lt); // 'lt' might throw!
swap(temp, data); // considered safe.
}
Just an easy (C++0x)-example how this is used:
int main() {
vector<int*> data { new int(3), new int(7), new int(2), new int(5) };
strongSort( data, [](int *a, int *b){ return *a<*b;} );
for(auto e : data) cout << *e << " ";
}
Assuming LT does not change the elments, but it may throw. Is it correct to assume thiat the code provides
*
*the Strong Exception Safety guarantee
*Is Exception Neutral, w.r.t to LT
A: Yes. Strong exception guarantee means that the operation completes successfully or leaves the data unchanged.
Exception neutral means that you let the exceptions propagate.
A: It is exception safe. To be more safe, why not use vector<shared_ptr<int>>
template<typename Type, typename Func>
void StrongSort( vector<shared_ptr<Type>>& elems, Func fun)
{
vector<shared_ptr<Type>> temp ( elems.begin(), elems.end());
sort(temp.begin(), temp.end(), fun);
swap(elems, temp);
}
vector<shared_ptr<int>> ints;
ints.push_back(shared_ptr<int>(new int(3)));
ints.push_back(shared_ptr<int>(new int(1)));
ints.push_back(shared_ptr<int>(new int(2)));
StrongSort(ints, [](shared_ptr<int> x, shared_ptr<int> y) -> bool { return *x < *y; });
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6972813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: javax.validation.ConstraintViolationException I am using JSF+JPA iam not fix this error:
javax.validation.ConstraintViolationException: Bean Validation
constraint(s) violated while executing Automatic Bean Validation on
callback event:'prePersist'. Please refer to embedded
ConstraintViolations for details.
@ManagedBean(name = "clientCon")
public class ClientController {
@PostConstruct
public void init() {
System.out.println("Salam");
clients = new Clients();
}
private EntityManagerFactory emf = null;
public ClientController() {
emf = Persistence.createEntityManagerFactory("ClinicProjectPU");
}
private List<Clients> clientList;
private Clients clients;
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
public Clients getClients() {
return clients;
}
public void setClients(Clients clients) {
this.clients = clients;
}
public List<Clients> getClientList() {
this.clientList = getEntityManager().createNamedQuery("Clients.findAll").getResultList();
return clientList;
}
public void createClient() {
EntityManager em = null;
try {
em = getEntityManager();
em.getTransaction().begin();
em.persist(clients); // the only interesting method
em.flush();
em.getTransaction().commit();
System.out.println("created");
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
}
<h:form>
<fieldset>
<h:panelGrid columns="2">
<h:outputText value="Ad" style="color: #0099cc"/>
<h:inputText class="form-client" value="#{clientCon.clients.name}" />
<h:outputText value="Soyad" style="color: #0099cc" />
<h:inputText class="form-client" value="#{clientCon.clients.surname}" />
<h:outputText value="Telefon" style="color: #0099cc" />
<h:inputText class="form-client" value="#{clientCon.clients.phone}" />
</h:panelGrid>
<div class="btns">
<center><h:commandButton action="#{clientCon.createClient()}" value="Saxla" style="width: 60%;margin-top: 5%;border-radius: 5px;color: #ffffff;background-color: #0099cc" /></center>
</div>
</fieldset>
</h:form>
javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on callback event:'prePersist'. Please refer to embedded ConstraintViolations for details.
at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.validateOnCallbackEvent(BeanValidationListener.java:90)
at org.eclipse.persistence.internal.jpa.metadata.listeners.BeanValidationListener.prePersist(BeanValidationListener.java:62)
at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyListener(DescriptorEventManager.java:748)
at org.eclipse.persistence.descriptors.DescriptorEventManager.notifyEJB30Listeners(DescriptorEventManager.java:691)
at org.eclipse.persistence.descriptors.DescriptorEventManager.executeEvent(DescriptorEventManager.java:229)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectClone(UnitOfWorkImpl.java:4310)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNotRegisteredNewObjectForPersist(UnitOfWorkImpl.java:4287)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.registerNotRegisteredNewObjectForPersist(RepeatableWriteUnitOfWork.java:518)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4229)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at controller.ClientController.createClient(ClientController.java:69)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at javax.el.ELUtil.invokeMethod(ELUtil.java:326)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:536)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:269)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:87)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:724)
A: This is another way from correct answer on Sujan Sivagurunathan, i wrote not in comment because i dont have 50 reputation.
If you have AbstractFacade.java write this on create method
public void create(T entity) {
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
javax.validation.Validator validator = factory.getValidator();
Set<ConstraintViolation<T>> constraintViolations = validator.validate(entity);
if (constraintViolations.size() > 0 ) {
System.out.println("Constraint Violations occurred..");
for (ConstraintViolation<T> contraints : constraintViolations) {
System.out.println(contraints.getRootBeanClass().getSimpleName()+
"." + contraints.getPropertyPath() + " " + contraints.getMessage());
}
getEntityManager().persist(entity);
}
}
A: To know what caused the constraint violation, you can use the following validator and logger.
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Clients>> constraintViolations = validator.validate(clients);
if (constraintViolations.size() > 0 ) {
System.out.println("Constraint Violations occurred..");
for (ConstraintViolation<Clients> contraints : constraintViolations) {
System.out.println(contraints.getRootBeanClass().getSimpleName()+
"." + contraints.getPropertyPath() + " " + contraints.getMessage());
}
}
Put the logger before persisting the entity. So between
em.getTransaction().begin();
//here goes the validator
em.persist(clients);
Compile and run. The console will show you, just before the exception stack trace, which element(s) caused the violation(s).
You can but should catch your try block containing any persistence method with ConstraintViolationException (to avoid further problems and/or inform the user an error occurred and its reason). However, in a well built system there shouldn't be any constraint violation exception during persistence. In JSF, and other MVC framework, the validation step must be totally or partially done at the client side before submit/persistence. That's a good practice I would say.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22946549",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: Read and write structure containing std::string to .dat file using std::write and std::read C++ I have a structure
struct details
{
std::string username;
std::string password;
bool isActive;
};
struct details v_Details;
i wish to write these data into a file and then read it at some other point in the code as means of storing details. I have tried using std::write which seems to do its job
std::ofstream out_file;
out_file.open ("db.dat" , ios::out | ios::binary)
out_file.write((char*)&v_details , sizeof (struct details))
but when i try to read the data it reads only username and password and then it crashes.
My read part of the code is as below
std::ifstream in_file;
in_file.open (fileName.c_str() , std::ifstream::in);
std::string readFileLine = "\0";
if (in_file.is_open())
{
do
{
in_file.read ((char*)&details , sizeof(details));
cout << "\nDEBUG message-> " << __FILE__ <<" : " << __func__ << " : " << __LINE__ << " : Read - "<< details.username << " " << details.password << " " << isActive ;
}while (!in_file.eof());
in_file.close();
}
Anybody who can help and provide me a fix on this.
A: You cannot directly write the object and expect it to store everything properly when you have members that don't have a fixed size.
If it were char array you could use this way.
Given this situation, I would manually write the details, like length of username first, then write characters in username so that while reading I can read the length of username and read that number of characters from file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/21772378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Syncing objects imported at runtime using PUN In our multiplayer project on Unity, each user imports model at runtime, then joins room, and then configures runtime imported object as networked object. The problem is, the imported model gets destroyed when host leaves. Here is my code snippet:
private void Start()
{
pView = GetComponent<PhotonView>();
pView.ownershipTransfer = OwnershipOption.Takeover;
pView.ObservedComponents = new List<Component>();
photonTransformView = transform.GetComponent<PhotonTransformView>();
pView.ObservedComponents.Add(photonTransformView);
pView.synchronization = ViewSynchronization.UnreliableOnChange;
photonTransformView.m_PositionModel.SynchronizeEnabled = true;
photonTransformView.m_RotationModel.SynchronizeEnabled = true;
if (GetComponent<OVRGrabbable>() != null)
transform.GetComponent<OVRGrabbable>().runtimeObj = this;
partInfo = transform.GetComponent<PartInfo>();
if (partInfo)
partInfo.dynamicDync = this;
if (PhotonNetwork.isMasterClient)
{
int objId = PhotonNetwork.AllocateViewID();
// pView.viewID = objId;
//TakeOwnership(PhotonNetwork.player);
MSetPhotonViewId(PhotonNetwork.player.ID, gameObject.name, objId);
}
}
public void MSetPhotonViewId(int id, string objName, int objId)
{
//pView.RPC("SetOwnerForObject", PhotonTargets.Others, id);
object[] content = new object[3];
content[0] = id;
content[1] = objName;
content[2] = objId;
PhotonNetwork.RaiseEvent(ownerId, content, true, new RaiseEventOptions() { Receivers = ReceiverGroup.All, CachingOption = EventCaching.AddToRoomCache });
}
private void OnEvent(byte eventcode, object content, int senderid)
{
if (eventcode == ownerId)
{
object[] data = (object[])content;
if (gameObject.name == (string)data[1])
{
if (!pView)
StartCoroutine(MGetPhotonViewId(content, senderid));
else
{
pView.viewID = (int)data[2];
//Debug.Log("transfering ownership of: " + gameObject.name + " to: " + ((int)data[0]).ToString());
pView.TransferOwnership((int)data[0]);
}
}
}
}
IEnumerator MGetPhotonViewId(object content, int senderid)
{
while (!pView)
{
yield return null;
}
object[] data = (object[])content;
if (gameObject.name == (string)data[1])
{
pView.viewID = (int)data[2];
//Debug.Log("transfering ownership of: " + gameObject.name + " to: " + ((int)data[0]).ToString());
pView.TransferOwnership((int)data[0]);
}
}
How do I avoid object getting destroyed on other systems, when host leaves?
A: When a player quits a game, usually his/her actions are no longer relevant for new players. To avoid congestion on join, Photon server by default automatically cleans up events that have been cached by a player, that has left the room for good.
If you want to manually clean up the rooms' event cache you can create rooms with RoomOptions.CleanupCacheOnLeave set to false.
See the docs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55197849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Runspace Dispose in Powershell (GUI specific) I'm an active reader of StackOverflow as it usually helps me resolve all my issues.
But for my first question ever I'll ask your help about runspaces in Powershell, specifically for memory management.
I created some PS apps with GUI and now I use runspaces to avoid hang of the GUI when big operations are running.
My problem is that I can't manage to dispose my runspaces when they are finished.
Regarding the code below, it's a simple script to try to understand how I can dispose of my runspaces. I tried to incorporate a unique runspace to monitor and dispose the app runspaces, I inspired myself from a proxb's script (huge fan btw) but it doesn't seems to work.
Everytime I execute the runspace I gain 10Mb of memory, huge leak!
Can you help me to resolve this problem please ?
[xml]$xaml = @'
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Runspace" FontFamily="Calibri" Height="400" Width="400" FontSize="14">
<Grid Margin="10,10,10,10">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="10"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<TextBox x:Name="TB_Results" Grid.Row="0" TextWrapping="Wrap" VerticalScrollBarVisibility="Auto"/>
<Button x:Name="BT_Run" Grid.Row="2" Content="Run" Height="30"/>
</Grid>
</Window>
'@
# Inits
Add-Type -AssemblyName PresentationFramework
Add-Type -AssemblyName PresentationCore
Add-Type -AssemblyName WindowsBase
$gui = [hashtable]::Synchronized(@{})
$reader = (New-Object Xml.XmlNodeReader $xaml)
$gui.Window = [Windows.Markup.XamlReader]::Load($reader)
$xaml.SelectNodes("//*[@*[contains(translate(name(.),'n','N'),'Name')]]") | ForEach-Object { $gui.Add($_.Name,$gui.Window.FindName($_.Name)) }
$Script:Jobs = [system.collections.arraylist]::Synchronized((New-Object System.Collections.ArrayList))
$Script:JobCleanup = [hashtable]::Synchronized(@{ Host = $host })
# Test function
function RunFunc {
$newRunspace = [runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("gui",$gui)
$Code = {
$memupdate = "Memory: $($(Get-Process -Id $PID).PrivateMemorySize64 / 1mb) mb"
$gui.Window.Dispatcher.invoke("Normal",[action]{
$gui.TB_Results.Text = "$memupdate`r`n" + $gui.TB_Results.Text
})
}
$Powershell = [powershell]::Create().AddScript($Code)
$Powershell.Runspace = $newRunspace
[void]$Script:Jobs.Add((
[PSCustomObject]@{
PowerShell = $PowerShell
Runspace = $PowerShell.BeginInvoke()
}
))
}
# Background Runspace to clean up jobs
$newRunspace =[runspacefactory]::CreateRunspace()
$newRunspace.ApartmentState = "STA"
$newRunspace.ThreadOptions = "ReuseThread"
$newRunspace.Open()
$newRunspace.SessionStateProxy.SetVariable("jobs",$Script:Jobs)
$Code = {
$JobCleanup = $true
do {
foreach($runspace in $jobs) {
if ($runspace.Runspace.isCompleted) {
$runspace.powershell.EndInvoke($runspace.Runspace) | Out-Null
$runspace.powershell.dispose()
$runspace.Runspace = $null
$runspace.powershell = $null
}
}
$temphash = $jobs.clone()
$temphash | Where-Object { $_.runspace -eq $Null } | ForEach-Object { $jobs.remove($_) }
Start-Sleep -Seconds 1
} while ($JobCleanup)
}
$Powershell = [powershell]::Create().AddScript($Code)
$Powershell.Runspace = $newRunspace
$PowerShell.BeginInvoke()
# gui events
$gui.BT_Run.add_Click({ RunFunc })
$gui.Window.ShowDialog() | Out-Null
A: When you call $runspace.PowerShell.Dispose(), the PowerShell instance is disposed, but the runspace that it's tied to is not automatically disposed, you'll need to do that first yourself in the cleanup task:
$runspace.powershell.EndInvoke($runspace.Runspace) | Out-Null
$runspace.powershell.Runspace.Dispose() # remember to clean up the runspace!
$runspace.powershell.dispose()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/51799834",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Rest API Consumption in flutter Problem
I'm trying to receive data from a rest API in my flutter app, inside a future function but i keep getting the following error:
type 'CastList<dynamic, List>' is not a subtype of type 'List'.
The function I'm using to fetch the data is as follows:
static Future<List<Questionnaire>> fetchQuestionnaires() async {
try {
final response =
await http.get('http://10.0.2.2:4010/phone/questionnaires');
if (response.statusCode == 200) {
List<Questionnaire> resp =
json.decode(response.body).cast<List<Questionnaire>>();
List<Questionnaire> questionnaires = resp
.map<Questionnaire>((dynamic item) => Questionnaire.fromJson(item))
.toList();
log(
questionnaires.toString(),
);
return questionnaires;
} else {
throw Exception('Unable to fetch questionnaires');
}
} catch (error) {
log(error.toString());
}
}
I don't understand why this is. Why does using cast, cast to CastList<dynamic, Type> and not the original Type? What changes do I do to get my data?
The data model is given below.
Data Model
The Data i expect from my backend is like this. An array called questionnaires, containing multiples of a questionnaire, each containing an id and a displayQuestion. A displayQuestion in turn has the question text and the answers Array_.
For this, I have the following structure in my Json.
[
{
"questionId": 1,
"displayQuestions": [
{
"question": "how old are you",
"answers": [
"1",
"2",
"3",
"4"
]
}
]
}
]
This is my questionnaires.dart model
class Questionnaires {
List<Questionnaire> _questionnaires;
Questionnaires.fromJson(this._questionnaires);
}
This is questionnaire.dart model
class Questionnaire {
int questionnaireId;
List<DisplayQuestion> displayQuestions = [];
Questionnaire(this.questionnaireId, this.displayQuestions);
Questionnaire.fromJson(Map<String, dynamic> json)
: questionnaireId = json['questionnaireId'],
displayQuestions = json['displayQuestions'];
}
The code from display-question.dart model
class DisplayQuestion {
String _question;
List<String> _answers;
String get question => this._question;
List get answers => this._answers;
DisplayQuestion(this._question, [List<String> answers])
: this._answers = answers ?? [];
DisplayQuestion.fromJson(Map<String, dynamic> json)
: _question = json['question'],
_answers = json['answers'];
}
A:
Why does using cast, cast to CastList<dynamic, Type> and not the original Type?
From the docs, myList.cast<MyType> returns a List<MyType>. In your case you're calling resp.cast<List<Questionnaire>>, so the return will be List<List<Questionnaire>>, which is not what you want.
If you're asking about CastList<dynamic, Type>, it's a subclass of List<Type>, see the source code. It's useful because CastList doesn't need to create a new list, it's just a wrapper around the original list where each element is cast with as Type before being returned.
What changes do I do to get my data?
The problem is you're calling resp.cast<Type> where resp is not a list that constains Type.
Here's a working sample based on the code you provided:
import 'dart:convert';
final sampleJson = """[
{
"questionId": 1,
"displayQuestions": [
{
"question": "how old are you",
"answers": [
"1",
"2",
"3",
"4"
]
}
]
}
]
""";
class DisplayQuestion {
String question;
List<String> answers;
DisplayQuestion.fromJson(Map<String, dynamic> json)
: question = json["question"],
answers = json["answers"].cast<String>();
String toString() => 'question: $question | answers: $answers';
}
class Questionnaire {
int questionnaireId;
List<DisplayQuestion> displayQuestions;
Questionnaire.fromJson(Map<String, dynamic> json)
: questionnaireId = json['questionnaireId'],
displayQuestions = (json['displayQuestions'] as List<dynamic>)
.map((questionJson) => DisplayQuestion.fromJson(questionJson))
.toList();
String toString() => '$displayQuestions';
}
List<Questionnaire> parseQuestionnaires() {
List<Questionnaire> questionnaires =
(json.decode(sampleJson) as List<dynamic>)
.map((questionnaireJson) => Questionnaire.fromJson(questionnaireJson))
.toList();
return questionnaires;
}
void main() {
print(parseQuestionnaires());
// => [[question: how old are you | answers: [1, 2, 3, 4]]]
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/65783405",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Server Error 500 .htaccess I have this working on my dedicated server but it fails on my shared hosting please what can be wrong? Thank you.
AddHandler phpini-cgi .php
#Action phpini-cgi /cgi-bin/php5-custom-ini.cgi
Options -Indexes
Options FollowSymLinks
# Make Drupal handle any 404 errors.
ErrorDocument 404 /404.php
# Set the default handler.
DirectoryIndex index.php
<IfModule mod_rewrite.c>
RewriteEngine on
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)$ index.php?q=$1 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)$ index.php?q=$1&r=$2 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/([^/]+)$ index.php?q=$1&r=$2&s=$3 [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([^/]+)/([^/]+)/([^/]+)/([^/]+)$ index.php?q=$1&r=$2&s=$3&t=$4 [L]
</IfModule>
A: I figure out the problem. I noticed the hosting company do not configure Php to display error thus making it difficult for you to know where the problem is. The problem is actually the database connection to the server. Once I fix the database connection my website came on fine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/36009974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: After IORegisterForSystemPower failing to call IODeregisterForSystemPower I have an application, written in Objective-C for MacOS 10.10+ which registers for sleep/wake notifications (code sample below, but the code isn't the question). What I am wondering is, if I call IORegisterForSystemPower at App initialisation, but during debugging I kill the app before it has a chance to call IODeregisterForSystemPower, what are the implications? Does the app get de-registered automatically when it dies in any case? Is there a system dictionary I need to clear out (a plist somewhere, etc.)? Thanks in advance for any help.
io_object_t root_notifier = MACH_PORT_NULL;
IONotificationPortRef notify = NULL;
DebugLog(@"App: Logging IORegisterForSystemPower sleep/wake notifications %@", [NSDate date]);
/* Log sleep/wake messages */
powerCallbackPort = IORegisterForSystemPower ((__bridge void *)self, ¬ify, sleepWakeCallback, &root_notifier);
if ( powerCallbackPort == IO_OBJECT_NULL ) {
DebugLog(@"IORegisterForSystemPower failed");
return;
}
self.rootNotifierPtr = &(root_notifier); // MARK: deregister with this pointer
if ( notify && powerCallbackPort )
{
CFRunLoopAddSource(CFRunLoopGetCurrent(),IONotificationPortGetRunLoopSource(notify), kCFRunLoopDefaultMode);
}
A: To be honest, I don't know the exact answer. But it may help you.
First of, if you call IORegisterForSystemPower, you need to make two calls in this order: - Call IODeregisterForSystemPower with the 'notifier' argument returned here. - Then call IONotificationPortDestroy passing the 'thePortRef' argument returned here (Please visit apple's document for more detail).
In case of port binding, if I use CFSocketSetAddress, before releasing this socket no other can use this port for binding. But in case of app terminate/closed without releasing this socket this port is available. That means after terminated the app system automatically releasing this.
Does the app get de-registered automatically when it dies in any case?
I think it will automatically de-registered by system.
I also used similar code as you in one of my project. But recently replaced with below codes:
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self selector: @selector(receiveWakeNotification:) name: NSWorkspaceDidWakeNotification object: nil];
[[[NSWorkspace sharedWorkspace] notificationCenter] addObserver: self selector: @selector(receiveSleepNotification:) name: NSWorkspaceWillSleepNotification object: nil];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/63965921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: JPA ObjectOptimisticLockingFailureException on an Insert sql execution followed by an Update sql execution I'm using Spring-data-jpa with Kotlin and I faced this error:
org.springframework.orm.ObjectOptimisticLockingFailureException: Batch update returned unexpected row count from update [0]; actual row count: 0; expected: 1; statement executed
Here is my parent entity (unnecessary parts are omitted):
@Entity
class Parent(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0L,
@OneToMany(mappedBy = "parent", cascade = [CascadeType.ALL], orphanRemoval = true)
val children: MutableList<Child> = mutableListOf()
) {
fun addChild(child: Child) {
this.children.add(child)
child.parent = this
}
}
Here is my child entity (omitted too):
@Entity
@Table(uniqueConstraints = [UniqueConstraint(columnNames = ["parent_id"])]
class Child(
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Long = 0L,
) {
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "parent_id")
lateinit var parent: Parent
}
Transactional code is simple as follows:
@Transactional
fun saveChildren() {
...
val parent: Parent = parentRepo.findById(parentId)
parent.addChild(Child())
parent.addChild(Child())
validateSavedChildren() // select all children data to validate for some business reason
parentRepo.save(parent)
}
I turn on the sql log for debugging and the sqls are like (It assumes the parent's id = 4):
insert into
child
(... parent_id)
values
(... 4)
enter code here
...
select
.... parent_id
from Child
where parent_id = 4
...
update Child
set
parent_id = 4
...
where id = 1
The query parameters are just correct. As I guess, the error occurred by the last update sql and also know what the error means. I think the data in insert sql is not yet visible when the update sql is executed. Why I'm thinking this way is because I tried to reproduce the error with debug mode with my IDE(IntelliJ) and I executed the codes line by line, and the error is disappeared. Is this common case in JPA??
What I really wonder is the reason why the update sql is executed. It seems useless because the setting data in update sql is just the same as insert sql. After some Internet research, I found out some cases that update happens after insert, but none of them fits my case.
I also tried to change one line of code:
parentRepo.saveAndFlush(parent)
It made the upate sql disappear and the error is gone forever.
Why does this happen?? What am I missing??
UPDATE
Here is the function validateSavedChildren code:
fun validateSavedChildren() {
val parents: List<Parant> parentRepo.findAll() // it select all parents in DB
var childrenCount = 0
parents.forEach { parent ->
childrenCount += parent.children.size
}
if (childrenCount > CHILDREN_LIMIT) {
throw ChildrenCountExceededLimitException()
}
}
Following a comment by @XtremeBaumer, It seems like the above function has the key point because the update sql execution is removed by erasing the above function call.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/72772827",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Unable to locate a link using xpath I am unable to locate a link on a page using the xpath. When I use the Inspect Element command, the page source for the object is as follows:
<a id="TreeView1_LinkButtonMore" href="javascript:__doPostBack('TreeView1$LinkButtonMore','')">
See more
</a>
My Selenium Code is as follows:
driver.FindElement(By.XPath("//*[@id='TreeView1_LinkButtonMore')")).Click();
Error I get is as follows:
The given selector //*[@id='TreeView1_LinkButtonMore') is either invalid or does not result in a WebElement. The following error occurred:
InvalidSelectorError: Unable to locate an element with the xpath expression //*[@id='TreeView1_LinkButtonMore')
Thanks in Advance
A: Try this:
driver.FindElement(By.XPath("//*[@id='TreeView1_LinkButtonMore']")).Click();
However, it might be worth pointing out that the shortcut for this exact same thing is:
driver.FindElement(By.Id("TreeView1_LinkButtonMore")).Click();
A: There is syntax error in your xpath. The closing should be square bracket not the curve bracket
Syntax: //tag-name[@attribute='value']
Try this:
driver.FindElement(By.XPath("//a[@id='TreeView1_LinkButtonMore']")).Click();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/23837448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Does each apple developer has to pay $99 fee? We have Apple Developer Account and we invited new guy,
does he have to pay $99 to become a member and get certificates?
A: To share access with new guy I had to add him to https://developer.apple.com/account/#/people/ , not only to https://itunesconnect.apple.com/WebObjects/iTunesConnect.woa/ra/ng/users_roles
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50796788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
} |
Q: HtmlAgilityPack set node InnerText I want to replace inner text of HTML tags with another text.
I am using HtmlAgilityPack
I use this code to extract all texts
HtmlDocument doc = new HtmlDocument();
doc.Load("some path")
foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//text()[normalize-space(.) != '']")) {
// How to replace node.InnerText with some text ?
}
But InnerText is readonly. How can I replace texts with another text and save them to file ?
A: The HtmlTextNode class has a Text property* which works perfectly for this purpose.
Here's an example:
var textNodes = doc.DocumentNode.SelectNodes("//body/text()").Cast<HtmlTextNode>();
foreach (var node in textNodes)
{
node.Text = node.Text.Replace("foo", "bar");
}
And if we have an HtmlNode that we want to change its direct text, we can do something like the following:
HtmlNode node = //...
var textNode = (HtmlTextNode)node.SelectSingleNode("text()");
textNode.Text = "new text";
Or we can use node.SelectNodes("text()") in case it has more than one.
* Not to be confused with the readonly InnerText property.
A: Try code below. It select all nodes without children and filtered out script nodes. Maybe you need to add some additional filtering. In addition to your XPath expression this one also looking for leaf nodes and filter out text content of <script> tags.
var nodes = doc.DocumentNode.SelectNodes("//body//text()[(normalize-space(.) != '') and not(parent::script) and not(*)]");
foreach (HtmlNode htmlNode in nodes)
{
htmlNode.ParentNode.ReplaceChild(HtmlTextNode.CreateNode(htmlNode.InnerText + "_translated"), htmlNode);
}
A: Strange, but I found that InnerHtml isn't readonly. And when I tried to set it like that
aElement.InnerHtml = "sometext";
the value of InnerText also changed to "sometext"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8274421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "31"
} |
Q: aws serverless - exporting output value for cognito authorizer I'm trying to share cognito authorizer between my stacks for this I'm exporting my authorizer but when I try to reference it in another service I get the error
Trying to request a non exported variable from CloudFormation. Stack name: "myApp-services-test" Requested variable: "ExtApiGatewayAuthorizer-test".
Here is my stack where I have authorizer defined and exported:
CognitoUserPool:
Type: AWS::Cognito::UserPool
Properties:
# Generate a name based on the stage
UserPoolName: ${self:provider.stage}-user-pool
# Set email as an alias
UsernameAttributes:
- email
AutoVerifiedAttributes:
- email
ApiGatewayAuthorizer:
Type: AWS::ApiGateway::Authorizer
Properties:
Name: CognitoAuthorizer
Type: COGNITO_USER_POOLS
IdentitySource: method.request.header.Authorization
RestApiId: { "Ref": "ProxyApi" }
ProviderARNs:
- Fn::GetAtt:
- CognitoUserPool
- Arn
ApiGatewayAuthorizerId:
Value:
Ref: ApiGatewayAuthorizer
Export:
Name: ExtApiGatewayAuthorizer-${self:provider.stage}
this is successfully exported as I can see it in stack exports list from my aws console.
I try to reference it in another stack like this:
myFunction:
handler: handler.myFunction
events:
- http:
path: /{userID}
method: put
cors: true
authorizer:
type: COGNITO_USER_POOLS
authorizerId: ${myApp-services-${self:provider.stage}.ExtApiGatewayAuthorizer-${self:provider.stage}}
my env info
Your Environment Information ---------------------------
Operating System: darwin
Node Version: 12.13.1
Framework Version: 1.60.5
Plugin Version: 3.2.7
SDK Version: 2.2.1
Components Core Version: 1.1.2
Components CLI Version: 1.4.0
A: Answering my own question
it looks like I should have imported by output name not output export name, which is bit weird and all the docs I have seen point to export name, but this is how I was able to make it work
replaced this -
authorizerId:${myAppservices-${self:provider.stage}.ExtApiGatewayAuthorizer-${self:provider.stage}}
with -
authorizerId: ${myApp-services-${self:provider.stage}.ApiGatewayAuthorizerId}
A: If you come across Trying to request a non exported variable from CloudFormation. Stack name: "myApp-services-test" Requested variable: "ExtApiGatewayAuthorizer-test"., when exporting profile i.e.,
export AWS_PROFILE=your_profile
It must be done on the terminal window where you are doing sls deploy not on another terminal window. It is a silly mistake but I don't want anyone else waste their time around that
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59813541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Use sed with special character I try to use sed with special character:
sed -i -e "1i$jtempo" $file
$file is my file.
$jtempo is my variable with special character like: " or [ or (
But, when I run this script, I have this error:
sed: -e expression #1, char 17: unknown command: `"'
My file:
"desc_test":[
"id",
"name",
],
In my script bash:
jtempo=`cat myfile`
An idea ?
Thanks you !
A: $ cat f1
"desc_test":[
"id",
"name",
],
$ cat ip.txt
1
2
3
I would suggest to avoid i command and use r command which will be robust regardless of file content
$ # to insert before first line
$ cat f1 ip.txt
"desc_test":[
"id",
"name",
],
1
2
3
$ # to insert any other line number, use line_num-1
$ # for example, to insert before 2nd line, use 1r
$ # r command will read entire contents from a file
$ sed '1r f1' ip.txt
1
"desc_test":[
"id",
"name",
],
2
3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/48404898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Update a custom field on "Update Cart" click in WooCommerce Cart I added a custom <select> field to each product in cart page to be able to update variation, but when I change it's value and click "Update Cart", nothing updates unless quantity field has also been changed.
Is there a way to avoid this?
My code:
functions.php file:
add_filter( 'woocommerce_update_cart_action_cart_updated', 'on_action_cart_updated', 20, 1 );
function on_action_cart_updated( $cart_updated ){
if ($cart_updated) {
$cart_content = WC()->cart->get_cart_contents();
$update_cart = false;
$cart_totals = isset( $_POST['cart'] ) ? wp_unslash( $_POST['cart'] ) : '';
if ( ! empty( $cart_content ) && is_array( $cart_totals ) ) {
foreach ($cart_content as $key => $item) {
$lease_period = $cart_totals[$key]['lease'];
if ( ! empty( $lease_period )) {
$cart_content[$key]['variation']['attribute_pa_lease-period'] = $lease_period;
$update_cart = true;
}
}
if ($update_cart) {
WC()->cart->set_cart_contents($cart_content);
}
}
}
}
cart.php file:
<td class="product-lease-period" data-title="<?php esc_attr_e( 'Lease Period', 'woocommerce' ); ?>">
<div class="product-lease-period-select">
<select name="cart[<?php echo $cart_item_key ?>][lease]">
<?php
$lease_periods = ['6-months'=> '6 Months',
'12-months' => '12 Months',
'18-months' => '18 Months',
'24-months' => '24 Months'];
foreach ($lease_periods as $key => $period) {
$selected = '';
if ($cart_item['variation']['attribute_pa_lease-period'] == $key) {
$selected = 'selected="selected"';
}
echo "<option value=" . $key . " $selected>" . $period . "</option>";
}
?>
</select>
</div>
</td>
My conclusions so far:
I believe it's because of these pieces of code inside the class-wc-form-handler.php :
// Skip product if no updated quantity was posted.
if ( ! isset( $cart_totals[ $cart_item_key ] ) || ! isset( $cart_totals[ $cart_item_key ]['qty'] ) ) {
continue;
}
and a bit below:
if ( '' === $quantity || $quantity === $values['quantity'] ) {
continue;
}
A: I extended the WC_Form_Handler class in my functions.php file, copied a method I needed and edited it, and gave it higher hook priority in my extended class than it's in the original class:
class WC_Form_Handler_Ext extends WC_Form_Handler {
/**
* Hook in method.
*/
public static function init() {
add_action( 'wp_loaded', array( __CLASS__, 'update_cart_action' ), 30 );
}
/**
* Remove from cart/update.
*/
public static function update_cart_action() {
// method content edited
}
}
WC_Form_Handler_Ext::init();
UPDATE:
To make price change after variation value in cart is updated, this function needs to be added to the functions.php
function find_matching_product_variation_id($product_id, $attributes)
{
return (new WC_Product_Data_Store_CPT())->find_matching_product_variation(
new WC_Product($product_id),
$attributes
);
}
And it should be called from the loop in functions.php I mentioned in my question this way:
$attributes = $cart_content[$key]['variation'];
$variation_id = find_matching_product_variation_id($product_id, $attributes);
$price = get_post_meta($variation_id, '_price', true);
$item['data']->set_price($price);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/55200491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Remove string after specific character from list using powershell I am attempting to clean up (reformat) a list of servers that has been provided to me containing the full domain name so that I can use it elsewhere. The list of servers arrive formatted like: servername.domain.com. I read the list into a variable using import-csv and remove the other columns of data not needed using the format-table command. My resulting command looks something like this:
$l=Import-Csv .\filename.csv | Format-Table TARGET
TARGET is the column name containing the server names.
When I use the following to remove the domain name portion of the server name, the resulting value is "Microsoft" repeated for each line containing the server name. I have confirmed the server names are being read into the variable correctly.
$l -replace '(.+?)\..+','$1'
The command does work if there is only one server name in the variable. I know I was able to trim the names of the servers down at one point but I think I had a brain lapse that day and just did not write down the command I used. :(
Any suggestions? My end goal is to incorporate the commands into a script for scheduled processing.
A: There are a few considerations here. Firstly, as matt has said, objects are destroyed by formatting commands. Only use them if you are trying to achieve a pretty view of the properties of objects, otherwise use select.
I would argue that you would be doing that unnecessarily: why throw away information that you might later want? I've lost count of the number of times that I've realised I can do something new and useful with the script or function I've just written, if I just expand it a little.
When you import a .csv file, you create objects with the property names of the column headings, so you can just refer to that property by name later.
Your problem with the replace command is related to the fact that you need to loop through the objects stored in $l, when there is more than one, Foreach-Object will do that.
So, for the file servers.csv:
TARGET,VALUE2,VALUE3
server1.domain.com,2,3
server2.domain.com,2,3
server3.domain.com,2,3
server4.domain.com,2,3
server5.domain.com,2,3
The import gives us a nice array of objects (nicely formatted in a table):
Import-Csv .\servers.csv | ft -a
TARGET VALUE2 VALUE3
------ ------ ------
server1.domain.com 2 3
server2.domain.com 2 3
server3.domain.com 2 3
server4.domain.com 2 3
server5.domain.com 2 3
We can use Foreach-Object (% is the alias) to get the 'TARGET' property of each object (equivalent to each line the in file), use the 'Split' method to split on the dots of the FQDN and then take the first token of that split:
Import-Csv .\servers.csv | % {$_.TARGET.Split('.')[0]}
server1
server2
server3
server4
server5
You can import to a variable first and then pipe that to the loop if you want.
Cheers
A: ALWAYS: If you plan on doing data manipulation remove the | Format-Table TARGET as it destroys the objects.
One approach would be to extract a string array of the column TARGET which you could then process.
$l=Import-Csv .\filename.csv | Select -Expand TARGET
Assuming you have a properly formed CSV your code could be simplified. Since it does not require regex you could also do.
$l=Import-Csv .\filename.csv | Select -Expand TARGET | ForEach-Object{$_ -Split "." | Select -First 1}
$l should contain just the server names at this point. You regex is not wrong however in order to use it you would have to refine it or use it in a loop similar to how I use -split.
$l=Import-Csv .\filename.csv | Select -Expand TARGET
$l | ForEach-Object{$_ -replace '(.+?)\..+','$1'}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28351275",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to parse json data recieved as a string [
{"CityName":"Jaipur","CityId":1},
{"CityName":"Jodhpur","CityId":2},
{"CityName":"Ajmer","CityId":3},
{"CityName":"Bikaner","CityId":4}
]
I want to get all the citynames and their id but i don't know how to do that. As I new to android any answer will be a great help for me..Thanks in advance
A: Try this..
Your getting response as JSONArray like below
JSON
[ //JSONArray array
{ //JSONObject jObj
"CityName": "Jaipur", //optString cityName
"CityId": 1 //optInt CityId
},
{
"CityName": "Jodhpur",
"CityId": 2
},
{
"CityName": "Ajmer",
"CityId": 3
},
{
"CityName": "Bikaner",
"CityId": 4
}
]
Code
JSONArray array = new JSONArray(response);
for(int i=0;i<array.length();i++){
JSONObject jObj = array.optJSONObject(i);
String cityName = jObj.optString("CityName");
int CityId = jObj.optInt("CityId");
Log.v("cityName :",""+cityName);
Log.v("CityId :",""+CityId);
}
A: try this one
JSONArray jarray =new JSONArray(response);
String[] cityName = new String[jarray.length()]
JSONObject jObject=null;
for(int j=0;j<jarray.length();j++){
jObject=jarray.getJSONObject(j);
cityName[j]=jObject.getString("CityName");
}
A: Do like this
ArrayList<String> cityname=new ArrayList<String>();
JSONArray jsonarr=new JSONArray(string);
for(i=0;i<jsonarr.length();i++){
cityname.add(jsonarr.getJSONObject(i).getString("CityName"));
}
A: Use JSON classes for parsing e.g
JSONObject mainObject = new JSONObject(Your_Sring_data);
String CityName= mainObject .getJSONObject("CityName");
String CityId= mainObject .getJSONObject("CityId");
...
A: Try this:
JSONArray jsonArray= jsonResponse.getJSONArray("your_json_array_name");
for (int i=0; i<jsonArray.length(); i++) {
JSONObject jsonObject= jsonArray.getJSONObject(i);
String name = jsonObject.getString("CityName");
String id = jsonObject.getString("CityId");
}
A: You can use json-path library it will simplifies the JSON parsing.
You can download json-path lib from here
Then add this library to your project /libs/ folder.
Then import the project name like this
import com.jayway.jsonpath.JsonPath;
Then parse your JSON data like this
JSONArray jsonData= new JSONArray(JsonPath.read(jsonStringData,"$..CityId[*]").toString());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22861707",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
} |
Q: Unable to send mail to more than 200 member at at a time using php mail function Hello guy i am using php mail function to deliver my mails if i run the code locally with 5 email id then it working fine without any error but if i run the same code with more than 400 email id then it show the warning messages link
Warning: mail() [function.mail]: Could not execute mail delivery program '/usr/sbin/sendmail -t -i' in /home/sendInvite.php on line 147
i am using this code :
$sqlquery1 = "select employee from empl where sstatus != 'C'";
$sqlmath1 = mysql_query($sqlquery1) or die("Error: (" . mysql_errno() . ") " . mysql_error());
$cnt = mysql_num_rows($sqlmath1);
if($cnt !="0") {
while($query1 = mysql_fetch_array($sqlmath1))
{
$email1=$query1['employee'];
$emid1=base64_encode($email1);
$sid1 =base64_encode($sidtest);
$email_from1 = "[email protected]";
$link1="http://www.xx.php?mid=$emid1&sid=$sid1";
//send mail
$emailto_web1 = $email1;
$email_headers1 = "From: ".$email_from1;
num_sent_web1 = 0;
$email_message21 = "Dear Employee, \n";
$email_message21 .= "\n";
$email_message21 .= "If you cannot click on the URL, copy the URL and paste it on your address bar.\n";
$email_message21 .= "\n";
$email_message21 .= $link1."\n";
$email_message21 .= "\n\n\n";
$email_message21 .= "Regards,\n";
$email_message21 .= "Admin Team. \n";
$mail_web1 = mail($emailto_web1,$email_subject1,$email_message21,$email_headers1);
if($mail_web1)
{ $err = "Remainder Send Successfully";
}
else
{ $err=$email." Try Again";
}
}
} // not equal to zero condition
I dont know the exact reason why i receive this warning message, Please Post your valuble suggestion. Thanks in advance !!!
A: Use cron job for this and send mails in chunks instead of sending all mails in one time.
A: Please see the php mail function documentation:
It is worth noting that the mail() function is not suitable for larger volumes of email in a loop. This function opens and closes an SMTP socket for each email, which is not very efficient.
For the sending of large amounts of email, see the » PEAR::Mail, and » PEAR::Mail_Queue packages.
Also, see the related questions on serverfault: https://serverfault.com/questions/67154/sending-an-email-to-about-10k-users-not-spam, where PHPlist is mentioned, along with others. And here - https://serverfault.com/questions/68357/whats-the-best-way-to-send-bulk-email,https://stackoverflow.com/questions/1543153/is-there-a-limit-when-using-php-mail-function
A: I think there is no problem with your script but its rather an installation issue with your operating system or sending mail program is poorly configured or perhaps missing. Try all possibilities, from php side its okay.
A: Your best option is to use a cron job. Doing it like this, your server will have a lot of stress. The mail() function isn't meant for a large volume of emails. It will slow done your server if your using a large amount.
This will explain how to make a cron job on your server.
Hope it helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4342678",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Caused by: io.cucumber.datatable.UndefinedDataTableTypeException: Can't convert DataTable to List I am updating cucumber version from 3x to 7x and I faced following exception:
Caused by: io.cucumber.datatable.UndefinedDataTableTypeException: Can't convert DataTable to List
There was no table entry or table row transformer registered for com.x.config
Please consider registering a table entry or row transformer.
and code is as follows:
@And("^configurations$")
public void configurations(List<Config> configs) {
initialConfigs = configs.stream().map(cfg -> Config.builder()
}
A: I found how to solve it, by adding Transformer in step definition that should be as follows:
@DataTableType
public Config entryTransformer(Map<String, String> row) {
return Config.builder()
.id(Integer.parseInt(row.get("id")))
.active(row.get("active"))
.build();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/74472560",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Accessing an Audio File From a Different Folder I am doing a project for my computer science class in which I am adding audio into my website. I am doing this in cloud 9. And I have a folder of different songs on a different folder. I need to be able to access the song from the higher folder. People have been saying to use this code:
<source src="../folder/filename.mp3" type=mpeg">
But the code was given to me fro images, I have not been able to do it with a song. When I use this code I get the normal looking play button on my website, but it is grayed out. I have been able to get it to work, but only if I take the song out of the folder and put it at the same level as the file. I have also tested different audio files to see if that is the problem.
A: Use absolute site URI routing whereby your sound file address starts with a / and so indicates the path from the root of the URL.
For instance:
Your current output file is, say, www.site.com/output/file.html, and you want to load a sound from, say, www.site.com/sounds/laugh.mp3 then you simply use the /sounds/laugh.mp3 part of the address as your reference. Becauseit starts with a / this indicates it's an absolute site URL and indicates the root HTML directory, rather than a page specific url.
<source src="/sounds/filename.mp3" type=mpeg">
If you used a relative path such as ../sounds/filename.mp3 this would break if you used it in the base folder (www.site.com/index.html) or in a deeper directory tree such as www.site.com/sounds/silly/horses.html. But the absolute path would always work (as long as the destinaton file exists and is accessible).
Tip: Make sure you've also uploaded your sound file!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40061056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to create a model instance that has a belongsTo property? var attr = DS.attr,
hasMany = DS.hasMany,
belongsTo = DS.belongsTo;
Admin.Category = DS.Model.extend({
name: attr(),
mstore: belongsTo('mstore')
});
console.log(mstore); // this is a PromiseObject object passed from "{{action createCategory mstore}}" tag
var newCategory = this.store.createRecord('category', {
name: 'nn',
mstore: mstore
});
I get an error like:
Assertion failed: You can only add a 'mstore' record to this relationship.
How can I set a belongsTo property using a PromiseObject object? Thanks.
A: In your {{action...}} you should pass a real model, not a promise. To get a model from a promise you need to do something like this:
var myMstore;
that.store.find('mstore', mstoreId).then(function(mstore) {
myMstore = mstore;
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/19176979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Populate JTable with strings from JTextFields I am building a GUI for MySQL, with JFrames with collaboration with jdbc.
I am not that good in Java and I can't figure the following out.
I want to populate a JTable with data from a query of mine, but I want this query to have user parameters inside. So..
Here is the query:
String sql = "SELECT `field1`, `field2`, `field3`"
+ "FROM `Table1` INNER JOIN `Table2` on `table1PK` = `table2PK`"
+ "WHERE `column1Value` = '"+JTextfield1.getText()+'" AND"
+ " `column2Value` = '"+JTextfield2.getText()+"'";
And then, with the output of this string, after pressing a JButton, I want to populate a JTable.
In other words I want the "output" of the JTable to be "UserParameterDefined" (through the JTextFields)
Here is the hole code for a working auto-populating JTable but without User Defined Parameters which I have and works perfectly:
package pkginterface;
import java.awt.*;
import java.sql.*;
import java.util.*;
import javax.swing.*;
import javax.swing.table.*;
import java.time.*;
import java.sql.Date;
import java.text.*;
public class Movies_Info extends JFrame
{
public Movies_Info()
{
ArrayList columnNames = new ArrayList();
ArrayList data = new ArrayList();
// Connect to an MySQL Database, run query, get result set
String url = "jdbc:mysql://localhost:3306/cinema";
String userid = "root";
String password = "root";
String sql = "SELECT movie_title, timetable_starttime, timetable_movietype "
+ "FROM Movies INNER JOIN TimeTable on timetable_movie_ID = movie_ID";
try (Connection connection = DriverManager.getConnection( url, userid, password );
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery( sql ))
{
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++)
{
columnNames.add( md.getColumnName(i) );
}
// Get row data
while (rs.next())
{
ArrayList row = new ArrayList(columns);
for (int i = 1; i <= columns; i++)
{
row.add( rs.getObject(i) );
}
data.add( row );
}
}
catch (SQLException e)
{
System.out.println( e.getMessage() );
}
Vector columnNamesVector = new Vector();
Vector dataVector = new Vector();
for (int i = 0; i < data.size(); i++)
{
ArrayList subArray = (ArrayList)data.get(i);
Vector subVector = new Vector();
for (int j = 0; j < subArray.size(); j++)
{
subVector.add(subArray.get(j));
}
dataVector.add(subVector);
}
for (int i = 0; i < columnNames.size(); i++ )
columnNamesVector.add(columnNames.get(i));
// Create table with database data
JTable table = new JTable(dataVector, columnNamesVector)
{
public Class getColumnClass(int column)
{
setTitle("Staff Interface - Movies Info");
for (int row = 0; row < getRowCount(); row++)
{
Object o = getValueAt(row, column);
if (o != null)
{
return o.getClass();
}
}
return Object.class;
}
};
JScrollPane scrollPane = new JScrollPane( table );
getContentPane().add( scrollPane );
JPanel buttonPanel = new JPanel();
getContentPane().add( buttonPanel, BorderLayout.SOUTH );
TableCellRenderer tableCellRenderer = new DefaultTableCellRenderer() {
// Time shown correction
SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss");
public Component getTableCellRendererComponent(JTable table,
Object value, boolean isSelected, boolean hasFocus,
int row, int column) {
if( value instanceof Time) {
value = f.format(value);
}
return super.getTableCellRendererComponent(table, value, isSelected,
hasFocus, row, column);
}
};
table.setDefaultRenderer(Time.class, tableCellRenderer);
// Time shown correction finish
pack();
}
public static void main(String[] args)
{
Movies_Info frame = new Movies_Info();
frame.setDefaultCloseOperation( EXIT_ON_CLOSE );
frame.pack();
frame.setVisible(true);
}
}
Thanks in advance for any kind of help!
A: The basic concept would look something like...
import java.awt.BorderLayout;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.Vector;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
public class Test {
public static void main(String[] args) {
new Test();
}
public Test() {
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
JFrame frame = new JFrame("Testing");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.add(new TestPane());
frame.pack();
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
});
}
public class TestPane extends JPanel {
private JTextField field;
private JTable table;
public TestPane() {
setLayout(new BorderLayout());
field = new JTextField(20);
table = new JTable();
add(field, BorderLayout.NORTH);
add(new JScrollPane(table));
JButton update = new JButton("Update");
add(update, BorderLayout.SOUTH);
update.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
TableModel model = executeQueryWith(field.getText());
table.setModel(model);
} catch (SQLException ex) {
JOptionPane.showMessageDialog(TestPane.this, "Failed to execute query", "Error", JOptionPane.ERROR_MESSAGE);
ex.printStackTrace();
}
}
});
}
protected TableModel executeQueryWith(String value) throws SQLException {
String url = "jdbc:mysql://localhost:3306/cinema";
String userid = "root";
String password = "root";
String sql = "SELECT movie_title, timetable_starttime, timetable_movietype "
+ "FROM Movies INNER JOIN TimeTable on timetable_movie_ID = ?";
DefaultTableModel model = new DefaultTableModel();
try (Connection connection = DriverManager.getConnection(url, userid, password)) {
try (PreparedStatement stmt = connection.prepareStatement(sql)) {
stmt.setString(1, value);
try (ResultSet rs = stmt.executeQuery()) {
ResultSetMetaData md = rs.getMetaData();
int columns = md.getColumnCount();
// Get column names
for (int i = 1; i <= columns; i++) {
model.addColumn(md.getColumnName(i));
}
// Get row data
while (rs.next()) {
Vector<Object> row = new Vector(columns);
for (int i = 1; i <= columns; i++) {
row.add(rs.getObject(i));
}
model.addRow(row);
}
}
}
}
return model;
}
}
}
You might also like to have a look at:
*
*Using Prepared Statements
*How to Use Tables
*Concepts: Editors and Renderers
*Using Custom Renderers
*How to Use Buttons, Check Boxes, and Radio Buttons
*How to Write an Action Listeners
| {
"language": "en",
"url": "https://stackoverflow.com/questions/35402520",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Spring Cannot deserialize request param date "Thu Dec 26 20:53:18 GMT+01:00 2019" Cannot parse "Thu Dec 26 20:53:18 GMT+01:00 2019" using @DateTimeFormat(pattern ="EEE MMM dd HH:mm:ss 'GMT'XXX yyyy").
Failed to convert from type [java.lang.String] to type [@org.springframework.format.annotation.DateTimeFormat @org.springframework.web.bind.annotation.RequestParam java.util.Date] for value 'Thu Dec 26 20:53:18 GMT+01:00 2019'; nested exception is java.lang.IllegalArgumentException: Invalid format: "Thu Dec 26 20:53:18 GMT+01:00 2019" is malformed at "+01:00 2019"]
A: Thanks a lot to @Deadpool and @Stephen C, Combining your answers solved my problem.
public static final String DATE_TIME_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSXX";
public filter(@DateTimeFormat(pattern =DATE_TIME_FORMAT) LocalDate fromDate) {
...
}
I updated date format as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59493688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Implementation AbstractPreferenceInitializer won't get called in my Eclipse RCP I want to use the Eclipse mechanism to set default preferences in my RCP application. Therefore I extended the class AbstractPreferenceInitializer to set my default preferences:
public class PreferenceInitializer extends AbstractPreferenceInitializer {
@Override
public void initializeDefaultPreferences() {
IPreferenceStore preferenceStore = PlatformUI.getPreferenceStore();
preferenceStore.setDefault("xyz", xyz);
preferenceStore.setDefault("abc", false);
}
}
Then I defined the extension point:
<extension point="org.eclipse.core.runtime.preferences">
<initializer class="com.abc.PreferenceInitializer">
</initializer>
</extension>
But unfortunately, the initializer won't get called during startup (whereas Eclipse's WorkbenchPreferenceInitializer will be called).
Can someone give me a hint, what to do, to get this run?
A: Your preference initializer code won't get called until those default values are needed (rather than on application startup, which I'm guessing was your expectation).
If you have yourself a preference page that contains some FieldEditors using your preference names, your preference initializer will get called when you go to the Preferences dialog and select that preference page.
Something along the lines of:
public class MyPreferencePage extends FieldEditorPreferencePage implements IWorkbenchPreferencePage {
public void createFieldEditors() {
Composite parent = getFieldEditorParent();
addField(new StringFieldEditor(Constants.PREFERENCES.FILE_COMPARE_TOOL_LOCATION, "File compare tool location", parent));
addField(new StringFieldEditor("xyz", "XYZ Value", parent));
addField(new BooleanFieldEditor("abc", "Enable the ABC widget", parent));
}
}
And of course, an extension point for the page:
<extension point="org.eclipse.ui.preferencePages">
<page
class="whatever.package.MyPreferencePage"
id="whatever.package.MyPreferencePage"
name="MyPrefs">
</page>
</extension>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11046158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Deadlock in DB2 while updating a table using jdbc template I'm trying to update a table for multiple rows in AS400 DB2. This query works fine when I test in work bench. When I use the same query from jdbc template, it creates dead lock and a lock is made on the table. What might be the issue here? Here is my code.
QUERY
UPDATE <table name> SET status= 'CLOSED' WHERE PROCESSID IN ('ABC1243', 'DTH4666');
From using code.
public void updateStatus() {
try { getJdbcTemplate().update("UPDATE <table name> SET status= 'CLOSED' WHERE PROCESSID IN ('ABC1243', 'DTH4666');}
catch (Exception e) { logger.error(e); throw e; }
}
Any ideas would be very useful for me.
A: 1.Is autocommit turned on or turned off on your database connection ?
2. In DB2, there are chances of deadlock when you are firing a select query and
update query within same transaction.
3. If the auto commit is turned off and you have fired a select query on the
table then try committing or rollback that transaction and then fire update
query. It should work.
Let me know in case if you are still facing above issue.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/47736195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to save whitespaces while parsing array to string? Let's say during some string operations we have this kind of array:
[0] = "Foo"
[1] = " " (3 spaces)
[2] = "bar"
[3] = " " (2 spaces)
we separated incoming string with regex using word break (/\b/g), and we wanna save all source spaces in output
doing
str.join(" ")
will erase all elements with spaces resulting in "Foo bar", instead we want to get "Foo bar " string. I guess this is because of converting arr[1] that is " " (3 spaces) to String.
A:
const arr = ["Foo", " ", "bar", " "];
var str = arr.join(" ");
console.log('"' + str + '"');
console.log("str length: " + str.length);
Works here... although you probably really meant to do arr.join(""); without the space.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/53318843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Jersey + Spring 3 + Maven 3 + Tomcat 7 @Resource in @Component Class are always null I have searched and tried about everything I can think of to fix this but the Dao in the TestService class is always null. I see the Spring logs showing that the Dao is injected as well as the TestService class. I have tried running under WTP for eclipse as well as straight up in Tomcat. Both result in the same error. Can anybody please help decipher where the error is that causes the Dao to be null in the TestService Class.
Versions:
Jersey 1.8
Spring 3.0.5Release
Tomcat apache-tomcat-7.0.27
Maven 3.0.3 (r1075438; 2011-02-28 12:31:09-0500)
Java 1.6.0_31
Eclipse Java EE IDE for Web Developers.
Version: Indigo Service Release 2
Build id: 20120216-1857
Logging - Showing the injection happening (Cut off DEBUG and ClassNames for brevity)
Creating shared instance of singleton bean 'dataSource'
Creating instance of bean 'dataSource'
Eagerly caching bean 'dataSource' to allow for resolving potential circular references
Finished creating instance of bean 'dataSource'
Creating shared instance of singleton bean 'jdbcTemplate'
Creating instance of bean 'jdbcTemplate'
Eagerly caching bean 'jdbcTemplate' to allow for resolving potential circular references
Returning cached instance of singleton bean 'dataSource'
Invoking afterPropertiesSet() on bean with name 'jdbcTemplate'
Finished creating instance of bean 'jdbcTemplate'
Creating shared instance of singleton bean 'testClassDao'
Creating instance of bean 'testClassDao'
Found injected element on class [test.dao.TestClassDao]: AutowiredMethodElement for public void test.dao.TestClassDao.setDataSource(javax.sql.DataSource)
Eagerly caching bean 'testClassDao' to allow for resolving potential circular references
Processing injected method of bean 'testClassDao': AutowiredMethodElement for public void test.dao.TestClassDao.setDataSource(javax.sql.DataSource)
Returning cached instance of singleton bean 'dataSource'
Autowiring by type from bean name 'testClassDao' to bean named 'dataSource'
Finished creating instance of bean 'testClassDao'
Creating shared instance of singleton bean 'testService'
Creating instance of bean 'testService'
Found injected element on class [test.service.admin.TestService]: AutowiredFieldElement for test.dao.TestClassDao test.service.admin.TestService.dao
Eagerly caching bean 'testService' to allow for resolving potential circular references
Processing injected method of bean 'testService': AutowiredFieldElement for test.dao.TestClassDao test.service.admin.TestService.dao
Returning cached instance of singleton bean 'testClassDao'
Autowiring by type from bean name 'testService' to bean named 'testClassDao'
Finished creating instance of bean 'testService'
Error - Null Pointer Exception in TestService.java because TestClassDao is null
Apr 25, 2012 9:07:04 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jersey] in context with path [/test-service] threw exception
java.lang.NullPointerException
at test.service.admin.TestService.createCompanyProfile(TestService.java:35)
TestClassDao.java
package test.dao;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.MapSqlParameterSource;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Repository;
import test.domain.TestClass;
@Repository
public class TestClassDao {
private NamedParameterJdbcTemplate namedParamJdbcTemplate;
private DataSource dataSource;
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
this.namedParamJdbcTemplate = new NamedParameterJdbcTemplate(dataSource);
}
public void insertTestClass(TestClass testClass)
{
String query = "INSERT INTO TEST_CLASS_TABLE(NAME) VALUES (:NAME)";
MapSqlParameterSource namedParams = new MapSqlParameterSource();
mapParams(namedParams, testClass);
namedParamJdbcTemplate.update(query, namedParams);
}
private void mapParams(MapSqlParameterSource namedParams, TestClass testClass)
{
namedParams.addValue("NAME", testClass.getName());
}
}
TestClass.java
package test.domain;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
public class TestClass implements java.io.Serializable {
private String name;
public TestClass(String name){
this.name = name;
}
public String getName() {
return this.name;
}
}
TestService.java
package test.service.admin;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.UriInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import test.dao.TestClassDao;
import test.domain.TestClass;
@Path("/resttest")
@Component
public class TestService {
@Context
UriInfo uriInfo;
@Context
Request request;
@Autowired
TestClassDao dao;
static Logger log = Logger.getLogger(TestService.class);
@GET
@Path("/test")
public String createCompanyProfile() {
TestClass test = new TestClass("MyTestName");
dao.insertTestClass(test);
return "test done";
}
}
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:annotation-config />
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:1234/testClassDatabase" />
<property name="username" value="user" />
<property name="password" value="password" />
</bean>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource">
<ref bean="dataSource" />
</property>
</bean>
<context:component-scan base-package="test"/>
</beans>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>jersey</servlet-name>
<servlet-class>
com.sun.jersey.spi.container.servlet.ServletContainer
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
UPDATE: Added this for the web-app but it didn't change anything
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
pom.xml - Which I think is where the issue may lie, a dependency or something
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>test-service</groupId>
<artifactId>test-service</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Test Service</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- Jersey -->
<dependency>
<groupId>commons-dbcp</groupId>
<artifactId>commons-dbcp</artifactId>
<version>1.4</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.19</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-server</artifactId>
<version>${jersey.version}</version>
</dependency>
<!-- Spring 3 dependencies -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework.version}</version>
</dependency>
<!-- Jersey + Spring -->
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-spring</artifactId>
<version>${jersey.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
</exclusion>
<exclusion>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.8.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
</dependencies>
<build>
<finalName>test-service</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.6</source>
<target>1.6</target>
</configuration>
</plugin>
</plugins>
</build>
<properties>
<org.springframework.version>3.0.5.RELEASE</org.springframework.version>
<jersey.version>1.8</jersey.version>
</properties>
</project>
UPDATE FIXED: My friend took a look and noticed I didn't have the param set for com.sun.jersey.config.property.packages, once we added that in, everything automagically worked.
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:server-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
<listener>
<listener-class>
org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<servlet>
<servlet-name>jersey-serlvet</servlet-name>
<servlet-class>
com.sun.jersey.spi.spring.container.servlet.SpringServlet
</servlet-class>
<init-param>
<param-name>
com.sun.jersey.config.property.packages
</param-name>
<param-value>service</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>jersey-serlvet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
A: Spring is injecting an instance of TestService with a DAO, but that instance isn't the one that requests are going to. You're using Jersey's ServletContainer to host your Jersey app, which doesn't integrate with Spring in any way. It'll be creating instances as needed all on its own, which obviously won't be injected by Spring (without doing some bytecode weaving, anyway). I'd recommend using the SpringServlet, which is a ServletContainer that knows how to get resource classes from a Spring context. That'll clear up your problem.
A: Same as Ryan pointed out - your ServletContainer servlet doesn't know about Spring container, so your @Resource/@Autowired never gets dependency injected.
Use SpringServlet instead, either by adding it to web.xml`, or adding it in your Spring WebInitializer, not both. See examples below.
Here's code example for web.xml:
<servlet>
<servlet-name>jersey-spring</servlet-name>
<servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>jersey-spring</servlet-name>
<url-pattern>/resources/*</url-pattern>
<load-on-startup>1</load-on-startup>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>phonebook.rest</param-value>
</init-param>
</servlet-mapping>
Here's code example for your custom WebInitializer:
public class PhonebookApplicationWebInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext factory = new AnnotationConfigWebApplicationContext();
// factory.scan("phonebook.configuration");
factory.register(PhonebookConfiguration.class);
ServletRegistration.Dynamic dispatcher = container.addServlet("jersey-spring", new SpringServlet());
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/resources/*");
dispatcher.setInitParameter("com.sun.jersey.config.property.packages", "phonebook.rest");
container.addListener(new ContextLoaderListener(factory));
}
}
You can see some a nice example on Spring+Jersey integration here:
http://www.mkyong.com/webservices/jax-rs/jersey-spring-integration-example/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/10325550",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Is it true that a JSON document will not be parseable until the last byte is written? Is the following hypothesis valid?
Leaving aside whitespace, once the first character of a JSON document
has been written, the resulting stream will not parse as valid JSON
until the last character has been written.
I'm interested in using this assumption so that when I have one process writing a file and another reading it, I can safely ignore partially-written files by ignoring anything that doesn't parse as valid JSON.
A: I'm sure it depends on the parser you are using... it seems than any scrupulous parser would follow that rule due to the structure of JSON... curly brackets around every "object" key/value pair, including any wrapping document { }).
As always with programming, test rather than assume.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8524677",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Making and sending a mix double and int array in c I am trying to send a msg from a socket that will be in the form on
double,int,int,int,int,...,int
N int values
how can i send it?
i have opened a socket but how can i put all those elements in one array that will be sent in:
status=sendto(SendSocket,msg,sizeof(double)+N*sizeof(int),
0,(void*)&out_socketaddr,sizeof(out_socketaddr));
Where MSG is the memory(array) of all those elements and out_socketaddr is the destination
A: uint8_t array [sizeof(this) + sizeof(that) + ...];
uint8_t* ptr = array;
memcpy(ptr, &this, sizeof(this));
ptr+=sizeof(this);
memcpy(ptr, &that, sizeof(that));
ptr+=sizeof(that);
...
Avoid making a struct. Although structs will make the code more readable, they also introduce padding, which will be an issue in this case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/30188393",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Different class files for same dependency when used in different projects I was given a spring project with gradle as the build tool. Since I'm familiar with maven I tried to change the project build tool to maven. I defined the dependencies in pom.xml like it was in build.gradle using the same group id, artifact id and version. However with the maven version of the project there is an error with one dependency, comparing both dependencies I found that the class files are different, I've searched and found nothing close to my problem.
In build.gradle
compile 'org.springframework.data:spring-data-jpa:1.10.4.RELEASE'
In pom.xml
<!-- https://mvnrepository.com/artifact/org.springframework.data/spring-data-jpa -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-jpa</artifactId>
<version>1.10.4.RELEASE</version>
</dependency>
The difference in code is found in CrudRepository.class
In the project with pom.xml this is the class
/*
* Copyright 2008-2017 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.repository;
import java.util.Optional;
/**
* Interface for generic CRUD operations on a repository for a specific type.
*
* @author Oliver Gierke
* @author Eberhard Wolff
*/
@NoRepositoryBean
public interface CrudRepository<T, ID> extends Repository<T, ID> {
/**
* Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
* entity instance completely.
*
* @param entity must not be {@literal null}.
* @return the saved entity will never be {@literal null}.
*/
<S extends T> S save(S entity);
/**
* Saves all given entities.
*
* @param entities must not be {@literal null}.
* @return the saved entities will never be {@literal null}.
* @throws IllegalArgumentException in case the given entity is {@literal null}.
*/
<S extends T> Iterable<S> saveAll(Iterable<S> entities);
/**
* Retrieves an entity by its id.
*
* @param id must not be {@literal null}.
* @return the entity with the given id or {@literal Optional#empty()} if none found
* @throws IllegalArgumentException if {@code id} is {@literal null}.
*/
Optional<T> findById(ID id);
/**
* Returns whether an entity with the given id exists.
*
* @param id must not be {@literal null}.
* @return {@literal true} if an entity with the given id exists, {@literal false} otherwise.
* @throws IllegalArgumentException if {@code id} is {@literal null}.
*/
boolean existsById(ID id);
/**
* Returns all instances of the type.
*
* @return all entities
*/
Iterable<T> findAll();
/**
* Returns all instances of the type with the given IDs.
*
* @param ids
* @return
*/
Iterable<T> findAllById(Iterable<ID> ids);
/**
* Returns the number of entities available.
*
* @return the number of entities
*/
long count();
/**
* Deletes the entity with the given id.
*
* @param id must not be {@literal null}.
* @throws IllegalArgumentException in case the given {@code id} is {@literal null}
*/
void deleteById(ID id);
/**
* Deletes a given entity.
*
* @param entity
* @throws IllegalArgumentException in case the given entity is {@literal null}.
*/
void delete(T entity);
/**
* Deletes the given entities.
*
* @param entities
* @throws IllegalArgumentException in case the given {@link Iterable} is {@literal null}.
*/
void deleteAll(Iterable<? extends T> entities);
/**
* Deletes all entities managed by the repository.
*/
void deleteAll();
}
In the project with build.gradle this is the class
/*
* Copyright 2008-2011 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.data.repository;
import java.io.Serializable;
/**
* Interface for generic CRUD operations on a repository for a specific type.
*
* @author Oliver Gierke
* @author Eberhard Wolff
*/
@NoRepositoryBean
public interface CrudRepository<T, ID extends Serializable> extends Repository<T, ID> {
/**
* Saves a given entity. Use the returned instance for further operations as the save operation might have changed the
* entity instance completely.
*
* @param entity
* @return the saved entity
*/
<S extends T> S save(S entity);
/**
* Saves all given entities.
*
* @param entities
* @return the saved entities
* @throws IllegalArgumentException in case the given entity is {@literal null}.
*/
<S extends T> Iterable<S> save(Iterable<S> entities);
/**
* Retrieves an entity by its id.
*
* @param id must not be {@literal null}.
* @return the entity with the given id or {@literal null} if none found
* @throws IllegalArgumentException if {@code id} is {@literal null}
*/
T findOne(ID id);
/**
* Returns whether an entity with the given id exists.
*
* @param id must not be {@literal null}.
* @return true if an entity with the given id exists, {@literal false} otherwise
* @throws IllegalArgumentException if {@code id} is {@literal null}
*/
boolean exists(ID id);
/**
* Returns all instances of the type.
*
* @return all entities
*/
Iterable<T> findAll();
/**
* Returns all instances of the type with the given IDs.
*
* @param ids
* @return
*/
Iterable<T> findAll(Iterable<ID> ids);
/**
* Returns the number of entities available.
*
* @return the number of entities
*/
long count();
/**
* Deletes the entity with the given id.
*
* @param id must not be {@literal null}.
* @throws IllegalArgumentException in case the given {@code id} is {@literal null}
*/
void delete(ID id);
/**
* Deletes a given entity.
*
* @param entity
* @throws IllegalArgumentException in case the given entity is {@literal null}.
*/
void delete(T entity);
/**
* Deletes the given entities.
*
* @param entities
* @throws IllegalArgumentException in case the given {@link Iterable} is {@literal null}.
*/
void delete(Iterable<? extends T> entities);
/**
* Deletes all entities managed by the repository.
*/
void deleteAll();
}`
They differ in their import and there is a method findOne(Id id) in the project with gradle but its missing in the project with maven. I can't understand what I've done wrong.
A: Gradle and maven have different conflict resolution strategies when there's more than one version of an artifact in the dependency graph
*
*Maven has a "nearest definition wins" strategy where the version which is defined in a transitive pom which is "nearest" to your project wins. In my opinion this is a stupid strategy. You can force a version by explicitly stating the required version in your project's pom.xml since that is "nearest"
*Gradle by default will pick the highest version number. The resolution strategy is fully configurable in Gradle (eg you can force a specific version)
For maven, type
mvn dependency:tree
For gradle type
gradle dependencies
If you compare the results you should see the difference
| {
"language": "en",
"url": "https://stackoverflow.com/questions/50042268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Getting "io.cucumber.junit.UndefinedStepException", while using the same step defination given in trace snippet i have created a cucumber class and trying to modified, while doing so its continously showing the "io.cucumber.junit.UndefinedStepException" again and again when i try to run. I have tried with the steps showing in trace snippet but again the result is same. Here below is the code i am trying
//feature_file
Feature: Application login
Scenario: Home page default login
Given user navigate to login page
When user login into application with "abhishek" and password "abhi234"
Then home page appears
And objects showed are "true"
Scenario: Home page default login
Given user navigate to login page
When user login into application with "Amit" and password "amit345"
Then home page appears
And objects showed are "false"
//stepdefination
public class stepdefination2 {
@Given("^user navigate to login page$")
public void navigate() {
System.out.println("welcome");
throw new io.cucumber.java.PendingException();
}
@When("user login into application with {string} and password {string}")
public void user_login(String arg1, String arg2) {
System.out.println(arg1);
System.out.println(arg2);
throw new io.cucumber.java.PendingException();
}
@Then("^home page appears$")
public void home_page() {
System.out.println("homepage");
throw new io.cucumber.java.PendingException();
}
@Then("objects showed are {string}")
public void objects(String obj) {
System.out.println("objects appeared");
throw new io.cucumber.java.PendingException();
}
}
//Runner
@RunWith(Cucumber.class)
@CucumberOptions(
features = "src/test/java/nfeature",
glue = "stepdefination2"
)
public class TestRun2{
public void success() {
System.out.println("test run successfully");
}
}
A: I think that your @CucumberOptions are not correct and that's why the steps are not found
A: glue = "stepdefination2" here you need to specify package name under which stepdefinations class files are available. Avoid giving same name for package&class file.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/71185312",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python doesn't go automatically to next line when writing to CSV file I am trying to open a source CSV file (source.csv) and decompose it into several CSV files according to first column name. I show it with this example:
Content of source.csv:
2016-11,a
2016-11,b
2016-12,a
2016-12,b
2016-12,c
and I expect the program to create two files with 2016-11.csv and 2016-12.csv names:
expected content of 2016-11.csv:
2016-11,a
2016-11,b
expected content of 2016-12.csv:
2016-12,a
2016-12,b
2016-12,c
I developed this code:
import csv
path1='/home/sourcefilepath/'
path2='/home/targetpath/'
filename='source.csv'
with open(path1+filename) as f:
reader = csv.reader(f)
for row in reader:
date=row[0]
with open(path2+date+'.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
writer.writerow(row)
The problem is it just write the first line of each file and doesn't automatically goes to next line while writing. How can I fix this issue?
A: You're overwriting the previous files with 'w'. Besides opening the file and closing at every iteration is not a very good idea.
Why not read all the rows and group them with itertools.groupby using the first item in each row (i.e. date) as the grouping criterion. Then write into each file after splitting. The file names will be the key for each group.
A: You're overwriting the contents of your file each time you open them with the w flag, try instead by grouping your rows with itertools.groupby:
import csv
import itertools
with open(path1 + filename) as f:
reader = csv.reader(f)
for date, rows in itertools.groupby(reader, lambda row: row[0]):
with open(path2 + date + '.csv', 'w') as csvfile:
writer = csv.writer(csvfile, delimiter=',')
writer.writerows(rows)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40367161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Magento: Add additional info to Invoice PDF I am utilizing M2EPro to sync orders from eBay and Amazon.
I would like to add the Amazon Order ID and Ebay Order ID to my PDF invoices.
I need the data from:
Column amazon_order_id from m2epro_ebay_order
and
Column ebay_order_id from m2epro_amazon_order
Can anyone offer suggestions as to a protected function to add to Abstract.php or any other solution?
A: Thank you for the help! I used:
$order = Mage::getModel('sales/order')->load(entity_id);
$paymentInfo = Mage::helper('payment')->getInfoBlock($order->getPayment())
->setIsSecureMode(true);
$channelOrderId = $paymentInfo->getChannelOrderId();
A: You should create models for the tables (if there aren't any available already)
How to create a model
Then you can simply get an instance of the model
$ebay = Mage::getModel('m2epro/ebay')->load($row_id);
echo $ebay->getData('ebay_order_id');
| {
"language": "en",
"url": "https://stackoverflow.com/questions/13805523",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Drawing STL with OpenGl and Python3 I am trying to port a program from Python2 to Python3. Everything is fine with Python2.
OpenGl returns an error when trying to draw the object. Here is the function:
def draw_facets(self):
glPushMatrix()
# Ligthing, color and Material Stuff
...
### VBO stuff
glBegin(GL_LINES)
# THE ERROR COMES FROM THAT POINT
self.vertex_buffer.bind()
glVertexPointer(3, GL_FLOAT, 0, None)
self.normal_buffer.bind()
glNormalPointer(GL_FLOAT, 0, None)
glEnableClientState(GL_VERTEX_ARRAY)
glEnableClientState(GL_NORMAL_ARRAY)
glDrawArrays(GL_TRIANGLES, 0, len(self.vertices))
glDisableClientState(GL_NORMAL_ARRAY)
glDisableClientState(GL_VERTEX_ARRAY)
self.normal_buffer.unbind()
self.vertex_buffer.unbind()
glEnd()
glPopMatrix()
Python returns this error:
File "../libtatlin/actors.py", line 553, in draw_facets
glVertexPointer(3, GL_FLOAT, 0, None)
File "/usr/local/lib/python3.8/dist-packages/PyOpenGL-3.1.5-py3.8.egg/OpenGL/latebind.py", line 43, in __call__
return self._finalCall( *args, **named )
File "/usr/local/lib/python3.8/dist-packages/PyOpenGL-3.1.5-py3.8.egg/OpenGL/wrapper.py", line 818, in wrapperCall
storeValues(
File "/usr/local/lib/python3.8/dist-packages/PyOpenGL-3.1.5-py3.8.egg/OpenGL/arrays/arrayhelpers.py", line 156, in __call__
contextdata.setValue( self.constant, pyArgs[self.pointerIndex] )
File "/usr/local/lib/python3.8/dist-packages/PyOpenGL-3.1.5-py3.8.egg/OpenGL/contextdata.py", line 58, in setValue
context = getContext( context )
File "/usr/local/lib/python3.8/dist-packages/PyOpenGL-3.1.5-py3.8.egg/OpenGL/contextdata.py", line 40, in getContext
raise error.Error(
OpenGL.error.Error: Attempt to retrieve context when no valid context
Any help is welcome
| {
"language": "en",
"url": "https://stackoverflow.com/questions/66918642",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Controlling compiler directive in file from other file C++ Consider following header file,
// filename : packet_types.h
#ifndef _PACKET_TYPES_
#define _PACKET_TYPES_
struct Packet {
enum Type {
typ_ONE,
typ_TWO,
typ_THREE,
};
static const char * STRINGS[] = {
"ONE",
"TWO",
"THREE"
};
const char * getText( int enum ) {
return STRINGS[enum];
}
};
#endif
As Arduino has limited memory, I don't want to include this portion of code when I include this file, packet_types.h,
static const char * STRINGS[] = {
"ONE",
"TWO",
"THREE"
};
const char * getText( int enum ) {
return STRINGS[enum];
}
But for my GUI application, I want the complete file. I want to use same file for both Arduino and GUI, but how can I add compiler directive #define,#ifdef, #ifndef... to do this job, when I include this file from some other file(main.cpp). Thanks.
A: Although it is possible to use some preprocessor juggling, the right solution is to simply use C++ as it was intended to be used. Only declare these class members and methods in the header file:
static const char * STRINGS[];
const char * getText( int enum );
And then define them in one of the source files:
const char * Packet::STRINGS[] = {
"ONE",
"TWO",
"THREE"
};
const char * Packet::getText( int enum ) {
return STRINGS[enum];
}
With the aforementioned preprocessor juggling, all it ends up accomplishing is the same logical result, but in a more confusing and roundabout way.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/40203472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Facebook API, Phone Numbers I am developing a Facebook Application that I need to get all the information of user, including mobile phone. However, even this page claims https://developers.facebook.com/blog/post/446 that user_mobile_phone permission exists, neither the documentation includes a field of mobile phone number. I am creating a synchronization of contacts, so the phone field is very important.
Why this is blocked? Spamming with mobile is not a very nice spamming approach, it has a cost. They even let e-mails to be given (although you can change it to a cloaking address), but we cannot get phone numbers or addresses.
Is there a way to get it via an app?
EDIT: Even this: http://developers.facebook.com/blog/post/447
A: http://developers.facebook.com/blog/post/2011/01/14/platform-updates--new-user-object-fields--edge-remove-event-and-more/
say:
Update: The user_address and user_mobile_phone permissions have been removed. Please see this post for more info.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/6563786",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: Equal distance between children when using grid and flex I have this sample:
link
.container {
display: grid;
grid-gap: 5px;
grid-template-columns: repeat(4, 1fr);
margin: 0 auto;
}
h6 {
background: red;
}
.pre-el {
background: gray;
display: flex;
justify-content: center;
width: 100%;
}
.pre-el:first-child {
justify-content: flex-start;
}
.pre-el:last-child {
justify-content: flex-end;
}
<div class="container">
<div class="pre-el">
<h6>Title 1</h6>
</div>
<div class="pre-el">
<h6>Title 2</h6>
</div>
<div class="pre-el">
<h6>Title 3</h6>
</div>
<div class="pre-el">
<h6>Title 4</h6>
</div>
</div>
The first column and the last column must have the content on the left and on the right, respectively.
This makes the space between the elements no longer equal.
For example, the distance between "title 1" and "title 2" is not equal to the distance between "title 2" and "title 3".
How can I solve this problem?
Thanks in advance!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/69853380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Python String Method Conundrum The following code is supposed to print MyWords after removing SpamWords[0]. However; instead of returning "yes" it instead returns "None". Why is it returning "None"?
MyWords = "Spam yes"
SpamWords = ["SPAM"]
SpamCheckRange = 0
print ((MyWords.upper()).split()).remove(SpamWords[SpamCheckRange])
A: Because remove is a method that changes the mutable list object it's called on, and returns None.
l= MyWords.upper().split()
l.remove(SpamWords[SpamCheckRange])
# l is ['YES']
Perhaps you want:
>>> [word for word in MyWords.split() if word.upper() not in SpamWords]
['yes']
A: remove is a method of list (str.split returns a list), not str. It mutates the original list (removing what you pass) and returns None, not a modified list.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/2247600",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to use dependency injection with Zend_Soap_AutoDiscover I'm trying to use a dependency injection container for the first time in a project, but I just discovered a problem that I'm not sure how to address.
The project provides a SOAP web service, which is implemented atop the SOAP component of Zend Framework. The way this works is that you define a class that acts as your service, you create a Zend_Soap_AutoDiscover or Zend_Soap_Server class (for the WSDL or the class itself, as appropriate), and finally, you pass ZF the name of the service class via the constructor or via the setClass method. For example:
class MyService {}
$autodiscoveryObj = new Zend_Soap_AutoDiscover();
$autodiscoveryObj->setClass('MyService');
...
The problem is with that last step. My DI container can create a service object and inject into it all the required dependencies. That's fine if I need an instance in my own code. However, b/c you just pass the name of the class into ZF, and you don't get to actually instantiate it yourself, it doesn't get properly instantiated through the container so its dependencies are never injected. Further, I don't think I can use any sort of wrapper class, as ZF uses reflection on the class.
What's the best way to handle this?
A: In Zend_Soap_Server you can attach/set an object like in SoapServer
/**
* Attach an object to a server
*
* Accepts an instanciated object to use when handling requests.
*
* @param object $object
* @return Zend_Soap_Server
*/
public function setObject($object)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/8189966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Connecting to a MySQL Database and do a query using only client side Javascript and HTA In a HTA application, how to connect to a MySQL database using JavaScript ONLY and do a query in it? No VBScript and no third parties like node.js, just JavaScript.
A: A HUGE thanks to Kul-Tigin for providing the answer for the USE of ADO ActiveX which I did not even think about. I was not searching properly the ODBC connection methods and always fell on VBScript. So here is a working code of a personal test I did after installing the latest MySQL ODBC Connector as of the date of this comment.
var hmess = document.getElementById("mess");
var oconn = new ActiveXObject("ADODB.Connection");
var ors = new ActiveXObject("ADODB.Recordset");
var sconn = "";
var scn_driver = "DRIVER=MySQL ODBC 8.0 Unicode Driver;";
var scn_server = "SERVER=localhost;";
var scn_database = "DATABASE=DatabaseName;";
var scn_userid = "USER ID=UserName;";
var scn_password = "PASSWORD=UserPassword;";
var ssql = "SELECT * FROM Table WHERE IDField=1";
sconn = scn_driver + scn_server + scn_database + scn_userid + scn_password;
oconn.Open(sconn);
ors.Open(ssql,oconn);
ors.MoveFirst();
hmess.innerHTML = ors("TableFieldName");
ors.Close();
oconn.Close();
Thank you for the answers and your help.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/62939144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to click and drag an object in pygame? I have created this window that allows the user to create dots in the windows and link them,
What I'm trying to do now is to allow him to move which ever point he wants after finishing drawing them
In my example I allow him to draw five dots, then I want him to move the point of his choice, I really don't know how to do this
This is my code:
import pygame
#Initialise pygame
pygame.init()
#Create the screen
screen = pygame.display.set_mode((1200, 700))
#Change the title and the icon
pygame.display.set_caption('The Thoughtful Minds')
icon = pygame.image.load('IA.png')
pygame.display.set_icon(icon)
#Dots
dot = pygame.image.load('point.png')
class Dot:
def __init__(self, pos):
self.cx, self.cy = pos
def draw(self):
screen.blit(dot,(self.cx-8 , self.cy-8))
def text_objects(text,font):
textSurface = font.render(text, True, (100,100,100))
return textSurface, textSurface.get_rect()
dots = []
#Running the window
i = 0
running = True
while running:
mx, my = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.MOUSEBUTTONDOWN:
for oPosition in dots:
if ((oPosition.cx - 8) < mx < (oPosition.cx + 8)) and ((oPosition.cy - 8) < my < (oPosition.cy + 8)):
'''
What should I put her to allow him to move the dot he clicked on
'''
if i<3:
# append a new dot at the current mouse position
dots.append(Dot((mx,my)))
i += 1
# clear the display
screen.fill((30,30,30))
# draw all the dots
if len(dots)>1:
for i in range(len(dots)-1):
pygame.draw.line(screen, (50, 50, 50), [dots[i].cx,dots[i].cy],[dots[i+1].cx,dots[i+1].cy],2 )
for d in dots:
d.draw()
if mx < 50 and my < 50:
pygame.draw.rect(screen,(24,24,24),(0,0,50,50))
else:
pygame.draw.rect(screen,(20,20,20),(0,0,50,50))
text = pygame.font.Font("freesansbold.ttf",25)
textSurf, textRect = text_objects('–', text)
textRect.center = (25,25)
screen.blit( textSurf, textRect )
if 52 < mx < 102 and my < 50:
pygame.draw.rect(screen,(24,24,24),(52,0,50,50))
else:
pygame.draw.rect(screen,(20,20,20),(52,0,50,50))
textSurf, textRect = text_objects('+', text)
textRect.center = (76,25)
screen.blit( textSurf, textRect )
# update the dispalay
pygame.display.flip()
Thanks.
A: Ok this is the answer if you are interested
import pygame
#Initialise pygame
pygame.init()
#Create the screen
screen = pygame.display.set_mode((1200, 700))
screen.set_alpha(None)
#Change the title and the icon
pygame.display.set_caption('The Thoughtful Minds')
icon = pygame.image.load('IA.png')
pygame.display.set_icon(icon)
#Dots
dot = pygame.image.load('point.png')
class Dot:
def __init__(self, pos):
self.cx, self.cy = pos
def draw(self):
screen.blit(dot,(self.cx-8 , self.cy-8))
def text_objects(text,font):
textSurface = font.render(text, True, (100,100,100))
return textSurface, textSurface.get_rect()
dots = []
#Running the window
i = 0
running = True
draging = False
while running:
mx, my = pygame.mouse.get_pos()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
pass
elif event.type == pygame.MOUSEBUTTONDOWN:
for oPosition in dots:
if ((oPosition.cx - 8) < mx < (oPosition.cx + 8)) and ((oPosition.cy - 8) < my < (oPosition.cy + 8)):
draging = True
break
if i<3:
# append a new dot at the current mouse position
dots.append(Dot((mx,my)))
i += 1
elif event.type == pygame.MOUSEBUTTONUP:
draging = False
elif event.type == pygame.MOUSEMOTION:
if draging :
oPosition.cx = mx
oPosition.cy = my
# clear the display
screen.fill((30,30,30))
# draw all the dots
if len(dots)>1:
for i in range(len(dots)-1):
pygame.draw.line(screen, (50, 50, 50), [dots[i].cx,dots[i].cy],[dots[i+1].cx,dots[i+1].cy],2 )
for d in dots:
d.draw()
if mx < 50 and my < 50:
pygame.draw.rect(screen,(24,24,24),(0,0,50,50))
else:
pygame.draw.rect(screen,(20,20,20),(0,0,50,50))
text = pygame.font.Font("freesansbold.ttf",25)
textSurf, textRect = text_objects('–', text)
textRect.center = (25,25)
screen.blit( textSurf, textRect )
if 52 < mx < 102 and my < 50:
pygame.draw.rect(screen,(24,24,24),(52,0,50,50))
else:
pygame.draw.rect(screen,(20,20,20),(52,0,50,50))
textSurf, textRect = text_objects('+', text)
textRect.center = (76,25)
screen.blit( textSurf, textRect )
# update the dispalay
pygame.display.flip()
A: pygame is low lewel, it does not have any preimplemented method for drag and drop. You have to built it by yourself.
You have to play with the various events types. Here is the idea:
First, create a variable dragged_dot = None outside the main loop. And in the event loop check for the following events:
*
*pygame.MOUSEBUTTONDOWN event tells you when the button is pressed. When you detect this event, check if the mouse is clicking on an existing dot or not. This is what your for loop does. If not, add a new dot like you are already doing. Otherwise, set the dot to be dragged: dragged_dot = oPosition.
*pygame.MOUSEMOTION event tells you when the mouse moves. When you detect this event, check if there is a dragged dot: if dragged_dot is not None. If so, edit it's coordinates adding the mouse motion so that it can be redrawn at a new position (remember to delete the image of the dot at the previous postion). Use event.rel to know the difference between previous mouse position and current mouse position.
*pygame.MOUSEBUTTONUP event tells you when the button is released. Simply set dragged_dot = None, so that the dot is dropped and will not follow the mouse motion anymore.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/59008485",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Mule ESB - does the lib override any application library I have used Mule Studio 3.2.1 to develop a Mule application. Within that application I have used org.springframework.ws.client.core.WebServiceTemplate to send a Webservice request to another application.
I have used the following config
<bean id="myWsTemplate" clsass="org.springframework.ws.client.core.WebServiceTemplate">
<constructor-arg ref="messageFactory" />
<property name="defaultUri" value="${my.soap.endpoint}" />
<property name="interceptors">
<list>
<ref bean="acqSecurityInterceptor" />
</list>
</property>
<bean id="acqSecurityInterceptor" class="org.springframework.ws.soap.security.wss4j.Wss4jSecurityInterceptor">
<property name="validationActions" value="NoSecurity"/>
<property name="securementActions" value="NoSecurity" />
</bean>
I have used Maven dependency of
<dependency>
<groupId>org.springframework.ws</groupId>
<artifactId>spring-ws-security</artifactId>
<version>2.1.0.RELEASE</version>
</dependency>
This uses wss4j-1.6.5.jar as a dependency.
Now when I deploy the application in Mule 3.2.0 it throws the following error
PropertyAccessException 1: org.springframework.beans.MethodInvocationException: Property 'validationActions' threw exception; nested exception is java.lang.NoSuchMethodError: org.apache.ws.security.util.WSSecurityUtil.decodeAction(Ljava/lang/String;Ljava/util/List;)I
PropertyAccessException 2: org.springframework.beans.MethodInvocationException: Property 'securementActions' threw exception; nested exception is java.lang.NoSuchMethodError: org.apache.ws.security.util.WSSecurityUtil.decodeAction(Ljava/lang/String;Ljava/util/List;)I
Now the lib/opt directory of Mule 3.2.0 comes with wss4j-1.5.8-osgi.jar for which the the method signature on WSSecurityutil is public static int decodeAction(String action, Vector actions)
while the one that has been attempted is
decodeAction(Ljava/lang/String;Ljava/util/List;) which is present in wss4j.1.6.5
My question is even if my app has the wss4j-1.6.5.jar in it why is the classloader still trying to use the one in mule/lib/opt. Should the one in the app not override of take precedence?
If not is there a way to get it work that way
A: ok using the following config in mule-deploy.properties helped
loader.override=-org.apache.ws.security.util.WSSecurityUtil
ref
http://www.mulesoft.org/documentation/display/MULE3USER/Classloader+Control+in+Mule
but still loads of issues with jars coming built in Mule Studio as plugins and then trying to deploy in standalone Mule. Will create an assorted list of such issues in another thread.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/11672371",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Transport-level vs message-level security I'm reading a book on WCF and author debates about pros of using message-level security over using transport-level security. Anyways, I can't find any logic in author's arguments
One limitation of transport
security is that it relies on every
“step” and participant in the network
path having consistently configured
security. In other words, if a message
must travel through an intermediary
before reaching its destination, there
is no way to ensure that transport
security has been enabled for the step
after the intermediary (unless that
interme- diary is fully controlled by
the original service provider). If
that security is not faithfully
reproduced, the data may be
compromised downstream.
Message security focuses on ensuring the integrity and privacy of
individ- ual messages, without regard
for the network. Through mechanisms
such as encryption and signing via
public and private keys, the message
will be protected even if sent over an
unprotected transport (such as plain
HTTP).
a)
If that security is not faithfully
reproduced, the data may be
compromised downstream.
True, but assuming two systems communicating use SSL and thus certificates, then the data they exchange can't be decrypted by intermediary, but instead it can only be altered, which the receiver will notice and thus reject the packet?!
b) Anyways, as far as I understand the above quote, it is implying that if two systems establish a SSL connection, and if intermediary system S has SSL enabled and if S is also owned by a hacker, then S ( aka hacker ) won't be able to intercept SSL traffic travelling through it? But if S doesn't have SSL enabled, then hacker will be able to intercept SSL traffic? That doesn't make sense!
c)
Message security focuses on ensuring the integrity and privacy of individ-
ual messages, without regard for the network. Through mechanisms such
as encryption and signing via public and private keys, the message will be
protected even if sent over an unprotected transport (such as plain HTTP).
This doesn't make sense, since transport-level security also can use encryption and certificates, so why would using private/public keys at message-level be more secure than using them at transport-level? Namelly, if intermediary is able to intercept SSL traffic, why wouldn't it also be able to intercept messages secured via message-level private/public keys?
thank you
A: I think I see what he's getting at. Say like this:
Web client ---> Presentation web server ---> web service call to database
In this case you're depending on the middle server encrypting the data again before it gets to the database. If the message was encrypted instead, only the back end would know how to read it, so the middle doesn't matter.
A: Consider the case of SSL interception.
Generally, if you have an SSL encrypted connection to a server, you can trust that you "really are* connected to that server, and that the server's owners have identified themselves unambiguously to a mutually trusted third party, like Verisign, Entrust, or Thawte (by presenting credentials identifying their name, address, contact information, ability to do business, etc., and receiving a certificate countersigned by the third party's signature). Using SSL, this certificate is an assurance to the end user that traffic between the user's browser (client) and the server's SSL endpoint (which may not be the server itself, but some switch, router, or load-balancer where the SSL certificate is installed) is secure. Anyone intercepting that traffic gets gobbledygook and if they tamper with it in any way, then the traffic is rejected by the server.
But SSL interception is becoming common in many companies. With SSL interception, you "ask" for an HTTPS connection to (for example) www.google.com, the company's switch/router/proxy hands you a valid certificate naming www.google.com as the endpoint (so your browser doesn't complain about a name mismatch), but instead of being countersigned by a mutually trusted third party, it is countersigned by their own certificate authority (operating somewhere in the company), which also happens to be trusted by your browser (since it's in your trusted root CA list which the company has control over).
The company's proxy then establishes a separate SSL-encrypted connection to your target site (in this example, www.google.com), but the proxy/switch/router in the middle is now capable of logging all of your traffic.
You still see a lock icon in your browser, since the traffic is encrypted up to your company's inner SSL endpoint using their own certificate, and the traffic is re-encrypted from that endpoint to your final destination using the destination's SSL certificate, but the man in the middle (the proxy/router/switch) can now log, redirect, or even tamper with all of your traffic.
Message-level encryption would guarantee that the message remains encrypted, even during these intermediate "hops" where the traffic itself is decrypted.
Load-balancing is another good example, because the SSL certificate is generally installed on the load balancer, which represents the SSL endpoint. The load balancer is then responsible for deciding which physical machine to send the now-decrypted traffic to for processing. Your messages may go through several "hops" like this before it finally reaches the service endpoint that can understand and process the message.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/4270883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Trouble making an executable jar with lwjgl When I try to make an executable jar in NetBeans I get this error:
C:\lwjgl\lwjgl-2.8.5\res is a directory or can't be read. Not copying the libraries.
The res folder holds files like jpgs and wavs that the program relies on to function. I'm using lwjgl, would that be part of the problem? What could be causing this?
A: If you're trying to run from a .jar file and it's giving you this issue but not from the IDE, you should just be able to open the jar file with winrar or another similar program and just copy/paste the whole res directory into the jar file.
You then use the following code to retrieve your file in the program (instead of where you're retrieving from "C:\lwjgl\lwjgl-2.8.5\res":
ResourceLoader.getResource(stringLocationToResource);
This will return the resource that you were trying to get.
The file has to be next to your src file, and not in it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/16219056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a nodejs equivalent to PHP's mail() function I come from the world of PHP and I'm accustomed to using mail() to send quick diagnostic emails on occasion.
Is there a module or method in the standar library of NodeJS that's roughly the equivalent of this?
A: Sure:
const nodemailer = require('nodemailer');
const transporter = nodemailer.createTransport({sendmail: true}, {
from: '[email protected]',
to: '[email protected]',
subject: 'test',
});
transporter.sendMail({text: 'hello'});
Also see Configure sendmail inside a docker container
A: Nodemailer is a popular, stable, and flexible solution:
*
*http://www.nodemailer.com/
*https://github.com/andris9/Nodemailer
Full usage looks something like this (the top bit is just setup - so you would only have to do that once per app):
var nodemailer = require("nodemailer");
// create reusable transport method (opens pool of SMTP connections)
var smtpTransport = nodemailer.createTransport("SMTP",{
service: "Gmail",
auth: {
user: "[email protected]",
pass: "userpass"
}
});
// setup e-mail data with unicode symbols
var mailOptions = {
from: "Fred Foo ✔ <[email protected]>", // sender address
to: "[email protected], [email protected]", // list of receivers
subject: "Hello ✔", // Subject line
text: "Hello world ✔", // plaintext body
html: "<b>Hello world ✔</b>" // html body
}
// send mail with defined transport object
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
// if you don't want to use this transport object anymore, uncomment following line
//smtpTransport.close(); // shut down the connection pool, no more messages
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/14678447",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: Text bubble only two characters wide - JSQmessagesviewcontroller Text bubble only allow 2character then create a new line break for the next 2 characters. this will happen randomly. I did not make any adjustments to the bubble characters it just appears like that. Thank you in advance for the help
import UIKit
import JSQMessagesViewController
import MobileCoreServices
import AVKit
import Firebase
import Braintree
class messagesViewController: JSQMessagesViewController {
//braintree info
var braintreeClient: BTAPIClient?
var clientToken = String()
var formInfo = [String: AnyObject]()
// this is the id of the post id number
var previousViewMessageId:String!
)
var messages = [JSQMessage]()
//ref to retrieve message
var messageRef:FIRDatabaseReference! //
override func viewDidLoad() {
super.viewDidLoad()
//braintreeSetup()
navBar()
// tappedMyPayButton()
self.messageRef = fireBaseAPI().childRef("version_one/frontEnd/post/\(previousViewMessageId)")
let currentUser = fireBaseAPI().currentUserId()
self.senderId = currentUser
self.senderDisplayName = ""
let ref = fireBaseAPI().ref()
let messagRef = ref.child("version_one/frontEnd/post/\(previousViewMessageId)messages")
// messagRef.childByAutoId().setValue("first Message")
messagRef.observeEventType(.ChildAdded, withBlock: {snapshot in
//if let dict = snapshot.value as? String {
//}
})
observerveMessages()
}
}
extension messagesViewController {
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.messages.count
}
override func collectionView(collectionView: JSQMessagesCollectionView!, messageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageData! {
let data = self.messages[indexPath.row]
return data
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = super.collectionView(collectionView, cellForItemAtIndexPath: indexPath) as! JSQMessagesCollectionViewCell
return cell
}
override func collectionView(collectionView: JSQMessagesCollectionView!, didDeleteMessageAtIndexPath indexPath: NSIndexPath!) {
self.messages.removeAtIndex(indexPath.row)
}
override func collectionView(collectionView: JSQMessagesCollectionView!, messageBubbleImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageBubbleImageDataSource! {
let bubbleFactory = JSQMessagesBubbleImageFactory()
let message = messages[indexPath.item]
if message.senderId == self.senderId {
return bubbleFactory.outgoingMessagesBubbleImageWithColor(UIColor(r: 43, g: 216, b: 225))
}else{
return bubbleFactory.incomingMessagesBubbleImageWithColor(UIColor(r: 125, g: 125, b: 125))
}
}
override func collectionView(collectionView: JSQMessagesCollectionView!, avatarImageDataForItemAtIndexPath indexPath: NSIndexPath!) -> JSQMessageAvatarImageDataSource! {
return nil
}
}
//MARK - image
extension messagesViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
override func didPressSendButton(button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: NSDate!) {
let newMessage = messageRef.child("messages")
let messageData = ["text":text,"senderId":senderId,"senderDisplayName":senderDisplayName, "mediaType":"TEXT"]
newMessage.childByAutoId().setValue(messageData)
self.finishSendingMessage()
}
func observerveMessages(){
let obRef = fireBaseAPI().childRef("version_one/frontEnd/post/\(previousViewMessageId)/messages")
obRef.observeEventType(.ChildAdded, withBlock: {snapshot in
//
if let dict = snapshot.value as? [String:AnyObject]{
let mediaType = dict["mediaType"] as! String
let senderId = dict["senderId"] as! String
let senderName = dict["senderDisplayName"] as! String
switch mediaType {
case "TEXT":
let text = dict["text"] as? String
self.messages.append(JSQMessage(senderId: senderId, displayName: senderName, text: text))
case "PHOTO":
let fileUrl = dict["fileUrl"] as! String
let url = NSURL(string: fileUrl)
let data = NSData(contentsOfURL: url!)
let picture = UIImage(data: data!)
let photo = JSQPhotoMediaItem(image: picture!)
self.messages.append(JSQMessage(senderId: senderId,displayName: senderName, media: photo))
if self.senderId == senderId {
photo.appliesMediaViewMaskAsOutgoing = true
}else{
photo.appliesMediaViewMaskAsOutgoing = false
}
case "VIDEO":
let fileUrl = dict["fileUrl"] as! String
let video = NSURL(string: fileUrl)
let videoItem = JSQVideoMediaItem(fileURL: video, isReadyToPlay: true)
self.messages.append(JSQMessage(senderId: senderId,displayName:senderName,media: videoItem))
if self.senderId == senderId {
videoItem.appliesMediaViewMaskAsOutgoing = true
}else{
videoItem.appliesMediaViewMaskAsOutgoing = false
}
default :
print("Unknown data")
}
self.collectionView.reloadData()
}
})
}
override func didPressAccessoryButton(sender: UIButton!) {
let sheet = UIAlertController(title: "Media Messages", message: "Please select an images", preferredStyle: .ActionSheet)
let cancel = UIAlertAction(title: "Cancel", style: .Cancel) { (alert) in
}
let photoLibrary = UIAlertAction(title: "Photo Library", style: .Default) { (alert) in
self.getMediafrom(kUTTypeImage)
}
let VideoLibrary = UIAlertAction(title: "Video Library", style: .Default) { (alert) in
self.getMediafrom(kUTTypeMovie)
}
sheet.addAction(photoLibrary)
sheet.addAction(VideoLibrary)
sheet.addAction(cancel)
self.presentViewController(sheet, animated: true, completion: nil)
// let imagePicker = UIImagePickerController()
// imagePicker.delegate = self
// self.presentViewController(imagePicker, animated: true, completion: nil)
//
}
func getMediafrom(type:CFString){
let mediaPicker = UIImagePickerController()
mediaPicker.delegate = self
mediaPicker.mediaTypes = [type as String]
self.presentViewController(mediaPicker, animated: true, completion: nil)
}
// Display video message
override func collectionView(collectionView: JSQMessagesCollectionView!, didTapMessageBubbleAtIndexPath indexPath: NSIndexPath!) {
let message = messages[indexPath.item]
if message.isMediaMessage {
if let mediaItem = message.media as? JSQVideoMediaItem{
let player = AVPlayer(URL: mediaItem.fileURL)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.presentViewController(playerViewController, animated: true, completion: nil)
}
}
}
func sendMedia(picture:UIImage?,video: NSURL?){
let filePath = "frontEnd/users/\(fireBaseAPI().currentUserId()!)/images/\(NSDate.timeIntervalSinceReferenceDate())/"
if let picture = picture{
let data = UIImageJPEGRepresentation(picture, 0.1)
let metaData = FIRStorageMetadata()
metaData.contentType = "image/jpg"
FIRStorage.storage().reference().child(filePath).putData(data!, metadata: metaData) { (metaData, error) in
if error != nil {
print(error)
return
}
let fileUrl = metaData?.downloadURLs![0].absoluteString
let newMessage = self.messageRef.child("messages")
let messageData = ["fileUrl":fileUrl,"senderId":self.senderId,"senderDisplayName":self.senderDisplayName, "mediaType":"PHOTO"]
newMessage.childByAutoId().setValue(messageData)
}
}else if let video = video{
let data = NSData(contentsOfURL: video)
let metaData = FIRStorageMetadata()
metaData.contentType = "video/mp4"
FIRStorage.storage().reference().child(filePath).putData(data!, metadata: metaData) { (metaData, error) in
if error != nil {
print(error)
return
}
let fileUrl = metaData?.downloadURLs![0].absoluteString
let newMessage = self.messageRef.child("messages")
let messageData = ["fileUrl":fileUrl,"senderId":self.senderId,"senderDisplayName":self.senderDisplayName, "mediaType":"VIDEO"]
newMessage.childByAutoId().setValue(messageData)
}
}
}
//photothe
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
if let picture = info[UIImagePickerControllerOriginalImage] as? UIImage{
// let photo = JSQPhotoMediaItem(image: picture)
//// messages.append(JSQMessage(senderId: senderId,displayName: senderDisplayName,media: photo))
sendMedia(picture,video:nil)
}else if let video = info[UIImagePickerControllerMediaURL] as? NSURL {
// let videoItem = JSQVideoMediaItem(fileURL: video, isReadyToPlay: true)
// messages.append(JSQMessage(senderId: senderId,displayName:senderDisplayName,media: videoItem))
sendMedia(nil, video: video)
}
self.dismissViewControllerAnimated(true, completion: nil)
collectionView.reloadData()
}
}
extension messagesViewController{
func dismissVc(){
self.dismissViewControllerAnimated(true, completion: nil)
}
//button setup
}
// button Actions
| {
"language": "en",
"url": "https://stackoverflow.com/questions/39418260",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What value is in the variable myletter after the above code executes? According to the ASCII table for the char variable 'e' it seems that corresponds to 65. The code goes like this
char myletter = 'e';
myletter++;
I know that you add 1 to the variable myletter by the post increment. I assuming is 66 but it is not. Can someone tell me the real value? I know,Im in the right track.
Thanks
A:
According to the ASCII table for the char variable 'e' it seems that corresponds to 65.
Lowercase 'e' is 65 HEX. In decimal that would be 101. When you increment it, you get 66 HEX, or 102 decimal.
A: Adding to dasblinkenlights's answer...The byte code will give you a clear idea of what is happening behind the scenes :
public static void main(java.lang.String...);
descriptor: ([Ljava/lang/String;)V
flags: ACC_PUBLIC, ACC_STATIC, ACC_VARARGS
Code:
stack=2, locals=2, args_size=1
0: bipush 101 // push decimal value of 'e'
2: istore_1
3: iload_1
4: iconst_1
5: iadd // add 1 to 101 ==> 102
6: i2c // convert 102 to char ==> f
7: istore_1 // store it in the var myLetter
8: return
| {
"language": "en",
"url": "https://stackoverflow.com/questions/28624313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Correctly awaiting in F# an async C# method with return type of Task I'd like to be able to consume a C# library from F#. Mostly this has been pretty straightforward. However, if I try to call a function that returns a Task<T> I am not able to get the returned value.
So, I have C# method with the following definition:
public async Task<TEvent> ReadEventAsync<TEvent>(string streamName, int position) where TEvent: class
And I am trying to consume this method from F# as follows:
let readEventFromEventStore<'a when 'a : not struct> (eventStore:IEventStoreRepository) (streamName:string) (position:int) =
async {
return eventStore.ReadEventAsync(streamName, position)
|> Async.AwaitTask
}
I partially apply this function with an instance of an IEventStoreRepository and the stream name I wish to retrieve the event from:
let readEvent = readEventFromEventStore eventStore streamName
Then, finally, I apply the remaining parameter:
let event = readEvent StreamPosition.Start
When I get the value of event it is a FSharpAsync<object> rather than the T from the Task<T> that I had expected.
What is the correct method in F# of calling an async method written in C# with a return type of Task<T> and accessing the value of T?
A: First of all, in your use case, there's no need for the async { } block. Async.AwaitTask returns an Async<'T>, so your async { } block is just unwrapping the Async object that you get and immediately re-wrapping it.
Now that we've gotten rid of the unnecessary async block, let's look at the type you've gotten, and the type you wanted to get. You got an Async<'a>, and you want an object of type 'a. Looking through the available Async functions, the one that has a type signature like Async<'a> -> 'a is Async.RunSynchronously. It takes two optional parameters, an int and a CancellationToken, but if you leave those out, you've got the function signature you're looking for. And sure enough, once you look at the docs it turns out that Async.RunSynchronously is the F# equivalent of C#'s await, which is what you want. sort of (but not exactly) like C#'s await. C#'s await is a statement you can use inside an async function, whereas F#'s Async.RunSynchronously takes an async object blocks the current thread until that async object has finished running. Which is precisely what you're looking for in this case.
let readEventFromEventStore<'a when 'a : not struct> (eventStore:IEventStoreRepository) (streamName:string) (position:int) =
eventStore.ReadEventAsync(streamName, position)
|> Async.AwaitTask
|> Async.RunSynchronously
That should get you what you're looking for. And note that technique of figuring out the function signature of the function you need, then looking for a function with that signature. It'll help a LOT in the future.
Update: Thank you Tarmil for pointing out my mistake in the comments: Async.RunSynchronously is not equivalent to C#'s await. It's pretty similar, but there are some important subtleties to be aware of since RunSynchronously blocks the current thread. (You don't want to call it in your GUI thread.)
Update 2: When you want to await an async result without blocking the current thread, it's usually part of a pattern that goes like this:
*
*Call some async operation
*Wait for its result
*Do something with that result
The best way to write that pattern is as follows:
let equivalentOfAwait () =
async {
let! result = someAsyncOperation()
doSomethingWith result
}
The above assumes that doSomethingWith returns unit, because you're calling it for its side effects. If instead it returns a value, you'd do:
let equivalentOfAwait () =
async {
let! result = someAsyncOperation()
let value = someCalculationWith result
return value
}
Or, of course:
let equivalentOfAwait () =
async {
let! result = someAsyncOperation()
return (someCalculationWith result)
}
That assumes that someCalculationWith is NOT an async operation. If instead you need to chain together two async operations, where the second one uses the first one's result -- or even three or four async operations in a sequence of some kind -- then it would look like this:
let equivalentOfAwait () =
async {
let! result1 = someAsyncOperation()
let! result2 = nextOperationWith result1
let! result3 = penultimateOperationWith result2
let! finalResult = finalOperationWith result3
return finalResult
}
Except that let! followed by return is exactly equivalent to return!, so that would be better written as:
let equivalentOfAwait () =
async {
let! result1 = someAsyncOperation()
let! result2 = nextOperationWith result1
let! result3 = penultimateOperationWith result2
return! (finalOperationWith result3)
}
All of these functions will produce an Async<'T>, where 'T will be the return type of the final function in the async block. To actually run those async blocks, you'd either do Async.RunSynchronously as already mentioned, or you could use one of the various Async.Start functions (Start, StartImmediate, StartAsTask, StartWithContinuations, and so on). The Async.StartImmediate example talks a little bit about the Async.SwitchToContext function as well, which may be something you'll want to read about. But I'm not familiar enough with SynchronizationContexts to tell you more than that.
A: An alternative to using the async computation expression for this situation (F# calling C# Task-based XxxAsync method) is to use the task computation expression from:
https://github.com/rspeele/TaskBuilder.fs
The Giraffe F# web framework uses task for more or less the same reason:
https://github.com/giraffe-fsharp/Giraffe/blob/develop/DOCUMENTATION.md#tasks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/41743602",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "22"
} |
Q: Azure Function sometimes can't access Azure SQL DB I have an Azure Function which writes to an Azure SQL DB. Sometimes it works, other times I get an error...
Cannot open server 'removed' requested by the login. Client with IP address 'removed' is not allowed to access the server. To enable access, use the Windows Azure Management Portal or run sp_set_firewall_rule on the master database to create a firewall rule for this IP address or address range. It may take up to five minutes for this change to take effect.
The function is running on a consumption plan and connects to SQL with managed identity. From what I understand the IP address won't stay the same and seemingly this is likely what it happening as sometimes it can connect and other times it can't.
Any ideas on how to make it always connect?
A: My issue turned out to be that the DB had been created with a firewall rule for 1 IP named Azure. This was somehow set to the IP address the function app was sometimes using. No idea how this got setup.
The DB firewall rules have a switch to allow Azure resources to connect. No need for v-net and premium plans, unless you want it more secure.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/67088581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to pass variable to named function with angular $on? I have created the following listener:
scope.$on('location', updateMap)
This worked great, but now updateMap needs to take a variable:
function updateMap(request){
...
}
I need to pass the variable request:
var request = {
origin: origin,
destination: new_destination,
travelMode: google.maps.DirectionsTravelMode[attrs.type],
};
How do I pass the variable request to the named function?
A: It's the job of the broadcast/emit event to send arguments to the listeners, so:
scope.$broadcast('location', request);
scope.$emit('location', request);
Or if you want to call updateMap with a parameter you just need to call it within the listener function:
scope.$on('location', function() {
updateMap(request);
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/22864190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits