text:
Q: Countdown clock date formate is not working properly javascript

My code is in javascript,html . Date of setting is not working properly.
        settings.date is incorrect. i would happy if anyone can help.

>      // CountDown Clock
>     // Version   : 1.0.1
>     // Developer : Ekrem KAYA
>     // Website   : http://e-piksel.com
>     // GitHub    : https://github.com/epiksel/countdown

(function ($) {

    'use strict';
    $.fn.countdown = function (options, callback) {
        var settings = $.extend({
            date: 12/13/2018 12:00:00.,
            offset: null,
            day: 'Day',
            days: 'Days',
            hour: 'Hour',
            hours: 'Hours',
            minute: 'Minute',
            minutes: 'Minutes',
            second: 'Second',
            seconds: 'Seconds'
        }, options);

!settings.date == is not showing correctly.

        // Throw error if date is not set
        if (!settings.date) {
            $.error('Date is not defined.');
        }

        // Throw error if date is set incorectly
        if (!Date.parse(settings.date)) {
            $.error('Incorrect date format, it should look like this, 12/24/2012 12:00:00.');
        }

        // Save container
        var container = this;

/**
             * Change client's local date to match offset timezone
             * @return {Object} Fixed Date object.
             */

        var currentDate = function () {
            // get client's current date
            var date = new Date();

            // turn date to utc
            var utc = date.getTime() + (date.getTimezoneOffset() * 60000);

            // set new Date object
            var new_date = new Date(utc + (3600000 * settings.offset));

            return new_date;
        };

/**
             * Main countdown function that calculates everything
             */

        function countdown() {
        //    alert("countdown");
            var target_date = new Date(settings.date), // set target date
                current_date = currentDate(); // get fixed current date
// alert(current_date);
// console.log(target_date);
console.log(settings.date);
            // difference of dates
            var difference = target_date - current_date;

            // if difference is negative than it's pass the target date
            if (difference < 0) {
                // stop timer
                clearInterval(interval);

                if (callback && typeof callback === 'function') callback();

                return;
            }

            // basic math variables
            var _second = 1000,
                _minute = _second * 60,
                _hour = _minute * 60,
                _day = _hour * 24;

            // calculate dates
            var days = Math.floor(difference / _day),
                hours = Math.floor((difference % _day) / _hour),
                minutes = Math.floor((difference % _hour) / _minute),
                seconds = Math.floor((difference % _minute) / _second);

            // based on the date change the refrence wording
            var text_days = (days === 1) ? settings.day : settings.days,
                text_hours = (hours === 1) ? settings.hour : settings.hours,
                text_minutes = (minutes === 1) ? settings.minute : settings.minutes,
                text_seconds = (seconds === 1) ? settings.second : settings.seconds;

            // fix dates so that it will show two digets
            days = (String(days).length >= 2) ? days : '0' + days;
            hours = (String(hours).length >= 2) ? hours : '0' + hours;
            minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
            seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;
console.log(days,text_days);
            // set to DOM
            container.find('.days').text(days);
            container.find('.hours').text(hours);
            container.find('.minutes').text(minutes);
            container.find('.seconds').text(seconds);

            container.find('.days_text').text(text_days);
            container.find('.hours_text').text(text_hours);
            container.find('.minutes_text').text(text_minutes);
            container.find('.seconds_text').text(text_seconds);
        }

        // start
        var interval = setInterval(countdown, 1000);
    };

})(jQuery);

A:
I got my answer.I Just need to put this code in HTMl, I am able to set my date.

 <script class="source" type="text/javascript">

  var now = new Date();
  var day = now.getDate();
  var month = now.getMonth() + 1;
  var year = now.getFullYear() + 1;
  var nextyear = month + '/' + day + '/' + year + ' 07:07:07';
  $('#example').countdown({
   date: '12/13/2018 12:00:00' , // TODO Date format: 07/27/2017 17:00:00
   offset: +2, // TODO Your Timezone Offset
   day: 'Day',
   days: 'Days'
 }, function () {
    alert('Done!');
 });
</script>

<script class="source" type="text/javascript">
  var now = new Date();
  var day = now.getDate();
  var month = now.getMonth() + 1;
  var year = now.getFullYear() + 1;
  var nextyear = month + '/' + day + '/' + year + ' 07:07:07';
  $('.clock').countdown({
    date: '12/13/2018 12:00:00' ,  // TODO Date format: 07/27/2017 17:00:00
    offset: +2, // TODO Your Timezone Offset
    day: 'Day',
    days: 'Days'
  }, function () {
     alert('Done!');
  });
 </script>


text:
Q: Fatal: Syntax error, "." expected but ";" found program Hello;
var

a,b,c,x,d: integer;
x1,x2: real;

begin

readln(a,b,c);

if a = 0 then
begin
    if b = 0 then
    begin
        if c = 0 then
        begin
            writeln('11');
        end
        else
            writeln('21');
        end;
    end
    else
        writeln('31');
    end;
end
else
    d := b^2 - 4*a*c;

    if d < 0 then
    begin
        writeln('Нет Вещественных корней!');
    end
    else
        x1 := (-b + sqrt(d))/(2*a);
        x2 := (-b - sqrt(d))/(2*a);
        writeln('Первый Корень:' + x1 + ' ' + 'Второй Корень:' + x2);
    end;
end;
end.

A: The reason for this is that your begins and ends are not balanced;  disregarding the opening begin and closing end. for the program's syntax to be correct, you should have equal numbers of each, but you have 4 begins and 8 ends.
Obviously, your code is to compute the solutions of a quadratic equation.  What I think you should do is to adjust the layout of your code so that it reflects that and then correctly the begins and ends.  In particular, your program is trying to detect whether any of a, b and d is zero and, if so, write a diagnostic message, otherwise calculate the roots by the usual formula.
Unfortunately, your begins and ends do not reflect that. Either the whole of the block starting d := ... needs to be executed or none of it does, so the else on the line before needs to be followed by a begin, as in
  else begin
    d := b*b - 4*a*c;  //b^2 - 4*a*c;
    if d < 0 then begin
      writeln('Нет Вещественных корней!');
    end
    else begin
      x1 := (-b + sqrt(d))/(2*a);
      x2 := (-b - sqrt(d))/(2*a);
//      writeln('Первый Корень:' + x1 + ' ' + 'Второй Корень:' + x2);
      writeln('Первый Корень:', x1, ' Второй Корень:' , x2);
    end;
  end;

(You don't say which Pascal compiler you are using, but the above fixes two points which are flagged as errors in FreePascal.
If you need more help than that, please ask in a comment.
Btw, there are some grammatical constructs in Pascal implementations where an end can appear without a matching preceding begin such as case ... of ...end.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Streaming Mp4 video through RTP protocol using Gstreamer in Ubuntu I'm trying to fetch the video file from my local directory,enable the stream from server and capture these frames from my Client side.I have used the following pipelines:
Server side:
gst-launch -v  filesrc location=/home/gokul/Videos/Econ_TestVideo/radioactive.mp4 ! qtdemux ! rtpmp4vpay ! udpsink host=192.168.7.61 port=5000 sync=true

Setting pipeline to PAUSED ...
Pipeline is PREROLLING ...
/GstPipeline:pipeline0/GstRtpMP4VPay:rtpmp4vpay0.GstPad:src: caps = application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)MP4V-ES, profile-level-id=(string)1, config=(string)000001b001000001b58913000001000000012000c48d8800f528045a1443000001b24c61766335332e33352e30, payload=(int)96, ssrc=(uint)3003638799, clock-base=(uint)1542273545, seqnum-base=(uint)49176
/GstPipeline:pipeline0/GstRtpMP4VPay:rtpmp4vpay0.GstPad:sink: caps = video/mpeg, mpegversion=(int)4, systemstream=(boolean)false, profile=(string)simple, level=(string)1, codec_data=(buffer)000001b001000001b58913000001000000012000c48d8800f528045a1443000001b24c61766335332e33352e30, width=(int)1280, height=(int)720, framerate=(fraction)91/3, pixel-aspect-ratio=(fraction)1/1
/GstPipeline:pipeline0/GstRtpMP4VPay:rtpmp4vpay0: timestamp = 1542273545
/GstPipeline:pipeline0/GstRtpMP4VPay:rtpmp4vpay0: seqnum = 49176
/GstPipeline:pipeline0/GstUDPSink:udpsink0.GstPad:sink: caps = application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)MP4V-ES, profile-level-id=(string)1, config=(string)000001b001000001b58913000001000000012000c48d8800f528045a1443000001b24c61766335332e33352e30, payload=(int)96, ssrc=(uint)3003638799, clock-base=(uint)1542273545, seqnum-base=(uint)49176
Pipeline is PREROLLED ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock

Client side:
gst-launch -v udpsrc port=5000 caps="application/x-rtp" ! rtpmp4vdepay ! mpeg4videoparse ! queue ! ffdec_mpeg4 ! ffmpegcolorspace !  xvimagesink

Setting pipeline to PAUSED ...
/GstPipeline:pipeline0/GstUDPSrc:udpsrc0.GstPad:src: caps = application/x-rtp, media=(string)video, payload=(int)96, clock-rate=(int)1, encoding-name=(string)MP4V-ES
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock

After setting these,i'm not seeing any display(Not even the launch application screen)
To add to the above info,i'm running these command in command line in Ubuntu-12.04

A: Below is the pipeline for receiver
Sender:

gst-launch-1.0 -v filesrc location = video.mp4 ! decodebin ! x264enc ! rtph264pay ! udpsink host=192.168.1.159 port=5000

will output CAPS use this caps at the receiver side:
caps="application/x-rtp, media=video, clock-rate=90000, encoding-name=H264, payload=96, ssrc=3394826012, timestamp-offset=2215812541, seqnum-offset=46353"
Receiver:

gst-launch-1.0 -v udpsrc port=5000 caps="application/x-rtp, media=video, clock-rate=90000, encoding-name=H264, payload=96, ssrc=3394826012, timestamp-offset=2215812541, seqnum-offset=46353" ! rtph264depay ! decodebin ! videoconvert ! autovideosink sync=false

hence you will be able to stream and video will be smooth and clean.
In above pipeline if you are using gst-launch-0.10 then replace videoconvert with ffmpegcolorspace

A: Finally i will be able to see some video in launch screen.I have used the following pipeline.But the video is not clear.
SERVER:
gst-launch-0.10 -v filesrc  location=/home/gokul/video.mp4 ! qtdemux name=d ! queue ! rtpmp4vpay ! udpsink port=5000
CLIENT:
gst-launch-0.10 udpsrc port=5000 caps = "application/x-rtp, media=(string)video, clock-rate=(int)90000, encoding-name=(string)MP4V-ES, profile-level-id=(string)243, config=(string)000001b0f3000001b50ee040c0cf0000010000000120008440fa282fa0f0a21f, payload=(int)96, ssrc=(uint)4291479415, clock-base=(uint)4002140493, seqnum-base=(uint)57180" ! rtpmp4vdepay ! ffdec_mpeg4 ! xvimagesink sync=false
So can anyone suggest me how to enhance the video image in the client side,by modifying of adding some of the pipeline parameters.


text:
Q: thead position absolute not working in IE7 I try to make a table header fixed when scoll down on pages. The problem is in IE7, the thead are not absolute but are showing in the "right" positions. It need to fly over the table. It works perfect in FireFox 11
I have a table structure as follow:

        t
        t
        t
        t
        t
        t

    Total

    2
    2
    2
    2

        t
        t
        t
        t
        t
        t

    Total

    2
    2
    2
    2

CSS
.tableFloatingHeader {
    overflow: hidden;
    position: absolute;
    top: 0;
    display: none;
    left: auto;
    background-color: red;
}

JQuery

A: This may help you, basically add a conditional CSS expression style for IE7.  I don't like using expressions, but IE7 is another animal.
thead tr {
     position: relative;
     top: expression(this.offsetParent.scrollTop);
    }

http://geekswithblogs.net/LSheu/archive/2009/01/30/css-table-scrolling-with-fixed-header-for-ie-7.aspx
Edit* Wrong URL


text:
Q: create custom links in OSX dock I have a program that runs from the command line but not correctly from the icon in the applications menu. While I would like to figure that out, all I want right now is  way to create a link in the dock where I can click that link, and run the command that lauches the program correctly.

A: I use the platypus tool/framework to roll scripts into apps all the time:

*

*http://sveinbjorn.org/platypus/
The code for it is available and it's a free download with a request to donate financial support if you can/care.


text:
Q: Android Studio textAllCaps turning letter "i" to caps in my native language as "İ". Do you know a way to avoid this? I'm trying to learn Android Studio (v. 3.6.3).  I am setting the attribute textAllCaps to true in the XML code source forTextView, as follows:
"android:text="@string/quantity"
"android:textAllCaps="true"

However, on the screen, the word "Quantity" is capitalized incorrectly as "QUANTİTY" (the uppercase i is dotted).
The letter "İ" (dotted uppercase i, Unicode U+0130), is used in Turkish, not in English. The language for the app is English.
I could not figure this out. Do you know any solution for this?


text:
Q: Creating DataFrame from dictionary with different lengths of values So, I'm looking to create a DataFrame from a dictionary similar to the follow:
d = {A: ['cat','dog','zebra'],
     B: ['frog,'lion'],
     C: ['snake','cat','ant','bird','turtle'],
     D: ['sloth']}

I want the dataframe to look as such:
Col1   Col2   Col3   Col4   Col5   Col6
 A    'cat'  'dog'  'zebra'  na     na
 B    'frog' 'lion'   na     na     na
 C    'snake' 'cat'  'ant'  'bird'  'turtle'
 D    'sloth'  na      na    na     na

Any ideas? thank you!

A: Use list comprehension for add keys of dictionary for nested lists, pass to DataFrame constructor and add DataFrame.add_prefix:
df = pd.DataFrame([[k,] + v for k, v in d.items()]).add_prefix('Col')
print (df)
  Col0   Col1  Col2   Col3  Col4    Col5
0    A    cat   dog  zebra  None    None
1    B   frog  lion   None  None    None
2    C  snake   cat    ant  bird  turtle
3    D  sloth  None   None  None    None

Or use DataFrame.from_dict with convert index to column and then set new columns names:
df = pd.DataFrame.from_dict(d, orient='index').reset_index()
df.columns = [f'col{x}' for x in range(1, len(df.columns) + 1)]
print (df)
  col1   col2  col3   col4  col5    col6
0    A    cat   dog  zebra  None    None
1    B   frog  lion   None  None    None
2    C  snake   cat    ant  bird  turtle
3    D  sloth  None   None  None    None

If want starting by col1 is possible use rename with custom function:
f = lambda x: f'col{x+1}'
df = pd.DataFrame([[k,] + v for k, v in d.items()]).rename(columns=f)
print (df)
  col1   col2  col3   col4  col5    col6
0    A    cat   dog  zebra  None    None
1    B   frog  lion   None  None    None
2    C  snake   cat    ant  bird  turtle
3    D  sloth  None   None  None    None


text:
Q: How to store a long array's value in to variales using php How to save each value of the above array in a variable using PHP.
Array ( [0] => Abbottabad )
Array ( [0] => Faisalabad )
Array ( [0] => Gujranwala )
Array ( [0] => Hyderabad )
Array ( [0] => Islamabad )
Array ( [0] => Karachi )
Array ( [0] => Lahore )
Array ( [0] => Mangla )
Array ( [0] => Multan )
Array ( [0] => Muree )
Array ( [0] => Peshawar )
Array ( [0] => Quetta )
Array ( [0] => Rawalpindi )
Array ( [0] => Sialkot )

I have got these values form mysql. Now I want to store in to a variable in such a way that I cant print each value separately.

A: Save these array into an array (I hope you are talking about array of objects that is returned by database), if not just save it in array to avoid static checks.
foreach($arrayResult as $key => $value){
 foreach($value as $dataArray){
   echo $dataArray;
 }
}


text:
Q: Adding Aloha Editor to Django Admin, jQuery compatibility issues ensue I'm writing a personal blog in Django, and would like to include Aloha Editor into the admin panel. I have been following the instructions, which failed. I then tried other things, including putting a newer version of jQuery (instead of Django's 1.4.2) into my /static/admin/js, which only broke things*. It seems jQuery is not available when it's needed (at document.ready), but at any later point, enabling Aloha from console works... through django.jQuery.
>>> django.jQuery('.vLargeTextField').aloha() //works
>>> $('.vLargeTextField').aloha() // does not work; jQuery 1.7.2 loaded by Aloha

My templates/admin/base_site.html (relevant blocks):
{% block extrastyle %}
<link href="/static/admin/local-lib/alohaeditor-0.21.3/aloha/css/aloha.css" rel="stylesheet" type="text/css" />
{% endblock %}

{% block extrahead %}
<script type="text/javascript" src="http://requirejs.org/docs/release/2.0.6/minified    /require.js"></script>
<script src="/static/admin/local-lib/alohaeditor-0.21.3/aloha/lib/aloha.js"
data-aloha-plugins="common/ui,
        common/format,
        common/list,
        common/link,
        common/highlighteditables">
</script>
<script type="text/javascript">
Aloha.ready( function() {
  Aloha.jQuery('.vLargeTextArea').aloha();
});
</script>
{% endblock %}

*Breakage includes: Tabular inline is now wonky, collapsible fieldsets now have a bit different behaviour than with jQuery 1.4.2.
Edit
It seems that the only real way of inserting Aloha into the admin panel is to put the last script in the blockbots (!!!) block, which is rendered under standard Django admin inclusions. Also, it is imperative to use the jQuery supplied by Aloha to work with Aloha, as the 1.8 I put in my /static/admin will not work. For Django's admin, I reverted to the supplied 1.4.2. However, new problems arose: The tooltips for Aloha bunch up at the bottom of the page, and do not disappear. Additionally, the console is littered with errors. Is there any way I can fix this?

A: You might try using a pre-built django integration package for aloha:
https://pypi.python.org/pypi/django-aloha-edit,
Then use the HTMLField, or simply use the AlohaWidget and specify the backend. The HTMLField does important sanitation, but if you're only editing from the backend with trusted users this is not necessary, and you can just override the widget in the backend.
formfield_overrides = {
    models.TextField: {'widget': AlohaWidget(attrs={'style':'width:100%;max-width:800px;height:80ex;'})},
}

The advantage of this, is that the required js resources are automatically included - including the version of jQuery just for Aloha. (The two versions can act independently.)


text:
Q: How difficult would it be to add a "Favorite Users" tab in our profile? There are certain users on SO that we may highly trust, that we know in real life, or that we are tutoring. And to prevent abuse of the feature, perhaps the number of "Favorite Users" can be limited to 5 or 10 or 20.
I realize someone else lobbied for this before, but I think my appeal is a little different - just put a hard-limit on the number of favorites, to prevent this turning into a certain other website.    Thank You SO !

A: Somewhere (I don't have a link at hand) it was stated, that SO isn't a social network for developers, so no friends, no groups, no wall, etc. I think I haven't missed these things so far (still, you can subscribe to user feeds, if you wish to follow someone or browse some else's activity, etc.).

A: The benevolent creators of the Stack Exchange network (the SE family, if you will) have ever so thoughtfully already provided you this ability, you just need to follow these key steps:

*

*Create a [SE Site] / Favorite Users folder in your browser of choice.

*Add up to 1 billion SE users as bookmarks to this folder.

*???

*Profit

A: I'm trying to figure out what the benefit of this feature would be.  Since SO users can't contact each other directly, what would you do with your list of favorite users?  Would you be following other users' questions?  Answers?  Comments??
The only use case that I can think of would be to 'favorite' users who are recognized SMEs or who work on projects/systems that you are also working on... but you'd find their questions/answers by doing a search anyway....


text:
Q: Buscador de patrones Vuelvo a formular una pregunta que hice unos días atrás.
La intencion es hacer un programa que genere una plantilla como la de la imagen abajo mostrada de manera "inteligente". Es decir un generador de secuencias que variará en función de los valores para las S, E o A.
Quisiera pediros ayuda para que me orientaseis como enfocar el tema para empezar a programarlo.
La verdad es que tengo poca experiencia programando y no se por donde empezar.

A: A ver si esto te orienta para que empieces. Aunque lo puedes hacer de mil formas distintas y en cualquier plataforma yo te lo enfoco a .Net con lenguaje C#.
Secuencia
Para generar la secuencia te propongo que te crees algún objeto que encapsule el tratamiento de tus datos de tipo S, E y A. Por ejemplo:
// Enumerado con los tipos posibles
public enum TipoDato
{
    S,
    E,
    A
}

// Clase que trata los datos S, E y A
public class SEAData
{
    private int  S { get; set; }
    private int E { get; set; }
    private int A { get; set; }

    public SEAData(int s, int e, int a)
    {
        S = s;
        E = e;
        A = a;
    }

    public List<TipoDato> GetSEAList()
    {
        List<TipoDato> seaList = new List<TipoDato>();
        for (int i = 0; i < S; i++)
        {
            seaList.Add(TipoDato.S);
        }
        for (int i = 0; i < E; i++)
        {
            seaList.Add(TipoDato.E);
        }
        for (int i = 0; i < A; i++)
        {
            seaList.Add(TipoDato.A);
        }
        return seaList;
    }

    public List<TipoDato> GetSEAListRandom()
    {
        Random random = new Random();
        List<TipoDato> seaList = GetSEAList();
        return seaList.OrderBy(x => random.Next()).ToList();
    }
}

Para su uso podríamos hacerlo así:
private void Test()
{
    SEAData sea = new SEAData(74, 39, 71);
    List<TipoDato> sequence = sea.GetSEAListRandom();
}

La variable sequence te crea una lista alterada de forma aleatoria de la forma que querías.
Puedes hacer las pruebas que creas oporturnas hasta este punto.
UI
Siguiendo con .Net te sugiero que crees un proyecto nuevo de tipo Windows Forms y para empezar te crees un nuevo formulario (o usa el que se crea de forma automática al crear un proyecto nuevo) para hacer pruebas. Más adelante y cuando controles más yo me crearía un control de usuario (user control) al que le pasemos un objeto de nuestro tipo SEAData y sea capaz de pintar la UI necesaria.
Para las pruebas yo añadiría directamente en tu formulario un control de tipo flowLayoutPanel que hace de contenedor de otros controles y que te permite organizar controles de forma automática. Asegúrate de establecer la propiedad Dock de este control en Fill para que te ocupe toda la ventana. De esta forma podemos crear de forma dinámica controles en función del tamaño de nuestra lista de SEAData.
El siguiente ejemplo crea una matriz de controles con el valor S, E o A en el evento Load de un formulario:
private void Form1_Load(object sender, EventArgs e)
{
    SEAData seaData = new SEAData(74, 39, 71);
    List<TipoDato> seaListRandom = seaData.GetSEAListRandom();

    foreach (TipoDato tipo in seaListRandom)
    {
        flowLayoutPanel1.Controls.Add(new TextBox { Text = tipo.ToString() });
    }
}

El siguiente paso sería pintar de un color según sea S, E o A, centrar el texo....
Espero que te sirva como primer enfoque.
Esto es lo que pinta el ejemplo que te he propuesto:


text:
Q: pygtk change background color of gtkHBox widget I have a GTK ui that has a gtkVBox that gets gtkHbox's containing content dynamically added to it as the user works.
The ui is getting crowded and it's difficult to tell what Hbox the components belong to (they repeat.)
I would like to alter the background color of the gtkHboxes so it alternates between a lighter and darker color for each one.
Basically, I'm creating a dynamic table of combo boxes where each row represents an object.  Now I need to segment the rows since they are quiet complex and hard to follow.
Thanks,
Dave.

A: According to the docs, since hboxes "do not have an associated window", you can not directly modify the background color.  The docs suggest to wrap it in and event box.  This works quite well:
hbox = gtk.HBox()
eb = gtk.EventBox()
eb.add(hbox)
eb.modify_bg(gtk.STATE_NORMAL, gtk.gdk.Color(red=65535))


text:
Q: Wordpress thumbs - how to generate Black&white transparent png I'm trying to generate a b&w png thumb in wordpres. The problem is that the pngs I am uploading have transparency. They are different logos from partners I need in grayscale to match the design of the Template.
So far I got this:
// add thumb size
add_image_size('pvz-partnerbw-image', 9999, 64, false);

// Generate BW thumbnail
add_filter('wp_generate_attachment_metadata','pvz_bw_filter');
function pvz_bw_filter($meta) {
    $file = wp_upload_dir();
    $file = trailingslashit($file['path']).$meta['sizes']['pvz-partnerbw-image']['file'];
    list($orig_w, $orig_h, $orig_type) = @getimagesize($file);
    $image = wp_load_image($file);
    imagefilter($image, IMG_FILTER_GRAYSCALE);
    imagesavealpha($image,true);

    switch ($orig_type) {
        case IMAGETYPE_GIF:
            imagegif( $image, $file );
            break;
        case IMAGETYPE_PNG:
            imagepng( $image, $file );
            break;
        case IMAGETYPE_JPEG:
            imagejpeg( $image, $file );
            break;
    }
    return $meta;
}

It almost works but the problem is that on the edges between the artwork and transparent background the colors stay. So I get a b&w logo with 1px red (or some other color). Anyone got a better solution for this - The kind that doesn't include Photoshoping the images ;). Thank you in advance!

A: For starters, wp_load_image has been depreciated. You should be using wp_image_editor. I suggest rewriting your function using wp_image_editor to see if it creates the same problems whn applying the GRAYSCALE filter.


text:
Q: JSON file processing with a different structure I have an android app (Java) that processes an API from te web.
Currently the app is processing a JSON file that looks like this:
{
"contacts": [
    {
        "id": 1,
        "name": "name1",
        "email": "email1",
        "phone": "1234567890"
    },
    {
        "id": 2,
        ETC...

I need to process another JSON file but it has a different structure:
{
    "contacts": {
        "1": {
            "id": 1,
            "name": "name1",
            "email": "email1",
            "phone": "1234567890",
            "level1": {
                "level2": {
                    "level3": 3,
                }
            },
            "last_updated": 20180712
        },
        "2": {
            ETC...

How do I process this second JSON file by adjusting the below code?
    if (jsonSource != null) {
        try {
            JSONObject jsonObject = new JSONObject(jsonSource);
            JSONArray jsonArrayData = jsonObject.getJSONArray("contacts");

            for (int i = 0; i < jsonArrayData.length(); i++) {
                JSONObject contacts = jsonArrayData.getJSONObject(i);
                String id = contacts.getString("id");
                String name = contacts.getString("name");
                String email = contacts.getString("email");
                String phone = contacts.getString("phone");

                HashMap<String, String> values = new HashMap<>();
                values.put("id", id);
                values.put("name", name);
                values.put("email, email);
                values.put("phone, phone);
                contactList.add(values);
            }
        } catch (final JSONException e) {
            Log.e(TAG, "JSON parsing error: " + e.getMessage());
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
                }
            });
        }
    } else {
        Log.e(TAG, "Unable to retrieve JSON file from URL");
        getActivity().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(getContext(), "ERROR", Toast.LENGTH_LONG).show();
            }
        });
    }
    return null;

Any help is much appreciated!

A: It looks, that inside first json you have "contacts" as array of objects, and inside second one you have "contacts" as object. Inside it you have other objects, simplified version looks like this:
"contacts": [
    {...},
    {...},
    {...}
]
"contacts": {
    "1": {...},
    "2": {...},
    "3": {...}
}

So, the only option you have is to check manually is "contacts" array or object, and based on it change your code.
It would look like this:
JSONObject jsonObject = new JSONObject(jsonSource);
if (jsonObject.get("contacts") instanceof JSONObject) {
    JSONObject contactsJson = jsonObject.getJSONObject("contacts");
    for (Iterator<String> it = contactsJson.keys(); it.hasNext(); ) {
        String key = it.next();
        JSONObject contactJson = contactsJson.getJSONObject(key);
        // your code to process contact item
    }
} else {
    // Your code to process every contact item
}


text:
Q: Angle of Elevation in Earth Coordinate Systems Does a calculated angle of elevation differ between earth centered earth fixed (ECEF) coordinates and geodetic coordinates? I've computed an angle of elevation from one object to another in 3D space in ECEF using
$s = (x_1, y_1, z_1)$
$r = (x_2, y_2, z_2)$
Now, take
$rx = r \cdot r = |r|^2$
$ry = s \cdot s = |s|^2$
$v = \frac{r \cdot s}{\sqrt{rx \cdot ry}}$
So
$v = cos(\theta)$
The angle of elevation from $r$ to $s$ is then $90 - arccos(\theta)$. Is this correct? I'm getting a different result from the accepted answer. The interpretation of $r$ and $s$ are an observer and a satellite orbiting the earth so the desired elevation is the angle above the horizon.

A: Of course the angle of elevation is different. Computing the angle of elevation requires a local up vector since not every point on earth has the same up direction.


text:
Q: When is a Java subroutine not a method? I came across this during learning Java in the beginning, but I am learning top down, so I would like some direction:
This was on a Java tutorial relatively early on:

As one final general note, you should be aware that subroutines in Java are often referred to as methods. Generally, the term "method" means a subroutine that is contained in a class or in an object. Since this is true of every subroutine in Java, every subroutine in Java is a method (with one very technical exception). The same is not true for other programming languages. Nevertheless, the term "method" is mostly used in the context of object-oriented programming, and until we start doing real object-oriented programming in Chapter 5, I will prefer to use the more general term, "subroutine." However, I should note that some people prefer to use the term "method" from the beginning.

My question is what is that "one very technical exception."  Since I am learning multiple stack technologies, I would like to know this specific exception he is referring to.   It comes from this tutorial :
http://math.hws.edu/javanotes/c2/

A: Quoting from chapter 5 of the tutorial you linked to:

Constructors are subroutines, but they are subroutines of a special
  type. They are certainly not instance methods, since they don't belong
  to objects. Since they are responsible for creating objects, they
  exist before any objects have been created. They are more like static
  member subroutines, but they are not and cannot be declared to be
  static. In fact, according to the Java language specification, they
  are technically not members of the class at all! In particular,
  constructors are not referred to as "methods."

A: Class constructors are not methods.


text:
Q: Rails 4 scope model/controller In my  model I've defined:
scope :active, -> { where(active: 'true') }

And my controller
def index
    if logged_in?
     @objects = Objects.all
    else
    @objects = Objects.active
    end
  end

In my index view, when logged_in? is true, I get all records as expected, but otherwise, I get nothing (I know at least one record is active).
Have I written my scope incorrectly?

A: It should be
scope :active, -> { where(active: true) }

Note: true is not enclosed in quotes


text:
Q: jQuery add first part of div, then add last part of div seperatley I'm trying to wrap the following prices and text together, all in one div.
This is what I have:

          MSRP: $90.00

                     Burkett Price:
        $289.99

        A link goes here

A TABLE WITH STUFF GOES HERE

This is what I am trying to get:

        **

**

            MSRP: $90.00

                         Burkett Price:
          $289.99

 **

**
        A link goes here

A TABLE WITH STUFF GOES HERE

This doesn't work but you get the idea of what I'm doing wrong:
$(document).ready(function () {
$('.thePrices').find('td').find('font:first').before('
');
$('.thePrices').find('.colors_productprice').find('b').after('
');
});

Perhaps I should be using SLICE?

A: I think what you want is .wrapAll()
Updated, to use .andSelf() to include
$('.thePrices').find('td').children().first().nextUntil('a').andSelf().wrapAll('

');

Example on jsfiddle

A: $('.thePrices>tbody>tr>td').children().slice(0,3).wrapAll('

');

Uses slice() to slice the first 3 children before wrapping them, note a
 is a child if you want to wrap the br before the a change the 3 to 4


text:
Q: Reinstalling bumblebee on Kernel 4.4 I updated my kernel from 3.19 to 4.4, but afterwards the initialization of bumblebee failed. Therefore I removed it completely (purge) and reinstalled it, this time with the current nvidia driver (352) instead of the older one (331). But I still have the NVidia GPU running, and if I start optirun, I get
[ 1255.207756] [ERROR]The Bumblebee daemon has not been started yet or the socket path /var/run/bumblebee.socket was incorrect.
[ 1255.207776] [ERROR]Could not connect to bumblebee daemon - is it running?

If I check if the nvidia driver is loaded (with lsmod | grep -E 'nvidia|nouveau'), I get nothing in return. How can I fix that?

A: Loadable kernel modules in Linux are loaded (and unloaded) by the modprobe command. They are located in /lib/modules and have had the extension .ko ("kernel object") since version 2.6 (previous versions used the .o extension). Often when you update your kernel and have compiled your own drivers in previous kernels you must compile them again. If binaries were obtained through pre-compiled such as deb Debian packages which are handled via dpkg through package managers such as apt/aptitude or  if your distribution is another flavor of Linux such as RHEL then BRPM's or RPM Package Manager sometimes known as RedHat Package Manager.
Depending on your distribution an attempt to load either drivers with "modprobe [options] [-i] [-b] modulename" or in your case "modprobe nouveau" | "modprobe nvidia" | "modprobe nv" if they exists and if they are located in the corresponding location for your distribution. Ubuntu is based off of Debian and it may be assumed packages are most likley handled through dpkg managers on your system if its what these forums are designated for.
If your problem still exists, perhaps shed more light on the issue by including these outputs:
/usr/bin/dmesg
/usr/bin/uname -a

If possible please include information on your kernel objects by attempting:
/usr/sbin/modinfo nvidia
/usr/sbin/modinfo bbswitch

Did you compile bumblebee & your NVIDIA driver from source or did you use a pre-compiled package? If they were compiled by you what versions did you use? If you installed the pre-compiled packages please provide the exact versions.


text:
Q: HTML Text positioning not aligning in center i want to center the text but the second line dont wanna raise litle bit help?

Orum Lipsum Blaste

laba Raba Lokus Focus

A: The first and the second line are not centered because of the margin-left applied to them.
Remove it and add a text-align: center;

Orum Lipsum Blaste

laba Raba Lokus Focus

http://jsbin.com/yegogefaqaxo/2/edit

A: Regarding centering the text, try it as simple as this one (adding text-align: center to the containing div):

Orum Lipsum Blaste

laba Raba Lokus Focus


text:
Q: Race condition when detecting connectivity status change in Android I need to monitor and determine connectivity status changes in my Android app. For that, I have registered my class as a broadcast receiver:
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(this, filter);

Now, for determining the connectivity status, you can do the following:
@Override
public void onReceive(Context context, Intent intent) {
  if (!ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
    return;
  }
  NetworkInfo aNetworkInfo =
      intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
  if (aNetworkInfo == null) {
    return;
  }

  boolean isConnected = aNetworkInfo.isConnected();
  int networkType = aNetworkInfo.getType();
  // by using isConnected & networkType, get the new connectivity status..
}

The issue is that ConnectivityManager.EXTRA_NETWORK_INFO is deprecated. Now, you are suggested to use the CONNECTIVITY_SERVICE with getActiveNetworkInfo(), something like that:
@Override
public void onReceive(Context context, Intent intent) {
  if (!ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
    return;
  }
  ConnectivityManager connManager =
      (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
  if (connManager == null) {
    return;
  }
  NetworkInfo activeNetworkInfo = connManager.getActiveNetworkInfo();
  boolean isConnected =
      (activeNetworkInfo != null) && activeNetworkInfo.isConnected();
  int networkType =
      (activeNetworkInfo != null) ? activeNetworkInfo.getType() : -1;
  // by using isConnected & networkType, get the new connectivity status..
}

This raises the following question:
In the 2nd implementation, when using the CONNECTIVITY_SERVICE and not the EXTRA_NETWORK_INFO:
Is there a chance for a race condition? As the onReceive is called asynchronously, when getting the network info from the connectivity  service, may the connectivity state be different from the network info in the intent (as the connectivity might change in the meanwhile)?
Meaning, when using the intent, I am sure that the network info includes the data that triggered the onReceive, but when using the service - the network info might be different...?
If so, what's the best way to get the info that triggered the onReceive?
Also, if the only way to do so is to keep using the intent - doesn't that make 2 sources of truth? (one from the Connectivity Service, and one from the sent intent...)
UPDATE:
An example of the possible race condition:
Someone connected to WiFi and immediately disconnected from WiFi. This will result in 2 intents to be sent (one for connected to WiFi, and one for disconnecting from WiFi. More intents are actually sent, but I will focus on these 2). The possible race condition I am asking about is that: when we get the first intent (WiFi connected), the intent extra EXTRA_NETWORK_INFO will result in isConnected = true and networkType = TYPE_WIFI. But, is it possible that when I get the data from the Connectivity Service, as the onReceive is called asynchronously, the WiFi has already disconnected, resulting in isConnected = false and networkType = TYPE_WIFI while the intent still holds the right values for this call of onReceive? Or this will always happen fast enough so you get the right values from the Connectivity Service in the onReceive.. ?

A: My solution was sending a broadcast everytime connection changes adding an extra if the status of connection is up or down, hope it helps:
public class ConnectivityChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
    Log.i(context.getClass().getName(), " Changed connection ");
    context.sendBroadcast(new Intent(MyApplication.ACTION_CONNECTION_CHANGED)
            .putExtra(MyApplication.INTENT_EXTRA_CONNECTION_STATUS,NetWorkUtils.isNetworkAvailable(context)));
}}

public static boolean isNetworkAvailable(Context context) {
    ConnectivityManager cm =
            (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    return activeNetwork != null &&
            activeNetwork.isConnectedOrConnecting();
}

Android manifest:
<receiver android:name=".ConnectivityChangeReceiver">
        <intent-filter>
            <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
        </intent-filter>
    </receiver>


text:
Q: What is the correct keyword for the Proximal AdaGrad optimizer on Tensorflow? I was experimenting with the Proximal AdaGrad for science fair and I was not able to use it because it counts it as it not existing.
My code:
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt
import numpy as np
import time

start_time = time.time()

data = tf.keras.datasets.fashion_mnist

(train_images, train_labels), (test_images, test_labels) = data.load_data()

class_names = ['T-shirt', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle Boot']

train_images = train_images/255.0

test_images = test_images/255.0

model = keras.Sequential([
                           keras.layers.Flatten(input_shape=(28, 28)),
                           keras.layers.Dense(100, activation="relu"),
                           keras.layers.Dense(10, activation="softmax")
])

model.compile(optimizer="Proximal AdaGrad", loss="sparse_categorical_crossentropy", metrics=["accuracy"])

model.fit(train_images, train_labels, epochs=200)

test_loss, test_acc = model.evaluate(test_images, test_labels)

print("Test acc is:", test_acc)
print("--- %s seconds ---" % (time.time() - start_time))

The Error:
ValueError                                Traceback (most recent call last)
<ipython-input-2-2d12844ae498> in <module>()
     24 ])
     25
---> 26 model.compile(optimizer="Proximal AdaGrad", loss="sparse_categorical_crossentropy", metrics=["accuracy"])
     27
     28 model.fit(train_images, train_labels, epochs=200)

6 frames
/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/training/tracking/base.py in _method_wrapper(self, *args, **kwargs)
    455     self._self_setattr_tracking = False  # pylint: disable=protected-access
    456     try:
--> 457       result = method(self, *args, **kwargs)
    458     finally:
    459       self._self_setattr_tracking = previous_value  # pylint: disable=protected-access

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, distribute, **kwargs)
    250         'experimental_run_tf_function', True)
    251
--> 252     self._set_optimizer(optimizer)
    253     is_any_optimizer_v1 = any(isinstance(opt, optimizers.Optimizer)
    254                               for opt in nest.flatten(self.optimizer))

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/engine/training.py in _set_optimizer(self, optimizer)
   1451       self.optimizer = [optimizers.get(opt) for opt in optimizer]
   1452     else:
-> 1453       self.optimizer = optimizers.get(optimizer)
   1454
   1455     if (self._dtype_policy.loss_scale is not None and

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/optimizers.py in get(identifier)
    844   elif isinstance(identifier, six.string_types):
    845     config = {'class_name': str(identifier), 'config': {}}
--> 846     return deserialize(config)
    847   else:
    848     raise ValueError('Could not interpret optimizer identifier:', identifier)

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/optimizers.py in deserialize(config, custom_objects)
    813       module_objects=all_classes,
    814       custom_objects=custom_objects,
--> 815       printable_module_name='optimizer')
    816
    817

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/utils/generic_utils.py in deserialize_keras_object(identifier, module_objects, custom_objects, printable_module_name)
    178     config = identifier
    179     (cls, cls_config) = class_and_config_for_serialized_keras_object(
--> 180         config, module_objects, custom_objects, printable_module_name)
    181
    182     if hasattr(cls, 'from_config'):

/usr/local/lib/python3.6/dist-packages/tensorflow_core/python/keras/utils/generic_utils.py in class_and_config_for_serialized_keras_object(config, module_objects, custom_objects, printable_module_name)
    163     cls = module_objects.get(class_name)
    164     if cls is None:
--> 165       raise ValueError('Unknown ' + printable_module_name + ': ' + class_name)
    166   return (cls, config['config'])
    167

ValueError: Unknown optimizer: Proximal AdaGrad

I tried naming it other things such as "ProximalAdaGrad" and "ProximalGrad" but non of those worked. The Activation Function looks to have no issues but the Optimizer itself seems to have a bug. I searched for  a post on GitHub but did not find anyone posting an issue about this.

A: There is an open issue about this. The TensorFlow implementation exists (even in TensorFlow 2.x, as tf.compat.v1.train.ProximalAdagradOptimizer), but there is no corresponding Keras implementation at the moment. However, the Keras API is able to wrap an existing TensorFlow optimizer, so you should be able to do the following:
# This works both in recent 1.x and 2.0
optimizer = tf.compat.v1.train.ProximalAdagradOptimizer(0.001)
model.compile(optimizer=optimizer,
              loss="sparse_categorical_crossentropy",
              metrics=["accuracy"])


text:
Q: Determine outer div's width by selected inner div I have a html segment that looks like the following:

      Lorem ipsum dolor sit amet // Can be very long, truncate as needed

The outer div has a minimal width, and can/will grow. What I want is so that the outer div's width grow as inner2 grows, but not for inner1. In other words, I want the outer div's width to be determined by inner2, as if inner1 doesn't exist, then add inner1 and let the width remain unchanged, e.g.
If inner2's width is less than 150px, then inner1's width will be 150px.
If inner2's width is more than 150px, then inner1's width will be the same as inner2's div.

A: You need JavaScript to accomplish your goal.

$(document).ready(function () {
    var $outer = $('.outer');
    var $inner1 = $('.inner1');
    var $inner2 = $('.inner2');

    if ($inner2.width() > 150) {
       $inner1.css('width', $inner2.width()+'px');
       $outer.css('width', $inner2.width()+'px');
    }
  else
    {
      $outer.css('width', '150px');
    }
});
.outer  {
  background-color: yellow;
}
.inner1 {
  display: inline-block;
  background-color: red;
}
.inner2 {
  display: inline-block;
  background-color: green;
}

      Lorem ipsum dolor sit amet // Can be very long, truncate as needed

  sadasda

I hope this helps you to achieve your goal :)


text:
Q: Collection Navigation Properties using Inheritance (Table Per Type ) Using Entity Framework: Code First, I am trying to define an collection navigation property using a navigation property of a base class.
Object structure:
public class Content
{
    public int ID { get; set; }
    public ModerationStatuses ModerationStatus { get; set; }
    public ContentItemTypes ContentType { get; set; }
    public virtual User Author { get; set; }
}

public class Image : Content
{
    public Image()
        : base()
    {
        ContentType = ContentItemTypes.Image;
    }
    public string FileName { get; set; }
    public string Location { get; set; }
    public int DisplayOrder { get; set; }
    public long FileSize { get; set; }
}

public class User
{
    public int UserID { get; set; }
    public string Username { get; set; }

    public virtual ICollection<Image> Images { get; set; }
}

Context OnModelCreating:
modelBuilder.Entity<Content>()
    .Map(i => i.ToTable("Content"));

modelBuilder.Entity<Image>()
    .Map(i => i.ToTable("Images"));

When the database is generated, it creates a User_UserID foreign key constraint into the Images table instead of using Author_UserID in the Content table.
How can I get it to recognize Content..Author_UserID field as the foreign key for the ICollection<Image> navigation property?

A: It's not possible. You either need to move the Author property from the Content into the Image class or make the collection in User of type ICollection<Content> Contents. A navigation property must always be declared in the entity class the inverse navigation property is refering to. It cannot be inherited from a base entity.

A: Actually it is possible... You just need to add a navigation property to your Content class so that you then have a reference to map to.
Here's the thorough walkthrough.


text:
Q: How to insert the output of a stored procedure into a table I have a stored procedure with 5 output columns and no arguments. Can you help me with the syntax? In mysql

A: You can use prepared statement and use the command :
insert into new_table select * from .....   (whatever your result-set is) within the stored procedure.
Thanks

A: I tried this one and this worked.
delimiter //

create procedure proc-name()
begin

insert into table-name

here we have the query for the proc

end //
delimiter ;


text:
Q: Check_box problems to retrieve the one checked I tried to use this form to put checkboxes on a form:

<input type="checkbox" autocomplete="off" checked> Checkbox 1 (pre-checked)

<input type="checkbox" autocomplete="off"> Checkbox 2

<input type="checkbox" autocomplete="off"> Checkbox 3

My problem is that when I try to get the checkboxes checked with my parameters, I always can get only one (the last one checked, example: if I check 1 and 2, I will get 2 only).
How can I do to get them in my controller?
Thanks in advance

A: Try giving your inputs a name attribute with unique value attributes and unique id attributes.
Example:

<input type="checkbox" autocomplete="off" id="first" value="1" name="box-selections[]" checked> Checkbox 1 (pre-checked)

<input type="checkbox" autocomplete="off" id="second" value="2" name="box-selections[]"> Checkbox 2

<input type="checkbox" autocomplete="off" id="third" value="3" name="box-selections[]"> Checkbox 3


text:
Q: AssertJ check if JSONArray contains a map with an entry with given key and value Hi I want to test with assertThat if a JSONArray contains an item with a key with a specific value.
For example I have JSONArray:
[
  {
    "eventType": "event_1",
    "name": "user_1",
    ....
  },
  {
    "eventType": "event_2",
    "name": "user_2",
    ....
  }
]

What I want to test is if this array contains an item with the key: eventType with the value: event_2
Is it possible to achieve this with assertThat without looping through the array and checking each item?
I know it is possible to check if a map contains a given key and value and I also know it is possible to check if an array contains given item. But I didn't found any solution how to combine both things. Someone has an idea how can I combine these two things?
Thank you for your help

A: This is best addressed by https://github.com/lukas-krecan/JsonUnit which will give you much better JSON assertions than the generic AssertJ.
Hope it helps!


text:
Q: Run Length Encoding Python The question asks: Write a function that takes, as an argument, a list of characters and returns a list reflecting the run-length encoding of that list. The elements in the returned list follow the following pattern: the even indices contain the characters and the odd indices contain the number of times the character is repeated consecutively.
When I type a list into the function, it does not iterate through the whole length of the list. It will work for lists of shorter lengths but not for longer ones.Not sure how to fix it.
def runLengthEncoding(myList):
    aList=[]
    count=1
    for i in range(1,len(myList)):
        if myList[i] == myList[i-1]:
            count=count+1
        else:
            aList.append(myList[i-1])
            aList.append(count)
            count=1
            if i == (len(myList)-1):
                aList.append(myList[i])
                aList.append(count)
    return aList

A: Your code is failing when the last item(s) are repeating, or when the length of the list is 1:
>>> runLengthEncoding("fooobar")
['f', 1, 'o', 3, 'b', 1, 'a', 1, 'r', 1]
>>> runLengthEncoding("fooobarr")
['f', 1, 'o', 3, 'b', 1, 'a', 1]
>>> runLengthEncoding("a")
[]

A fix for your solution would be to remove the three lines starting with if i == (len(myList)-1): and replace them with
if myList:
    aList.append(myList[-1])
    aList.append(count)

Move that block outside the loop.

However, the easiest way to implement run-length encoding would probably be with the itertools module:
from itertools import chain, groupby

def run_length(iterable):
    return list(chain.from_iterable(
        (val, len([*thing]))
        for val, thing in groupby(iterable)
    ))


text:
Q: Are there other "fun" packages like the "coffee stains" package? I'm trying to convert some friends to LaTeX and have come up against a (to me) unexpected objection: there are too few packages that support "fun" (really), to which I responded:

I know there are examples of clever and creative (and a bit silly) output coaxed out of otherwise quite sertious packages like TikZ, but I also wonder: Are there other packages, like Hanno Rein's coffee package, that demonstrate LaTeX's lighter side?

A: After @samcarter and @GuM presented their work, I present you my ducksay and duckuments packages:
\documentclass[border=2mm,preview]{standalone}

\usepackage{ducksay}[2018/09/21]
\DucksayOptions
  {
    ,arg=box
    ,vpad=1
  }

\usepackage{duckuments}
\usepackage{microtype}

\usepackage[]{graphicx}

\AddAnimal{marmot}
{  \
    \   %%% /////*%%%
     \  %///////////%
        //////////////
      /////%%////%%////
     .//((///(%%///((///
     ///((/,,(%%,,/((///
    //////,,%,,,(,,//////
    //////////*//////////
   .////////,,,,,/////////
   //%%#/,,,,,,,**/,//%%//
   /#%%%%,,.....,**/#%%%%/
   //%%%%/,.....,**(#%%%%/
   //(%%%(*,,,,,**/##%%%//
   ///,%%,/******///#%,///
    //,,,,,//////((,,,,///   %%
    ///,,,,,,,,,,,,,,,///%%%%%
     /////,,,,,,,,,*////%%%,
       ////////////////
     %%%%%%(//////(%%%%%}

\begin{document}
\duckthink[marmot]{\includegraphics{example-image-duck}}
\ducksay[wd=20,msg-align=j,msg=\normalfont]{\blindduck}
\end{document}

A: Not a package, but could be packaged pretty easily: beamerduck!
The following presentation will show a progress by having a duck walk from left side of the screen to the right side, saying annoying things every once a while.  You can of course replace the duck picture by any other animal (I am thinking about a man carrying a sack on his back.  On specific slides, the ones I plan to spend more time on, I want to have him drop the sack to the ground and rest).
\documentclass{beamer}
\usepackage{tikz}
\usepackage{lipsum}

% Duck stuff

\usetikzlibrary{shapes.callouts, calc}

% Parameters: file, number of pages, width
\newcommand\DuckSetup[3]{%
\foreach \n in {1,...,#2}{
\pgfdeclareimage[width=#3,page=\n]{duck\n}{#1}}
\def\ducknumberofpages{#2}}

\DuckSetup{duck}{2}{1cm} % "duck" is a pdf file with 2 pages that will
                         % alternate as they move from slide to slide.

\newcommand\duck{%
\tikz[remember picture]{\node (duck) {%
\pgfmathparse{int(mod(\thepage-1,\ducknumberofpages)+1)}%
\pgfuseimage{duck\pgfmathresult}};}
}

\setbeamertemplate{footline}
{%
\pgfmathparse{(\thepage-1)*\paperwidth/\insertdocumentendpage}%
\hspace{\pgfmathresult pt}%
\duck
}

\setbeamertemplate{navigation symbols}{}

\newcommand<>{\ducksez}[1]{%
\uncover#2{\tikz[remember picture,overlay]{\node[ellipse callout, draw, fill=white, overlay,
callout absolute pointer={($ (duck.north east) + (1,0) $)}] at ($ (duck.north east) + (3,1)
$) {#1};}}}

\newcommand<>{\ducksezrev}[1]{%
\uncover#2{\tikz[remember picture,overlay]{\node[ellipse callout, draw, fill=white, overlay,
callout absolute pointer={(duck.north west)}] at ($ (duck.north west) + (-3,1) $) {#1};}}}
% End of duck stuff

\author{Egon Ipse}
\title{The Importance of Being a Duck}
\begin{document}
\begin{frame}
   \maketitle
   \ducksez<2>{Hello!}
\end{frame}
\begin{frame}
   \frametitle{Purpose}
   \begin{enumerate}[<+->]
      \item Purpose of Ducks
      \item Purpose of Duckweed
   \end{enumerate}
   \ducksez<3>{Quack!}
\end{frame}

\foreach \i in {1,...,10}{
\begin{frame}
   \frametitle{Frame \i}
   \lipsum[\i]
   \ifnum \i=5 \ducksez{Five!} \fi
   \ifnum \i=9 \ducksezrev{Nine!} \fi
\end{frame}
}

\begin{frame}
   \frametitle{The last frame}
   \ducksezrev{See Ya!}
\end{frame}

\end{document}

A: Well,  as you can see in some of the other answers, there are a lot of font packages out there with what some may call a questionable amount of uses.
A lot of the fonts mentioned in the other answer, and some other "silly" fonts are grouped under the The font-novelty topic on CTAN.
Not all fonts that can be considered "just for fun" or "silly" are listed under font-novelty, though. Here is some "fun" stuff outside of font-novelty :

*

*The font-invented topic on CTAN lists fonts for fictional/invented languages, it includes packages for Klingon and several of J.R.R. Tolkien's Middle-Earth alphabets. There are also typesetting support packages for some of these languages listed under the CTAN's lang-invented topic.

P.S. I intended to post more links while typing this up, but SX won't let me post more than two links because I'm still a greenhorn over here. I'm planning to update this answer once I rack up some more reputation :)

A: For lobsters fans:
LobLib is a TeX package for creating lobster themed documents and inserting a wide range of lobster images into papers.
https://github.com/bae43/LobLib/

A: One of my favourite "fun" packages is the typewriter package, the one mimicking a party working mechanical typewriter.
https://ctan.math.illinois.edu/macros/luatex/latex/typewriter/typewriter-guide.pdf

A: Hope this counts. Cow font anyone :-)? It's part of TL Contrib.
http://www.tug.org/TUGboat/tb27-1/tb86hoekwater-cows.pdf

A: I like the chickenize package, which can do a lot of useless things, among others it can print in rainbowcolors. See yourself, works only with Lua(La)TeX.

A: The search "ducks are fun" yields 15,600,000 hits on google - so it seems evident that ducks are fun.
And latex can do ducks with the brand new tikzducks package (of which I am the author): https://github.com/samcarter/tikzducks and https://www.ctan.org/pkg/tikzducks
A small example:
\documentclass{article}
\usepackage{tikzducks}

\begin{document}
\begin{tikzpicture}
    \duck[body=yellow!50!brown!40!white,
        crazyhair=gray!50!white,
        eyebrow,
        glasses=brown!70!black,
        book=\scalebox{0.2}{$E=mc^2$},
        bookcolour=red!20!brown]
\end{tikzpicture}
\end{document}

There is also the younger sibling of the tikzducks, the tikzmarmots (https://github.com/samcarter/tikzmarmots and https://www.ctan.org/pkg/tikzmarmots)

And even more family members are on the way: the tikzlings (https://github.com/samcarter/tikzlings)

A: What about Peter Wilson's sudokubundle?
You can print, create and SOLVE! sudokus.

A: Well, there's always the package skull, which makes available a skull symbol for you to use in math mode. Fun, and of course extremely useful!

A: One of my students has taught himself TeX programming by developing:

*

*avremu – An 8-Bit Microcontroller Simulator written in LATEX
In my opinion this is the most strange thing one can possibly do just for fun!
(But I am biased, of course :-)
From the package readme:

Let's say we want to program our document in C on top of TeX. Then
  there would be the need to interpret the C semantics. Basically we
  would have to write a compiler for C in TeX. Not a very promising
  future, if you start this. But, we can use a normal C compiler to
  compile the C code to some simple platform. Like AVRs Atmega. Since I have
  other things to do than writing an AVR Emulator in TeX, here it is!

Actually, I even considered using this (!). In one of my lectures, I present lots of small AVR programs on beamer slides together with their "output" on a specific device with some LEDs and a 7 seg display. I already have been using LaTeX macros to typeset the status of the LED array and the 7 seg display, so the interpreter could, given the binary code, automatically derive the parameters for these macros. A special listings environment could automatically invoke the C-compiler (via \write18) to generate the respective binary code. The result would be truly "self-contained" slides: Whenever I change the given example code, the typesetting of the "output" would automatically be updated.
However, other deadlines were approaching, so in the end I dropped the idea.

A: Not really a fun package, because it's most likely the best ever invented drawing package for LaTeX, but here is pxpic:
\documentclass[border=3.14]{standalone}

\usepackage{pxpic}

\begin{document}
\pxpic[colours=r=green!60!black,skip=.,size=3.14pt,t]
  {
    {.....rrrrrrr}
    {....rrrrrrrrr}
    {....rrrrrrrr}
    {....rrr}
    {....rrr}
    {....rrrrrrr.....r...r....r}
    {....rrrrrrrr...rrr.rrr..rrr..rr}
    {....rrrrrrr....rrr.rrr..rrrrrrrr}
    {....rrr........rrrrrrr..rrrrrrrrr}
    {....rrr........rrrrrrr..rrrrrrrrr}
    {....rrr.........rrrrr...rrr...rrr}
    {....rrr.................rrr...rrr}
    {.....r...................r....rrr}
    {...............................r}
    {}
    {..rrrrr......................r}
    {.rrrrrrr....................rrr}
    {rrrrrrrrr...................rrr}
    {rrr...rrrr..................rrr}
    {rrrrrrrrrr..................rrr}
    {rrrrrrrrr...................rrr}
    {rrrrrrrr....................rrr}
    {rrr.......rrrrr.......rrr...rrr...r.....rrrrrr.......rrr......rrrr}
    {rrr......rrrrrrr....rrrrrr..rrr.rrrr...rrrrrrrr.....rrrrr....rrrrrr}
    {rrr......rrrrrrr...rrrrrr...rrrrrrr....rrrrrrrr....rrrrrrr..rrrrrrrr}
    {rrr.....rrrr..rrr..rrr......rrrrrr.....rrr..rrr....rrr..rrr.rrr..rrr}
    {rrr.....rrr...rrr..rrr......rrrrrrr....rrr..rrrr...rrr..rrr.rrrrrrrr}
    {rrr.....rrr...rrr..rrr......rrr.rrrr...rrr.rrrrr...rrr..rrr.rrrrrrr}
    {rrrr....rrrrrrrrr..rrrrrr...rrr..rrrr..rrrrrrrrr...rrrrrrrr.rrrrrr}
    {.rr......rrrrrrrrr.rrrrrrr..rrr...rrr..rrrrrrrrr...rrrrrrrr.rrr}
    {..........rrrrrrrr..rrrrr...rrr....r....rrrr..rrr...rrrrrrr..rrrrr}
    {................r............r.................r.......rrr...rrrrrr}
    {.....................................................rrrrr....rrrrr}
    {...................................................rrrrrr........r}
    {..................................................rrrrrr}
    {...................................................rrr}
  }
  \llap
    {%
      Created with \pxpiclogo
      \raise1ex\pxpic
        [
           colours=
            {
               1=[HTML]{E4E4E4},2=[HTML]{C8C8C8},3=[HTML]{ADADAD}
              ,4=[HTML]{919191},5=[HTML]{767676},6=[HTML]{555555}
              ,7=[HTML]{373737},8=[HTML]{121212},9=[HTML]{000000}
            }
          ,skip=.
          ,size=0.05pt
        ]
        {
          {.................1235678765431}
          {..............1369999999999999742}
          {............14999999999999999999962}
          {...........49999974211....12359999951}
          {.........16999942.............13799983}
          {........2899951..................389994}
          {.......399972.....................169995}
          {......299971........................59994}
          {.....189961..........................49993}
          {.....69971.....233333333221...........59992}
          {....39992......499999999999841........17997}
          {...18994.......4999999999999993........29993}
          {...49971.......49999999999999993........49981}
          {..18993........499999999999999981.......19993}
          {..39981........49999.....14999993........4997}
          {..6994.........49999.......299995........29992}
          {.19992.........49999........79997.........7994}
          {.29991.........49999........59999.........4996}
          {.3997..........49999........59997.........29991}
          {.4995..........49999.......189995.........19991}
          {.5994..........49999.......499993.........19992}
          {.6993..........49999....12599996...........9992}
          {.7993..........49999999999999971...........9993}
          {.7993..........4999999999999961............9993}
          {.6993..........49999999999993..............9992}
          {.5994..........49999999999994.............19992}
          {.4995..........49999....599991............19991}
          {.3997..........49999....199995............29991}
          {.29991.........49999.....499992...........4997}
          {.19993.........49999.....189997...........6994}
          {..6995.........49999......399993.........19992}
          {..39991........49999.......799981........49991}
          {..19994........49999.......299995.......18994}
          {...49991.......49999........699992......49991}
          {...18995.......49999........299996.....29995}
          {....39993......49999.........599993...169981}
          {.....69992.....47777.........1777771..59993}
          {.....189982..........................49995}
          {......299982........................599961}
          {.......399993.....................1699961}
          {........2999962..................3999961}
          {.........16999952.............13799994}
          {..........149999974211....12359999972}
          {............15999999999999999999973}
          {..............1369999999999999952}
          {.................12356787654321}
        }%
    }
\end{document}

(no real trademarks apply)

A: You can have fun drawing Feynman diagrams with the feyn package... or is that just me?

A: I like the Tower of Hanoi, classical algorithm problem, illustrated and computed, via LaTex.
Tower of Hanoi in LaTex
You can also have the Simpsons family Demo here
You know what would be cool? A package for torn paper!

A: run texdoc pst-fun, it shows some funny macros

A: With a lack of confidence, I present my own. However, it has not been bundled into a package. :-D

A: Since @samcarter has mentioned her tikzducks package, I thought that, perhaps, I could cite my halloweenmath package as well.


text:
Q: How to: Using Combine to react to CoreData changes in the background I want to achieve the following: Whenever someone triggers a CoreData save (ie. NSManagedObjectContextDidSave notification gets sent), I'd like to perform some background calculation based the changed NSManagedObject. Concrete example: Assume in a notes app, I want to asynchronously calculate the total number of words in all notes.
The problem currently lies with the fact that NSManagedObject context is explicitly bound to thread and you are discouraged from using NSManagedObjects outside this thread.
I have setup two NSManagedObjectContexts in my SceneDelegate:
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let backgroundContext = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.newBackgroundContext()

I also have subscribed to the notification via NotificationCenter.default.publisher(for: .NSManagedObjectContextDidSave) and am receiving a save notification twice after I trigger only one managedObjectContext.save(). However, both notifications are sent from the same thread (which is the UIThread) and all NSManagedObjects in the user dictionary have a .managedObjectContext which is the viewContext and not the backgroundContext.
My idea was to filter the notifications based on whether or not the associated NSManagedObjectContext was the background one as I assumed that the notification is also sent on the (private) DispatchQueue but it seems all notifications are sent on the UIThread and the background context is never used.
Any idea on how to solve this? Is this a bug? How can I retrieve notifications based on the backgroundContext with downstream tasks being run on the associated DispatchQueue?

A: You can pass the object you want to observe to publisher(for:):
NotificationCenter.default
  .publisher(for: .NSManagedObjectContextDidSave, object: backgroundMoc)
  .sink(receiveValue: { notification in
    // handle changes
  })

That will only listen for notifications related to a background managed object context which means you can do processing on that context's queue safely.

A: You can create a Publisher which informs you when something relevant for you in Core Data has changed.
I wrote an article on this. Combine, Publishers and Core Data.
import Combine
import CoreData
import Foundation

class CDPublisher<Entity>: NSObject, NSFetchedResultsControllerDelegate, Publisher where Entity: NSManagedObject {
    typealias Output = [Entity]
    typealias Failure = Error

    private let request: NSFetchRequest<Entity>
    private let context: NSManagedObjectContext
    private let subject: CurrentValueSubject<[Entity], Failure>
    private var resultController: NSFetchedResultsController<NSManagedObject>?
    private var subscriptions = 0

      init(request: NSFetchRequest<Entity>, context: NSManagedObjectContext) {
        if request.sortDescriptors == nil { request.sortDescriptors = [] }
        self.request = request
        self.context = context
        subject = CurrentValueSubject([])
        super.init()
    }

      func receive<S>(subscriber: S)
        where S: Subscriber, CDPublisher.Failure == S.Failure, CDPublisher.Output == S.Input {
        var start = false

        synchronized(self) {
            subscriptions += 1
            start = subscriptions == 1
        }

        if start {
            let controller = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context,
                                                        sectionNameKeyPath: nil, cacheName: nil)
            controller.delegate = self

            do {
                try controller.performFetch()
                let result = controller.fetchedObjects ?? []
                subject.send(result)
            } catch {
                subject.send(completion: .failure(error))
            }
            resultController = controller as? NSFetchedResultsController<NSManagedObject>
        }
        CDSubscription(fetchPublisher: self, subscriber: AnySubscriber(subscriber))
    }

      func controllerDidChangeContent(_ controller: NSFetchedResultsController<NSFetchRequestResult>) {
        let result = controller.fetchedObjects as? [Entity] ?? []
        subject.send(result)
    }

      private func dropSubscription() {
        objc_sync_enter(self)
        subscriptions -= 1
        let stop = subscriptions == 0
        objc_sync_exit(self)

        if stop {
            resultController?.delegate = nil
            resultController = nil
        }
    }

    private class CDSubscription: Subscription {
        private var fetchPublisher: CDPublisher?
        private var cancellable: AnyCancellable?

        @discardableResult
        init(fetchPublisher: CDPublisher, subscriber: AnySubscriber<Output, Failure>) {
            self.fetchPublisher = fetchPublisher

            subscriber.receive(subscription: self)

            cancellable = fetchPublisher.subject.sink(receiveCompletion: { completion in
                subscriber.receive(completion: completion)
            }, receiveValue: { value in
                _ = subscriber.receive(value)
            })
        }

        func request(_ demand: Subscribers.Demand) {}

        func cancel() {
            cancellable?.cancel()
            cancellable = nil
            fetchPublisher?.dropSubscription()
            fetchPublisher = nil
        }
    }

}

A: If you aren't saving the context twice then you must be adding the observer twice.


text:
Q: C++ I'm having doubts about the security of this function In my networking project, For simplicity, I'm using XOR encryption / decryption with a user defined key. I've come up with the following function.
std::string XOR(std::string data, std::string encrypted_key) {

    char* key = new char [encrypted_key.length() + 1];
    strcpy (key, encrypted_key.c_str());
    std::string output = data;

    for (int i = 0; i < data.size(); i++){
        output[i] = data[i] ^ key[i % (sizeof(key) / sizeof(char))];
    }
    return output;
}

But I am having serious fears and doubts about the security of this. I fear that strcpy might cause a problem. Due to this I never even use the function, I use snprintf everytime. But here, it doesn't work. Can anyone confirm that is safe? Thanks! (Please excuse me if this is a silly question)

A: EDIT : After @JohnFilleau's comment, I've changed my function to this. I realized what I was doing wrong. Thanks!
std::string XOR(std::string data, std::string encrypted_key) {
    std::string output = data;

    for (int i = 0; i < data.size(); i++){
        output[i] = data[i] ^ encrypted_key[i % encrypted_key.size()];
    }
    return output;
}


text:
Q: Swift: If Let Conundrum Now I know there are other questions that have already been answered about the Initializer for conditional binding must have optional type error, but I have tried those solutions and none seem to work or be about NSURL. Mine is specifically talking about it can't be NSURL. I have no idea what to do to fix it.
let attemptedUrl = NSURL(string: "http://www.weather-forecast.com/locations/" +
textField.text!.stringByReplacingOccurrencesOfString(" ", withString: "-") +
"/forecasts/latest")!

if let url = attemptedUrl {

The specific line of code that is having an error is the
    if let url = attemptedUrl {

A: You are force unwrapping the result of your call to NSURL(string:), this is what the ! does at the end of that statement.  As such, your attemptedUrl variable is not an optional type, so unwrapping it again with an if let statement (in addition to your force unwrap with the ! statement) is redundant and will not compile.
I would recommend reading the Optionals section of The Swift Programming Language for more information.


text:
Q: How can I set react Hooks to another value when it is already set This is my first time using React hooks and I have stumbled across a problem I can't solve. I am using the formAmount hook to get the input value of store it in state.amount. When that happens the amount is supposed to reduce totaling to a number whenever a user puts it in. The problem is that I can't make a new array in the onChange event because it catalogs every stroke of the key and it doesn't give me the complete number and I can't set it directly on the state.amount. How can I get that amount and store in an array?
Here is my code:
const Transactions = () => {
    const [state, setState] = useState([
        {
            expense: [],
            amount: [],
            id: ''
        }

    ])

    const [formExpense, setFormExpense] = useState('')
    const [formAmount, setFormAmount] = useState([])

    const handleSubmit = (e) => {
        e.preventDefault();

        addExpense()
        e.target.reset()
    }
    // add total of array of amount
    let sum = formAmount.reduce((accumulator, currentValue) => {
        { return accumulator += currentValue }
    }, 0)

    // push value of input to array
    const addExpense = (e) => {

        setState([...state, { expense: formExpense, amount: [...formAmount], id: Math.random() * 100 }])

    }

    return (

                <form onSubmit={handleSubmit}>
                    <input
                        type="text"
                        id="expense"
                        className="formfield"
                        name="expense"
                        placeholder="Expense..."
                        onChange={(e) => setFormExpense(e.target.value)}
                    />
                    <input
                        type="text"
                        id="amount"
                        className="formfield"
                        name="amount"
                        placeholder="Amount..."
                        onChange={(e) => setFormAmount([Number(e.target.value)])}
                    />
                    <button type="submit">Submit</button>
                </form>

                    Total Expense
                    {'$' + sum.toLocaleString()}
                    {
                        state.map(stat => {
                            return (

{stat.expense + stat.amount}

                            )
                        })
                    }

    )
}

A: Here's is the answer for you. I have done a Fiddle as well here

function Transaction(props){

    const [listOfExpenses, setlistOfExpenses] = React.useState([]);
    const [expense, setExpense] = React.useState("");
    const [amount, setAmount] = React.useState(0);
    const [totalExpenditure, setTotalExpenditure] = React.useState(0);

    const handleInputChange = (hookSetterMethod) => (e) =>{
        let {value} = e.target;
        return hookSetterMethod(value);
    }

    const addExpense = (expenseObject) => {
        setlistOfExpenses([...listOfExpenses, expenseObject])
    }

    const getTotalExpenditure = (listOfExpenses) =>
    {
            if(listOfExpenses.length > 0)
        {
          let tempExpenseAmountList = listOfExpenses.map((expense, id)=>{
              if(expense.amount)
              {
                  return expense.amount;
              }else{
                  return 0;
              }
          });

          return tempExpenseAmountList.reduce((accumulator, currentVal)=>{
              return Number(accumulator) + Number(currentVal);
          })
        }
        return 0;
    }

    React.useEffect(()=>{
        setTotalExpenditure(getTotalExpenditure(listOfExpenses));
    }, [listOfExpenses])

    const handleFormSubmission = (e) =>{
        e.preventDefault();
        addExpense({
            amount,
            expense
        });
    }

    const renderExpenses = (expenseList) => {
      return expenseList.map((expense, id)=>{
        return (

            {++id}
            {expense.expense}
            : ${expense.amount}

        )
      });
    }

    return(

Add your expenses below

                <form onSubmit={handleFormSubmission}>

                        Expense
                        <input value={expense} onChange={handleInputChange(setExpense)} />

                        Amount
                        <input value={amount} onChange={handleInputChange(setAmount)} />

                        <button type="submit">Add Expense</button>

                </form>

                      Id
                      Expense
                      Amount

                {renderExpenses(listOfExpenses)}

                  Total Expenses
                  : ${totalExpenditure}

    );
}

ReactDOM.render(<Transaction />,
document.getElementById("root"));
table{
  margin-top: 15px;
}

.total{
  display: table;
  border-top: 1px solid #434649;
  border-bottom: 2px double #434649;
  color: #f80000;
}


text:
Q: java.lang.SecurityException : Permission Denial, cannot get file from URI I'm trying to make an app that opens files in PDF format. I got stuck because when I click on a file and select my app to open them with, the URI I get through the Intent cannot be converted to an InputStream. Below is my code:
        Uri uri = getIntent().getData();
        try {
            pdfView.fromStream(getContentResolver().openInputStream(uri))
                    .load();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

The URI I get when debugging looks like this:
content://com.mi.android.globalFileexplorer.myprovider/external_files/Download/3E-Summatif-C%CC%A7%C4%B1km%C4%B1s%CC%A7-Birles%CC%A7tirilmis%CC%A7.pdf

and I get this error:
Permission Denial: opening provider com.android.fileexplorer.provider.FileExplorerFileProvider from ProcessRecord{897bfb1 6648:com.example.pdfviewer/u0a585} (pid=6648, uid=10585) that is not exported from UID 10151

The compile SDK version is 29.
Thank you in advance!
EDIT:
The intent-filter of the redirected activity looks like the following:
<activity android:exported="true"
            android:name=".PdfActivity">

            <intent-filter>
                <action android:name="android.intent.action.VIEW"/>
                <category android:name="android.intent.category.DEFAULT"/>
                <category android:name="android.intent.category.BROWSABLE"/>
                <data
                    android:scheme="content"
                    android:mimeType="application/pdf"
                    android:pathPattern=".*\\.pdf" />

            </intent-filter>

            <intent-filter>
                <data android:scheme="file"
                    android:mimeType="*/*"
                    android:pathPattern=".*\\.pdf "
                    android:host="*"/>

                <action android:name="android.intent.action.VIEW" />

                <category android:name="android.intent.category.DEFAULT" />
                <category android:name="android.intent.category.BROWSABLE" />
            </intent-filter>

        </activity>


text:
Q: Javascript - How to replace white spaces which are not in HTML tags? The following codes doesn't work and the result is broken because there are white spaces in a HTML tag.
HTML:

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

Javascript:
var div = document.getElementsByTagName('div')[0];
div.innerHTML = div.innerHTML.replace(/\s/g, ' ');

How to replace replace white spaces which are not in HTML tags?

A: It would be a better idea to actually use the DOM functions rather than some unreliable string manipulation using a regexp. splitText is a function of text nodes that allows you to split text nodes. It comes in handy here as it allows you to split at spaces and insert a  element between them. Here is a demo: http://jsfiddle.net/m5Qe8/2/.
var div = document.querySelector("div");

// generates a space span element
function space() {
    var elem = document.createElement("span");
    elem.className = "space";
    elem.textContent = " ";
    return elem;
}

// this function iterates over all nodes, replacing spaces
// with space span elements
function replace(elem) {
    for(var i = 0; i < elem.childNodes.length; i++) {
        var node = elem.childNodes[i];
        if(node.nodeType === 1) {
            // it's an element node, so call recursively
            // (e.g. the  element)
            replace(node);
        } else {
            var current = node;
            var pos;
            while(~(pos = current.nodeValue.indexOf(" "))) {
                var next = current.splitText(pos + 1);
                current.nodeValue = current.nodeValue.slice(0, -1);
                current.parentNode.insertBefore(space(), next);
                current = next;
                i += 2;  // childNodes is a live array-like object
                         // so it's necessary to advance the loop
                         // cursor as well
            }
        }
    }
}

A: First split the string at every occurrence of > or <. Then fit together all parts to a string again by replacing spaces only at the even parts:
var div = document.getElementsByTagName('div')[0];
var parts = div.innerHTML.split(/[<>]/g);
var newHtml = '';
for (var i = 0; i < parts.length; i++) {
    newHtml += (i % 2 == 0 ? parts[i].replace(/\s/g, ' ') : '<' + parts[i] + '>');
}
div.innerHTML = newHtml;

Also see this example.
=== UPDATE ===
Ok, the result of th IE split can be different then the result of split of all other browsers. With following workaround it should work:
var div = document.getElementsByTagName('div')[0];
var sHtml = ' ' + div.innerHTML;
var sHtml = sHtml.replace(/\>\</g, '> <');
var parts = sHtml.split(/[<>]/g);
var newHtml = '';
for (var i = 0; i < parts.length; i++) {
    if (i == 0) {
        parts[i] = parts[i].substr(1);
    }
    newHtml += (
        i % 2 == 0 ?
        parts[i].replace(/\s/g, ' ') :
        '<' + parts[i] + '>'
    );
}
div.innerHTML = newHtml;

Also see this updated example.
=== UPDATE ===
Ok, I have completly changed my script. It's tested with IE8 and current firefox.
function parseNodes(oElement) {
    for (var i = oElement.childNodes.length - 1; i >= 0; i--) {
        var oCurrent = oElement.childNodes[i];
        if (oCurrent.nodeType != 3) {
            parseNodes(oElement.childNodes[i]);
        } else {
            var sText = (typeof oCurrent.nodeValue != 'undefined' ? oCurrent.nodeValue : oCurrent.textContent);
            var aParts = sText.split(/\s+/g);
            for (var j = 0; j < aParts.length; j++) {
                var oNew = document.createTextNode(aParts[j]);
                oElement.insertBefore(oNew, oCurrent);
                if (j < aParts.length - 1) {
                    var oSpan = document.createElement('span');
                    oSpan.className = 'space';
                    oElement.insertBefore(oSpan, oCurrent);
                    var oNew = document.createTextNode(' ');
                    oSpan.appendChild(oNew);
                }
            }
            oElement.removeChild(oCurrent);
        }
    }
}

var div = document.getElementsByTagName('div')[0];
parseNodes(div);

Also see the new example.

A: You can deal with the text content of the container, and ignore the markup.
var div = document.getElementsByTagName('div')[0];
if(div.textContent){
    div.textContent=div.textContent.replace(/(\s+)/g,' ';
}
else if(div.innerText){
    div.innerText=div.innerText.replace(/(\s+)/g,' ';
}


text:
Q: java.util.concurrent.TimeoutException: Futures timed out after [3000 milliseconds] When creating akka actorSystem I'm using akka cluster in out project.
Below is the akka configuration -
    akka {
      loggers = ["akka.event.slf4j.Slf4jLogger"]
      loglevel = "DEBUG"
      logging-filter = "akka.event.slf4j.Slf4jLoggingFilter"

      actor {
        provider = "akka.cluster.ClusterActorRefProvider"
        creation-timeout = 20s
        warn-about-java-serializer-usage = on
        enable-additional-serialization-bindings = on
      }

      remote {
        log-remote-lifecycle-events = off
        log-frame-size-exceeding = 15 MiB
        artery {
          enabled = on
          canonical {
            port = 2551
          }
          advanced {
            maximum-frame-size = 15 MiB
            buffer-pool-size = 1024
            maximum-large-frame-size = 15 MiB
            large-buffer-pool-size = 4096
            outbound-message-queue-size = 4096
            outbound-control-queue-size = 20000
            outbound-large-message-queue-size = 4096
          }
        }
      }

      cluster {
        seed-node-timeout = 15s
        retry-unsuccessful-join-after = 15s
        shutdown-after-unsuccessful-join-seed-nodes = off
        auto-down-unreachable-after = off
        seed-nodes = ["akka://ClusterSystem@SERVER1:2551", "akka://ClusterSystem@SERVER2:2551"]
      }
    }

Actor System is created using -
package com.mycompany.akka;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;
import akka.actor.ActorSystem;

public class ActorSystemFactory {
    public static ActorSystem getActorSystem() {

        try {

            String hostName = String hostName = InetAddress.getLocalHost().getHostName();

            Config cfg = ConfigFactory.parseString(
                    "akka.remote.artery.canonical.hostname=" + hostName).withFallback(
                    ConfigFactory.load());

            String prop = System.getProperty("cluster_name");
            if (prop == null)
                throw new Exception("property cluster_name is not set");

            ActorSystem as = ActorSystem.create(prop, cfg);
            return as;
        } catch ( Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
}

Consistently I'm able to see actor system is shutdown with below error -
java.lang.RuntimeException: java.util.concurrent.TimeoutException: Futures timed out after [3000 milliseconds]
    at com.mycompany.akka.ActorSystemFactory.getActorSystem(ActorSystemFactory.java:22)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:497)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162)
    ... 25 more
Caused by: java.util.concurrent.TimeoutException: Futures timed out after [3000 milliseconds]
    at scala.concurrent.impl.Promise$DefaultPromise.ready(Promise.scala:223)
    at scala.concurrent.impl.Promise$DefaultPromise.result(Promise.scala:227)
    at scala.concurrent.Await$$anonfun$result$1.apply(package.scala:190)
    at scala.concurrent.BlockContext$DefaultBlockContext$.blockOn(BlockContext.scala:53)
    at scala.concurrent.Await$.result(package.scala:190)
    at akka.remote.artery.aeron.ArteryAeronUdpTransport.retry$1(ArteryAeronUdpTransport.scala:235)
    at akka.remote.artery.aeron.ArteryAeronUdpTransport.blockUntilChannelActive(ArteryAeronUdpTransport.scala:232)
    at akka.remote.artery.aeron.ArteryAeronUdpTransport.runInboundStreams(ArteryAeronUdpTransport.scala:347)
    at akka.remote.artery.ArteryTransport.start(ArteryTransport.scala:467)
    at akka.remote.RemoteActorRefProvider.init(RemoteActorRefProvider.scala:234)
    at akka.cluster.ClusterActorRefProvider.init(ClusterActorRefProvider.scala:40)
    at akka.actor.ActorSystemImpl.liftedTree2$1(ActorSystem.scala:912)
    at akka.actor.ActorSystemImpl._start$lzycompute(ActorSystem.scala:908)
    at akka.actor.ActorSystemImpl._start(ActorSystem.scala:908)
    at akka.actor.ActorSystemImpl.start(ActorSystem.scala:930)
    at akka.actor.ActorSystem$.apply(ActorSystem.scala:258)
    at akka.actor.ActorSystem$.apply(ActorSystem.scala:302)
    at akka.actor.ActorSystem$.apply(ActorSystem.scala:276)
    at akka.actor.ActorSystem$.create(ActorSystem.scala:199)
    at akka.actor.ActorSystem.create(ActorSystem.scala)
    at com.mycompany.akka.ActorSystemFactory.getActorSystem(ActorSystemFactory.java:22)
    ... 30 more

akka version - 2.5.25
scala version - 2.11
What is the issue with actor system and how can I fix this?

A: Working Solution:
I also had to struggle to find out exact solution and here it is based on the exception I could find. You have to add bind.bind-timeout in your akka -> actor -> remote -> artery -> bind configuration.
  remote.artery {
    # The port clients should connect to.
    canonical.port = 2551
    bind.bind-timeout = 30s
  }


text:
Q: Specializing the template of std::vector I am trying to get an std::vector to hold fixed-length strings without introducing indirection through a wrapper class. My idea is to have a specialization of std::vector for my custom type that behaves like an std::vector to the outside, but uses its own storage layout. Kind of like std::vector<bool>.
I looked at "Extending the namespace std" and didn't find a reason why I shouldn't. Can I do the following, and if not, what type of hell am I facing?
#include <iostream>
#include <vector>

class FixedString {};

namespace std {
    template <>
    class vector<FixedString> {
    public:
        void push_back( FixedString&& value ) {
            std::cout << "Welcome to my vector. Let's play a game!" << std::endl;
        }
    };

    // here be more vector methods.
}

int main () {
    std::vector<int> a;
    a.push_back(int{});

    std::vector<FixedString> b;
    b.push_back(FixedString{});
}

Edit: I understand that there may be better ways of doing this and the discussion in the comments has helped me in understanding what's wrong with this. Still, I would like to understand if this is legal (even if undesirable) C++ code. People have hinted at [namespace.std] below, but I would like to understand which of the rules a fully specialized vector class would violate.

A: The rule in [namespace.std] is:

A program may add a template specialization for any standard library template to namespace std only if the declaration depends on a user-defined type and the specialization meets the standard library requirements for the original template and is not explicitly prohibited.

So, two criteria: "depends on a user-defined type" (a better term, that hopefully will be adopted, is program-defined type) and "meets the standard library requirements for the original template." Your example meets the first criteria but breaks the second, so it's undefined behavior.
However, if you go ahead and fill in the rest of the requirements (see [container.requirements] and [sequence.reqmts] and [vector]) to meet the second criteria, then it'll be fine. But questionable. Just write your own container, principle of least surprise and all that. When people see std::vector<T> they assume it's actually a std::vector. std::vector<bool> is bad enough, don't add another one.


text:
Q: How to split a sequence into two pieces by predicate? How do I split a sequence into two lists by a predicate?
Alternative: I can use filter and filterNot, or write my own method, but isn't there a better more general (built-in) method ?

A: By using partition method:
scala> List(1,2,3,4).partition(x => x % 2 == 0)
res0: (List[Int], List[Int]) = (List(2, 4),List(1, 3))

A: You might want to take a look at scalex.org - it allows you to search the scala standard library for functions by their signature. For example, type the following:
List[A] => (A => Boolean) => (List[A], List[A])

You would see partition.

A: Good that partition was the thing you wanted -- there's another method that also uses a predicate to split a list in two: span.
The first one, partition will put all "true" elements in one list, and the others in the second list.
span will put all elements in one list until an element is "false" (in terms of the predicate). From that point forward, it will put the elements in the second list.
scala> Seq(1,2,3,4).span(x => x % 2 == 0)
res0: (Seq[Int], Seq[Int]) = (List(),List(1, 2, 3, 4))

A: You can also use foldLeft if you need something a little extra.  I just wrote some code like this when partition didn't cut it:
val list:List[Person] = /* get your list */
val (students,teachers) =
  list.foldLeft(List.empty[Student],List.empty[Teacher]) {
    case ((acc1, acc2), p) => p match {
      case s:Student => (s :: acc1, acc2)
      case t:Teacher  => (acc1, t :: acc2)
    }
  }

A: I know I might be late for the party and there are more specific answers, but you could make good use of groupBy
val ret = List(1,2,3,4).groupBy(x => x % 2 == 0)

ret: scala.collection.immutable.Map[Boolean,List[Int]] = Map(false -> List(1, 3), true -> List(2, 4))

ret(true)
res3: List[Int] = List(2, 4)

ret(false)
res4: List[Int] = List(1, 3)

This makes your code a bit more future-proof if you need to change the condition into something non boolean.

A: If you want to split a list into more than 2 pieces, and ignore the bounds, you could use something like this (modify if you need to search for ints)
def split(list_in: List[String], search: String): List[List[String]] = {
  def split_helper(accum: List[List[String]], list_in2: List[String], search: String): List[List[String]] = {
    val (h1, h2) = list_in2.span({x: String => x!= search})
    val new_accum = accum :+ h1
    if (h2.contains(search)) {
      return split_helper(new_accum, h2.drop(1), search)
    }
    else {
    return accum
    }
  }
  return split_helper(List(), list_in, search)
}

// TEST

// split(List("a", "b", "c", "d", "c", "a"), {x: String => x != "x"})


text:
Q: Invoking a private method, within the object on a UML sequence diagram So I have a class diagram here:

A here's my sequence diagram

I'm invoking a method in object of Newton class and in this method I have to invoke a private method fact() which returns me a factorial of a given number.
This is the body of that newton() method
float Newton::newton(int n, int k) {
    return fact(n)/(fact(k) * fact(n-k));
}

As you can see fact() is invoked three times. So my question is: do I have to acknowledge (in my sequence diagram) that, fact() is used three times here, and if so - how? Or my sequence diagram is correct?

A: It depends on the purpose of the diagram:

*

*Is it to document a specific implementation? In this case, you may show the calls to fact().
Accuracy is then necessary: the arrow in a sequence diagram is not a dependency (i.e.  "I'll need this function within newton()") but a message (i.e. "I'll call this function one time with those arguments").  So, as Bruno mentioned in the comments, you should then show three distinct calls (i.e. 3 times a call like in your message 5).

*Is it to document your design? In this case the focus is more on  the interactions between objects. You do not need to show private implementation detail like fact() unless the private method would be essential to understand the design. The outside world does not need to know.
In case you're in the first case, note that fact() can be implemented recursively or iteratively.  Again an implementation detail.  In both case, I'd not show what's behind (is it what you tried to do with message 6?): in the case of a recursive implementation, it would make the diagram terribly complex for something easily understood in the code, whereas it would bring no additional information for the interaction scenario.