Structurize multicell inside FPDF - fpdf

I have names received from database table:
ADEEB (staff) , ALISTER (staff), AMER (staff), AMIRABUBAKAR (staff), AMIRULHAFIZ (staff),
ANA (staff), ANDIKA (staff), ANDREW (staff), ARINA (staff), DIANADEWI (staff), DINA (staff),
DINIE (staff), DUDU (staff), DUNCAN (staff), ELIZABETH (staff), ERIC (staff), ERIN (staff),
FAUZE(staff), FAZLY (staff),FELIZ (staff), HAYKAL (staff), IVANPINTO (staff), IVORY (staff),
IVY (staff)
I want to create pdf file and print names like that inside fpdf using multicell:
function Mach($header, $header1, $lbl3)
{
$this->Line(10,$this->GetY(),200,$this->GetY());
//Times 12
$this->SetFont('Times','B',12);
//Background color
$this->SetFillColor(255,255,255);
//Title
$this->Cell(50,10,"$header1",0,1,'L');
$this->SetFont('Times','',12);
$this->MultiCell(185,10,"$lbl3",1,1,'L');
}
$con = mysqli_connect(DATABASE_HOST, DATABASE_USER, DATABASE_PASSWORD, DATABASE_NAME);
$pdf = new PDF();
$pdf->AliasNbPages();
$pdf->AddPage();
for($y=0;$y<$len;$y++)
{
$column_procStaff = '';
$result6 = getProcessStaff($projectNo,$proc[$y]);
if (!$result6) {
die('Invalid query: ' . mysqli_error($con));
}
$c=0;
while($row6 = mysqli_fetch_array($result6))
{
$procStaff = $row6['proc_staff'];
if($c==0)
{
$column_procStaff .= $procStaff." (staff) ";
}
else
{
$column_procStaff .= ", ".$procStaff." (staff)";
}
$c++;
}
$pdf->Mach("Process Name: $proc[$y]", $column_procStaff);
}
Also I want structure received names. Is there any way to do it to display smth like this:
ADEEB (staff), ALISTER (staff), AMER (staff),
AMIRABUBAKAR (staff), AMIRULHAFIZ (staff), ANA (staff),
ANDIKA (staff), ANDREW (staff), ARINA (staff),
DIANADEWI (staff), DINA (staff), DINIE (staff),
DUDU (staff), DUNCAN (staff), ELIZABETH (staff),
ERIC (staff), ERIN (staff), FAUZE(staff),
FAZLY (staff), FELIZ (staff), HAYKAL (staff),
IVANPINTO (staff), IVORY (staff), IVY (staff)

Here is a snippet using fPDF to write the names the way you want :
// Your data
$names= array("ADEEB (staff)", "ALISTER (staff)" ,"AMER (staff)" ,"AMIRABUBAKAR (staff)" ,"AMIRULHAFIZ (staff)", "ANA (staff)" ,"ANDIKA (staff)" ,"ANDREW (staff)" ,"ARINA (staff)" ,"DIANADEWI (staff)" ,"DINA (staff)", "DINIE (staff)" ,"DUDU (staff)" ,"DUNCAN (staff)" ,"ELIZABETH (staff)" ,"ERIC (staff)" ,"ERIN (staff)", "FAUZE(staff)" ,"FAZLY (staff),FELIZ (staff)" ,"HAYKAL (staff)" ,"IVANPINTO (staff)" ,"IVORY (staff)", "IVY (staff)");
// Number of column wanted
$nbColumn = 3;
// Computing width of columns
$maxWidth = 0;
foreach ($names as $n){
$w = $pdf->GetStringWidth($n);
if($maxWidth<$w){
$maxWidth=$w;
}
}
// add Margin
$maxWidth = $maxWidth + 10;
foreach ($names as $index => $n){
// width, height, text, no norder, going to next line
$pdf->Cell($maxWidth, 5, $n, 0, $index%$nbColumn==$nbColumn-1);
}

Related

Voila not clearing output/dispalying new output

I am trying to get an ipywidget button to change colour when clicked. I figured a way to do it as below
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
new_btn = ipw.Button(description = 'PDF done',button_style = 'success',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
HBox1 = ipw.HBox([new_btn])
def clear(b):
clear_output()
display(HBox1)
pdf_btn.on_click(clear)
display(HBox)
When inputting this code in Jupyter Notebook and rendering through Voila nothing happens.
Any ideas why ? And any suggestions ?
You can just update the button style maybe? Like so:
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
def clear(b):
pdf_btn.button_style="success"
pdf_btn.description="PDF done"
pdf_btn.on_click(clear)
display(HBox)
Note that your code fails in JupyterLab.
Voila is much more similar to JupyterLab's rendering machinery than the classic interface. For now, it is best to use JupyterLab in conjunction with developing for Voila. (Note that this will change soon as the underlying machinery for what is now the traditional Jupyter notebook interface will soon run on machinery more in line with JupyterLab, see Build Jupyter Notebook v7 off of JupyterLab components. A lot of the old code / approaches will then consistently not work and either interface will be as suitable for developing with Voila in mind.)
When your code fails in JupyterLab it logs that to the console, similar to as shown here. I suspect you could follow Jason's advice, what I reference in my reply, which is here, if you actually want the other button there. (I guess I should say if you actually want the other HBox there since for some reason you have each button in a separate HBox in your code.) In other words, you'd need to add in how to handle the output from HBox1 correctly as part of the main output. Yours is going to the JupyterLab Log console as it is now.
So one option is to add HBox1 in as a displayed item, yet hide it initially:
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
new_btn = ipw.Button(description = 'PDF done',button_style = 'success',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
HBox1 = ipw.HBox([new_btn])
HBox1.layout.visibility = 'hidden' #based on https://github.com/jupyter-widgets/ipywidgets/issues/674#issuecomment-234321603
def clear(b):
HBox1.layout.visibility = 'visible'
HBox.layout.display = 'none' #based on https://stackoverflow.com/a/54134344/8508004
pdf_btn.on_click(clear)
display(HBox)
display(HBox1)
You could also make an overarching vertical box for the items and then toggle which one it contains, similar to here. This is the 'cleanest' option I'll list here, other than just having one button & changing the button itself:
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
new_btn = ipw.Button(description = 'PDF done',button_style = 'success',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
HBox1 = ipw.HBox([new_btn])
vb = VBox(children = [HBox])
def clear(b):
vb.children = [HBox1]
pdf_btn.on_click(clear)
display(vb)
('cleanest' in regards to it not creating extra space in the output area.)
Or combine the vertical box approach with the approach of toggling off via the layout settings:
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
new_btn = ipw.Button(description = 'PDF done',button_style = 'success',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
HBox1 = ipw.HBox([new_btn])
HBox1.layout.visibility = 'hidden' #based on https://github.com/jupyter-widgets/ipywidgets/issues/674#issuecomment-234321603
vb = VBox(children = [HBox, HBox1])
def clear(b):
HBox1.layout.visibility = 'visible'
HBox.layout.display = 'none' #based on https://stackoverflow.com/a/54134344/8508004
pdf_btn.on_click(clear)
display(vb)
And if you want to fully leverage Jupyter's display system further, combine it with an overarching out so you can use print(), too:
import ipywidgets as ipw
from ipywidgets import *
from IPython.display import display, HTML, clear_output
from IPython.display import display, HTML
out = widgets.Output()
pdf_btn = ipw.Button(description = 'Run PDF',button_style = 'danger',
layout=Layout(width='150px', height='30px'))
new_btn = ipw.Button(description = 'PDF done',button_style = 'success',
layout=Layout(width='150px', height='30px'))
HBox = ipw.HBox([pdf_btn])
HBox1 = ipw.HBox([new_btn])
vb = VBox(children = [HBox])
def clear(b):
vb.children = [HBox1]
with out:
print('Enjoy!')
pdf_btn.on_click(clear)
with out:
display(vb)
out

bypass 'google before you continue' pop-up

My code:
import pandas
import requests
from bs4 import BeautifulSoup
from pywebio.input import *
from pywebio.output import *
from time import sleep
from pywebio import start_server
print("News web application successfully started!")
def app():
request = requests.get("https://news.google.com/topics/CAAqRggKIkBDQklTS2pvUVkyOTJhV1JmZEdWNGRGOXhkV1Z5ZVlJQkZRb0lMMjB2TURKcU56RVNDUzl0THpBeFkzQjVlU2dBUAE/sections/CAQqSggAKkYICiJAQ0JJU0tqb1FZMjkyYVdSZmRHVjRkRjl4ZFdWeWVZSUJGUW9JTDIwdk1ESnFOekVTQ1M5dEx6QXhZM0I1ZVNnQVAB?hl=en-US&gl=US&ceid=US%3Aen")
content = BeautifulSoup(request.content, 'html.parser')
find = content.find('div', class_='ajwQHc BL5WZb')
#open('test.html', 'w').write(findstr.find)
h3 = find.find_all('h3')
time = find.find_all('time')
link = find.find_all('article')#.find_all('a').get('href').replace('.', '')
result = []
#print('https://news.google.com' + link)
#put_html('<table border="1" width="100%" cellpadding="5">')
source = find.find_all('a', {'data-n-tid' : '9'})
time = find.find_all('time')
textoutput = []
textoutput1 = []
textoutput2 = []
takeoutput3 = []
#writer = open('news.csv', 'w')
#writer1 = csv.writer(writer, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
for text in h3:
a1 = text.text
textoutput.append(a1)
for text2 in source:
a3 = text2.text
textoutput1.append(a3)
for text1 in time:
a5 = text1.text
textoutput2.append(a5)
#for result in link:
# alinks = result.find_all('a')
# alinks1 = []
# for alinks1 in alinks:
# alinks2 = alinks1.get('href')
# alinksreplace = str(alinks2)
# alinksreplace1 = alinksreplace.replace(".", "")
# alinksreplace2 = alinksreplace1.replace("None", "")
#
# if (alinksreplace2 != ''):
# if "publications" not in alinksreplace2:
# a = "https://news.google.com" + alinksreplace2
# takeoutput3.append(a)
pandas.set_option('display.max_colwidth', None)
frame = {'Title':textoutput, 'Time':textoutput2, 'Source' : textoutput1}
frame1 = pandas.DataFrame(frame)
#frame2 = {'Link' : takeoutput3}
#frame3 = pandas.DataFrame(frame2)
frametostring = frame1.to_string(index=False)
#frametostring1 = frame3.to_string(index=False)
#print(frametostring)
put_code(frametostring)
#put_code(frametostring1)
#writer1.writerow([textoutput, textoutput1, textoutput2])
start_server(app, 82)
it worked fine but today Google update something and now it don't start. And it's because Google add before you continue pop-up. How I can bypass this so my script continue to work?
If it was Selenium I've just clicked the button but here I don't know what to do
Thanks you helping!

Why Phantom Cassandra Insert getting "main" java.lang.NoClassDefFoundError: scala/reflect/runtime/package error

I very new to phantom and I have basic knowledge of scala and cassandra. so i am trying to do simple crud example using phantom so i have look at few examples at google. at last i have end up with this example. but I run this code not like as this project readme file said. I just create a intellij project and there is main class like following.
import org.creative.document.dao.impl.{PhantomConnectorExample}
import org.creative.document.database.SongsDatabase
import org.creative.document.entity.Song
object DocumentAPIMain {
def main(args: Array[String]): Unit = {
val song = Song(songId,"Wahinnta Athnam gigum di","Pawana","Nanda Malini")
val songsDatabase = new SongsDatabase(PhantomConnectorExample.connector)
songsDatabase.saveOrUpdate(song)
}
}
that was the only chage i have done other than that all the dependencies and everything as like above mention link.
I have created cassandra keyspace, songs table and songs_by_artist table manually. following is show my cassandra shema
CREATE KEYSPACE phantomtest WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '1'} AND durable_writes = true;
CREATE TABLE phantomtest.songs_by_artist (
artist text,
id timeuuid,
album text,
title text,
PRIMARY KEY (artist, id)
) WITH CLUSTERING ORDER BY (id ASC)
AND bloom_filter_fp_chance = 0.01
AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
AND comment = ''
AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
AND crc_check_chance = 1.0
AND dclocal_read_repair_chance = 0.1
AND default_time_to_live = 0
AND gc_grace_seconds = 864000
AND max_index_interval = 2048
AND memtable_flush_period_in_ms = 0
AND min_index_interval = 128
AND read_repair_chance = 0.0
AND speculative_retry = '99PERCENTILE';
CREATE TABLE phantomtest.songs (
id timeuuid PRIMARY KEY,
album text,
artist text,
title text
) WITH bloom_filter_fp_chance = 0.01
AND caching = {'keys': 'ALL', 'rows_per_partition': 'NONE'}
AND comment = ''
AND compaction = {'class': 'org.apache.cassandra.db.compaction.SizeTieredCompactionStrategy', 'max_threshold': '32', 'min_threshold': '4'}
AND compression = {'chunk_length_in_kb': '64', 'class': 'org.apache.cassandra.io.compress.LZ4Compressor'}
AND crc_check_chance = 1.0
AND dclocal_read_repair_chance = 0.1
AND default_time_to_live = 0
AND gc_grace_seconds = 864000
AND max_index_interval = 2048
AND memtable_flush_period_in_ms = 0
AND min_index_interval = 128
AND read_repair_chance = 0.0
AND speculative_retry = '99PERCENTILE';
After all when i run my main method it will end up with the following error
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
Exception in thread "main" java.lang.NoClassDefFoundError: scala/reflect/runtime/package$
at com.outworkers.phantom.column.AbstractColumn.com$outworkers$phantom$column$AbstractColumn$$_name(AbstractColumn.scala:55)
at com.outworkers.phantom.column.AbstractColumn.com$outworkers$phantom$column$AbstractColumn$$_name$(AbstractColumn.scala:54)
at com.outworkers.phantom.column.Column.com$outworkers$phantom$column$AbstractColumn$$_name$lzycompute(Column.scala:22)
at com.outworkers.phantom.column.Column.com$outworkers$phantom$column$AbstractColumn$$_name(Column.scala:22)
at com.outworkers.phantom.column.AbstractColumn.name(AbstractColumn.scala:58)
at com.outworkers.phantom.column.AbstractColumn.name$(AbstractColumn.scala:58)
at com.outworkers.phantom.column.Column.name(Column.scala:22)
at org.creative.document.database.SongsDatabase$anon$macro$1$1.store(SongsDatabase.scala:28)
at org.creative.document.database.SongsDatabase$anon$macro$1$1.store(SongsDatabase.scala:28)
at com.outworkers.phantom.CassandraTable.store(CassandraTable.scala:132)
at org.creative.document.database.SongsDatabase.saveOrUpdate(SongsDatabase.scala:28)
at org.creative.document.main.DocumentAPIMain$.main(DocumentAPIMain.scala:58)
at org.creative.document.main.DocumentAPIMain.main(DocumentAPIMain.scala)
Caused by: java.lang.ClassNotFoundException: scala.reflect.runtime.package$
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
... 13 more
Please help me to find out the problem. what I have did wrong...
I faced the same issue and added the following dependency.
"org.scala-lang" % "scala-reflect" % scalaVersion.value
It worked for me.

FFmpeg encoding produces slightly incompatible MKV/MP4 container

I've been using the FFmpeg libraries to read and write media files using the C API.
So far, reading seems to be pretty straightforward. I am able to read frames which I can then process, convert to RGB, process, and then convert back to YUV420 to be encoded.
The encoded files play back with VLC media player fine, and Windows Media Player if I have a codec pack installed. However, they do behave strangely: the stock Windows 10 player won't play them, same for Adobe Premiere. Also thumbnailers don't work on it.
Basically it seems like nothing other than VLC or FFmpeg itself can play/process the file. I have seen this with both MP4 and MKV, so it is not a format-specific issue.
The problems go away once you remux the file with FFmpeg, for example "ffmpeg -i input.mkv -c copy output.mkv". Everything can play the file correctly.
Also, the "remuxing.c" sample from the official samples works as well, with the same library version and compilers that I'm using (Visual Studio 2017, FFmpeg compiled with MinGW). It will fix the file and make it playable in all software.
I'm not sure what could be causing this. I also don't understand what the remuxing "fixed". It must be a container issue as the frames aren't touched by remuxing.
I have analysed the output MKVs with FFprobe -show_packets. It seems to have budged the packet timestamps a little constant factor, and the output stream now has
is_avc=true and nal_length_size=4 instead of is_avc=false and nal_length_size=0, but apart from that the files are identical.
Now here's the output of FFprobe with the 3 last test packets, stream info and format info for both streams. As you can see, they are identical except for a couple of field. But something in here must have been "fixed" during remuxing to make it work.
[PACKET]
codec_type=video
stream_index=0
pts=59050
pts_time=59.050000
dts=58890
dts_time=58.890000
duration=1
duration_time=0.001000
convergence_duration=N/A
convergence_duration_time=N/A
size=427
pos=277358
flags=__
[/PACKET]
[PACKET]
codec_type=video
stream_index=0
pts=58970
pts_time=58.970000
dts=58970
dts_time=58.970000
duration=1
duration_time=0.001000
convergence_duration=N/A
convergence_duration_time=N/A
size=205
pos=277792
flags=__
[/PACKET]
[PACKET]
codec_type=video
stream_index=0
pts=59130
pts_time=59.130000
dts=59050
dts_time=59.050000
duration=1
duration_time=0.001000
convergence_duration=N/A
convergence_duration_time=N/A
size=268
pos=278004
flags=__
[/PACKET]
[STREAM]
index=0
codec_name=h264
codec_long_name=H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
profile=Main
codec_type=video
codec_time_base=1/2000
codec_tag_string=[0][0][0][0]
codec_tag=0x0000
width=720
height=576
coded_width=720
coded_height=576
has_b_frames=2
sample_aspect_ratio=N/A
display_aspect_ratio=N/A
pix_fmt=yuv420p
level=50
color_range=unknown
color_space=unknown
color_transfer=unknown
color_primaries=unknown
chroma_location=left
field_order=progressive
timecode=N/A
refs=1
is_avc=false
nal_length_size=0
id=N/A
r_frame_rate=299/12
avg_frame_rate=1000/1
time_base=1/1000
start_pts=0
start_time=0.000000
duration_ts=N/A
duration=N/A
bit_rate=N/A
max_bit_rate=N/A
bits_per_raw_sample=8
nb_frames=N/A
nb_read_frames=N/A
nb_read_packets=737
DISPOSITION:default=1
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=0
DISPOSITION:timed_thumbnails=0
TAG:DURATION=00:00:59.211000000
[/STREAM]
[FORMAT]
filename=testEncLeft.mkv
nb_streams=1
nb_programs=0
format_name=matroska,webm
format_long_name=Matroska / WebM
start_time=0.000000
duration=59.211000
size=278349
bit_rate=37607
probe_score=100
TAG:COMMENT=Slickline Player Export
TAG:ENCODER=Lavf57.83.100
[/FORMAT]
And the info after remuxing, which works:
[PACKET]
codec_type=video
stream_index=0
pts=59050
pts_time=59.050000
dts=58890
dts_time=58.890000
duration=1
duration_time=0.001000
convergence_duration=N/A
convergence_duration_time=N/A
size=427
pos=277418
flags=__
[/PACKET]
[PACKET]
codec_type=video
stream_index=0
pts=58970
pts_time=58.970000
dts=58970
dts_time=58.970000
duration=1
duration_time=0.001000
convergence_duration=N/A
convergence_duration_time=N/A
size=205
pos=277852
flags=__
[/PACKET]
[PACKET]
codec_type=video
stream_index=0
pts=59130
pts_time=59.130000
dts=59050
dts_time=59.050000
duration=1
duration_time=0.001000
convergence_duration=N/A
convergence_duration_time=N/A
size=268
pos=278064
flags=__
[/PACKET]
[STREAM]
index=0
codec_name=h264
codec_long_name=H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10
profile=Main
codec_type=video
codec_time_base=1/2000
codec_tag_string=[0][0][0][0]
codec_tag=0x0000
width=720
height=576
coded_width=720
coded_height=576
has_b_frames=2
sample_aspect_ratio=N/A
display_aspect_ratio=N/A
pix_fmt=yuv420p
level=50
color_range=unknown
color_space=unknown
color_transfer=unknown
color_primaries=unknown
chroma_location=left
field_order=progressive
timecode=N/A
refs=1
is_avc=true
nal_length_size=4
id=N/A
r_frame_rate=299/12
avg_frame_rate=1000/1
time_base=1/1000
start_pts=0
start_time=0.000000
duration_ts=N/A
duration=N/A
bit_rate=N/A
max_bit_rate=N/A
bits_per_raw_sample=8
nb_frames=N/A
nb_read_frames=N/A
nb_read_packets=737
DISPOSITION:default=1
DISPOSITION:dub=0
DISPOSITION:original=0
DISPOSITION:comment=0
DISPOSITION:lyrics=0
DISPOSITION:karaoke=0
DISPOSITION:forced=0
DISPOSITION:hearing_impaired=0
DISPOSITION:visual_impaired=0
DISPOSITION:clean_effects=0
DISPOSITION:attached_pic=0
DISPOSITION:timed_thumbnails=0
TAG:DURATION=00:00:59.212000000
[/STREAM]
[FORMAT]
filename=fixedLeft.mkv
nb_streams=1
nb_programs=0
format_name=matroska,webm
format_long_name=Matroska / WebM
start_time=0.000000
duration=59.212000
size=278409
bit_rate=37615
probe_score=100
TAG:COMMENT=Slickline Player Export
TAG:ENCODER=Lavf58.12.100
[/FORMAT]
Here is how I'm setting up the output context, for reference: it's pretty standard, following the sample code.
int ret;
avformat_alloc_output_context2(&outputFormatCtx, nullptr, nullptr, outFilePath.c_str());
av_dict_set(&outputFormatCtx->metadata, "comment", "FFmpeg Export", 0);
if (!outputFormatCtx)
{
LOG_AND_THROW("Could not allocate output context");
}
outputVideoStream = avformat_new_stream(outputFormatCtx, nullptr);
outputVideoStream->time_base = AVRational{ 1, AV_TIME_BASE }; // Stream timebase will be used by codec
if (!outputVideoStream)
{
LOG_AND_THROW("Failed allocating output stream");
}
// defaults to "libx264"
AVCodec *outCodec = avcodec_find_encoder_by_name(selectedCodecName.c_str());
if (!outCodec)
{
LOG_AND_THROW("Failed finding output codec");
}
AVDictionary *opts = nullptr;
if (selectedCodecName == "libx264")
{
opts = getX264CodecOptions();
}
encoderCtx = avcodec_alloc_context3(outCodec);
if (!encoderCtx)
{
LOG_AND_THROW("Failed to allocate the encoder context");
}
encoderCtx->width = width;
encoderCtx->height = height;
encoderCtx->pix_fmt = AV_PIX_FMT_YUV420P;
// time base for the frames we will provide to the encoder
encoderCtx->time_base = AVRational{ 1, AV_TIME_BASE };
// convert framerate from double to rational
encoderCtx->framerate = AVRational{ (int)(frameRate * AV_TIME_BASE), AV_TIME_BASE};
// Match encoderCtx time base for the stream
outputVideoStream->time_base = encoderCtx->time_base;
ret = avcodec_open2(encoderCtx, outCodec, &opts);
if (ret < 0)
{
LOG_AND_THROW_PARAM("Cannot open video encoder for stream: %d", ret);
}
// Fill in some params for MP4 stream, details about encoder
ret = avcodec_parameters_from_context(outputVideoStream->codecpar, encoderCtx);
if (ret < 0)
{
LOG_AND_THROW_PARAM("Failed to copy encoder parameters to output stream: %d", ret);
}
if (outputFormatCtx->oformat->flags & AVFMT_GLOBALHEADER)
{
encoderCtx->flags |= AV_CODEC_FLAG_GLOBAL_HEADER;
}
av_dump_format(outputFormatCtx, 0, filePath.c_str(), 1);
// End of encoder settings, setting up MP4
if (!(outputFormatCtx->oformat->flags & AVFMT_NOFILE))
{
ret = avio_open(&outputFormatCtx->pb, outFilePath.c_str(), AVIO_FLAG_WRITE);
if (ret < 0)
{
LOG_AND_THROW_PARAMSTR("Could not open output file '%s'", outFilePath.c_str());
}
}
ret = avformat_write_header(outputFormatCtx, nullptr);
if (ret < 0)
{
LOG_AND_THROW_PARAM("Error occurred when opening output file for writing: %d", ret);
}
Can anyone help me figure out why the container is not playing properly?
Thanks in advance.
-James

Using private mibs with snmpv3

I am using below mentioned example to send v3 trap with custom notification mib
http://pysnmp.sourceforge.net/examples/current/v3arch/agent/ntforg/trap-v3.html
But the sendNotification function is accepting only the dotted format as in the example ..
What should I do to pass the symbols instead ?
E.g.(' MY-MIB:testTrap') instead of (1,3,2,0....)
You are linking a historical pysnmp documentation. Please, refer to the actual one.
To pass MIB symbols you should use ObjectIdentifier class which turns MIB names into OIDs behind the scenes.
But SNMP notifications can be quite complicated because they may imply certain other MIB objects to be automatically included with the notification being sent.
But you can still add whatever MIB objects you want through NotificationType.addVarBinds.
Here's a simple example:
from pysnmp.hlapi import *
errorIndication, errorStatus, errorIndex, varBinds = next(
sendNotification(
SnmpEngine(),
CommunityData('public'),
UdpTransportTarget(('demo.snmplabs.com', 162)),
ContextData(),
'trap',
NotificationType(
ObjectIdentity('MY-MIB', 'testTrap')
)
)
)
"Hi again below is a snippet of the way I am using the code . "
from pysnmp.entity import engine, config
from pysnmp.carrier.asynsock.dgram import udp
from pysnmp.entity.rfc3413 import ntforg, context
from pysnmp.proto.api import v2c
from pysnmp.proto import rfc1902
from pysnmp.smi import builder
file = open("."+"/file.txt","r")
line = file.read()
fields = line.split(",")
file.close()
file = open("."+"/credentials.txt","r")
cred = file.read()
fields = cred.split(",")
file.close()
snmpEngine = engine.SnmpEngine(snmpEngineID=v2c.OctetString(hexValue=cred[0]))
config.addV3User(snmpEngine, cred[1], config.usmHMACSHAAuthProtocol, cred[2], config.usmAesCfb128Protocol, cred[3])
config.addTargetParams(snmpEngine, 'my-creds', 'traptest', 'authPriv')
config.addSocketTransport(snmpEngine, udp.domainName, udp.UdpSocketTransport().openClientMode())
config.addTargetAddr(snmpEngine, 'my-nms', udp.domainName, ('127.0.0.1', 162), 'my-creds', tagList='all-my-managers')
config.addNotificationTarget(snmpEngine, 'my-notification', 'my-filter', 'all-my-managers', 'trap')
config.addContext(snmpEngine, '')
config.addVacmUser(snmpEngine, 3, 'traptest', 'authPriv', (), (), (1,3,6))
snmpContext = context.SnmpContext(snmpEngine)
ntfOrg = ntforg.NotificationOriginator()
ntfOrg.snmpContext = snmpContext
ntfOrg.sendNotification(
snmpEngine,
'my-notification',
(1,3,6,1,4,1,46033,1,1,2,2),
(((1,3,6,1,4,1,46033,1,1,1,1), v2c.OctetString(fields[0])),)
)
print('Notification is scheduled to be sent')