This is the code I used.
*** client ***
import { React } from "react";
function App() {
return (
<div className="App">
rtsp-streaming
<img src="http://localhost:8086/rtsp_streaming" alt="" />
</div>
);
}
*** server ***
main.py
from urllib import request
from flask import Flask, Response
from rtsp import RTSP_CONNECT
app = Flask(__name__)
def gen(rtsp):
while True:
frame = rtsp.get_frame()
yield (b'--frame\r\n'
b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n\r\n')
#app.route('/rtsp_streaming')
def video_feed():
rtsp_url = "req"
return Response(gen(RTSP_CONNECT(rtsp_url=rtsp_url)),
mimetype='multipart/x-mixed-replace; boundary=frame')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8086, threaded=True, use_reloader=True)
rtsp.py
import cv2
class RTSP_CONNECT(object):
def __init__(self, rtsp_url):
self.video = cv2.VideoCapture("rtsp://xxxx:xxxx#rtsp_url:rtsp_port/cam/realmonitor?channel=2/subtype=0")
self.video.set(cv2.CAP_PROP_BUFFERSIZE,2)
self.FPS = 1/30
self.FPS_MS = int(self.FPS * 1000)
def __del__(self):
self.video.release()
def get_frame(self):
ret, frame = self.video.read()
ret, jpeg = cv2.imencode('.jpg', frame)
return jpeg.tobytes()
the problem that occurred
It doesn't stop while it's running and goes up constantly.
Also, it actually crashes with a memory leak if left unattended for a long time.
Related
here is my code
It is form my old discord.py bot
I want change it to Py-cord
from core.classes import Core
from discord.ext import commands
import discord
from datetime import timedelta
import time
import json
antispam = {}
class Antispam:
def __init__(self):
self.last_msg_time = time.time()
class antispam(Core):
#commands.Cog.listener()
async def on_message(self, message):
with open(f"./GJ/{str(message.guild.id)}.json", "r", encoding="utf8")as jfile:
gdata = json.load(jfile)
if gdata["antispan"] == "off":
pass
elif gdata["antispan"] == "on":
username = message.author
user = str(message.author)
try:
spam = antispam[user]
if time.time()-spam.last_msg_time <= 1 and user != "Our AfterLife 我們的來世#9472":
timeouttime = timedelta(minutes=3, seconds=30)
await message.author.timeout(timeouttime, reason="洗頻")
embed = discord.Embed(
title="", description=f"{user}因為洗頻被伺服器禁言", color=0x005cb3)
if gdata["antispan-ch"] == "none":
if gdata["antispan-m"] == "msg":
await message.channel.send(f"{user}因為洗頻被伺服器禁言")
elif gdata["antispan-m"] == "embed":
await message.channel.send(embed=embed)
elif gdata["antispan-m"] == "embed+msg":
await message.channel.send(f"{user}因為洗頻被伺服器禁言", embed=embed)
else:
try:
channel = self.bot.get_channel(int(gdata["antispan-ch"]))
if gdata["antispan-m"] == "msg":
await channel.send(f"{user}因為洗頻被伺服器禁言")
elif gdata["antispan-m"] == "embed":
await channel.send(embed=embed)
elif gdata["antispan-m"] == "embed+msg":
await channel.send(f"{user}因為洗頻被伺服器禁言", embed=embed)
except:
pass
except:
spam = antispam[user] = Antispam()
spam.last_msg_time = time.time()
def setup(bot):
bot.add_cog(antispam(bot))
I tried it 20 times,but it still not work.
I hope it can work because I making a discord public bot now.
I am writing some scriptrunner listener code in Jira to be triggered when an issue of type impediment is updated and here is my code:
import com.atlassian.event.Event
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.ofbiz.core.entity.GenericValue;
import org.ofbiz.core.entity.GenericEntity;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.event.issue.AbstractIssueEventListener;
import com.atlassian.jira.event.issue.IssueEvent;
import com.atlassian.jira.issue.ModifiedValue;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder;
import com.atlassian.jira.issue.util.IssueChangeHolder;
import org.apache.log4j.Logger
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.component.ComponentAccessor
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.ofbiz.core.entity.GenericValue;
def log = Logger.getLogger("atlassian-jira.log")
log.warn("Start Auto Defaults Listener");
log.warn("IssueMounaEvent = " + event);
Issue issue = event.getIssue();
log.warn("IssueMouna = " + issue);
if (issue.getIssueType().getName().equalsIgnoreCase("Impediment"))
{
log.warn("Analyzing IMPEDIMENT changelog Mouna ...");
event2= (IssueEvent) event;
def warning = analyzeImpedimentChangeLog(event2);
}
def analyzeImpedimentChangeLog(IssueEvent event) {
def warning = "";
log.warn("IMPEDIMENT STATUS ")
List<GenericValue> changeItems = null;
def impedimentStatus = event.getIssue().getStatus().getName();
log.warn("IMPEDIMENT STATUS "+impedimentStatus)
if (!"New".equalsIgnoreCase(impedimentStatus) && !"Inspecting".equalsIgnoreCase(impedimentStatus)) {
GenericValue changeLog = event.getChangeLog();
log.warn("HERE 1")
HashMap<String, Object> fields = new HashMap<String,Object>();
log.warn("HERE 2")
fields.put("group", changeLog.get("id"));
log.warn("HERE 3")
String author = changeLog.getString("author");
log.warn("HERE 4")
try{
log.warn("CHANGE LOG: "+changeLog.internalDelegator)
changeItems = changeLog.internalDelegator.findByAnd("ChangeItem", fields);
log.warn("HERE 5")
}catch(Exception e){
log.warn("EXCEPTIONMOUNA "+e)
}
}
return warning;
}
I receive the following error, which is kind of weird because this was previously implemented in Java and it worked fine:
2022-08-11 EXCEPTIONMOUNA java.lang.IllegalArgumentException: [GenericEntity.get] "internalDelegator" is not a field of ChangeGroup
I would like to execute the following line of code:
changeItems = changeLog.internalDelegator.findByAnd("ChangeItem", fields);
and I receive the exception above when writing the following line of code into the log:
log.warn("CHANGE LOG: "+changeLog.internalDelegator)
This code was previously implemented as a Java plugin and it worked fine in this way. What needs to be done in this case in order to adapt this statement to groovy in ScriptRunner?
I found a way to access the log, this one:
import com.atlassian.event.Event
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.ofbiz.core.entity.GenericValue;
import org.ofbiz.core.entity.GenericEntity;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.event.issue.AbstractIssueEventListener;
import com.atlassian.jira.event.issue.IssueEvent;
import com.atlassian.jira.issue.ModifiedValue;
import com.atlassian.jira.issue.MutableIssue;
import com.atlassian.jira.issue.fields.CustomField;
import com.atlassian.jira.issue.util.DefaultIssueChangeHolder;
import com.atlassian.jira.issue.util.IssueChangeHolder;
import org.apache.log4j.Logger
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.component.ComponentAccessor
import java.util.HashMap;
import java.util.List;
import org.apache.log4j.Logger;
import org.ofbiz.core.entity.GenericValue;
import org.ofbiz.core.entity.GenericDelegator;
import com.atlassian.jira.issue.changehistory.ChangeHistoryManager;
import com.atlassian.jira.issue.history.ChangeItemBean;
import com.atlassian.jira.component.ComponentAccessor;
import com.atlassian.jira.issue.Issue;
import com.atlassian.jira.issue.comments.Comment
import com.atlassian.jira.workflow.JiraWorkflow
import com.atlassian.jira.workflow.WorkflowManager
import org.apache.log4j.Logger
import com.atlassian.jira.component.ComponentAccessor
import com.atlassian.jira.issue.changehistory.ChangeHistoryItem
def log = Logger.getLogger("atlassian-jira.log")
log.warn("Start Auto Defaults Listener");
log.warn("IssueMounaEvent = " + event);
Issue issue = event.getIssue();
log.warn("IssueMouna = " + issue);
if (issue.getIssueType().getName().equalsIgnoreCase("Impediment"))
{
log.warn("Analyzing IMPEDIMENT changelog Mouna ...");
event2= (IssueEvent) event;
def warning = analyzeImpedimentChangeLog(event2);
if (!warning.isEmpty()) {
log.warn("Set IMPEDIMENT warning tooo Mouna " + warning);
setWarning(issue, warning);
}
else {
log.warn("No IMPEDIMENT warning");
}
}
def analyzeImpedimentChangeLog(IssueEvent event) {
String warning = "";
log.warn("IMPEDIMENT STATUS ")
//List<GenericValue> changeItems = null;
def impedimentStatus = event.getIssue().getStatus().getName();
// status New and Inspecting are out of scope
log.warn("IMPEDIMENT STATUS "+impedimentStatus)
if (!"New".equalsIgnoreCase(impedimentStatus) && !"Inspecting".equalsIgnoreCase(impedimentStatus)) {
GenericValue changeLog = event.getChangeLog();
log.warn("HERE 1")
HashMap<String, Object> fields = new HashMap<String,Object>();
log.warn("HERE 2")
fields.put("group", changeLog.get("id"));
log.warn("HERE 3")
String author = changeLog.getString("author");
log.warn("HERE 4")
//changeItems = changeLog.internalDelegator.findByAnd("ChangeItem", fields);
log.warn("CHANGE LOG: "+changeLog.get("issue"))
List<GenericValue> changeItems = ComponentAccessor.getChangeHistoryManager().getAllChangeItems(issue)
// changeItems = changeLog.internalDelegator.findByAnd("ChangeItem", fields);
//changeItems = changeLog
log.warn("HERE 5::: "+ changeItems)
log.warn("MOUNA IS HERE AFTER HERE 5 " +changeItems.size());
log.warn("VALUES 1");
int lastIndex= changeItems.size()-1;
log.warn("MOUNA IS HERE AFTER HERE 5 " +changeItems.size()+ " "+changeItems.get(lastIndex));
ChangeHistoryItem value= changeItems.get(lastIndex) as ChangeHistoryItem;
log.warn("GENERIC VALUE "+ value.getField());
String modifiedField=value.getField();
if(modifiedField.equals("Source Type") ||modifiedField.equals("Class")||
modifiedField.equals("Planning Required")){
log.warn("MOUNA SIZE");
def ChangeHistoryManager= ComponentAccessor.getChangeHistoryManager();
List<ChangeItemBean> fieldchangeItems = ChangeHistoryManager.getChangeItemsForField(issue, modifiedField)
if (fieldchangeItems.size()>0) {
log.warn("MOUNA FIRST "+ modifiedField);
//String content = transientVars['Source Type'] as String
def customFieldManager = ComponentAccessor.getCustomFieldManager()
def newStringCf = customFieldManager.getCustomFieldObjectByName(modifiedField)
String newString = issue.getCustomFieldValue(newStringCf) as String
log.warn("MOUNA FIRST "+ newString);
//def val=cfValues['Source Type']?.value
//log.warn(sourceType+" MOUNA FIRST "+sourceTypechangeItems.get(sourceTypechangeItems.size()-1).getFromString());
String oldString = fieldchangeItems.get(fieldchangeItems.size()-1).getFromString();
warning = "Field \"" + modifiedField + "\" has been changed from \"" + oldString + "\" to \"" + newString + "\" by \"" + author + "\"";
log.warn("MOUNA FIRST "+warning);
}
}
changeItems.eachWithIndex { item, index ->
log.warn("ITEM MOUNA "+item);
}
}
log.warn("changeitemlog== "+warning);
return warning;
}
void setWarning(Issue mutableIssue, String warning)
{
log.warn("WARNING FUNC "+warning)
Warning = 13593
CustomField customField = ComponentAccessor.getCustomFieldManager().getCustomFieldObject(new Long(13593));
IssueChangeHolder issueChangeHolder = new DefaultIssueChangeHolder();
customField.updateValue(null, mutableIssue, new ModifiedValue(mutableIssue.getCustomFieldValue(customField), warning), issueChangeHolder);
}
How can I use import statements in Jenkinsfile?
This is the import statement:
import hudson.model.*
import jenkins.model.*
import hudson.tasks.test.AbstractTestResultAction
I want to use AbstractTestResultAction in a script section.
I solved it that way - this what the Jenkinsfile looks like:
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import hudson.tasks.test.AbstractTestResultAction;
#NonCPS
def getTestSummary = { ->
def testResultAction = currentBuild.rawBuild.getAction(AbstractTestResultAction.class)
def summary = ""
if (testResultAction != null) {
def total = testResultAction.getTotalCount()
def failed = testResultAction.getFailCount()
def skipped = testResultAction.getSkipCount()
summary = "Test results:\n\t"
summary = summary + ("Passed: " + (total - failed - skipped))
summary = summary + (", Failed: " + failed + " ${testResultAction.failureDiffString}")
summary = summary + (", Skipped: " + skipped)
} else {
summary = "No tests found"
}
return summary
}
pipeline {
...
post {
always {
script {
def testSummaryRaw = getTestSummary()
def testSummary = "`${testSummaryRaw}`"
...
}
}
}
...
}
I use this code to access weather data from yahoo and everything just work fine.
Somehow this stops working getting a "Bad request" from yahoo...
"Please provide valid credentials. OAuth oauth_problem="OST_OAUTH_PARAMETER_ABSENT_ERROR", realm="yahooapis.com"
"
I try to understood what happed and i think that has to do with the oAuth from yahoo but i don't know how to use it and the documentation from yahoo sucks...
code below..
mForcastTown.Add(MainForm.ExtraFE_IdHttp.Get('http://weather.yahooapis.com/forecastrss?w='+ mAdd_Town[mTonwNum].mWoeID +'&u='+ mAdd_Town[mTonwNum].mDegree);
Thank you...
UPDATE...
I found this below and when run in the browser i get the xml i need but when i run it to the
IdHttp.get('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20weather.forecast%20where%20woeid=55903793%20and%20u=%27c%27&format=xml')
i get unknown version found...
What is this...
Thank you...
I had the same problem for Java, maybe this will direct you to something.
In this link there is a sample java code:
// Copyright 2019 Oath Inc. Licensed under the terms of the zLib license see https://opensource.org/licenses/Zlib for terms.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;
import java.util.Base64;
import java.util.Base64.Encoder;
import java.util.Random;
import java.util.Collections;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpResponse.BodyHandlers;
import java.net.URI;
/**
*
* <pre>
* % java --version
* % java 11.0.1 2018-10-16 LTS
*
* % javac WeatherYdnJava.java && java -ea WeatherYdnJava
* </pre>
*
*/
public class WeatherYdnJava {
public static void main(String[] args) throws Exception {
final String appId = "test-app-id";
final String consumerKey = "your-consumer-key";
final String consumerSecret = "your-consumer-secret";
final String url = "https://weather-ydn-yql.media.yahoo.com/forecastrss";
long timestamp = new Date().getTime() / 1000;
byte[] nonce = new byte[32];
Random rand = new Random();
rand.nextBytes(nonce);
String oauthNonce = new String(nonce).replaceAll("\\W", "");
List<String> parameters = new ArrayList<>();
parameters.add("oauth_consumer_key=" + consumerKey);
parameters.add("oauth_nonce=" + oauthNonce);
parameters.add("oauth_signature_method=HMAC-SHA1");
parameters.add("oauth_timestamp=" + timestamp);
parameters.add("oauth_version=1.0");
// Make sure value is encoded
parameters.add("location=" + URLEncoder.encode("sunnyvale,ca", "UTF-8"));
parameters.add("format=json");
Collections.sort(parameters);
StringBuffer parametersList = new StringBuffer();
for (int i = 0; i < parameters.size(); i++) {
parametersList.append(((i > 0) ? "&" : "") + parameters.get(i));
}
String signatureString = "GET&" +
URLEncoder.encode(url, "UTF-8") + "&" +
URLEncoder.encode(parametersList.toString(), "UTF-8");
String signature = null;
try {
SecretKeySpec signingKey = new SecretKeySpec((consumerSecret + "&").getBytes(), "HmacSHA1");
Mac mac = Mac.getInstance("HmacSHA1");
mac.init(signingKey);
byte[] rawHMAC = mac.doFinal(signatureString.getBytes());
Encoder encoder = Base64.getEncoder();
signature = encoder.encodeToString(rawHMAC);
} catch (Exception e) {
System.err.println("Unable to append signature");
System.exit(0);
}
String authorizationLine = "OAuth " +
"oauth_consumer_key=\"" + consumerKey + "\", " +
"oauth_nonce=\"" + oauthNonce + "\", " +
"oauth_timestamp=\"" + timestamp + "\", " +
"oauth_signature_method=\"HMAC-SHA1\", " +
"oauth_signature=\"" + signature + "\", " +
"oauth_version=\"1.0\"";
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url + "?location=sunnyvale,ca&format=json"))
.header("Authorization", authorizationLine)
.header("X-Yahoo-App-Id", appId)
.header("Content-Type", "application/json")
.build();
HttpResponse<String> response = client.send(request, BodyHandlers.ofString());
System.out.println(response.body());
}
}
The problem with this code is where the oauthNonce generated with random bytes. Here, the error is caused by the unrecognized chars. Because for any random byte there can be any char that your system doesn't recognize and can't process because it converts it into a string.
I replace the whole part with this:
String oauthNonce = RandomStringUtils.random(10, true, true);
It worked like a charm. I currently don't have any errors now and able to get the response. I hope this helps.
hi i'm making program that record video with audio by javacv but i got some error. any suggestion?
lib version : jdk 1.8 javacv 0.8 opencv 2.4.9
Exception in thread "main" org.bytedeco.javacv.FrameGrabber$Exception: avformat_open_input() error -2: Could not open input "output.mp4". (Has setFormat() been called?)
at org.bytedeco.javacv.FFmpegFrameGrabber.startUnsafe(FFmpegFrameGrabber.java:362)
at org.bytedeco.javacv.FFmpegFrameGrabber.start(FFmpegFrameGrabber.java:312)
at com.unomic.securobot.javacv.main(javacv.java:14)
my code
FFmpegFrameGrabber grabber1 = new FFmpegFrameGrabber("output.mp4");
FFmpegFrameGrabber grabber2 = new FFmpegFrameGrabber("test.mp3");
grabber1.setFormat("mp4");
grabber1.start();
grabber2.start();
FFmpegFrameRecorder recorder = new FFmpegFrameRecorder("outputFinal.mp4",
grabber1.getImageWidth(), grabber1.getImageHeight(),
grabber2.getAudioChannels());
recorder.setFrameRate(grabber1.getFrameRate());
recorder.setSampleFormat(grabber2.getSampleFormat());
recorder.setSampleRate(grabber2.getSampleRate());
recorder.start();
Frame frame1;
Frame frame2 = null;
while ((frame1 = grabber1.grabFrame()) != null ||
(frame2 = grabber2.grabFrame()) != null) {
recorder.record(frame1);
recorder.record(frame2);
}
recorder.stop();
grabber1.stop();
grabber2.stop();
}
I was trying to get thumbnails from a videos using the framegrabber. I was getting the same error but then I just tried giving the full path of the files and voila it worked. Previously, I was using a relative path which was not working. When I gave the full path it started working.
package com.tape.controller;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import javax.imageio.ImageIO;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.OpenCVFrameGrabber;
public class VideoThumbTaker {
protected String ffmpegApp;
public VideoThumbTaker(String ffmpegApp)
{
this.ffmpegApp = ffmpegApp;
}
public void getThumb(String videoFilename, String thumbFilename, int width, int height,int hour, int min, float sec)
throws IOException, InterruptedException
{
ProcessBuilder processBuilder = new ProcessBuilder(ffmpegApp, "-y", "-i", videoFilename, "-vframes", "1",
"-ss", hour + ":" + min + ":" + sec, "-f", "mjpeg", "-s", width + "*" + height, "-an", thumbFilename);
Process process = processBuilder.start();
InputStream stderr = process.getErrorStream();
InputStreamReader isr = new InputStreamReader(stderr);
BufferedReader br = new BufferedReader(isr);
String line;
while ((line = br.readLine()) != null);
process.waitFor();
}
public static void main(String[] args) throws Exception, IOException
{
//Both case work
FFmpegFrameGrabber g = new FFmpegFrameGrabber("C:\\JavaEE\\New Project\\tape\\src\\main\\webapp\\web-resources\\videos\\vid.mp4");
g.setFormat("mp4");
g.start();
for (int i = 0 ; i < 50 ; i++) {
ImageIO.write(g.grab().getBufferedImage(), "png", new File("C:\\JavaEE\\New Project\\tape\\src\\main\\webapp\\web-resources\\thumbnails\\video-frame-" + System.currentTimeMillis() + ".png"));
}
g.stop();
}
}