text:
Q: When i try to delete redundant file even after closing all the references jvm throws the FileSystemException I'm creating a video record file (avi) with javacv after creation converting this file to an mp4 file with Jaffree. When i try to delete the now redundant avi file it throws the FileSystemException.
I've already released all the file holding Objects but still the exception is being thrown. Also tried to force the deletion with apache common io FileUtils.forceDelete(sample.getFile()); still having the same Exception.

public class PacketRecorderTest {

private static final DateFormat DATE_FORMAT = new SimpleDateFormat("yyyyMMdd__hhmmSSS");
private static final int RECORD_LENGTH = 10000;
private static final boolean AUDIO_ENABLED = false;
static String inputFile =  "rtsp://184.72.239.149/vod/mp4:BigBuckBunny_115k.mov";
static String outputFile = "C:\\Users\\team3\\Desktop\\User\\Vinay\\javacppffmpeg\\frame.avi";

public static void main(String[] args) throws FrameRecorder.Exception, FrameGrabber.Exception, InterruptedException{
    packetRecord(inputFile,outputFile);
    jafreeToMp4(outputFile, "C:\\Users\\team3\\Desktop\\User\\Vinay\\javacppffmpeg\\frame.mp4");
    try {
        Files.delete(Paths.get(outputFile));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

public static void packetRecord(String inputFile, String outputFile) throws FrameGrabber.Exception, FrameRecorder.Exception {

    FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(inputFile);
    grabber.start();
    FFmpegFrameRecorder recorder = new FFmpegFrameRecorder(
            outputFile,
            1280,
            720);
    recorder.start(grabber.getFormatContext());
    recorder.setFormat("avi");
    recorder.setPixelFormat(AV_PIX_FMT_YUV420P);
    recorder.setVideoOption("crf", "22");
    recorder.setVideoQuality(0);
    recorder.setFrameRate(15);
    recorder.start();

    avcodec.AVPacket packet;
    long t1 = System.currentTimeMillis();
    while ((packet = grabber.grabPacket()) != null) {
            recorder.recordPacket(packet);
            if ((System.currentTimeMillis() - t1) > RECORD_LENGTH) {
                break;
            }
    }
    grabber.stop();
    recorder.stop();
    recorder.release();
    grabber.release();

}

public static void jafreeToMp4 (String inputFile, String outputFile) {
    Path BIN = Paths.get("C:\\ffmpeg\\shared\\bin");
    Path VIDEO_MP4 = Paths.get(inputFile);
    Path OUTPUT_MP4 = Paths.get(outputFile);

    FFmpegResult result = FFmpeg.atPath(BIN)
            .addInput(UrlInput.fromPath(VIDEO_MP4))
            .addOutput(UrlOutput.toPath(OUTPUT_MP4)
            )
            .execute();
}

}

java.nio.file.FileSystemException: C:\Users\team3\Desktop\User\Vinay\javacppffmpeg\frame.avi: The process cannot access the file because it is being used by another process.
at sun.nio.fs.WindowsException.translateToIOException(WindowsException.java:86)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:97)
at sun.nio.fs.WindowsException.rethrowAsIOException(WindowsException.java:102)
at sun.nio.fs.WindowsFileSystemProvider.implDelete(WindowsFileSystemProvider.java:269)
at sun.nio.fs.AbstractFileSystemProvider.delete(AbstractFileSystemProvider.java:103)
at java.nio.file.Files.delete(Files.java:1126)
at playground.PacketRecorderTest.main(PacketRecorderTest.java:39)

A: I can't tell for sure, as I don't have immediate access to the libraries you're using.  However, it looks to me as though you still have open InputStreams and OutputStreams.  My suggestions would look something like this, depending on the return type of the helper methods:
try(InputStream in = UrlInput.fromPath(VIDEO_MP4);
    OutputStream out = UrlOutput.toPath(OUTPUT_MP4)) {

    FFmpegResult result = FFmpeg.atPath(BIN)
        .addInput(in)
        .addOutput(out)
        .execute();
}

This will close the resources after the statement is complete.

A: Was calling the start() method twice recorder.start(grabber.getFormatContext()); and start(). So may the first call may have left the references untracked.


text:
Q: I can't get value from application.properties in spring boot in any way I've tried using ways.
@Value("${app.host})

@AutoWired
Environment environment

I can get value from the application.properties in other files, but when I try to get it from thread task where I've implemented Callable Interface, I'm getting value null.
Here my application.properties
app.host = "xyz.com"

Service
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<FTPClient> result = executorService.submit(new FtpConnector());

FtpConnector.java

import java.util.concurrent.Callable;

@Service
@PropertySource("classpath:application.properties")
public class FtpConnector implements Callable<FTPClient>{

    FTPClient ftpClient = new FTPClient();
    Logger logger = LoggerFactory.getLogger(FtpConnector.class);

    @Autowired
    FtpClient client;

    @Value("${app.host}")
    private String host;

    @Override
    public FTPClient call() throws Exception {
        logger.info("Host from connecter {}",host);
}

output
2022-03-02 20:44:03.831  INFO 15135 --- [ool-13-thread-1] t.a.tech.ftpnew.service.FtpConnector     : Host from connecter null

Does anyone have any idea or solution to get values of application.properties in thread. ?

A: When you use new FtpConnector() it will not do any dependency injection thus FtpClient and host will not be injected. Do the following;
@Autowired
private FtpConnector ftpConnector;

ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<FTPClient> result = executorService.submit(ftpConnector);

redpajama_set_name: RedPajamaStackExchange


text:
Q: 'a sense of' before two nouns in a sentence May I ask if I would like to say someone is responsible and disciplined, can I put it as:

*

*He has a sense of responsibility and discipline.

or I need to put it as:

*He has the senses of responsibility and discipline.

Many thanks!!

A: The Cambridge Learner's Dictionary says that this meaning of sense cannot be pluralized1:

ABILITY [ no plural ]
  the ability to do something:
a sense of direction
  good business sense

So you should say

a sense of responsibility and discipline,

or if you want to convey the notion that these are two different things, you can say

a sense of responsibility and of discipline.

1 The closely related meaning of the senses of smell, taste, touch, etc. can be pluralized.

A: He has a sense of responsibility and discipline.
'sense' can be used because here both can be interdependent and thought of as one collective attribute without undermining the importance of any.


text:
Q: How to set custom URL in MVC4 I need in MVC4 in C#...
{id}.example.com or
{id}.example.com/{controller}/{action}
Or
In localhost how can I test it.
I means, can I debug this code in below format ...
{id}.localhost:51782 or
{id}.localhost:51782/{controller}/{action}
Please explain this in full steps.

A: You need to handle your requests with "virtual" URL, for example {user}.example.com and internally update httpcontext path using httpContext.RewritePath(). Finally you will have two types of URIs.

*

*Virtual: {id}.example.com/{controller}/{action}

*Real: {id}/{controller}/{action}

Handling is possible in Application_BeginRequest inside your Global.asax.cs file
protected void Application_BeginRequest(object sender, EventArgs e)
{
   var domainHandler = new DomainsHandler(Context);
   domainHandler.Handle();
}

And example of DomainHandler:
public class DomainsHandler
{
    private readonly HttpContext httpContext;

    public DomainsHandler(HttpContext httpContext)
    {
        this.httpContext = httpContext;
    }

    public void Handle()
    {
        httpContext.RewritePath(path);
    }
}

Rewriting logic inside Handle() method is up to you.


text:
Q: User input url modifier in html I am creating a site for a city and am going to add a phone number lookup box on it. I would like it to be pure html and simple. I need  somekind of user input boxes so in one box they could type the first name, then next box the last name, then a city box, then a state box. So when they push submit it fits it in this url: http://www.yellowpages.com/whitepages?first=FIRSTNAMEHERE&last=LASTNAMEHERE&zip=ZIPCODEHERE&state=STATEHERE
I have tried jQuery and it sort of worked but want to move on to pure html.
The code I have tried is:
 <input id="input" name="url" onfocus="this.value='';" style="border: 1px solid
#A4A4A4; font-size: 0.9em; padding: 5px; width: 350px;" type="text" value="Type url here..">
<input onclick="window.open('http://www.yellowpages.com/whitepages?first=&last=&zip=&state=' +

window.document.getElementById('input').value.replace(/^https?:\/\//,''))" style="font-family: Arial, sans-serif; font-size: 0.9em; margin: 2px 0; padding:

4px; width: 100px;" type="button" value="Surf">

I know I am making the mistake somewhere in the "onclick" value.

A: Sounds like you need just a simple GET request for your form. A GET request means it passes data to a page via URL parameters. This code takes every submitted input name and puts the data it contains after your yellowpages URL.
<form method="get" action="http://www.yellowpages.com/whitepages">
    <input name="first" type="text">
    <input name="last" type="text">
    <input name="zip" type="text">
    <input name="state" type="text">
    <input type="submit" value="Submit">
</form>


text:
Q: What's the difference between 0 and dword 0? As the question states,
What's the difference between (for example) mov eax, 0 and mov eax, dword 0?
I've been using cmp statements, and I can't catch the difference.
Is one an address and the other a numerical value?

A: As stated, no difference for the MOV instruction. For CMP, you would have difference between
CMP memory address of a qword,a 32 bit immediate
is different from
CMP memory address of a qword,an 8 bit immediate
as the comparison will be done after a sign extension, and hence, with a smaller dimension immediate number, expecially when its a negative number, some caution is advised.
Have fun programming...

A: It does not make a difference with a register since the name of the register already tells the assembler "how big" the data item (in this case, 0) is:
mov   eax, dword 0    ; move a 4-byte 0 into eax
mov   eax, 0          ; move a 0 into eax (eax is 4 bytes, so move 4 bytes)

However, there are cases where you might want to be able to specify how large the value is since there's a choice. In x86 32-bit assembly, the following would push a 4-byte 0 value on the stack:
push   0             ; push 4-byte 0 onto the stack

If you wanted to push a 2-byte 0 value, you would use:
push   word 0

If you wanted to be explicit so it's clear for the 4-byte immediate push, you could use the dword:
push   dword 0

If you want to move an immediate value to memory, the size specifier becomes necessary because the assembler doesn't know how large the data item is otherwise. For example, consider the following code in nasm assembly:
        section  .bss
num     resb     4

        ...
        section  .text
        ...
        mov    [num], 0

This will generate an error:
 error: operation size not specified

So you need to specify the size, say, 4-bytes:
        mov    [num], dword 0

A: They are exactly the same thing, it's just assembler syntax.
As a side note, xor eax, eax is generally preferred since it generates a two byte instruction which is much smaller.


text:
Q: What does it mean that a laplacian of directed graph has full rank? Suppose we have a directed graph $G=(V, E)$ with $N=|V|$ nodes.
Define normalized graph laplacian as $L=I-AD^{-1}$ where $A$ is a adjacency matrix of $G$ and $D$ is a degree matrix of $G$.
I'm interested in solving $Lx=b$ with nonsymmetric LAMG method, called NS-LAMG.
NS-LAMG requires right null-space vector $v$ by solving $Lv=0$.
However, there exist a inverse of $L$ if $L$ is a full-ranked, which means $v=0$.
Therefore, it's impossible to solve the full-rank graph laplacian with NS-LAMG.
So I was wondering, what does it mean that a laplacian of directed graph has full rank?
[EDIT]:
suppose we have graph $G$ like below,

so we have $$
    A =\left [ \begin{matrix}
    0 & 1 & 1 & 0 \\
    0 & 0 & 1 & 0 \\
    0 & 0 & 0 & 0 \\
    1 & 1 & 0 & 0 \\
   \end{matrix} \right ],
D =\left [ \begin{matrix}
    3 & 0 & 0 & 0 \\
    0 & 3 & 0 & 0 \\
    0 & 0 & 2 & 0 \\
    0 & 0 & 0 & 2 \\
   \end{matrix} \right ]
$$
then $$
L = I - AD^{-1} =
\left [ \begin{matrix}
    1 & -\frac{1}{3} & -\frac{1}{2} & 0 \\
    0 & 1 & -\frac{1}{2} & 0 \\
    0 & 0 & 1 & 0 \\
    -\frac{1}{3} & -\frac{1}{3} & 0 & 1 \\
   \end{matrix} \right ]
$$ and $rank(L)=4$

A: The rank of the (normalized) Laplacian is never full, because the vector $(1,...,1)$ is always an eigenvector associated with eigenvalue $0$ (which however solves your initial problem). See e.g.  wikipedia.
For an interpretation of the multiplicity of eigenvalue $0$ you can look at this question


text:
Q: function is not defined when using $.mobile.changepage I want to execute initialize() function on page load, but by simple  didn't work when page is called from other page by using $.mobile.changePage.
I've tried this, but it works fine only when i type the url of the page directly in the browser, not with redirecting.
FireBug: initialize is not defined

Skopje info guide

test

The function initialize() is in  part, and popTable() is in another .js file

A: Sounds like function initialize() is not in the calling page.  You either want the calling page to have the function definition, or include the function definition inside the data-role=page div


text:
Q: Getting the parent of a directory in Bash If I have a file path such as...
/home/smith/Desktop/Test
/home/smith/Desktop/Test/

How do I change the string so it will be the parent directory?
e.g.
/home/smith/Desktop
/home/smith/Desktop/

A: If /home/smith/Desktop/Test/../ is what you want:
dirname 'path/to/child/dir'

as seen here.

A: dir=/home/smith/Desktop/Test
parentdir="$(dirname "$dir")"

Works if there is a trailing slash, too.

A: Depending on whether you need absolute paths you may want to take an extra step:
child='/home/smith/Desktop/Test/'
parent=$(dirname "$child")
abs_parent=$(realpath "$parent")

A: Clearly the parent directory is given by simply appending the dot-dot filename:
/home/smith/Desktop/Test/..     # unresolved path

But you must want the resolved path (an absolute path without any dot-dot path components):
/home/smith/Desktop             # resolved path

The problem with the top answers that use dirname, is that they don't work when you enter a path with dot-dots:
$ dir=~/Library/../Desktop/../..
$ parentdir="$(dirname "$dir")"
$ echo $parentdir
/Users/username/Library/../Desktop/..   # not fully resolved

This is more powerful:
dir=/home/smith/Desktop/Test
parentdir=$(builtin cd $dir; pwd)

You can feed it /home/smith/Desktop/Test/.., but also more complex paths like:
$ dir=~/Library/../Desktop/../..
$ parentdir=$(builtin cd $dir; pwd)
$ echo $parentdir
/Users                                  # the fully resolved path!

NOTE: use of builtin ensures no user defined function variant of cd is called, but rather the default utility form which has no output.

A: Just use echo $(cd ../ && pwd) while working in the directory whose parent dir you want to find out. This chain also has the added benefit of not having trailing slashes.

A: ...but what is "seen here" is broken. Here's the fix:
> pwd
/home/me
> x='Om Namah Shivaya'
> mkdir "$x" && cd "$x"
/home/me/Om Namah Shivaya
> parentdir="$(dirname "$(pwd)")"
> echo $parentdir
/home/me

A: Motivation for another answer
I like very short, clear, guaranteed code.  Bonus point if it does not run an external program, since the day you need to process a huge number of entries, it will be noticeably faster.
Principle
Not sure about what guarantees you have and want, so offering anyway.
If you have guarantees you can do it with very short code. The idea is to use bash text substitution feature to cut the last slash and whatever follows.
Answer from simple to more complex cases of the original question.
If path is guaranteed to end without any slash (in and out)
P=/home/smith/Desktop/Test ; echo "${P%/*}"
/home/smith/Desktop

If path is guaranteed to end with exactly one slash (in and out)
P=/home/smith/Desktop/Test/ ; echo "${P%/*/}/"
/home/smith/Desktop/

If input path may end with zero or one slash (not more) and you want output path to end without slash
for P in \
    /home/smith/Desktop/Test \
    /home/smith/Desktop/Test/
do
    P_ENDNOSLASH="${P%/}" ; echo "${P_ENDNOSLASH%/*}"
done

/home/smith/Desktop
/home/smith/Desktop

If input path may have many extraneous slashes and you want output path to end without slash
for P in \
    /home/smith/Desktop/Test \
    /home/smith/Desktop/Test/ \
    /home/smith///Desktop////Test//
do
    P_NODUPSLASH="${P//\/*(\/)/\/}"
    P_ENDNOSLASH="${P_NODUPSLASH%%/}"
    echo "${P_ENDNOSLASH%/*}";
done

/home/smith/Desktop
/home/smith/Desktop
/home/smith/Desktop

A: If you need just the name of parent directory:
parent_dir_name=$(basename $(dirname $PWD))

A: use this : export MYVAR="$(dirname "$(dirname "$(dirname "$(dirname $PWD)")")")" if you want 4th parent directory
export MYVAR="$(dirname "$(dirname "$(dirname $PWD)")")"
if you want 3rd parent directory
export MYVAR="$(dirname "$(dirname $PWD)")"
if you want 2nd parent directory

A: ugly but efficient
function Parentdir()

{
local lookFor_ parent_ switch_ i_

lookFor_="$1"

#if it is not a file, we need the grand parent
[ -f "$lookFor_" ] || switch_="/.."

#length of search string
i_="${#lookFor_}"

#remove string one by one until it make sens for the system
while [ "$i_" -ge 0 ] && [ ! -d "${lookFor_:0:$i_}" ];
do
    let i_--
done

#get real path
parent_="$(realpath "${lookFor_:0:$i_}$switch_")"

#done
echo "
lookFor_: $1
{lookFor_:0:$i_}: ${lookFor_:0:$i_}
realpath {lookFor_:0:$i_}: $(realpath ${lookFor_:0:$i_})
parent_: $parent_
"

}
    lookFor_: /home/Om Namah Shivaya
{lookFor_:0:6}: /home/
realpath {lookFor_:0:6}: /home
parent_: /home

lookFor_: /var/log
{lookFor_:0:8}: /var/log
realpath {lookFor_:0:8}: /UNIONFS/var/log
parent_: /UNIONFS/var

lookFor_: /var/log/
{lookFor_:0:9}: /var/log/
realpath {lookFor_:0:9}: /UNIONFS/var/log
parent_: /UNIONFS/var

lookFor_: /tmp//res.log/..
{lookFor_:0:6}: /tmp//
realpath {lookFor_:0:6}: /tmp
parent_: /

lookFor_: /media/sdc8/../sdc8/Debian_Master//a
{lookFor_:0:35}: /media/sdc8/../sdc8/Debian_Master//
realpath {lookFor_:0:35}: /media/sdc8/Debian_Master
parent_: /media/sdc8

lookFor_: /media/sdc8//Debian_Master/../Debian_Master/a
{lookFor_:0:44}: /media/sdc8//Debian_Master/../Debian_Master/
realpath {lookFor_:0:44}: /media/sdc8/Debian_Master
parent_: /media/sdc8

lookFor_: /media/sdc8/Debian_Master/../Debian_Master/For_Debian
{lookFor_:0:53}: /media/sdc8/Debian_Master/../Debian_Master/For_Debian
realpath {lookFor_:0:53}: /media/sdc8/Debian_Master/For_Debian
parent_: /media/sdc8/Debian_Master

lookFor_: /tmp/../res.log
{lookFor_:0:8}: /tmp/../
realpath {lookFor_:0:8}: /
parent_: /

A: Started from the idea/comment Charles Duffy - Dec 17 '14 at 5:32 on the topic Get current directory name (without full path) in a Bash script
#!/bin/bash
#INFO : https://stackoverflow.com/questions/1371261/get-current-directory-name-without-full-path-in-a-bash-script
# comment : by Charles Duffy - Dec 17 '14 at 5:32
# at the beginning :

declare -a dirName[]

function getDirNames(){
dirNr="$(  IFS=/ read -r -a dirs <<<"${dirTree}"; printf '%s\n' "$((${#dirs[@]} - 1))"  )"

for(( cnt=0 ; cnt < ${dirNr} ; cnt++))
  do
      dirName[$cnt]="$( IFS=/ read -r -a dirs <<<"$PWD"; printf '%s\n' "${dirs[${#dirs[@]} - $(( $cnt+1))]}"  )"
      #information – feedback
      echo "$cnt :  ${dirName[$cnt]}"
  done
}

dirTree=$PWD;
getDirNames;

A: if for whatever reason you are interested in navigating up a specific number of directories you could also do: nth_path=$(cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && cd ../../../ && pwd). This would give 3 parents directories up

A: This would go up to the parent folder
cd ../


text:
Q: How To Get Page Public Content Access? Ok I've been having a hard time getting approved for page public content access.
I'm developing a facebook app that let's you search for facebook pages.
https://www.youtube.com/watch?v=Gc-Ah_To-xg
Sort of like this.
Here are my questions:

*

*How do I get approved for PPCA when I can't make a screencast of the app in action without actually having PPCA?

*Is it possible to search for pages without PPCA?

*Will hardcoding work?


text:
Q: Pandas - Convert object to string and then to int I have the following data frame.

What I am trying to do is

*

*Convert this object to a string and then to a numeric

I have looked at using the astype function (string) and then again to int. What I would like to get is the data type to be
df['a'] = df['a'].astype(string).astype(int).

I have tried other variations. What I have been trying to do is get the column values to become a number(obviously without the columns). It is just that the data type is an object initially.

Thanks so much!

A: You need to remove all the ,:
df['a'] = df['a'].str.replace(',', '').astype(int)

With both columns, you can do:
df[['a','b']] = df[['a','b']].replace(',', '', regex=True).astype('int')


text:
Q: col disappear when small the screen using bootstrap I have a problem with these 3 cards....when it's a large screen they fit perfect but when small the screen one of the col disappears and does not fit into the page:
-I tried to give height when it's mobile size but still the same problem.
Live Page preview:https://melad99.github.io/3-Column-Preview-Card/

A: The first col has the col-sm-3 class on it and the other 2 have col-sm as their class, thats why they are behaving differently


text:
Q: Kafka Streams 2.5.0 requires input topic Starting with Kafka Streams 2.5.0 it seems like a topology must include an input topic. In Kafka 2.4.1 (and earlier) that is not the case.
I have an application where the topology is just creating a few global state stores that read in data from topics written to by other applications.
With Kafka 2.5.0 I get this error:
13:24:27.161 [<redacted>-7cf1b5c9-4a6e-4bf2-9f77-f7f85f2df3bb-StreamThread-1] ERROR o.a.k.s.p.internals.StreamThread - stream-thread [<redacted>-7cf1b5c9-4a6e-4bf2-9f77-f7f85f2df3bb-StreamThread-1] Encountered the following error during processing:
java.lang.IllegalStateException: Consumer is not subscribed to any topics or assigned any partitions
    at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1228)
    at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:1216)
    at org.apache.kafka.streams.processor.internals.StreamThread.pollRequests(StreamThread.java:853)
    at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:753)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:697)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:670)

If I add a dummy input topic (e.g. via streamsBuilder.stream(Pattern.compile("hack"));) the application starts fine.
Is this behavior to be expected or is it an unintentional change in Kafka Streams 2.5.0?
More details: The use case above may seem a bit weird and I would have to agree. The reason for doing it in the first place was a shortcoming of Interactive Queries where for periods of time the application could not answer queries. I see that issue has been fixed in Kafka Streans 2.5.0 via KIP-535 which is great. I hope to look into IQ again later.

A: If you don't have any non-global parts of your topology, there's no reason to have any StreamThreads at all. Meaning you can easily work around this by just setting num.threads to zero -- arguably, you should be doing this anyways to avoid unnecessary overhead and group coordination. Setting this to zero by default when a global-only topology is detected is the "fix" anyway, so you don't need to wait for that

A: There was a regression introduced in 2.5.0 when we switched (back) to using collection subscription. A fix was just merged, so you should upgrade to 2.5.1 or 2.6 when they are released.

A: private void subscribeConsumer() {
    if (builder.usesPatternSubscription()) {
        // this is old behaviour - is there a config that will revert to this??
        consumer.subscribe(builder.sourceTopicPattern(), rebalanceListener);
    } else {
        consumer.subscribe(builder.sourceTopicCollection(), rebalanceListener);
    }
}


text:
Q: What is the proper way of changing current UIViewController without a memory leak in MonoTouch? I have a base UINavigationController class ( xib-less code ) using the singleton pattern with the fallowing code
[MonoTouch.Foundation.Register("NavController")]
public class NavController : UINavigationController
{
    public static NavController Instance = new NavController();

    public void ChangePage( UIViewController sender, UIViewController page, double duration )
    {
       this.PopViewControllerAnimated(true);
       this.PushViewController( page, false );
       //
       SetViewControllers( new UIViewController[]{ page }, false );
       if( sender != null )
       {
          sender.View.RemoveFromSuperview();
          sender = null;
       }
       GC.Collect();
    }
}

And also i have 4 UIWebController classes with this structure
[Register("HomePage")]
public class AViewPage : UIViewController
{
    UIButton    btn = new UIButton( new RectangleF( 0,0, 100, 100) );
    UIImageView img = new UIImageView( new RectangleF( 100, 100, 200, 200 );
    //and a lot of other widgets

    public override void ViewDidLoad ()
    {
         base.ViewDidLoad ();
         //
         btn.TouchUpInside += delegate{
             AnotherViewPage page = new AnotherViewPage();
             NavController.Instance.ChangePage( this, page,  1 );
         }
     //
     this.View.AddSubview( btn );
     this.View.AddSubview( img );
    }

}

My problem is that with current code, memory is leaking.  What am I doing wrong?

*

*Should i override the Dispose(bool) and manually dispose everything on the UIWebController classes ?

*I also have a lot of UIImages and UIImageViews on this UIViewControllers, what is the proper way of disposing them ?

*I have the feeling that the ChangePage function code is ugly.  Help me with a better example please.

A: A fix is coming in the MonoTouch 4.1 beta release, a temporary workaround is this:
Replace this line:
      sender.View.RemoveFromSuperview();

With:
      var super = sender.View.Superview;
      sender.View.RemoveFromSuperview ();
      var scratch = super.Subviews;

The correct fix in the next release will just work.  Apologies for that.

A: Ok, stupid question from the beginning.
If you run in to the same problem, just read a little about PushViewController, PopViewControllerAnimated, ViewDidAppear, ViewDidDisappear and ViewDidLoad.


text:
Q: Split the string in to center I want to split this string: Sun Apr 12 17:56:00 GMT+05:00 2015. I only get 17:56.
I tried this:
String[] splitStr = str.split("\\s+");

A: You could do it by String as well as parsing the date:
By String you can do it like:
String str = "Sun Apr 12 17:56:00 GMT+05:00 2015";
String time = str.split(" ")[3];
System.out.println(time.substring(0, time.lastIndexOf(':')));

By dateFormat you could use the pattern to parse the date and then get hour and minutes from it like with pattern below:
String str = "Sun Apr 12 17:56:00 GMT+05:00 2015";
SimpleDateFormat df = new SimpleDateFormat("EEE MMM d HH:mm:ss zzz yyyy");

A: you can try something like:
DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date result =  df.parse(target);

then to work with date use:
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.get(Calendar.HOUR_OF_DAY);


text:
Q: php sql doesnt recognise my variable and doesnt delete from data base I am having trouble with my php file and my sql statement. I want to delete the user I have selected from a drop list. I have tried everything and doesnt delete from the db. please help me
main.php
<!DOCTYPE html>

<html>
<head>

</head>
<body>
 <?php
   $link = mysql_connect("localhost","root","");
     mysql_select_db("pruebas", $link);

     /* El query valida si el usuario ingresado existe en la base de datos. Se utiliza la función
     htmlentities para evitar inyecciones SQL. */
     $myusuario = mysql_query("select nombre from usuarios");
     $nmyusuario = mysql_num_rows($myusuario);

//Como ya se dijo anteriormente la variable $conexion esta definida
//en el archivo 'conexion_mysqli.php'

?>

<form method="post" name="lista_form" action="delete.php">

<select name="lista">
    <?php
    while ( $row = mysql_fetch_array($myusuario) )
    {
        ?>

        <option value=" <?php echo $row['nombre'] ?> " >
        <?php echo $row['nombre']; ?>
        </option>

        <?php
    }
    ?>
</select>
<input type="submit" value="SEND">
</form>

</body>

</html>

delete.php
<?php
     /* A continuación, realizamos la conexión con nuestra base de datos en MySQL */
     echo $_POST["lista"];
     $my_post=mysql_escape_string($_POST["lista"]);
     echo $my_post;
     $link = mysql_connect("localhost","root","");
     mysql_select_db("pruebas", $link);

     /* El query valida si el usuario ingresado existe en la base de datos. Se utiliza la función
     htmlentities para evitar inyecciones SQL. */
 $sql=mysql_query("DELETE FROM usuarios WHERE nombre = '$my_post'", $link);

if($sql !=  0)
   {
    echo 'You DELETE';

   }
else
   {
    echo 'Your not in';
   }
          ?>

A: It would seem this is your problem:
<option value=" <?php echo $row['nombre'] ?> " >
               ^ here                       ^ and here

You are adding spaces around the string that comes from your database.
Apart from that you are not escaping your string for output to html so that could break your html and logic as well if the value contained a " character.
You should change it to something like:
<option value="<?php echo htmlspecialchars($row['nombre']); ?>" >

Also note that mysql_escape_string has been deprecated since php 4.3 (!) and all other mysql_* functions are now deprecated as well.


text: Q: Monitoring UUIDs of MariaDB servers in Galera cluster I want to be able to monitor the UUIDS of several MariaDB servers on a regular basis to make sure that they haven't somehow been removed from the cluster. I have a command that I run to retrieve it locally: mysql -umaria -e "SHOW GLOBAL STATUS LIKE 'wsrep_cluster_state_uuid'". I would like to be able to run this remotely somehow from one of the servers in the cluster that can compare its UUID to those of the rest of the servers. Unfortunately, I can't simply connect via remote shell so I need it to use commands found on the server already. The servers are all running RHEL 7 x64.


text:
Q: Searching Active Directory for Members of Specific Group Fails When User Has No Group the following code is supposed to run through all users in active directory and find everyone in a specific group. Once it gets the users, it will add them to a datatable which will be the source of a gridview for a final export to Excel.
However, while running and stepping through, I've noticed it gets stopped on a certain user with no group. I tried adding a conditional statement to skip that instance, but it isn't working, the code still stops running when it finds the user with no group.
Can someone show me what I could be doing differently?
Caveat: This is from a legacy site that I inherited, knowing very little about active directory and being a novice vb coder.
Dim entry As DirectoryEntry = New DirectoryEntry("LDAP://DOMAIN.EDU", "USERNAME", "PASSWORD", AuthenticationTypes.Secure)
    Dim search As DirectorySearcher = New DirectorySearcher(entry) With {
        .Filter = "(&(objectCategory=User)(objectClass=person))",
        .PageSize = 4000
    }
    search.PropertiesToLoad.Add("userPrincipalName").ToString
    search.PropertiesToLoad.Add("name").ToString
    Dim mySearchResultColl As SearchResultCollection = search.FindAll
    Dim results As DataTable = New DataTable
    results.Columns.Add("User ID")
    results.Columns.Add("Full Name")
    Dim CurrRow = 0

    For Each sr As SearchResult In mySearchResultColl

        Dim dr As DataRow = results.NewRow
        Dim de As DirectoryEntry = sr.GetDirectoryEntry
        !!!! line below is the problem !!!!
        If de.Properties("memberOf") IsNot Nothing AndAlso de.Properties("memberOf").Value.ToString = "CN=MYGROUP,OU=Security Groups,OU=Students,DC=DOMAIN,DC=edu" Then
            dr("User ID") = de.Properties("userPrincipalName").Value
            dr("Full Name") = de.Properties("name").Value
            results.Rows.Add(dr)
            de.Close
        End If
    Next

    gvNot.DataSource = results
    gvNot.DataBind()
    gvNot.Visible = True
    gvAgreed.Visible = False
    ExportToExcel("notagreed", gvNot)

A: I'm not sure what you mean by "gets stopped", but you can change this up so it performs better and fixes any issues you have.

*

*This loop will take forever since you have to inspect every user on the domain. If you only want users in a specific group, then you can speed this up by only asking for members of the group. You do that by adding a condition in the query for the memberOf attribute. This way, you only get results you care about.

(Note that if you have more than one domain in your forest, using memberOf to find members may not work the way you want. I wrote about that here. But if you only have one domain, then it'll be fine.)

*In the loop, don't create a DirectoryEntry for each result, since that will force it to go back out to AD and request the attributes for the object again, even though you already got what you needed in the search results. So use the values in the SearchResult object instead.

*The documentation for SearchResultCollection says:

Due to implementation restrictions, the SearchResultCollection class cannot release all of its unmanaged resources when it is garbage collected. To prevent a memory leak, you must call the Dispose method when the SearchResultCollection object is no longer needed.

So you should put that in a Using clause.

*I'm also not sure why you're calling ToString on PropertiesToLoad.Add when you're not using the return value. You can just remove that.

Here it is all together:
Dim entry As DirectoryEntry = New DirectoryEntry("LDAP://DOMAIN.EDU", "USERNAME", "PASSWORD", AuthenticationTypes.Secure)
Dim search As DirectorySearcher = New DirectorySearcher(entry) With {
    .Filter = "(&(objectCategory=User)(objectClass=person)(memberOf=CN=MYGROUP,OU=Security Groups,OU=Students,DC=DOMAIN,DC=edu))",
    .PageSize = 4000
}
search.PropertiesToLoad.Add("userPrincipalName")
search.PropertiesToLoad.Add("name")

Dim results As DataTable = New DataTable
results.Columns.Add("User ID")
results.Columns.Add("Full Name")
Dim CurrRow = 0

Using mySearchResultColl As SearchResultCollection = search.FindAll
    For Each sr As SearchResult In mySearchResultColl

        Dim dr As DataRow = results.NewRow
        dr("User ID") = sr.Properties("userPrincipalName")(0)
        dr("Full Name") = sr.Properties("name")(0)
        results.Rows.Add(dr)
    Next
End Using

gvNot.DataSource = results
gvNot.DataBind()
gvNot.Visible = True
gvAgreed.Visible = False
ExportToExcel("notagreed", gvNot)

I don't see you using CurrRow anywhere, but I left it in case you're using it in other code you didn't show here.

A: Try using String.Equals function with StringComparer.OrdinalIgnoreCase parameter instead of using equals operator.
Also what's the error you are getting?


text:
Q: Using SQL Server to get centroid of three circles intersecting I've been a long time GIS person but have recently been working in spatial side of SQL Server. I'm using SQL Server 2016 Express.
I'd like to get centroid of the polygon that is the intersection of these three circles. The Intersection should be a very small polygon (30 feet across or so).  However, my intersection creates a huge polygon.
Obviously I am doing something wrong.  Is that not how intersection works?
CREATE TABLE #myTable
(
    [Latitude] dec(15,10),
    [Longitude] dec(15,10),
    Dist dec(15,10),
    ID varchar(4),
    myGeog geography,
    MyBuff geography
)

INSERT INTO #myTable
VALUES (36.808838,  -119.792923, 347.2867998,'zX0', NULL,NULL),
       (36.145789,  -120.359316, 388.3265656,'zX1', NULL,NULL),
       (31.333473,  -110.867344, 1351.14404,'zX2', NULL,NULL)

UPDATE mt
SET myGeog = geography::Point(Latitude, Longitude, 4326)
FROM #myTable mt

UPDATE mt
SET MyBuff = myGeog.STBuffer(Dist*1000)
FROM #myTable mt

DECLARE @myB1 geography
DECLARE @myB2 geography
DECLARE @myB3 geography

SET @myB1 = (SELECT MyBuff FROM #myTable WHERE ID = 'zX0')
SET @myB2 = (SELECT MyBuff FROM #myTable WHERE ID = 'zX1')
SET @myB3 = (SELECT MyBuff FROM #myTable WHERE ID = 'zX2')

SELECT  @myB1.STIntersection(@myB2.STIntersection(@myB3))
SELECT @myB1.STIntersection(@myB2.STIntersection(@myB3)).ToString()

DROP TABLE #myTable

A: Your result is correct. If you just run:
SELECT MyBuff FROM #myTable;

And look at the 3 polygons it draws together and the result of your intersection, you will see that it is truly the intersection.  I think it may just be that it zooms in and blows up the scale of your intersection results.


text:
Q: Pre-launch-report failures due to missing methods (in com.google.android.apps.mtaas.crawler-1/base.apk) Since recently my app started to contain strange error messages in the pre-launch reports (automatically generated after upload to the Play store).
These reports contain exceptions such as the following:
Exception java.lang.NoSuchMethodError: No interface method a(Landroid/arch/lifecycle/e;Landroid/arch/lifecycle/b$a;)V in class Landroid/arch/lifecycle/GenericLifecycleObserver; or its super classes (declaration of 'android.arch.lifecycle.GenericLifecycleObserver' appears in /data/app/com.google.android.apps.mtaas.crawler-1/base.apk)
android.arch.lifecycle.f$a.a (f.java:326)
android.arch.lifecycle.f.a (f.java:159)
com.firebase.ui.database.FirebaseRecyclerAdapter.<init> (FirebaseRecyclerAdapter.java:40)

And:
Exception java.lang.NoSuchMethodError: No static method a(Landroid/app/Activity;)V in class Landroid/arch/lifecycle/ReportFragment; or its super classes (declaration of 'android.arch.lifecycle.ReportFragment' appears in /data/app/com.google.android.apps.mtaas.crawler-1/base.apk)
android.arch.lifecycle.LifecycleDispatcher$DispatcherActivityCallback.onActivityCreated (LifecycleDispatcher.java:77)
android.app.Application.dispatchActivityCreated (Application.java:219)
android.app.Activity.onCreate (Activity.java:1040)
android.support.v4.app.SupportActivity.onCreate (SupportActivity.java:66)
android.support.v4.app.FragmentActivity.onCreate (FragmentActivity.java:285)
android.support.v7.app.AppCompatActivity.onCreate (AppCompatActivity.java:84)

And:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int android.arch.core.internal.SafeIterableMap.size()' on a null object reference
    at android.arch.lifecycle.LifecycleRegistry.getObserverCount(LifecycleRegistry.java:204)
    at android.arch.lifecycle.ProcessLifecycleOwner.b(ProcessLifecycleOwner.java:154)
    at android.arch.lifecycle.ProcessLifecycleOwner.a(ProcessLifecycleOwner.java:100)
    at android.arch.lifecycle.LifecycleRuntimeTrojanProvider.onCreate(LifecycleRuntimeTrojanProvider.java:36)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:1751)
    at android.content.ContentProvider.attachInfo(ContentProvider.java:1726)
    at android.app.ActivityThread.installProvider(ActivityThread.java:6031)
    ... 10 more

The strange thing is that my released app seems to be running fine on real devices (the exceptions appear only during the pre-launch tests).
I tried to revert all (major) changes performed since the last build in which I had no pre-launch problem: from API 26 back to API 27, older version of the support libs, no D8 etc., but no success so far: of the 9 tests being performed only 1 or 2 succeed, the rest fails with this type of errors.
What can I do to solve this?

A: Just got an answer from Google Play developer support. They are looking into the problem.
As a workaround you can go back to the previous version of the crawler by opting out of the newly released one.
Here's how to opt-out:

*

*Sign in to your Play Console.

*Select an app.

*Select Release
management > Pre-launch report > Settings. In the "Pre-launch report
version" section, move the Opt-out switch to the right until it turns
blue.

After this, the launch reports appear correctly again.
PS - This will disable the default tests done by the Google Play and you might miss any other errors from other cause. Hence, be sure to implement your own tests before releasing into production.

A: The Gson error was caused by a regression. The issue has been fixed. It should work as expected after the fix is released in a day or two.


text:
Q: Kernel panic - not syncing: unable to mount root fs on unknown-block(0,0) after building a kernel without initramfs While trying to install KISS Linux (a distribution which doesn't use (or at least doesn't by default) an initramfs), a distribution that requires you to build your own kernel, I always get the same kernel panic message, no matter what configuration I try. I tried enabling all the right device drivers for my SATA/SCSI/ATA controllers to no avail. I'm still unsure if the problem is my GRUB configuration or my kernel configuration, or some mix of both.
I found a post here saying that to find the root device without an initramfs, you have to use PARTUUID for the root kernel parameter, like this:
root=PARTUUID=SSSSSSSS-PP. I tried that (along with several different kernel configurations), but nothing seems to work. No matter what I did nothing about the kernel panic message would change, and the logs would be the exact same.
[~] λ lspci
00:00.0 Host bridge: Advanced Micro Devices, Inc. [AMD] RS780 Host Bridge
00:02.0 PCI bridge: Advanced Micro Devices, Inc. [AMD] RS780 PCI to PCI bridge (ext gfx port 0)
00:05.0 PCI bridge: Advanced Micro Devices, Inc. [AMD] RS780/RS880 PCI to PCI bridge (PCIE port 1)
00:06.0 PCI bridge: Advanced Micro Devices, Inc. [AMD] RS780 PCI to PCI bridge (PCIE port 2)
00:07.0 PCI bridge: Advanced Micro Devices, Inc. [AMD] RS780/RS880 PCI to PCI bridge (PCIE port 3)
00:11.0 SATA controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 SATA Controller [IDE mode]
00:12.0 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB OHCI0 Controller
00:12.1 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0 USB OHCI1 Controller
00:12.2 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB EHCI Controller
00:13.0 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB OHCI0 Controller
00:13.1 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0 USB OHCI1 Controller
00:13.2 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB EHCI Controller
00:14.0 SMBus: Advanced Micro Devices, Inc. [AMD/ATI] SBx00 SMBus Controller (rev 3c)
00:14.1 IDE interface: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 IDE Controller
00:14.2 Audio device: Advanced Micro Devices, Inc. [AMD/ATI] SBx00 Azalia (Intel HDA)
00:14.3 ISA bridge: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 LPC host controller
00:14.4 PCI bridge: Advanced Micro Devices, Inc. [AMD/ATI] SBx00 PCI to PCI Bridge
00:14.5 USB controller: Advanced Micro Devices, Inc. [AMD/ATI] SB7x0/SB8x0/SB9x0 USB OHCI2 Controller
00:18.0 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 15h Processor Function 0
00:18.1 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 15h Processor Function 1
00:18.2 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 15h Processor Function 2
00:18.3 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 15h Processor Function 3
00:18.4 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 15h Processor Function 4
00:18.5 Host bridge: Advanced Micro Devices, Inc. [AMD] Family 15h Processor Function 5
01:00.0 VGA compatible controller: NVIDIA Corporation GP106 [GeForce GTX 1060 3GB] (rev a1)
01:00.1 Audio device: NVIDIA Corporation GP106 High Definition Audio Controller (rev a1)
02:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168/8411 PCI Express Gigabit Ethernet Controller (rev 06)
03:00.0 USB controller: Renesas Technology Corp. uPD720201 USB 3.0 Host Controller (rev 03)
04:00.0 SATA controller: ASMedia Technology Inc. ASM1062 Serial ATA Controller (rev 02)

[~] λ sudo lsblk
NAME   MAJ:MIN RM   SIZE RO TYPE MOUNTPOINT
sda      8:0    0 111.8G  0 disk
├─sda1   8:1    0    50M  0 part
├─sda2   8:2    0 111.3G  0 part
└─sda3   8:3    0   499M  0 part
sdb      8:16   0 931.5G  0 disk
└─sdb1   8:17   0 931.5G  0 part /
sdc      8:32   0 931.5G  0 disk
├─sdc1   8:33   0 443.2G  0 part /home/void/hdd1
├─sdc2   8:34   0   250G  0 part
└─sdc3   8:35   0 238.3G  0 part /mnt/kiss
sdd      8:48   0 931.5G  0 disk
└─sdd1   8:49   0 931.5G  0 part


text:
Q: Running Edge in headless mode is not working I have been unable to run Edge in headless mode using Selenium with VBA in Excel - would someone be able to help me out with this? I can use the exact same code below using the ChromeDriver and it works as expected (i.e. - browser is hidden).
Here is a snippet of the code I am using...
sURL = "http://www.google.com"
Dim obj As Selenium.EdgeDriver
Set obj = New Selenium.EdgeDriver
obj.AddArgument "--headless"   <-- the code runs fine but the Edge Brower is still visible
obj.Start
'Open URL in Edge Browser

obj.Get sURL
Thanks -
Jen

A: Dim obj As Selenium.EdgeDriver Set obj = New Selenium.EdgeDriver

obj.SetCapability "ms:edgeOptions", _ "{" & _ """args"":[""headless""]" & _ "}"

obj.Start

'https://gist.github.com/yas78/2a563995fde04c48260cebfe3aae371b


text:
Q: how to get a string from split line and compare in python I have a line after split like in here:
lineaftersplit=Jan 31 00:57:07 2012 GMT

How do I get only year 2012 from this and compare if it falls between (2010) and (2013)

A: If lineaftersplit is a string value, you can use the datetime module to parse out the information, including the year:
import datetime

parsed_date = datetime.datetime.strptime(lineaftersplit, '%b %d %H:%M:%S %Y %Z')

if 2010 <= parsed_date.year <= 2013:
    # year between 2010 and 2013.

This has the advantage that you can do further tests on the datetime object, including sorting and date arithmetic.
Demo:
>>> import datetime
>>> lineaftersplit="Jan 31 00:57:07 2012 GMT"
>>> parsed_date = datetime.datetime.strptime(lineaftersplit, '%b %d %H:%M:%S %Y %Z')
>>> parsed_date
datetime.datetime(2012, 1, 31, 0, 57, 7)
>>> parsed_date.year
2012

A: You can use str.rsplit:
>>> strs = 'Jan 31 00:57:07 2012 GMT'

str.rstrip will return a list like this:
>>> strs.rsplit(None,2)
['Jan 31 00:57:07', '2012', 'GMT']

Now we need the second item:
>>> year = strs.rsplit(None,2)[1]
>>> year
'2012'
>>> if 2010 <= int(year) <= 2013:  #apply int() to get the integer value
...     #do something
...

A: Try this:
st="Jan 31 00:57:07 2012 GMT".split()
year=int(st[3])

This actually works if the string is always of this format

A:  str='Jan 31 00:57:07 2012 GMT'
 str.split()[3]


text:
Q: add  tag dynamically using javascript or jquery index.html

testing Ist part http://www.youtube.com/watch?v=aqveRU1eAmA testing 2nd part

I want to add an  tag for "testing 2nd part" dynamically using java-script or iquery.
Is it possible.

A: Looks like you want to wrap text:  http://jsfiddle.net/h9rxq/
$('p').contents().filter(function(){
    return this.nodeType === 3;
}).wrap(function(){
    return $('', {href: "anyURL"});
});

A: A solution in jQuery using split and join to find the text testing 2nd part in all
 tags and replace them with testing 2nd part
$("p:contains('testing 2nd part')").html(function(_, html) {
   return html.split('testing 2nd part').join("testing 2nd part");
});

In your question you do not have a starting
 tag add it like so:

  testing Ist part
  http://www.youtube.com/watch?v=aqveRU1eAmA
 testing 2nd part


text:
Q: Why does encoding wav file to base64 with python and online webapp give different results? I am making a simple web app that needs to play a some audio files, using howler.js. howler.js accepts base64 URI as input, so I wanted to try that out. To test it, I took a sample audio file and used an online audio-to-base64 encoder to get the base64 URI. I added the data description ("data:audio/wav;base64,") the front of the base64 string and copy and pasted into the following JS function...:
function playSound() {
    var data = "";
    var sound = new Howl({
      src: [data],
      loop: false
    });
    sound.play();
}

...and it worked perfectly. Since I would be dealing with a fair number of audio files, I figured I'd use a short python script to convert them all to the base64. To test, I converted the same audio to a base64 string with the following python code:
import base64
with open("0.wav", "rb") as f1,open("b64.txt", "w") as f2:
    encoded_f1 = base64.b64encode(f1.read())
    f2.write("data:audio/wav;base64,")
    f2.write(str(encoded_f1))

I noticed the base64 string was different front the one I got from the website earlier. I pasted this into the JS function shown earlier, but when I attempt to play the sound, I get the following error:
Uncaught DOMException: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

There seems to be some sort of difference in the way python is encoding to base64. What could the cause for this be?

A: Came back to this after a while and the problem became apparent. It was just a problem with the block of code I mentioned in OP (the second block) that I used to write the base64 encoding to a file.
base64.b64encode(f1.read()) returns a bit string, which in Python, is symbolized with the following notation (i.e. when you print/write it, you'll see it like this): b'string goes here'. So the issue was just that the b' ' was wrapped around my actual base64 string, and I was using that. All I had to do get rid of the b' ' which I did by converting the bitstring to ASCII like this: str(encoded_f1,'ascii', 'ignore').
Really silly mistake, but hopefully it helps someone out.


text:
Q: Is 576 bytes the safe size for UDP payload to eliminate fragmentation? The safe size of a datagram packet (considering the MTU such that packet will not get fragmented) is said to be 576 bytes for IPV4 and 1500 for IPV6.

*

*Is this correct ?

*If i am having a connection from my machine to a server in another country, two of which communicate using UDP, what is the maximum (safest) payload size i should have for the UDP packet, 1500 or 576 ?
Thank you

A: *

*No. That's the safe size of the total IP packet.

*534.

A: I found the real IP address in my local network. Then, I used recommendations at "www dot asus dot com/support/FAQ/1007914" in order to "check the best value of MTU(Maximum Transmission Unit) for the internet".


text:
Q: RetroFit passing base url as variable I have created a flutter web application using retrofit for consuming API. I am stuck with the issue of passing baseUrl as a variable to Retrofit which takes only const value. Base URL is different for different Environments.
final String apiDomain = globalWebApiUrl;
@RestApi(baseUrl: apiDomain);

This is throwing error:
Arguments of a constant creation must be constant expressions.

A: You can change class declaration by following.
@RestApi()
abstract class ApiService {
    factory ApiService({required Dio dio}) => _ApiService(dio);
}

// Use api service:

final String apiDomain = globalWebApiUrl;

final service = ApiService(dio: Dio(BaseOptions(baseUrl: apiDomain)));


text:
Q: Hadoop FTPFileSystem fails to list files and throws SocketTimeOutException I am using Apache Hadoop FTPFileSystem version 3.2.0 to list and read files from an FTP Server.
Here is my test code:
public static void main(String[] args) throws IOException {
    String host = "some-host";
    int port = 21;
    Configuration conf = new Configuration(false);
    conf.set("fs.ftp.host", host);
    conf.setInt("fs.ftp.host.port", port);
    conf.set("fs.ftp.user." + host, "username");
    conf.set("fs.ftp.password." + host, "password");
    conf.set("fs.ftp.data.connection.mode", "PASSIVE_LOCAL_DATA_CONNECTION_MODE");
    conf.set("fs.ftp.impl", "org.apache.hadoop.fs.ftp.FTPFileSystem");

    String fsURL = String.format("ftp://%s:%s", host, String.valueOf(port));
    conf.set("fs.default.name", fsURL);
    FileSystem fs =  FileSystem.newInstance(conf);
    Path somePath = new Path("actual/path");
    fs.getFileStatus(somePath).isDirectory(); // returns true
    fs.listStatus(somePath); // keeps spinning then throws SocketTimeOutException
}

After some debugging the deadlock or the delay happens at this method org.apache.commons.net.ftp.FTPClient.initiateListParsing(FTPFileEntryParser, String) at this method execution: engine.readServerList(socket.getInputStream(), getControlEncoding()); as below:
private FTPListParseEngine initiateListParsing(
        FTPFileEntryParser parser, String pathname)
throws IOException
{
    Socket socket = _openDataConnection_(FTPCmd.LIST, getListArguments(pathname));

    FTPListParseEngine engine = new FTPListParseEngine(parser, __configuration);
    if (socket == null)
    {
        return engine;
    }

    try {
        engine.readServerList(socket.getInputStream(), getControlEncoding());
    }
    finally {
        Util.closeQuietly(socket);
    }

    completePendingCommand();
    return engine;
}

The method call keeps blocked until it finally throws a socketTimeoutException, even-though using FileZilla with same credentials and properties I can list & read files smoothly and in a much faster time.
The credentials I am using and properties are correct as the initial connection and fs.getFileStatus(somePath).isDirectory(); call works and return correct value.
Is there a property I can add to make things faster or is it a bug in apache hadoop FTPFileSystem version 3.2.0?

A: You may need to change the transfer and/or connection mode to one of the following

conf.set("fs.ftp.transfer.mode", "COMPRESSED_TRANSFER_MODE");
// OR
conf.set("fs.ftp.transfer.mode", "STREAM_TRANSFER_MODE");

// AND

conf.set("fs.ftp.data.connection.mode", "PASSIVE_LOCAL_DATA_CONNECTION_MODE");
// OR
conf.set("fs.ftp.data.connection.mode", "PASSIVE_REMOTE_DATA_CONNECTION_MODE");


text:
Q: Running multiple PHP scripts at the same time (database loop issue) I am running 10 PHP scripts at the same time and it processing at the background on Linux.
For Example:
while ($i <=10) {
 exec("/usr/bin/php-cli run-process.php > /dev/null 2>&1 & echo $!");
 sleep(10);
 $i++;
}

In the run-process.php, I am having problem with database loop. One of the process might already updated the status field to 1, it seem other php script processes is not seeing it. For Example:
$SQL = "SELECT * FROM data WHERE status = 0";
$query = $db->prepare($SQL);
$query->execute();

while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
    $SQL2 = "SELECT status from data WHERE number = " . $row['number'];
    $qCheckAgain = $db->prepare($SQL2);
    $qCheckAgain->execute();
    $tempRow = $qCheckAgain->fetch(PDO::FETCH_ASSOC);

    //already updated from other processs?
    if ($tempRow['status'] == 1) {
        continue;
    }

    doCheck($row)
    sleep(2)
}

How do I ensure processes is not re-doing same data again?

A: When you have multiple processes, you need to have each process take "ownership" of a certain set of records. Usually you do this by doing an update with a limit clause, then selecting the records that were just "owned" by the script.
For example, have a field that specifies if the record is available for processing (i.e. a value of 0 means it is available). Then your update would set the value of the field to the scripts process ID, or some other unique number to the process. Then you select on the process ID. When your done processing, you can set it to a "finished" number, like 1. Update, Select, Update, repeat.

A: The reason why your script executeds the same query multiple times is because of the parallelisation you are creating. Process 1 reads from the database, Process 2 reads from the database and both start to process their data.
Databases provide transactions in order to get rid of such race conditions. Have a look at what PDO provides for handling database transactions.

A: i am not entirely sure of how/what you are processing.
You can introduce limit clause and pass that as a parameter. So first process does first 10, the second does the next 10 and so on.

A: you need lock such as "SELECT ... FOR UPDATE".
innodb support row level lock.
see http://dev.mysql.com/doc/refman/5.0/en/innodb-locking-reads.html for details.


text:
Q: How to hide status bar and navigation bar in flutter when user clicks on screen or open keyboard? I have a flutter app that is fullscreen  .
but the problem is when user touches screen the Top Status Bar appears , or When user touches a textfield  , the Bottom Status Bar and Top Status Bar appears .
How can i prevent this problem  .
Here is My Code For Make Flutter App fullscreen :
await SystemChrome.setPreferredOrientations(
      [DeviceOrientation.landscapeRight]);
await SystemChrome.setEnabledSystemUIOverlays([]);

A: Output:

I'm not sure where are you using that call. Here is minimum code reproduction.
void main() => runApp(MaterialApp(home: HomePage()));

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
    SystemChrome.setEnabledSystemUIOverlays([]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Full screen")),
      body: SizedBox.expand(child: FlutterLogo()),
    );
  }
}

A: For Textfield the solution I settled with is to return the user to Full Screen mode (i.e. hide status & navigation) when the Textfield losses focus...
class _SomeWidget extends State<SomeWidget> {

    FocusNode _focus = new FocusNode();

    void _onFocusChange(){
        SystemChrome.setEnabledSystemUIOverlays([]); // hide status + action buttons
    }

    @override
    void initState() {
        super.initState();
        _focus.addListener(_onFocusChange);
    }

   @override
   Widget build(BuildContext context) {

       return TextField(
           focusNode: _focus,
           ...
           );
    }
}


text:
Q: Can the existence of geodesics be deduced from properties of the Laplacian? As I understand it, the semiclassical trace formula in particular relates lengths of geodesics to eigenvalues of the Laplacian.

Is it possible to prove that every compact Riemannian manifold has a closed geodesic using some property of the Laplacian (or ideas otherwise around the semiclassical trace formula)?

Of course, it is a classical result that geodesics exist, but the only proof I know uses Morse theory on the free loop space of the manifold, plus some algebraic topology to argue that the free loop space has more homology than the original manifold.


text:
Q: How to implement TabHost with the ability to use multiple activities under a tab? As the title says, I want to know how to implement TabHost with the ability to switch between activities under a tab.Simple example would be to have two tabs(tab1 & tab2) with a button under tab1. when this button is clicked, a text appears.
(activity switch)
A google search suggested using GroupActivities, but upon further searching I came to know that this is deprecated.
So would appreciate any help in this matter.

A: you can find more help here...
http://www.vogella.com/code/ApiDemos/src/com/example/android/apis/app/FragmentTabsFragment.html


text:
Q: grpc make can't find protoc 3 I installed grpc-java according to the instructions on my Mac (running Mavericks). This included installing protobuf v3.0.0-alpha-2, which I did:
$ which protoc
/usr/local/bin/protoc

$ /usr/local/bin/protoc --version
libprotoc 3.0.0

The Java examples work fine. Now I'd like to try the C++ examples and, ideally, have a C++ client talk to a Java server and visa-versa.
I cloned grpc and attempted to install it. sudo make install and, subsequently, make verify-install fail, telling me that protobuf 3 is not installed:
$ make verify-install
We couldn't find protoc 3.0.0+ installed on your system. While this
won't prevent grpc from working, you won't be able to compile
and run any meaningful code with it.

Please download and install protobuf 3.0.0+ from:

   https://github.com/google/protobuf/releases

Once you've done so, or if you think this message is in error,
you can re-run this check by doing:

   make verify-install

On line 259 of grpc/Makefile, I see this test:
PROTOC_CHECK_CMD = protoc --version | grep -q libprotoc.3

If I run protoc --version on my Mac, I see something different (see above), so I tried changing the line above to
PROTOC_CHECK_CMD = protoc --version | grep -q 'libprotoc 3.0.0'

However I get the same error from make verify-install.
I'e also tried removing the PROTOBUF_CHECK_CMD and PROTOC_CHECK_CMD tests at run_dep_checks (about line #895) but install still fails with the same error.
When I run make on grpc-common/cpp/helloworld, it builds, but greeter_client and greeter_server both fail:
$ ./greeter_server
E0310 17:38:23.349841000 140735186797328 server.c:617] assertion failed: grpc_is_initialized() && "call grpc_init()"
Abort trap: 6

I assume because the problem with installing grpc.
So, protobuf 3 is clearly installed. How can I convince the Makefile of that, or at least bypass that test?

A: The message you are seeing about protoc does not indicate that make failed. It is just a warning. You successfully installed gRPC and successfully built the hello world example.
The example does not work on Mac due to a bug in gRPC that is currently being investigated in this GitHub issue.

A: The problem is that sudo make install installed the protoc under /usr/local/bin but grpc looks under /usr/bin.
Try to configure protobuf using:
./configure --prefix=/usr

This will install the protoc binary in a place that grpc is expecting it. When you do sudo make install on grpc then sudo will find protoc properly.
You can verify that sudo sees it with this command:
sudo which protoc
sudo sh -c 'echo $PATH'

Note that sudo echo $PATH does not tell you where sudo's path is.


text:
Q: How do I access the Azure function present in one subscription into another subscription? I have two subscriptions in the Azure Portal.
One is for development and the other is for production.
I want to shift the logic apps created within development subscription to production subscription.
I have in total 5 logic apps. There is a main logic app and other four are sub logic apps.
I also have an Azure function within the development subscription.
Now, as far as I know, to deploy the main logic app to the production subscription, the production subscription should also have access to the Azure function present in the development subscription. However, currently I want to deploy only the logic apps to the production subscription and not the Azure function.
While I deploy the main logic app, I get an error as the Azure function is not accessed by the production subscription.
Can anyone help me with the issue?
I want to know, how do I provide access to production subscription to access the Azure function present in the development subscription without actually deploying the function to PROD.


text:
Q: Is finding the closure of a space a method of the completion of a metric space? Suppose we have a metric space $(X,d)$. I wonder whether finding the closure of it is the completion of the metric space?
My thinking
I do know the defination of the completion of a metric space. It seems it's more general and complex than just find the closure. But why we need such a complex defination if clusure can make the space complete?

A: Consider $(0,1) \cap \mathbb{Q}$. Its closure in $\mathbb{Q}$ is $[0,1] \cap \mathbb{Q}$, but this space is not complete. Its completion would be $[0,1]$, as a subset of real numbers.
Similarly, $\mathbb{Q}$, $(0,1)$, an open ball in any metric space, etc. are closed in themselves, but are not equal to their completion. Recall that a space $Y \subset X$ is closed in $X$ if the complement $X \backslash Y$ is open. If $Y=X$, then this complement is the empty set, and the empty set is certainly open.


text:
Q: Is this change of variable correct? Take the following function:
$$\frac{dn}{d[\log(x)]} = a\exp{\frac{-(\log(x) - b)^2}{c}}$$
I'm interested in obtaining the form for $dn/dx$, so I take:
$$\frac{d[\log(x)]}{dx} = \frac{1}{x} \rightarrow d[\log(x)] = \frac{dx}{x}$$
I use this in the first Eq. to obtain:
$$\frac{dn}{d[\log(x)]} = \frac{dn}{dx} x$$
which  means:
$$\frac{dn}{dx} = \frac{1}{x} a\exp{\frac{-(\log(x) - b)^2}{c}}$$
Is this correct? I feel like I'm missing something.

A: $\frac{dn}{dx} = \frac{1}{x} a\exp{\frac{-(\log(x) - b)^2}{c}}\ \ $ is correct.
But it doesn't give the solution of the equation $\frac{dn}{d[\log(x)]} = a\exp{\frac{-(\log(x) - b)^2}{c}}$.
Better, change of variable $X=\log(x)$ which leads to $dn = a\exp{\frac{-(X - b)^2}{c}}dX$.
The antiderivative is : $n=\frac{a\sqrt{\pi c}}{2}\text{erf}(\frac{X-b}{\sqrt c})+constant$
$$n=\frac{a\sqrt{\pi c}}{2}\text{erf}(\frac{e^x-b}{\sqrt c})+constant$$


text:
Q: ActiveJDBC has SQLSyntaxErrorException Using ActiveJDBC, I've been manually opening and closing connections, inserting and reading anything, all with no errors like this:
public class DatabaseLoader {

    private static final Logger logger = LogManager.getLogger(DatabaseLoader.class);

    public static void openConnection() {
        Base.open("com.mysql.cj.jdbc.Driver", ConfigManager.getAddress(), ConfigManager.getUsername(), ConfigManager.getPassword());
    }

    public static void openConnectionIfClosed() {

        if (!Base.hasConnection()) {
            logger.info("Connecting to database!");
            openConnection();
        }
    }

    public static void closeConnectionIfOpen() {
        if (Base.hasConnection()) {
            logger.info("Disconnecting from database!");
            Base.close();
        }
    }
}

However, I have recently attempted to add C3P0 and connection pool, following https://github.com/javalite/javalite/blob/master/activejdbc/src/test/java/org/javalite/activejdbc/C3P0PoolTest.java as closely as possible. The new code looks like this:
public class DatabaseLoader {

    private static final Logger logger = LogManager.getLogger(DatabaseLoader.class);

    static DataSource dataSourceUnpooled;
    static DataSource dataSourcePooled;

    static {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            dataSourceUnpooled = DataSources.unpooledDataSource(ConfigManager.getAddress(), ConfigManager.getUsername(), ConfigManager.getPassword());
            dataSourcePooled = DataSources.pooledDataSource(dataSourceUnpooled); //init the connection pool
        } catch (SQLException | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void openConnection() {
        Base.open(dataSourcePooled);
    }

    public static void openConnectionIfClosed() {
        if (!Base.hasConnection()) {
            openConnection();
        }
    }

    public static void closeConnectionIfOpen() {
        if (Base.hasConnection()) {
            logger.info("Disconnecting from database!");
            Base.close();
        }
    }
}

Using this code, initial connection to the database appears successful and all is well, until I insert something. For example, like this:
// ServerMessage is an activejdbc model that has worked to insert things 31k times before adding C3P0

ServerMessage message = ServerMessage.findOrCreateIt("message_id_snowflake", messageIdSnowflake, "server_id", serverId, "user_id", userId);

Whenever I do insert something, I now get this error:
org.javalite.activejdbc.DBException: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '::BIGINT,19::INT,1772::INT)' at line 1, query: INSERT INTO server_messages (message_id_snowflake, server_id, user_id) VALUES (?::BIGINT,?::INT,?::INT), params: 928224895626793001, 19, 1772
        at org.javalite.activejdbc.DB.execInsert(DB.java:734)
        at org.javalite.activejdbc.Model.insert(Model.java:2741)
        at org.javalite.activejdbc.Model.save(Model.java:2673)
        at org.javalite.activejdbc.Model.saveIt(Model.java:2597)
        at org.javalite.activejdbc.ModelDelegate.createIt(ModelDelegate.java:146)
        at org.javalite.activejdbc.ModelDelegate.findOrCreateIt(ModelDelegate.java:438)
        at org.javalite.activejdbc.ModelDelegate.findOrCreateIt(ModelDelegate.java:412)
        at dev.laarryy.eris.models.guilds.ServerMessage.findOrCreateIt(ServerMessage.java:219)
        at dev.laarryy.eris.listeners.MessageCreateListener.on(MessageCreateListener.java:49)
        ... 21 more
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '::BIGINT,19::INT,1772::INT)' at line 1
        at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
        at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:953)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1092)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1040)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1348)
        at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1025)
        at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeUpdate(NewProxyPreparedStatement.java:1502)
        at org.javalite.activejdbc.DB.execInsert(DB.java:713)
        ... 29 more

This seems strange to me, since the bigint, int, and int that are supposed to be inserted are indeed a bigint, int and int as required, and I don't know what else I might do to find the cause of the error. The C3P0 line at the second to last line of the stacktrace makes me think that the statement as prepared by ActiveJDBC is somehow not the statement making it to the database.
I have also already tried enabling the C3P0 statement cache, in case that had an effect, but it did not.
Any advice or guidance would be appreciated!
Update
I have now also attempted to follow the quick-start procedure here https://www.mchange.com/projects/c3p0/#quickstart in the hopes that manually setting the driver class might resolve the issue, however it does not. I still get the same stacktrace. The code I tried:
public class DatabaseLoader {

    private static final Logger logger = LogManager.getLogger(DatabaseLoader.class);

    static ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();

    static {
        try {
           comboPooledDataSource.setDriverClass("com.mysql.cj.jdbc.Driver");
            comboPooledDataSource.setJdbcUrl(ConfigManager.getAddress());
            comboPooledDataSource.setUser(ConfigManager.getUsername());
            comboPooledDataSource.setPassword(ConfigManager.getPassword());
        } catch (PropertyVetoException e) {
            e.printStackTrace();
        }
    }

    public static void openConnection() {
        Base.open(comboPooledDataSource);
    }

    public static void openConnectionIfClosed() {
        if (!Base.hasConnection()) {
            openConnection();
        }
    }

    public static void closeConnectionIfOpen() {
        if (Base.hasConnection()) {
            logger.info("Disconnecting from database!");
            Base.close();
        }
    }
}

I have also attempted switching to Hikari version 5, and I get precisely the same error except the second-to-last line is from Hikari instead of c3p0. This leads me to believe something is wrong on the ActiveJDBC end rather than the connection pooling end.
Requested Details:

*

*Java Version 17.0.1 (Corretto)

*ActiveJDBC Version 3.0-SNAPSHOT

*MySQL Version 8.0.26

*mysql-connector-java version 8.0.26 (Driver.getMajorVersion() returns 8 and #getMinorVersion() returns 0 as expected, as well)

*C3P0 Version 0.9.5.5

A: Unfortunately, there was a defective snapshot published for a few hours. That snapshot v 3.0-SNAPSHOT had a bug where PostgreSQL syntax was accidentally made default for MySQL. It seems that it caused a problem for you. The JDBC connection pool has nothing to do with this. We are careful with snapshots,  but things like this happens (once in a few years). You got unlucky by getting right in the middle of the update.
How to fix this is to blow away all your Maven  caches:
rm -rf ~/.m2/repository/org/javalite

On the next build, you will get a new (vastly improved :)) snapshot that is free from this defect.
Sorry about the trouble, but snapshots are "work in progress".
Related bug: https://github.com/javalite/javalite/issues/1187


text:
Q: Why symfony can't find template it rendered in other function I have a function in my controller like this:
<?php

namespace GradeBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use GradeBundle\Entity\User;
use GradeBundle\Entity\SchoolClass;

class MainController extends Controller
{
/**
* @Route("/", name="index_page")
*/
public function index()
{

  return $this->render('GradeBundle:Default:index.html.twig');

}

It renders the twig template correctly. However when I use other function:
  /**
    * @Route("/adminNew", name="add_admin")
    */

    public function addAdmin()
    {
       $session = new Session();

      if($session->get('loggedIn') == null)
         return $this->redirect($this->generateUrl('index_page'));
      else
        return $this->render('GradeBundle:Add:newAdmin.html.twig');

    }

I have the following error:
Unable to find template "GradeBundle:Default:index.twig.html".

Does anybody have any idea what might be wrong?

A: Have you made sure to use the correct namespace for the Controller you're using? And are you including the correct files? Also I'm not sure I understand the question correctly - are you saying if you add another function with a different twig file render, the first one no longer renders? Could I see your class names and the namespaces / use statements?
Usually in these instances, it's that the templates are in the wrong place or the correct file is not included in order to find it.
Michael

A: It's a typo somewhere you call template:
GradeBundle:Default:index.twig.html

But you have only GradeBundle:Default:index.html.twig template.
Note the difference: html.twig twig.html
I suspect that you extend it in GradeBundle:Add:newAdmin.html.twig by:
{% extends 'GradeBundle:Default:index.twig.html' %}

but should be:
{% extends 'GradeBundle:Default:index.html.twig' %}


text:
Q: Как заставить читать бота, читать беседу? Давным давно, делал бота, на модуле vk_api. Делал без каких-либо LongPoll, CallBack. Но в связи, изменение политики VK, пришлось делать на нём.
Начал с простого, решил попробовать сделать группу, как бота. Написал код. Код - работает. Когда пишу боту, всё отвечает. Именно в ЛС сообщества. Но решил сделать для беседы. Добавил бота, предоставил всё что нужно. Но.. Почему то не работает.
Подскажите, что не так.
Код:
import vk_api
from vk_api.longpoll import VkLongPoll, VkEventType
from samp_client.client import SampClient

token = 'd25778e160a0beaac30bdbae********************************************b58ac0bf7'
vk = vk_api.VkApi(token=token)
longpoll = VkLongPoll(vk)

def write_msg(user_id, message):
    vk.method('messages.send', {'user_id': user_id, 'message': message})

with SampClient(address='185.169.134.68', port=7777, rcon_password='password') as client:
    info = client.get_server_info()

for event in longpoll.listen():
    if event.type == VkEventType.MESSAGE_NEW:
        if event.from_chat:
            request = event.text
            if request == "!evolve02":
                write_msg(event.chat_id, 'Информация о сервере: Evolve 02: ' + '\n\nНазвание: ' + str(info.hostname) + '\nИгроки: ' + str(info.players))
            if request == "тест":
                write_msg(event.chat_id, '+')

A: Это из-за VkLongPoll. В документации указано, что это модуль для пользователей. Так как Вы авторизуетесь с ключом сообщества, Вам требуется VkBotLongPoll. Обратите внимание, что он в другом модуле, а именно в vk_api.bot_longpoll.VkBotLongPoll
Вот пример рабочего бота:
from random import random
from vk_api import VkApi
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType

vk_session = VkApi(token="[Ваш токен]")
longpoll = VkBotLongPoll(vk_session, "[id сообщества]")
vk = vk_session.get_api()

for event in longpoll.listen():
    if event.type == VkBotEventType.MESSAGE_NEW and event.from_chat:
        random_id = round(random() * 10 ** 9)
        chat_id = int(event.chat_id)
        message = "[Ваш ответ]"

        vk.messages.send(
            random_id=random_id,
            chat_id=chat_id,
            message=message,
        )

UPD:
Не забывайте про права. Если не упомянуть бота, то он просто не увидит Ваши сообщения. Ещё можно дать доступ ко всей переписке или сделать его администратором.
UPD 2:
Вот готовый бот специально для Вас <3 (вставьте токен, id сообщества и rcon_password):
from random import random
from vk_api import VkApi
from vk_api.bot_longpoll import VkBotLongPoll, VkBotEventType
from samp_client.client import SampClient

with SampClient(address='185.169.134.68', port=7777, rcon_password='[Ваш пароль]') as client:
    info = client.get_server_info()

vk_session = VkApi(token='[Ваш токен]')
longpoll = VkBotLongPoll(vk_session, "[id сообщества]")
vk = vk_session.get_api()

def write_msg(chat_id, message):
    random_id = round(random() * 10 ** 9)

    vk.messages.send(
            random_id=random_id,
            chat_id=chat_id,
            message=message,
        )

for event in longpoll.listen():
    if event.type == VkBotEventType.MESSAGE_NEW and event.from_chat:

        request = event.object.get('text')
        chat_id = event.chat_id

        if request == "!evolve02":
            write_msg(chat_id, 'Информация о сервере: Evolve 02: ' + '\n\nНазвание: ' + str(info.hostname) + '\nИгроки: ' + str(info.players))
        if request == "тест":
            write_msg(chat_id, '+')


text:
Q: Weird bug in trial code This is some code I have been working on for a simple pub style quiz to learn Java. For some reason it will ask the question the first time and then will just skip past it from then on. It also declares the strings null even though I initialize them.
Here is the code
    public class PubQuizWMethod
    {
        private static Scanner keyboard = new Scanner (System.in);
        static String a1,a2,a3,a4;
        static String b1,b2,b3,b4;
        static String c1,c2,c3,c4;
        static String d1,d2,d3,d4;
        static String ans1,ans2,ans3,ans4;
        static String q1,q2,q3,q4;
        static String question;
        static boolean newQuiz = true;
        static boolean notStop = true;
        static char correctAnswer;
        static char answer1,answer2,answer3,answer4;
        static char answer;
        static int score = 0;

public static void mainMenu()
{
    {
        {
            do{
                gettingQuestion();
                question = q1;

                gettingAnswers();
                ans1 = a1;
                ans2 = b1;
                ans3 = c1;
                ans4 = d1;

                gettingCorrectAnswer();
                answer1 = correctAnswer;

                gettingQuestion();
                question = q2;

                gettingAnswers();
                ans1 = a2;
                ans2 = b2;
                ans3 = c2;
                ans4 = d2;

                gettingCorrectAnswer();
                answer2 = correctAnswer;

                gettingQuestion();
                question = q3;

                gettingAnswers();
                ans1 = a3;
                ans2 = b3;
                ans3 = c3;
                ans4 = d3;

                gettingCorrectAnswer();
                answer3 = correctAnswer;

                gettingQuestion();
                question = q4;
                ans1 = a4;
                ans2 = b4;
                ans3 = c4;
                ans4 = d4;

                gettingCorrectAnswer();
                answer4 = correctAnswer;

                if(notStop == true)
                {
                    score = 0;

                    System.out.println(q1);

                    System.out.println("a: " +a1);
                    System.out.println("b: " +b1);
                    System.out.println("c: " +c1);
                    System.out.println("d: " +d1);

                    answer = keyboard.next().charAt(0);

                    if(answer == answer1)
                    {
                        System.out.println("That was correct");
                        score ++;
                    }
                    else
                    {
                        System.out.println("That was incorrect");
                    }

                    System.out.println(q2);

                    System.out.println("a: " +a2);
                    System.out.println("b: " +b2);
                    System.out.println("c: " +c2);
                    System.out.println("d: " +d2);

                    answer = keyboard.next().charAt(0);

                    if(answer == answer2)
                    {
                        System.out.println("That was correct");
                        score ++;
                    }
                    else
                    {
                        System.out.println("That was incorrect");
                    }

                    System.out.println(q3);

                    System.out.println("a: " +a3);
                    System.out.println("b: " +b3);
                    System.out.println("c: " +c3);
                    System.out.println("d: " +d3);

                    answer = keyboard.next().charAt(0);

                    if(answer == answer3)
                    {
                        System.out.println("That was correct");
                        score ++;
                    }
                    else
                    {
                        System.out.println("That was incorrect");
                    }

                    System.out.println(q4);

                    System.out.println("a: " +a4);
                    System.out.println("b: " +b4);
                    System.out.println("c: " +c4);
                    System.out.println("d: " +d4);

                    answer = keyboard.next().charAt(0);

                    if(answer == answer4)
                    {
                        System.out.println("That was correct");
                        score ++;
                    }
                    else
                    {
                        System.out.println("That was incorrect");
                    }

                    System.out.println("You achieved a score of " +score +" out of 4");
                    System.out.println("Would you like to play again?  y/n ");
                    char yn = keyboard.next().charAt(0);

                    if(yn == 'y')
                    {
                        notStop = true;
                    }
                    else
                    {
                        notStop = false;
                    }
                }
                System.out.println("Would you like to make a new quiz? y/n");
                char yn = keyboard.next().charAt(0);
                if(yn == 'y')
                {
                    newQuiz = true;
                }
                else
                {
                    newQuiz = false;
                }

            }while(newQuiz = true);
        }
    }
}

public static void gettingQuestion()
{
    System.out.println("Please enter the question");
    question = keyboard.nextLine();
}//getting the questions

public static void gettingAnswers()
{
    System.out.println("Please enter in the four answers each on its own line.");
    ans1 = keyboard.nextLine();
    ans2 = keyboard.nextLine();
    ans3 = keyboard.nextLine();
    ans4 = keyboard.nextLine();

}

public static void gettingCorrectAnswer()
{
    System.out.println("Please enter the correct answer. a/b/c/d");
    correctAnswer = keyboard.next().charAt(0);
}

public static void main(String[] args)
{
    mainMenu();

}

}

and the result is this:

Please enter the question
ahsdf
Please enter in the four answers each on its own line.
adsfh
adsfh
asdfh
asdfh
Please enter the correct answer. a/b/c/d
a
Please enter the question
Please enter in the four answers each on its own line.
asdf
asdfh
asdfh
asdfh
Please enter the correct answer. a/b/c/d
a
Please enter the question
Please enter in the four answers each on its own line.
asdfh
asdfh
asdfh
adsfh
Please enter the correct answer. a/b/c/d
asdfh
Please enter the question
Please enter the correct answer. a/b/c/d
asdfh
null
a: null
b: null
c: null
d: null
a
That was correct
null
a: null
b: null
c: null
d: null
a
That was correct
null
a: null
b: null
c: null
d: null
a
That was correct
null
a: null
b: null
c: null
d: null
a
That was correct
You achieved a score of 4 out of 4
Would you like to play again?  y/n
y
Would you like to make a new quiz? y/n
n
Please enter the question
Please enter in the four answers each on its own line.

etc.

A: Classic mistake: Using == to compare Strings instead of equals.  It's not a bug; it's you and your code.

A: I have pasted some of your code to explain what is happening. We start here:
public static void mainMenu()
{
    {
        {
            do{
                gettingQuestion();
                question = q1;

In the line below you are reading from keyboard and loading all values in ans1, ans2, ans3 and ans4 variables.
                gettingAnswers();

Everything is ok, but when you do the following:
                ans1 = a1;
                ans2 = b1;
                ans3 = c1;
                ans4 = d1;

You are overwriting the ans1, ans2, ans3 and ans4 values, that's why you have null values.
As an extra note you can handle arrays or objects to keep your code with more order, it could be like this
public class Question{

private String realAnswer
private String question;
private String[] fakeAnswers = new String[4];

public Question(String realAnswer, String question, String [] fakeAnswers){
    this.realAnswer = realAnswer;
    this.question = question;
    this.fakeAnswers = fakeAnswers;
}

/*
   Some getters and setters
*/

}

Then you can create a main class that contains something like this:
public static void main(String[] args){

// Number 10 is the quantity of questions that your quiz will have
Question[] question = new Question[10];

/*
More code
*/

}

A: You are assigning null to question here.
gettingQuestion();
question = q1;    // q1 is null.

// Here question and q1 both are null and hence it is printing null in the answer.
Hence the output is printing null.
Also change the while condition.

A: next() doesn't handle the end of the line. So when you call nextLine() again, it'll take as input the enter (\n) you entered before. So it's "skipping" the actual input and swallows the \n from the previous input that was missed by next(). You have two solutions:

*

*Call another nextLine() before the real nextLine() (So it will swallow the \n).

*Get rid of next and replace it with nextLine().

Another thing:
The expression of the assignment returns the assigned value, look at this:
while(newQuiz = true);

What iside the while loop will be always true.
Also please note that it's redundant to write if(variable == true), it's enough to write if(variable).


text:
Q: Getting ''Missing SOI marker.' from JpegDecoderr I'm running into issues opening a jpg file. Here is the code I started with:
var image = await Image.LoadAsync("sample.jpg")

This produced the exception:
An exception of type 'SixLabors.ImageSharp.UnknownImageFormatException' occurred in System.Private.CoreLib.dll but was not handled in user code
Image cannot be loaded. Available decoders:
 - PNG : PngDecoder
 - GIF : GifDecoder
 - BMP : BmpDecoder
 - TGA : TgaDecoder
 - JPEG : JpegDecoder

To determine why the file wasn't recognized as jpeg, I used the following code:
using (var stream = File.OpenRead("sample.jpg"))
{
   var jpegDecoder = new JpegDecoder();

   jpegDecoder.Decode(Configuration.Default, stream);
}

That gave me the following exception:
An unhandled exception of type 'SixLabors.ImageSharp.InvalidImageContentException' occurred in SixLabors.ImageSharp.dll
Missing SOI marker.

I'm inclined to believe that the image involved has an issue, but I'm able to view it in windows photo viewer and in Google Chrome. How do I determine what is wrong with the file?
Edit:
Thanks to @user9938, I was able to determine that this is a RIFF or WEBPV8 file:

Is there a riff plugin for ImageSharp by any chance?

A: It looks like the ImageSharp folks have been toiling away at WebP support.
This issue does a great job of describing where the progress is at:
https://github.com/SixLabors/ImageSharp/issues/121

A: if Image.Load(imageStream) called with a fileStream but Position is not set to zero you can also get decoder not found kind of errors...
stream.Position = 0;

https://github.com/SixLabors/ImageSharp/issues/164#issuecomment-291784371


text:
Q: How should I properly block outgoing http traffic with iptables I'm experimenting with iptables, and I'm trying to allow all outgoing requests for HTTPS, but to block HTTP.
I have the code below;
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh
ACCEPT     udp  --  anywhere             anywhere             udp dpt:ssh
ACCEPT     udp  --  anywhere             anywhere             udp dpt:https
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
DROP       tcp  --  anywhere             anywhere
DROP       udp  --  anywhere             anywhere

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:ssh
ACCEPT     udp  --  anywhere             anywhere             udp dpt:https
ACCEPT     udp  --  anywhere             anywhere             udp dpt:ssh
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:https
DROP       tcp  --  anywhere             anywhere
DROP       udp  --  anywhere             anywhere

.

Apparently this blocks just about every webpage I try to browse, doesn't matter whether it's http://example.com or https://example.com
What do I not get? Many thanks for your help!

A: I think there's nothing wrong with those rules as far as HTTP and HTTPS go.  The problem is that you've also blocked DNS resolution, so no client can resolve a host in order to try an HTTPS connection thereto.
You have noted that adding NEW to the permitted states in line 1 of your OUTPUT chain allows DNS resolution - but it also allows everything else, including outbound HTTP; all the return-half packets are then permitted in by rule 1 of yourINPUT chain.  Instead, revert to the ruleset above and allow DNS explicitly with
iptables -I OUTPUT 2 -p udp --dport 53 -j ACCEPT

That should allow the DNS resolution of hosts to work, but continue to block attempts to connect to them via HTTP.  Note that the 404 you seek is a layer-4 (protocol layer) error, and you can't achieve that with a layer-3 tool like iptables.  Instead, outbound HTTP connections will simply time out, whereas HTTPS connections should succeed.


text:
Q: Convexity of complex quadratic form $x^*Ax$ It's well-known that $x \mapsto x^\top A x$ is a convex function of $x \in \mathbb R^n$ when the matrix $A$ is (real) positive semidefinite (PSD).  Is this still true when $x \in \mathbb C^n$ and $A$ is Hermitian PSD?  More precisely, is $x \mapsto x^*Ax$ a convex function of $x$ when we view $x$ as a variable in $\mathbb R^{2n}$, i.e., $$\left[\begin{array}{c} \mathrm{Re}(x)\\ \mathrm{Im}(x)\end{array}\right]?$$
EDITS 2023/2/16:
Thanks to user550103's comments below, the answer seems to be yes, and a simple proof may be:
Let $f(x)\triangleq x^*Ax=g(h(x))$, where $g(x)=\Vert x\Vert^2$ and $h(x)=\sqrt{A}x$.  Since $g$ is clearly convex, and $h$ is a linear transformation, it follows that $f=g\circ h$ is convex, whether we view $x$ as a variable in $\mathbb C^n$ or $\mathbb R^{2n}$, c.f. $g(h(ax+by))=g(ah(x)+bh(y))\le ag(h(x))+bg(h(y))$.
Please correct me if I'm mistaken somewhere above.


text:
Q: Problem with using time check with if statments - BASH I am currently checking a .sh script just to do some basic things.
chmod +x catbash.sh

echo 'Hello, Please Enter your User Name'
echo
read VarUserName

currenttime=$(date +%H:%M)
if [[ $currenttime > 11:59 ]] || [[ $currenttime < 12:00 ]];
    then echo 'Good Morning' $VarUserName'.'
        fi

if [[ $currenttime > 12:00 ]] || [[ $currenttime < 16:59 ]];
    then echo 'Good Afternoon' $VarUserName'.'
        fi

if [[ $currenttime > 17:00 ]] || [[ $currenttime < 19:59 ]];
    then echo 'Good Evening' $VarUserName'.'
        fi

if [[ $currenttime > 20:00 ]] || [[ $currenttime < 23:59 ]];
    then echo 'Good Night' $VarUserName'.'
        fi

My issue is that i am trying to use the systems current time to be used in a if statement and depending on the time for a different output.
right now the script outputs all all of the "good...." echos and does not output a single echo depending on the time.
thank you for the help.

A: The problem is with your conditions, all of them permit any given value, did you maybe want to use && instead of ||?

A: It would be much simpler if you would write it using the elif construction and start from the later times and work your way down.
chmod +x catbash.sh

currenttime=$(date +%H:%M)
if [[ "$currenttime" > "19:59" ]]; then echo "Good Night ${USER}"
elif [[ "$currenttime" > "16:59" ]]; then echo "Good Evening ${USER}"
elif [[ "$currenttime" > "11:59" ]]; then echo "Good Afternoon ${USER}"
elif [[ "$currenttime" > "05:59" ]]; then echo "Good Morning ${USER}"
else echo "Good Night ${USER}"


text:
Q: G/Setting JavaScript handler defined in FXML How can I programatically get and set the JavaScript onAction handler for a Button that is defined in FXML?
I have FXML defining a couple of Buttons and a Label
<?xml version="1.0" encoding="UTF-8"?>

<?language javascript?>
<?import javafx.scene.control.Button?>
<?import javafx.scene.control.Label?>
<?import javafx.scene.layout.AnchorPane?>

<AnchorPane id="AnchorPane" prefHeight="200" prefWidth="320" xmlns="http://javafx.com/javafx/8.0.65" xmlns:fx="http://javafx.com/fxml/1" fx:controller="javascriptfxmlapplication.FXMLDocumentController">
    <children>
        <Button fx:id="javaButton" layoutX="116.0" layoutY="50.0" mnemonicParsing="false" onAction="#handleButtonAction" text="Java Button" />
        <Button fx:id="javaScriptButton" layoutX="97.0" layoutY="90.0" onAction="label.setText('hi');" text="JavaScript Button" />
        <Label fx:id="label" layoutX="126" layoutY="120" minHeight="16" minWidth="100" />
    </children>
</AnchorPane>

One of the buttons has a Java handler defined in the Java controller for this FXML document, the other button has an inline handler defined as a JavaScript snippet.
The Java document handler is as follows:
package javascriptfxmlapplication;

import java.net.URL;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Button;
import javafx.scene.control.Label;

public class FXMLDocumentController implements Initializable {

    @FXML
    private Label label;
    @FXML
    private Button javaScriptButton, javaButton;

    @FXML
    private void handleButtonAction(ActionEvent event) {
        label.setText("Hello World!");
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
    }

}

All works well. But is it possible to dynamically get/set the JavaScript to be executed by the button?
As far as i can see the FXML loader creates a javafx.fxml.FXMLLoader$ScriptEventHandler for buttons defined in the FXML to have JavaScript handlers, but ScriptEventHandler is private and there is no obvious way to programatically get or set the JavaScript text.
My aim is to create a JavaScriptButton that extends Button. It has drag and drop event handlers such that you can drop some text (JavaScript) on the button and that JavaScript gets executed when the button is pressed. This I have implemented by explicitly creating a JavaScriptEngine and adding a Script property to my JavaScriptButton. It just seems a shame since much of this work must have already been done in core JavaFX.


text:
Q: Wordpress removing p tags when not logged in I have been struggling to understand why my text was changing size on a daily basis and have come to realise that wordpress is stripping the P tags out of the pages every time the_content() is used.
When I am logged in to wordpress and view the site everything is perfectly fine and the P tags appear which makes my fonts much nicer. However when logged out of wordpress all P tags are stripped. the_content() is not within any conditional statements it is completely alone in the code so I can't understand why this behaviour would happen.
If anyone has an any idea on this it would be appreciated.
Thanks

A: Use this useful Pluggin
After Installation:
Settings > TinyMCE Advanced > check the    Stop removing the P tag .....
Now, WordPress will not remove any paragraph tag.Hope this will help you