text:
Q: Is this possible to compress a JPEG file with zip libraries As I know the jpeg file have a best compression ratio between another image extensions, and if I correct we can not more compress a jpeg file because that have best compression, so please help me about this. I create some jpegs as following:
ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
ImageCodecInfo ici = null;
foreach(ImageCodecInfo codec in codecs) {
if(codec.MimeType == "image/jpeg")
    ici = codec;
}
EncoderParameters ep = new EncoderParameters();
ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, _quality);

using(MemoryStream ms = new MemoryStream()) {
     Bitmap capture = GetImage();
     capture.Save(ms, ici, ep);
  }

And I zipped them with sharpziplib, in average every jpeg size is 130KB and after zip every file compressed to about 70KB, how it possible? there is just 2 answer I can Imagine.
1- We can Compress Jpeg file with more compression ratio by zip libraries
2- My jpeg file not correctly created, and we can create better jpegs (with more compression ratio as we can not more compress them with zip libraries)
Does any one know about this? if we can create better jpegs please help me about it.
Edit:
this is my zip code to compress jpegs:
void addnewentry(MemoryStream stream, string pass,
                 string ZipFilePath, string entryname){

ICSharpCode.SharpZipLib.Zip.ZipFile zf = new ZipFile(ZipFilePath);

            if(!String.IsNullOrEmpty(pass))
                zf.Password = pass;

            StaticDataSource sds = new StaticDataSource(Stream);
            zf.BeginUpdate();
            zf.Add(sds, entryName);
            zf.CommitUpdate();
            zf.IsStreamOwner = true;
            zf.Close();
}

public class StaticDataSource : IStaticDataSource {

    public Stream stream { get; set; }

    public StaticDataSource() {
        this.stream.Position = 0;
    }

    public StaticDataSource(Stream stream) {

            this.stream = stream;
            this.stream.Position = 0;
        }

    public Stream GetSource() {
            this.stream.Position = 0;
            return stream;

    }

}

A: As most of people already stated, you can't compress such already compressed files further easily. Some people works hard on JPEG recompression (recompression = partially decoding already compressed file, and then compressing those data with a custom stronger model and entropy coder. Recompression usually ensures bit-identical results). Even that advanced recompression techniques, I only saw at most 25% improvement. PackJPG is one them. You can have a look at the other compressors here. As you realize, even top rank compressor couldn't reach exactly 25% (even though it's very complex).
Taking these facts into considerations, ZIP (actually deflate) cannot improve compression that much (it's a very old and inefficient if you compare it with top 10 compressors). I believe there are two possible reasons for that problem:

*

*You're accidentally adding some extra data to JPEG stream (possibly adding after JPEG stream).

*.NET outputs lots of redundant data to JFIF file. Maybe some big EXIF data and such.

To solve the problem, you can use a JFIF dump tool to observe what's inside the JFIF container. Also, you may want to try your JPEG files with PackJPG.

A: The JPEG compression algorithm has two stages: a "lossy" stage where visual elements that should be imperceptible to the human eye are removed, and a "lossless" stage where the remaining data is compressed using a technique called Huffmann coding. After Huffmann coding, further lossless compression techniques (like ZIP) will not reduce the size of the image file by significant amount.
However, if you were to zip multiple copies of the same small image together, the ZIP ("DEFLATE") algorithm will recognise the repetition of data, and exploit it to reduce the total file size to less than the sum of the individual files' size. This may be what you're seeing in your experiment.
Stated very simply, losless compression techniques like Huffman coding (part of JPEG) and DEFLATE (used in ZIP) try to discover repeated patterns in your original data, and then represent those repeated patterns using shorter codes.
In short, you won't be able to really improve JPEG by adding on another lossless compression stage.

A: No one has mentioned that fact that JPEG is merely a container. There are many compression methods that can be used with that file format (JFIF, JPEG-2000, JPEG-LS, etc.) Further compressing that file can yield varying results depending on the content.
Also, some cameras store huge amounts of EXIF data (sometimes resulting in about 20K of data) and that might account for the difference you're seeing.

A: You can attempt to compress anything with zlib. You just don't always get a reduction in size.
Usually compressing a whole jpeg file will yield a handful of bytes savings as it will compress the jpeg header (including any plain text comments or EXIF data)
This may not fully account for the 40K of compression you see unless you have a huge amount of header data or your jpeg data somehow winds up with alot of repeating values inside.

A: Zipping JPEGs reduces size because: EXIF data isn't compressed, JPEG is optimized for photos and not GIF-like data, and compressing files creates a single data stream, allowing patterns across multiple files and removing the requirement that each must be aligned with a specific block on disk. The latter can alone save around 4KB per compressed file.
The main problem with zipping pre-compressed images is that it requires extra work (human and CPU) for prep and viewing, which may not be worth the effort (unless you have millions of images that are infrequently accessed, or some kind of automated image service you're developing).
A better approach is to minimize the native file size, forgetting zip. There are many free libraries and apps out there to help with this. For example, ImageOptim combines several libs into one (OptiPNG, PNGCrush, Zopfli, AdvPNG, Gifsicle, PNGOUT), for a barrage of aggressive tricks to minimize size. Works great for PNGs; haven't tried it much with JPEGs.
Though remember that with any compression, there's always a point of diminishing returns. It's up to you to decide whether or not a few extra bytes really matter in the long run.


text:
Q: How to solve a transcendal equation I want to get the solution x of this equation
a (-(1/(1 + b c + a x)) - Log[b c + a x] + Log[1 + b c + a x]) - d = 0

in terms of a, b, c, d. Solve and FindRoot do not give any answer!

A: Clear[a, b, c, x, d, r]
eq1 = a (-(1/(1 + b c + a x)) - Log[b c + a x] + Log[1 + b c + a x]) - d == 0

To simplify, make common sub-expression substitution
eq2 = eq1 /. (b c + a x) -> z

Write it as
eq2 = (-(1/(1 + z)) - Log[z] + Log[1 + z]) == d/a

eq3 = eq2 /. (d/a) -> r

Now take the exponential
eq4 = Exp[#] & /@ eq3

eq5 = eq4 /. {(1 + z) -> k, z -> k - 1}

Now reduce comes to help. We can either use Reduce on Reals or not. For the general case
Reduce[eq5, k]

Using the last case for example:
eq6 = k == 1/(1 + ProductLog[C[1], -E^(-1 - r)])

Now start back substitution
 eq7 = eq6 /. {k -> 1 + z, r -> (d/a)}
 eq8 = eq7 /. z -> (b c + a x)

Now solve for x
 Solve[eq8, x]
 (*x -> (-1 - b c + 1/(1 + ProductLog[C[1], -E^(-1 - d/a)]))/a *)

But notice there is arbitrary parameters C[1] which is an integer. So there are infinite number of solutions. Also, the other Reduce results are still applicable in this final solution

redpajama_set_name: RedPajamaStackExchange


text:
Q: I would like to know of a site that would be useless if JavaScript was disabled I am looking for a site that if I disabled JavaScript the site would be useless, and what other functions would I not be able to use. Does anyone have a name of a site that I can look at? I want to know what no longer works.

A: You're looking at one right now.

A: Not quite sure if this is really programming related... but YouTube and Google Docs for instance.

A: http://jsfiddle.net
Most sites that use javascript heavily become less useful rather than useless.  In order to do that, many of them will implement the important parts twice - once with javascript, and a less sophisticated version without.

A: Despite the popularity of the question, this one doesn't even load w/o JS.
http://www.graphikdesign.it/

A: Google.com looses it's Instant search capability with Javascript off.


text:
Q: How to get a time difference between two time columns for SSRS I have two tables I am trying to get a difference from in SQL. Table A has a time in the following format: 07:40:06,
08:33:34,
13:42:09,
Table B is in the same format. I want to return in an actual time for example 7:40:00 in A and 7:50:00 in B result in new column 00:10:00.
Thanks,

A: I admit that this is sort of cheesy, but appears to work.  You could use a constant date, and add the times to that as strings.  Then subtract and format however you like.  For example: HH:mm:ss.  This will give the result of 00:10:00
DECLARE @contstantDate DATETIME = DATEFROMPARTS(1900,1,1)
DECLARE @date1 DATETIME = @contstantDate + '7:40:00'
DECLARE @date2 DATETIME = @contstantDate + '7:50:00'

SELECT FORMAT(@date2-@date1, 'HH:mm:ss')


text:
Q: Identified Suspected Robo-Reviewer. What now? I have identified a suspected robo-reviewer. They are spending on average 4 seconds per review, they always select 'No Action Needed', and on a number of occassions, they have done this on obvious NAA posts.
I don't want to name the user here on Meta, but I am wondering how this activity should be highlighted?
I have previously flagged the activity and I believe they received a review ban, but they have now continued to do robo reviews.

A: Flag one of their posts with a custom flag, asking for a mod to look into it. Mods can issue a review ban or send a warning to the user if it's borderline.
However, it's not entirely necessary to flag on the sites which have  review audits in place. IIRC, the review ban scales up on second offence, so they'll soon be hit with an automated one. Still, it's better to curb this behavior earlier --so flagging is preferable.


text:
Q: A function composition operator in Python In this question I asked about a function composition operator in Python. @Philip Tzou offered the following code, which does the job.
import functools

class Composable:

    def __init__(self, func):
        self.func = func
        functools.update_wrapper(self, func)

    def __matmul__(self, other):
        return lambda *args, **kw: self.func(other.func(*args, **kw))

    def __call__(self, *args, **kw):
        return self.func(*args, **kw)

I added the following functions.
def __mul__(self, other):
    return lambda *args, **kw: self.func(other.func(*args, **kw))

def __gt__(self, other):
    return lambda *args, **kw: self.func(other.func(*args, **kw))

With these additions, one can use @, *, and > as operators to compose functions. For, example, one can write print((add1 @ add2)(5), (add1 * add2)(5), (add1 > add2)(5)) and get # 8 8 8. (PyCharm complains that a boolean isn't callable for (add1 > add2)(5). But it still ran.)
All along, though, I wanted to use . as a function composition operator. So I added
def __getattribute__(self, other):
    return lambda *args, **kw: self.func(other.func(*args, **kw))

(Note that this fouls up update_wrapper, which can be removed for the sake of this question.)
When I run print((add1 . add2)(5)) I get this error at runtime: AttributeError: 'str' object has no attribute 'func'. It turns out (apparently) that arguments to __getattribute__ are converted to strings before being passed to __getattribute__.
Is there a way around that conversion? Or am I misdiagnosing the problem, and some other approach will work?

A: You can't have what you want. The . notation is not a binary operator, it is a primary, with only the value operand (the left-hand side of the .), and an identifier. Identifiers are strings of characters, not full-blown expressions that produce references to a value.
From the Attribute references section:

An attribute reference is a primary followed by a period and a name:
attributeref ::=  primary "." identifier

The primary must evaluate to an object of a type that supports attribute references, which most objects do. This object is then asked to produce the attribute whose name is the identifier.

So when compiling, Python parses identifier as a string value, not as an expression (which is what you get for operands to operators). The __getattribute__ hook (and any of the other attribute access hooks) only has to deal with strings. There is no way around this; the dynamic attribute access function getattr() strictly enforces that name must be a string:
>>> getattr(object(), 42)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: getattr(): attribute name must be string

If you want to use syntax to compose two objects, you are limited to binary operators, so expressions that take two operands, and only those that have hooks (the boolean and and or operators do not have hooks because they evaluate lazily, is and is not do not have hooks because they operate on object identity, not object values).

A: I am actually unwilling to provide this answer. But you should know in certain circumstance you can use a dot "." notation even it is a primary. This solution only works for functions that can be access from globals():
import functools

class Composable:

    def __init__(self, func):
        self.func = func
        functools.update_wrapper(self, func)

    def __getattr__(self, othername):
        other = globals()[othername]
        return lambda *args, **kw: self.func(other.func(*args, **kw))

    def __call__(self, *args, **kw):
        return self.func(*args, **kw)

To test:
@Composable
def add1(x):
    return x + 1

@Composable
def add2(x):
    return x + 2

print((add1.add2)(5))
# 8

A: You can step around the limitation of defining composable functions exclusively in the global scope by using the inspect module. Note that this is about as far from Pythonic as you can get, and that using inspect will make your code that much harder to trace and debug. The idea is to use inspect.stack() to get the namespace from the calling context, and lookup the variable name there.
import functools
import inspect

class Composable:

    def __init__(self, func):
        self._func = func
        functools.update_wrapper(self, func)

    def __getattr__(self, othername):
        stack = inspect.stack()[1][0]
        other = stack.f_locals[othername]
        return Composable(lambda *args, **kw: self._func(other._func(*args, **kw)))

    def __call__(self, *args, **kw):
        return self._func(*args, **kw)

Note that I changed func to _func to half-prevent collisions should you compose with a function actually named func. Additionally, I wrap your lambda in  a Composable(...), so that it itself may be composed.
Demonstration that it works outside of the global scope:
def main():
    @Composable
    def add1(x):
        return x + 1

    @Composable
    def add2(x):
        return x + 2

    print((add1.add2)(5))

main()
# 8

This gives you the implicit benefit of being able to pass functions as arguments, without worrying about resolving the variable name to the actual function's name in the global scope. Example:
@Composable
def inc(x):
    return x + 1

def repeat(func, count):
    result = func
    for i in range(count-1):
        result = result.func
    return result

print(repeat(inc, 6)(5))
# 11


text:
Q: Show that either $f$ or $\bar{f}$ have derivative at $z_0$ So the problem here is the following:
If the limit $\lim_{z \to z_0} \left|\frac{f(z)-f(z_0)}{z-z_0}\right| $ exists and is finite, show that  $f$ or $\bar{f}$ has a derivative at $z_0$.
The previous question of the excercise was about the total differential of a complex function and its conjugate. I tried to use it but it didn't help. I would like to give me a small tip and not the whole solution of the excercise if possible!
Edit: The function $f$ has a total differential at the point $z_0$ so it is real differential as well.


text:
Q: Chaining iterators together to remove repeated code The following code attempts to chain two iterators together.
fn main() {
    let height = 3;
    let width = 4;
    let horizontal = (0..height).map(|row| {let rw = row * width; rw..rw + width});
    horizontal.for_each(|x| { print!("("); x.for_each(|x|print!(" {:?} ", x)); println!(")");});
    let vertical = (0..width).map(|col| (0..height).map(move |n| col + n * width));
    vertical.for_each(|x| { print!("("); x.for_each(|x|print!(" {:?} ", x)); println!(")");});
    let all = horizontal.chain(vertical);
    //all.for_each(|x| { print!("("); x.for_each(|x|print!(" {:?} ", x)); println!(")");});
}

But the compiler complains about mismatched types.
error[E0271]: type mismatch resolving `<Map<std::ops::Range<{integer}>, [closure@src/main.rs:6:35: 6:82]> as IntoIterator>::Item == std::ops::Range<{integer}>`
 --> src/main.rs:8:26
  |
8 |     let all = horizontal.chain(vertical);
  |                          ^^^^^ expected struct `Map`, found struct `std::ops::Range`
  |
  = note: expected type `Map<std::ops::Range<{integer}>, [closure@src/main.rs:6:57: 6:81]>`
           found struct `std::ops::Range<{integer}>`

The signature of chain is:
fn chain<U>(self, other: U) -> Chain<Self, <U as IntoIterator>::IntoIter>ⓘ where
    U: IntoIterator<Item = Self::Item>

Both iterators have as Item type an Iterator with the same Item type, which admittedly is not quite what the signature demands. But I can call for example .for_each(|x| { print!("("); x.for_each(|x|print!(" {:?} ", x)); println!(")");}) on each iterator, so why can't I construct the chain to call it on the chain? Is there another way to remove such code duplication?

A: It's because your types doesn't have the same Item:
.map(|row| {let rw = row * width; rw..rw + width});
.map(|col| (0..height).map(move |n| col + n * width))

One is a Range the other is a Map of a Range.
The solution is to use flatten() or on your case flat_map():
fn main() {
    let height = 3;
    let width = 4;

    println!("Horizontal:");
    let horizontal = (0..height).flat_map(|row| {
        let rw = row * width;
        rw..rw + width
    });
    for x in horizontal.clone() {
        println!("{:?}", x);
    }

    println!("\nVertical:");
    let vertical = (0..width).flat_map(|col| (0..height).map(move |n| col + n * width));
    for x in vertical.clone() {
        println!("{:?}", x);
    }

    println!("\nAll:");
    let all = horizontal.chain(vertical);
    for x in all {
        println!("{:?}", x);
    }
}

This made both vertical and horizontal iterator have the same Item type. Also, I remove for_each() in my opinion it's make the code unclear as for loop are for side effect that is imperative paradigm and iterator chaining is functional paradigm.

Bonus:
fn print_my_iter(name: &str, iter: impl Iterator<Item = i32>) {
    println!("{}:", name);
    for x in iter {
        println!("{:?}", x);
    }
}

fn main() {
    let height = 3;
    let width = 4;

    let horizontal = (0..height).flat_map(|row| {
        let rw = row * width;
        rw..rw + width
    });
    print_my_iter("Horizontal", horizontal.clone());

    let vertical = (0..width).flat_map(|col| (0..height).map(move |n| col + n * width));
    print_my_iter("\nVertical", vertical.clone());

    let all = horizontal.chain(vertical);
    print_my_iter("\nAll", all);
}

Ultra bonus:
use std::io::{self, Write};

fn print_my_iter(name: &str, iter: impl Iterator<Item = i32>) -> Result<(), io::Error> {
    let stdout = io::stdout();
    let mut handle = stdout.lock();

    writeln!(handle, "{}:", name)?;
    iter.map(|x| writeln!(handle, "{:?}", x)).collect()
}

fn main() -> Result<(), io::Error> {
    let height = 3;
    let width = 4;

    let horizontal = (0..height).flat_map(|row| {
        let rw = row * width;
        rw..rw + width
    });
    print_my_iter("Horizontal", horizontal.clone())?;

    let vertical = (0..width).flat_map(|col| (0..height).map(move |n| col + n * width));
    print_my_iter("\nVertical", vertical.clone())?;

    let all = horizontal.chain(vertical);
    print_my_iter("\nAll", all)?;

    Ok(())
}


text:
Q: constructor function objects Ok So i am trying to create a constructor function that defines the
Circle class.
The class contains a single property named radius that is received as
an argument. The class has two methods: area which computes the area
of a circle, formula is radius*radius*3.14. diameter which computes the
diameter of a circle, formula is radius*2.
Prompt for a radius of a circle, and create an instance of the circle.
Display the result of the circle area method using document.write().
Display the result of the circle diameter method using
document.write(). Result for radius = 5; you may have slight
differences due to rounding.
circle area: 78.5 circle diameter: 10 Here's what I got but I've been
staring at this too long so I figured another set of eyes would help
<!DOCTYPE html>

A:


text:
Q: change id of button depending on current viewed div ive a problem which is driving me crazy. im trying to explain...
i have a very long scrolling page with about 10 divs, one below the other (no space between).
at the bottom of the viewing port is a button with an id and a position: fixed. when i scroll up or down the button is fixed while the divs move up or down.
i want to have different id's on the button depending on which div layer is in the viewing port. that means if one divlayer fills over 50% of the available space the href of the button should change...
i tried the inview.js, but the problem is, that 2 divs at the same time have the inview class...
my current code:
$('#div4, #div5, #div6').bind('inview', function (event, visible) {
        if (visible == true) {
        $(this).addClass("inview");

        } else {

        $(this).removeClass("inview");
        }
    });

var $div4 = $('#div4');

if($div4.hasClass("inview")){
    $('#button1').attr('id', 'button2');
  }

you see, every div which is in the viewport the button gets a new id.
has anyone of you a solution?
thanks ted

A: You can try to remove the inview class before adding it.. Something like this:
var $divs = $('#div4,#div5,#div6';
$divs.bind('inview', function (event, visible) {
        $divs.not(this).removeClass("inview");
        if (visible == true) {
          $(this).addClass("inview");
        }
     });

Another suggestion is to use the Waypoints plugin and fire when the div crosses the 50% mark.
The only difficult part is that depending on the direction you'll need to select the current div or the one above.
Plugin: http://imakewebthings.com/jquery-waypoints/
Demo: http://jsfiddle.net/lucuma/nFfSn/1/
Code:
 $('.container div').waypoint(function (direction) {
        if (direction=='up')
            alert('hit ' + $.waypoints('above')[$.waypoints('above').length-2].id);
        else
            alert('hit ' + $(this).attr('id'));
    }, {
        offset: $.waypoints('viewportHeight') / 2

});


text:
Q: Django- IndentationError Hello everyone I am new to django please help me to solve error,I am using termux for it and Acoder for editing code
In my django urls.py code
In urls.py
In termux error showing like this
Error message of indentation in urls.py

A: Try to put a comma at the end of the 2nd path specification in urls.py
It is usual to have a comma after every line under these circumstances, even the last one.
Without knowing more about your code, it is hard to say, but I would try that one first.


text:
Q: How to detect if the uploaded file is not an image? How to check if the file uploaded file is solely an image and not video file and anything?
I tested out a simple code that will check if the uploaded file is an image.
form
<form method="post" enctype="multipart/form-data">
    <input type="file" name="photo" accept="image/*">
    <input type="submit" name="submit" value="Test">
</form>

Although I have accept="image/*", I can easily change it to All types and get a non-image file.
code to check if the file is a valid image (This is only for testing)
if($_POST['submit']) {
    $tmp_file = $_FILES['photo']['tmp_name'];
    if(mime_content_type($tmp_file)) {
        var_dump(mime_content_type($tmp_file));
    } else {
        echo 'error1';
    }
    if(getimagesize($tmp_file)) {
        var_dump(getimagesize($tmp_file));
    } else {
        echo 'error2';
    }
}

As of now I have 3 test to this, 2 passed 1 failed:

*

*Testing an image = passed.

*Testing a non-image valid .srt file = passed (gives an error to getimagesize)

*Testing a valid video file .mp4 = failed (after the submission, it is loading for 5-10 seconds and not gives any error)

What do I need to do about this? I do not know what is the problem because it does not gives any results from both var_dump() and echo 'errors'. What I do think now is that PHP is accepting the file.
Note
I need to do this so that only a valid image will be uploaded.
Note 2
The accepted answer on the marked question is not working with me.
Update
If I try to upload a video that is less than 128M it returns something. But if it is greater than 128M it gets nothing in my localhost, but I tested this in a production site it gives me a REQUEST TIME OUT.

A: Find file extension like this and check for valid types...
function  getextension($name){
    $count=substr_count($name,".");
    if($count>1){//some cases have two dotes
        $name= preg_replace('/\.(?=.*\.)/', '_', $name);
    }
    list($txt, $ext) = explode(".", $name);
    return $ext;
}

$name = $_FILES['imageupload']['name'];//Name of the File
$image_extension = getextension($name);

 $allowed_extension = array("jpg", "png", "gif", "bmp", "jpeg","JPG","PNG","GIF","BMP","JPEG");
 $image_extension=getextension($name);
  if (!in_array($image_extension, $allowed_extension)) {
    $error_flag = 1;
    $message = "Invalid File Format";
 }

A: Parsing and checking extensions are not enough as per the question points to.
I suggest to check file EXIF (Exchangeable image information) data after loading a file.
You can put basic validation on basis on extension and after that if it succeed , check exif data of image.
For that you will need a separate DLL to load, that will have exif related function.
http://php.net/manual/en/ref.exif.php


text:
Q: Generate & List all Lucky numbers from 1 to n using Numpy A lucky number is found by listing all numbers up to n.
1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32
And then remove every second number so we get: 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31
Now the next number after 1 here is 3 so now remove every third number:
1,3,7,9,13,15,19,21,25,27,29
Now the next number after 3 is 7, so now remove every seventh number:
1,3,7,9,13,15,21,25,27,29
And the next number after 7 in our list is 9 so now remove every ninth number.
etc
The remaining numbers are lucky numbers: 1,3,7,9,13,15,21,25,31
Hello, I am a relatively new Python programmer who is trying to figure this out.
I did not even come close to solving this, and I want them up to the 100 billions so an advice of the best way to go about this is welcome. here is my best try to get this done in Numpy:
import numpy as np
a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31])
b = a[::2]           #using skip of 2 on our array
c = b[::3]           #using skip of 3 on our array
d = c[::7]           #using skip of 7 on our array
e = d[::9]           #using skip of 9 on our array
print(e)

It returns only 1 so this requires more advanced programming to find the lucky numbers,
I need some clever programming in order to automatically find the next skip also since I can't input millions of skips like I have done here with the skips of 2, 3, 7 & 9.

A: IIUC, one way using while loop with checker:
def find_lucky(n):
    arr = list(range(1, n+1))
    done = set()
    ind = 1
    while len(arr) >= (i:= arr[ind]):
        if i in done:
            ind += 1
        else:
            del arr[i-1::i]
            done.add(i)

    return arr

Output:
find_lucky(32)

# [1, 3, 7, 9, 13, 15, 21, 25, 31]


text:
Q: Using Moq to mock a repository that returns IQueryable How to I setup my Moq to return some values and having the tested service select the right one?
IRepository:
public interface IGeographicRepository
{
    IQueryable<Country> GetCountries();
}

Service:
public Country GetCountry(int countryId)
{
    return geographicsRepository.GetCountries()
             .Where(c => c.CountryId == countryId).SingleOrDefault();
}

Test:
    [Test]
    public void Can_Get_Correct_Country()
    {
        //Setup
        geographicsRepository.Setup(x => x.GetCountries()).Returns()
        //No idea what to do here.

        //Call
        var country = geoService.GetCountry(1);
        //Should return object Country with property CountryName="Jamaica"

        //Assert
        Assert.IsInstanceOf<Country>(country);
        Assert.AreEqual("Jamaica", country.CountryName);
        Assert.AreEqual(1, country.CountryId);
        geographicsRepository.VerifyAll();
    }

I'm basically stuck at the setup.

A: Couldn't you use AsQueryable()?
List<Country> countries = new List<Country>();
// Add Countries...
IQueryable<Country> queryableCountries = countries.AsQueryable();

geographicsRepository.Setup(x => x.GetCountries()).Returns(queryableCountries);

A: I suggest do not use AsQueryable(). it works only with some simple scenarios before you meet some specific methods on your ORM query language (Fetch, FetchMany, ThenFetchMany, Include, ToFuture and so on).
Better to use in memory database. Link below describes NHibernate Unit Testing.

We can either use a standard RDBMS or use an in memory database such as SQLite in order to get very speedy tests.

http://ayende.com/blog/3983/nhibernate-unit-testing

A: What you can do is write a private helper method that will generate an IQueryable of Country objects and have your mock return that.
[Test]
public void Can_Get_Correct_Country()
{
    // some private method
    IQueryable<Country> countries = GetCountries();

    //Setup
    geographicsRepository.Setup(x => x.GetCountries()).Returns(countries);

    //Should return object Country with property CountryName="Jamaica"
    //Call
    var country = geoService.GetCountry(1);

    //Assert
    Assert.IsInstanceOf<Country>(country);
    Assert.AreEqual("Jamaica", country.CountryName);
    Assert.AreEqual(1, country.CountryId);
    geographicsRepository.VerifyAll();
}


text:
Q: Laravel Migrate to AWS RDS using Lambda I am looking to deploy a Laravel app on AWS Lambda. The app requires a PostgreSQL database access.
The idea is am using Bref to deploy on AWS Lambda. I created a RDS PostgreSQL  database manually and updated the inbound rule and added the connection parameter to the .env file and serverless.yml template in the app.
After deploying the app I am receiving error SQLSTATE[42P01]: Undefined table. I belive the problem is that no migration occurred. So the question is how to migrate from Laravel/Lambda to RDS? Shall I use the artisan and the CLI? Or there is a way to create an automated way to migrate?
Thanks

A: When you don't make a custom setting for Postgresql, by default the sql queries should be like this
SELECT * FROM database_name.table_name

There are two options or you should specify the table names in all your laravel model files as below
protected $table = 'database_name.table';

or you should connect to rds postgresql via terminal and set the following
SET search_path TO database_name,public;

postgresql schemas


text:
Q: Structure of Planck volumes in String theory This question (as the previous one) is mostly arose from such pictures:

As explained by Brian Greene, this is something what our Universe should look like at a Planck scales in superstring theories.
Now, from an article on Wikipedia:

The central idea is that the visible 3D Universe is restricted to a brane inside a higher-dimensional space, called the "bulk". If the additional dimensions are compact, then no reference to the bulk is appropriate.

So here goes my questions (all for the compact extra dimensions):

*

*If we imagine our whole Universe as a giant 3D Volume, am I correct that this compactified "extra space" is a "complete subset" of that 3D Volume? I.e. (since I am terrible with math and it's terms), there're no "points" inside them (like coordinates) that do not belong to (shared with) our 3D Volume, right?..

*Are these shapes (called Calabi-Yau manifolds) meant to be connected with each other? Like, if you were small enough to place yourself inside 1 Planck volume of our Universe (or even smaller if it needed), could you use 1 (or any) of these compactified dimensions to travel from 1 Planck volume to another Planck volume?.. Or prof. Greene did picture them separately on purpose, to mean specifically that they're unconnected? And if he did, how a String can get from 1 Planck (or any) volume to another if there's no "bulk" - ?..

*If there's no higher-dimensional space (as suggested by any recent experiments, including this one), how compactified dimensions could be even considered "dimensions", if 3D (4D) is all we need to specify any point inside them? May be "solutions" (of some equation, like $\text{Lagrangian}$, or other) is the better term then?..

A: I cannot really answer this from a string theory point of view, just from the mathematical perspective of extra dimensions:

*

*I am not sure your intuition is correct, or if I just misunderstood you. The points in the compact dimensions are not a subset of our large 3D space, but what we call 'points' in the large dimensions are actually a subset of all of space, where the latter includes the compactified dimensions. Mathematically spoken, there are NO points that are either in
compactified dimensions OR in the large ones. Every point is just
a point in 9D space (ignoring the time-dimension for the whole answer, but taking the 6 compact dimensions from superstring theory) and if you
want to give a coordinate of such a point in local coordinates,
every point always has 9 coordinates, which you can write as
$x=(x^1,x^2,x^3,...,x^9)^T$, where, if we have 6 small dimensions,
w.l.o.g. we can say the first three coordinates can have arbitrary real values, while the other 6 can only have 'small' values,
or just loop very fast (meaning larger values corresponds to the
same point as smaller values), because the dimensions are so small.
Since we are so large compared to the compactified dimensions, it
seems we can never distinguish for any point with the same first 3
coordinates any of the coordinates from $x^4$ to $x^9$, so we only
use the first three to specify points in 3D space. So the points in
the compactified dimensions are not a subset of the 3D volume, and
also not the other way around, but the 3D world we experience is
actually a subset of the whole 9D universe, while it not relevant in
our three dimensional macroscopic world at which coordinates $x^4$
to $x^9$ any object is, if that is even defined, since even what
we call elementary particles seems to be larger than the
compactified dimensions, at least that is how I understand it.

*All the small dimensions are connected, and the picture you posted is misleading in that sense. If you would be small enough to move around in compactified dimensions, you would need to move along a large dimension to get to 'another' Calabi-Yau manifold (at another 3D point) (which is quite obvious if you think about it). Think about the example with the straw, which is a small cylinder: The length of the straw is the large dimension (let's assume the straw is infinitely long), while the circle around the 'hole' of the straw is the small dimension. You can specify a point on a cylinder by two coordinates, one that can have arbitrary real values (since the straw/cylinder is infinite), and one that loops as soon as you circled around the straw. Mathematically this is equivalent to gluing a circle to every point of the number line (remember we said the straw is infinite), which could be written as $\mathbb{R}\times S^1$. All these circles, $S^1$, are definitely connected. How? No matter at which point on the circle you are, you can always get to 'another circle' just by moving along the 'large' dimension, which does not change your coordinate on the circle, i.e. in the small dimension, but nevertheless could be pictured as moving you to 'a ('different') circle glued to another point on the straw'. It is analogous with 6D-CY-manifolds and 3 large dimensions, just harder, or impossible, to picture.

*I do not understand this question. If there are no additional dimensions additional to our large space-time dimensions and time, then there cannot be any compactified dimensions. But I do not think that was your question. :-D


text:
Q: Delete Ubuntu & allocate space back to Windows? So after fighting with Ubuntu, Microsoft Windows and UEFI for far too long, my patience has finally run out...
I have been unable to get everything working properly, and thus the kids exclusively use Windows 8.1 on this computer... So I want want to remove Ubuntu entirely.
But short of a (Windows 8.1) clean install, what is the easiest way to:
* Completely remove Ubuntu;
* Allocate the space back to Windows 8.1 and;
* Undo any changes to my UEFI/restore my UEFI back to its factory state (if required or recommended)?
Thanks!

A: First of all, sorry that you have problems with ubuntu. To remove it entirely and use the space in windows, boot with windows (I do not know which win you are using ), under control panel, administrative tools, find disk manager (name may be smt different). Find the partitions you have installed ubuntu. Format them to ntfs and set it as a windows drive by giving it drive letter. To restore your UEFI please follow this link How to fix the MBR for Windows 7?

A: If installed via Windows Installer, you can simply select Ubuntu from your programs list and choose uninstall.
From there, it is quite simple to re-allocate the data back to Windows 8.1.
You can do this by opening Start and typing Disk Management. You will see an option along the lines of manage disk partitions.
This program will allow you to select and allocate un-allocated data.
Simply right click Drive C (or whichever drive volume you wish to assign the un-allocated data to) and click Extend Volume, where you will follow the instructions given by the confirmation window.
However, if you did not install Ubuntu via WUBI, then you will still be using Disk Management program.
The process is similar: Simply select the drive volume labeled Ubuntu or something similar and delete the volume. Then follow the above steps to allocate the newly un-allocated data to a usable volume.
Hope this helps!


text:
Q: MYSQL - FK ERROR Oi, poderiam me ajudar? estou tentando adicionar as FK na tabela funcionarios, só que está dando este erro OBS estou criando as outras tabelas antes da funcionarios
20:29:15    CREATE TABLE Funcionarios( id INT(5) NOT NULL AUTO_INCREMENT, nomeCompleto VARCHAR(120) NOT NULL, cpf VARCHAR(11) NOT NULL, rg VARCHAR(15) NOT NULL, pis VARCHAR(20) NOT NULL, numeroDaCarteira VARCHAR(25) NOT NULL, dataNascimento DATE NOT NULL, dataEntrada DATE NOT NULL, dataSaida DATE NULL, endereco VARCHAR(80), bairro VARCHAR(50), cidade VARCHAR(50), estado CHAR(2), telefone VARCHAR(15), salario VARCHAR(10), agencia VARCHAR(10), conta VARCHAR(10), idCargo INT(5), idSetor INT(5), codBanco INT(5), idEstadocivil INT(5),   PRIMARY KEY (id),  FOREIGN KEY (idCargo) REFERENCES Cargo(id), FOREIGN KEY (idSetor) REFERENCES Setor (id), FOREIGN KEY (codBanco) REFERENCES Banco (codigo), FOREIGN KEY (idEstadocivil) REFERENCES EstadoCivil (id)  )  Error Code: 1215. Cannot add foreign key constraint 0.735 sec

Não sei o que fazer, estou tendo arrumar e nada, poderiam me ajudar?
CREATE DATABASE Empresa2;

CREATE TABLE Funcionarios(
id INT(5) NOT NULL AUTO_INCREMENT,
nomeCompleto VARCHAR(120) NOT NULL,
cpf VARCHAR(11) NOT NULL,
rg VARCHAR(15) NOT NULL,
pis VARCHAR(20) NOT NULL,
numeroDaCarteira VARCHAR(25) NOT NULL,
dataNascimento DATE NOT NULL,
dataEntrada DATE NOT NULL,
dataSaida DATE NULL,
endereco VARCHAR(80),
bairro VARCHAR(50),
cidade VARCHAR(50),
estado CHAR(2),
telefone VARCHAR(15),
salario VARCHAR(10),
agencia VARCHAR(10),
conta VARCHAR(10),
idCargo INT(5),
idSetor INT(5),
codBanco INT(5),
idEstadocivil INT(5),

PRIMARY KEY (id),

FOREIGN KEY (idCargo) REFERENCES Cargo(id),
FOREIGN KEY (idSetor) REFERENCES Setor (id),
FOREIGN KEY (codBanco) REFERENCES Banco (codigo),
FOREIGN KEY (idEstadocivil) REFERENCES EstadoCivil (id)

);

CREATE TABLE EstadoCivil(
id INT(5) NOT NULL AUTO_INCREMENT,
referencia VARCHAR(50),
PRIMARY KEY (id)
);

CREATE TABLE Cargo(
id INT(5) NOT NULL AUTO_INCREMENT,
referencia VARCHAR(50),
PRIMARY KEY (id)
);

CREATE TABLE Setor(
id INT(5) NOT NULL AUTO_INCREMENT,
referencia VARCHAR(50),
PRIMARY KEY (id)
);

CREATE TABLE Banco(
id INT(5) NOT NULL AUTO_INCREMENT,
referencia VARCHAR(50),
codigo int(5),
PRIMARY KEY (id)
);

A: Não estou usando MySql Server, mas dando uma adaptada no seu SQL descobri duas coisas:

*

*Você está tentando criar as chaves estrangeiras antes das tabelas,
isso é impossível.

*O campo chave estrangeira codBanco da tabela de funcionários
referencia o campo codigo da tabela banco, que além de permitir
nulos não é chave primária (deve referenciar o Id da tabela).

Corrigi esses erros e funcionou normal aqui.
Agora, uma coisa que sempre recomendo fazer é separar os scripts por tarefa, senão vai virar uma maçaroca e você nunca vai entender.
Dessa forma, recomendo que crie os scripts separadamente, sendo um que:

*

*Crie o banco e o selecione - i.e 1-CriaESelecionaBanco.sql.

*Crie APENAS as tabelas - 2-CriaTabelas.sql.

*Depois crie as chaves primárias das tabelas - 3-CriaChavesPrimarias.sql .

*Por último APENAS as chaves estrangeiras - 4-CriaChavesEstrangeiras.sql.

Fazendo isso fica bem mais difícil de errar.


text:
Q: Arranging m distinct groups of k elements each? There are n elements in total which is already divided into m groups of k elements each. Thus, n=m*k.
The question is, how many arrangements of these m groups are possible?
I came to a possible solution of n!/m! but am not sure if that covers all permutations possible among each group (i.e, k! ways of arranging each group).
The original problem is as follows:
There exists an array of n distinct numbers. This array is divided into m sub-sequences of k elements each.
All elements of a subsequence are either greater than or less than all elements of another subsequence.
I have to find the number of possible permutations of the indices in the array which may appear in the sorted array.

A: The groups are completely determined by the requirement that all elements of a subsequence are either greater than or less than all elements of another subsequence.  As you realized, the elements in each of the $m$ groups of $k$ elements can be arranged in $k!$ orders.  The $m$ subsequences can be arranged in $m!$ orders.  Thus, the number of possible permutations of the indices in the array is $m!(k!)^m$.


text:
Q: Algolia&Angular : NullInjectorError: No provider for NgAisInstantSearch I am trying to add an algolia search field to my angular app but I still come across this error. I followed this tutorial (link) but I have the impression that there is an error but I cannot find it. In this deposit I have copied / pasted what they say : https://github.com/filol/algolia-test
I tried to add NgAisInstantSearch in the providers but I come across other errors and in their examples they do not (eg : link example)
Error :
ERROR NullInjectorError: StaticInjectorError(AppModule)[AutocompleteComponent -> NgAisInstantSearch]:
  StaticInjectorError(Platform: core)[AutocompleteComponent -> NgAisInstantSearch]:
    NullInjectorError: No provider for NgAisInstantSearch!
    at NullInjector.get (http://localhost:4200/vendor.js:59947:27)
    at resolveToken (http://localhost:4200/vendor.js:74865:24)
    at tryResolveToken (http://localhost:4200/vendor.js:74791:16)
    at StaticInjector.get (http://localhost:4200/vendor.js:74641:20)
    at resolveToken (http://localhost:4200/vendor.js:74865:24)
    at tryResolveToken (http://localhost:4200/vendor.js:74791:16)
    at StaticInjector.get (http://localhost:4200/vendor.js:74641:20)
    at resolveNgModuleDep (http://localhost:4200/vendor.js:85828:29)
    at NgModuleRef_.get (http://localhost:4200/vendor.js:86894:16)
    at resolveDep (http://localhost:4200/vendor.js:87425:45)


text:
Q: Copy file does not copy but gives error php_network_getaddresses: getaddrinfo failed: -PHP I am trying to copy an image from an url eg: http://www.slate.com/content/dam/slate/articles/technology/technology/2013/01/130110_TECH_SamsungCES.jpg.CROP.rectangle3-large.jpg which is accessible via the browser, but the error is: *Warning: copy() [function.copy]: php_network_getaddresses: getaddrinfo failed: Name or service not known in*
$file_name="http://www.slate.com/content/dam/slate/articles/technology/technology/2013/01/130110_TECH_SamsungCES.jpg.CROP.rectangle3-large.jpg";

copy($file_name,"uploads/");

No error is returned when I use move_uploaded_file($file_name,"uploads/"); and file is not copied too.
Any clue to what is wrong here?

A: <?php
$file_name="http://www.slate.com/content/dam/slate/articles/technology/technology/2013/01/130110_TECH_SamsungCES.jpg.CROP.rectangle3-large.jpg";

copy($file_name,"test.jpg");
?>

This works , make sure that:

*

*You are specifying a destination filename for the copy command (not
just a directory)

*in your php.ini allow_url_fopen = On

A: It also works here, but try the next code, just changed the domain name to the resolved IP address:
Looks like the server is not resolving the domain correctly.
<?php

$file_name="http://50.17.234.211/content/dam/slate/articles/technology/technology/2013/01/130110_TECH_SamsungCES.jpg.CROP.rectangle3-large.jpg";

copy($file_name,  "uploads/130110_TECH_SamsungCES.jpg.CROP.rectangle3-large.jpg");

?>


text:
Q: GATEWAY_TIMEOUT deployment issues of the application built using NextJS on Vercel and Cloudflare We made an application using ReactJS.
Everything was working fine, except that we were not able to preview pages when it was shared on a social media platform. We tried using React-Helmet and other methods, but it did not resolve any issues. It is mentioned in this StackOverflow question How to render a shared post's tilte and tags when shared in social platforms or other applications?.
We then transitioned to NextJS, so we could SSR (server-side render) some of the pages we wanted to preview when shared on social media apps. This would also potentially help with SEO.
Deployment success on local host using ngrok
The transition worked functionally on a local host, and I can preview when the application is hosted via ngrok. But, I am having issues deploying it through Cloudflare and Vercel for production.
Vercel:
First, I attempted to deploy on Vercel. The web app was successfully deployed and is operational. One of my test pages is server-side rendered using the getServerSidePrpos() async function, and I can preview when the app is hosted on ngrok. But, when hosting the app through Vercel and I visit the page with getServerSideProps(), the following issue occurs:

Cloudflare:
Method 01-  I also attempted to deploy the app through CloudFlare and built it using "yarn build". The web app was deployed but threw a 404 Not Found error when navigating to a page that was server-side rendered.
Method 02-  I also tried to deploy on Cloudflare, by building it using the command "npx @cloudflare/next-on-pages --experimental-minify." But, got unlucky with this method too. The build is not complete and throws the following error:

The following next.config file settings were used for Cloudflare-method 02 (only and not for other methods) deployment.
module.exports = {
  experimental: {
    runtime: 'experimental-edge'
  },
  reactStrictMode: true,
  swcMinify: true
}

I used the following package versions for all my deployment methods.
"node": "^17.0.0",
"next": "^13.1.6",
"react": "^18.2.0"
"yarn": "^1.22.17",
"react-dom": "^18.2.0",


text:
Q: Notification is not fully match parent My notification is not fully match parent this is how it looks

this is how i'm creating my notification
NotificationCompat.Builder(this, CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher_foreground)
                .setStyle(NotificationCompat.DecoratedCustomViewStyle())
                .setCustomContentView(remoteViews)
                .setContentIntent(
                    PendingIntent.getActivity(
                        this,
                        0,
                        Intent(
                            this,
                            MainActivity::class.java
                        ).setFlags(Intent.FLAG_ACTIVITY_NEW_TASK),
                        0
                    )
                )
                .setAutoCancel(false)
                .setPriority(NotificationCompat.PRIORITY_HIGH)
                .build()

A: that happens, because you are targetting Android 12. And since this version you can't create "real" customizable Notification, you have only some area to occupy


text:
Q: Recursive definition of this sequence I'm having some trouble finding a recursive definition for the following sequence:
$x_0 = \sqrt{1+n}$
$x_1 = \sqrt{1+n\sqrt{1+(n+1)}}$
$x_2 = \sqrt{1+n\sqrt{1+(n+1)\sqrt{1+(n+2)}}}$
$x_3 = \sqrt{1+n\sqrt{1+(n+1)\sqrt{1+(n+2)\sqrt{1+(n+3)}}}}$
and so on (where $n \in \mathbb{N}$). I tried using something like $x_{i+1} = \sqrt{1 + n f(x_i)}$ where $f$ would be a function that sends $n$ to $n+1$ wherever $n$ appears in $x_i$. So for instance $f(x_0) = \sqrt{1 + (n+1)}$ and $f(x_1) = \sqrt{1+(n+1)\sqrt{1+(n+2)}}$. My problem is that I can't figure out an explicit form for $f$. If it's any help, the limit of the sequence is $n+1$.

A: One has $x_k(n) = f_{k+1}(n)$, where $(f_k)_{k \geqslant 0}$ is the sequence of functions defined recursively as follows:
$f_0(n) = 1$
$f_{k+1}(n) = \sqrt{1+nf_k(n+1)}$
Indeed,
$f_0(n) = 1$
$f_1(n) = \sqrt{1+n}$
$f_2(n) = \sqrt{1+n\sqrt{1+(n+1)}}$
$f_3(n) = \sqrt{1+n\sqrt{1+(n+1)\sqrt{1+(n+2)}}}$
etc.

A: Recall that a sequence $(x_k)$ can be defined recursively if there exists some function $g$ such that $x_{k+1}=g(x_k)$ for every $k$.
Of course, every given strictly increasing sequence, such as the sequences considered in the question, can be defined recursively, using any function $g$ defined on $X=\{x_k\mid k\geqslant0\}$ by $g(x_k)=x_{k+1}$ and, say, by $g(x)=0$ for every $x\notin X$.
This version of the question is rather shallow since every sequence $(x_k)$ can be defined recursively in this sense except if there exists $k<\ell$ such that $x_k=x_\ell$ and $x_{k+1}\ne x_{\ell+1}$, which never happens for strictly monotonous sequences.
A more interesting version would be to ask whether all the sequences $(x_k)$ in the question can be simultaneously defined recursively, that is, whether there exists a common function $g$ for every value of $x_0$, or, equivalently, for every value of $n$.
Then the answer is negative.
To wit, for $n=4$, $x_0=\sqrt5$ and $x_1=\sqrt{1+4\sqrt6}$ while, for $n=2$, $x_1=\sqrt5$ and $x_2=\sqrt{1+2\sqrt{1+3\sqrt5}}$, thus, one would need that $$\sqrt{1+4\sqrt6}=g(\sqrt5)=\sqrt{1+2\sqrt{1+3\sqrt5}}$$ which is absurd.


text:
Q: Change `` element attributes from objective-C I'm trying to change the value of an element in a <input type="checkbox"> from null to checked.
How would I do this from objective-C (iOS application)?
Here's the relevant HTML of the page

    <input id="chk_Assignments" type="checkbox" class="ShowAll" />
    Show All

I was thinking I'd use POST or something, but I'm not sure how to access the element, add a checked attribute, and set the value of the attribute to "checked".

A: NSString *javaScript = @"document.getElementById('chk_Assignments').setAttribute('checked', 'checked');";

// Make the UIWebView method call
NSString *response = [webViewA stringByEvaluatingJavaScriptFromString:javaScript];
NSLog(@"javascript result: %@", response);

If HTML page got jQuery included, the javascript could be simplified:
NSString *javaScript = @"$('#chk_Assignments').attr('checked', 'checked');";
NSString *response = [webViewA stringByEvaluatingJavaScriptFromString:javaScript];
NSLog(@"javascript result: %@", response);


text:
Q: CursorLoader and CursorTreeAdapter I'm trying to use CursorLoader with a CursorTreeAdapter but am running into an issue I can't figure out. (If you have a working example of this, feel free to skip the rest and attach it below. I would be very thankful)
The first time I open a group, everything works fine. If I then close and re-open the group, I get an overflow error. Here is the error:
V/SpellBook(29520): Activity being created
D/SpellBook(29520): onCreateLoader for id 123456
V/SpellBook(29520): Resuming
V/SpellBook(29520): Processing query for uri content://com.zalzala.spellbook.SpellProvider/levels/bard
D/SpellBook(29520): onLoadFinished() for id 123456
D/SpellBook(29520): onCreateLoader for id 3
V/SpellBook(29520): Processing query for uri content://com.zalzala.spellbook.SpellProvider/class/bard/3
D/SpellBook(29520): onLoadFinished() for id 3

Everything is fine here. So far I've opened the activity and opened group number 3. Here is what happens if I close group 3 and open it again:
D/SpellBook(29520): onLoadFinished() for id 3
D/SpellBook(29520): onLoadFinished() for id 3
D/SpellBook(29520): onLoadFinished() for id 3
D/SpellBook(29520): onLoadFinished() for id 3
D/SpellBook(29520): onLoadFinished() for id 3
(... and a lot more of these)
    E/AndroidRuntime(29520): FATAL EXCEPTION: main
E/AndroidRuntime(29520): java.lang.StackOverflowError
E/AndroidRuntime(29520):    at java.util.HashMap.get(HashMap.java:302)
E/AndroidRuntime(29520):    at android.database.sqlite.SQLiteCursor.getColumnIndex(SQLiteCursor.java:355)
E/AndroidRuntime(29520):    at android.database.CursorWrapper.getColumnIndex(CursorWrapper.java:67)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment$MyExpandableListAdapter.getChildrenCursor(SpellListView.java:216)
E/AndroidRuntime(29520):    at android.widget.CursorTreeAdapter.getChildrenCursorHelper(CursorTreeAdapter.java:106)
E/AndroidRuntime(29520):    at android.widget.CursorTreeAdapter.setChildrenCursor(CursorTreeAdapter.java:159)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment.onLoadFinished(SpellListView.java:183)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment.onLoadFinished(SpellListView.java:1)
E/AndroidRuntime(29520):    at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:413)
E/AndroidRuntime(29520):    at android.support.v4.app.LoaderManagerImpl.initLoader(LoaderManager.java:547)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment$MyExpandableListAdapter.getChildrenCursor(SpellListView.java:217)
E/AndroidRuntime(29520):    at android.widget.CursorTreeAdapter.getChildrenCursorHelper(CursorTreeAdapter.java:106)
E/AndroidRuntime(29520):    at android.widget.CursorTreeAdapter.setChildrenCursor(CursorTreeAdapter.java:159)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment.onLoadFinished(SpellListView.java:183)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment.onLoadFinished(SpellListView.java:1)
E/AndroidRuntime(29520):    at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:413)
E/AndroidRuntime(29520):    at android.support.v4.app.LoaderManagerImpl.initLoader(LoaderManager.java:547)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment$MyExpandableListAdapter.getChildrenCursor(SpellListView.java:217)
E/AndroidRuntime(29520):    at android.widget.CursorTreeAdapter.getChildrenCursorHelper(CursorTreeAdapter.java:106)
E/AndroidRuntime(29520):    at android.widget.CursorTreeAdapter.setChildrenCursor(CursorTreeAdapter.java:159)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment.onLoadFinished(SpellListView.java:183)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment.onLoadFinished(SpellListView.java:1)
E/AndroidRuntime(29520):    at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:413)
E/AndroidRuntime(29520):    at android.support.v4.app.LoaderManagerImpl.initLoader(LoaderManager.java:547)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment$MyExpandableListAdapter.getChildrenCursor(SpellListView.java:217)
E/AndroidRuntime(29520):    at android.widget.CursorTreeAdapter.getChildrenCursorHelper(CursorTreeAdapter.java:106)
E/AndroidRuntime(29520):    at android.widget.CursorTreeAdapter.setChildrenCursor(CursorTreeAdapter.java:159)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment.onLoadFinished(SpellListView.java:183)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment.onLoadFinished(SpellListView.java:1)
E/AndroidRuntime(29520):    at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:413)
E/AndroidRuntime(29520):    at android.support.v4.app.LoaderManagerImpl.initLoader(LoaderManager.java:547)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment$MyExpandableListAdapter.getChildrenCursor(SpellListView.java:217)
E/AndroidRuntime(29520):    at android.widget.CursorTreeAdapter.getChildrenCursorHelper(CursorTreeAdapter.java:106)
E/AndroidRuntime(29520):    at android.widget.CursorTreeAdapter.setChildrenCursor(CursorTreeAdapter.java:159)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment.onLoadFinished(SpellListView.java:183)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment.onLoadFinished(SpellListView.java:1)
E/AndroidRuntime(29520):    at android.support.v4.app.LoaderManagerImpl$LoaderInfo.callOnLoadFinished(LoaderManager.java:413)
E/AndroidRuntime(29520):    at android.support.v4.app.LoaderManagerImpl.initLoader(LoaderManager.java:547)
E/AndroidRuntime(29520):    at com.zalzala.spellbook.SpellListView$ExpandableListCursorLoaderFragment$MyExpandableListAdapter.getChildrenCursor(SpellListView.java:217)
E/AndroidRuntime(29520):    at android.widget.CursorTreeAdapter.getChildrenCursorHelper(CursorTreeAdapter.ja
W/ActivityManager( 6887):   Force finishing activity com.zalzala.spellbook/.SpellListView

So for some reason onLoadFinished() gets called over and over for the child cursor when re-opening a group.
Here is my loader implementation:
    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        // TODO Auto-generated method stub
        Log.d(Spellbook.TAG,"onCreateLoader for id "+id);
        if (id <123456){
            Uri spellUri = Uri.withAppendedPath(SpellProvider.CONTENT_URI, "class");
            spellUri = Uri.withAppendedPath(spellUri, mCLASS);
            spellUri = ContentUris.withAppendedId(spellUri, id);
            return new CursorLoader(getActivity(), spellUri, null, null, null, null);
        }else {
            //get group cursor
            Uri groupUri = Uri.withAppendedPath(SpellProvider.CONTENT_URI, "levels");
            groupUri = Uri.withAppendedPath(groupUri, mCLASS);
            return new CursorLoader(getActivity(), groupUri, null, null, null, null);
        }
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
        // TODO Auto-generated method stub
        int id = loader.getId();
        Log.d(Spellbook.TAG,"onLoadFinished() for id "+id);
        if (id < 123456){
            //child cursor
            ((CursorTreeAdapter) mAdapter).setChildrenCursor(id, data);
        } else {
            ((CursorTreeAdapter) mAdapter).setGroupCursor(data);
        }

    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        // TODO Auto-generated method stub
        int id = loader.getId();
        Log.d(Spellbook.TAG,"onLoaderReset() for id "+id);
        if (id < 123456){
            //child cursor
            ((CursorTreeAdapter) mAdapter).setChildrenCursor(id, null);
        } else {
            ((CursorTreeAdapter) mAdapter).setGroupCursor(null);
        }

    }

I call CursorTreeAdapter with the constructor which specifies auto requery as false.
    public class MyExpandableListAdapter extends CursorTreeAdapter {

        public MyExpandableListAdapter(Cursor cursor, Context context) {
            super(cursor, context, false); //do not auto requery. pretty sure CursorLoader needs this.
        }

        @Override
        protected Cursor getChildrenCursor(Cursor groupCursor) {
            // Given the group, we return a cursor for all the children within that group
            int id = groupCursor.getInt(groupCursor.getColumnIndex(SpellDbAdapter.KEY_LEVEL));
            getLoaderManager().initLoader(id, null, ExpandableListCursorLoaderFragment.this);
            return null;
        }

Thanks for any help!

A: This is an old question but there's still no correct answer (well now there is).
The MyExpandableListAdapter has a getChildrenCursor(Cursor) method:
@Override
protected Cursor getChildrenCursor(Cursor groupCursor) {
    int id = groupCursor.getInt(groupCursor.getColumnIndex(SpellDbAdapter.KEY_LEVEL));
    getLoaderManager().initLoader(id, null, ExpandableListCursorLoaderFragment.this);
    return null;
}

The method starts the Loader with the initLoader call. Once the data is loaded, onLoadFinished will be called and the children cursor is set:
@Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
    // some code
    ((CursorTreeAdapter) mAdapter).setChildrenCursor(id, data);
    // some more code
}

The CursorTreeAdapter.setChildrenCursor method goes like this:
public void setChildrenCursor(int groupPosition, Cursor childrenCursor) {
    MyCursorHelper childrenCursorHelper = getChildrenCursorHelper(groupPosition);
    childrenCursorHelper.changeCursor(childrenCursor, false);
}

It retrieves the childrenCursorHelper with a call to CursorTreeAdapter.getChildrenCursorHelper:
synchronized MyCursorHelper getChildrenCursorHelper(int groupPosition, boolean requestCursor) {
    MyCursorHelper cursorHelper = mChildrenCursorHelpers.get(groupPosition);

    if (cursorHelper == null) {
        if (mGroupCursorHelper.moveTo(groupPosition) == null) return null;

        final Cursor cursor = getChildrenCursor(mGroupCursorHelper.getCursor());
        cursorHelper = new MyCursorHelper(cursor);
        mChildrenCursorHelpers.put(groupPosition, cursorHelper);
    }

    return cursorHelper;
}

Under certain circumstances the childrenCursorHelper doesn't exist yet and the method now calls getChildrenCursor(Cursor) which is the method that started the whole call chain. Logically we will run into a StackOverflowError.
This is a bug in the CursorTreeAdapter class. While others recommend to use the BaseExpandableAdapter instead, I recommend to create a custom CursorTreeAdapter class and make the necessary changes and fixes.
The StackOverflowError can easily be fixed by changing the getChildrenCursorHelper method. Create the MyCursorHelper first, add it to mChildrenCursorHelpers and then retrieve the children cursor if retrieveChildCursor is set to true (new parameter). Calling the method from setChildrenCursor means we pass false to not get into the endless recursion.
synchronized MyCursorHelper getChildrenCursorHelper(int groupPosition, boolean retrieveChildCursor) {
    MyCursorHelper cursorHelper = mChildrenCursorHelpers.get(groupPosition);

    if (cursorHelper == null && mGroupCursorHelper.moveTo(groupPosition) != null) {
        cursorHelper = new MyCursorHelper(null);
        mChildrenCursorHelpers.put(groupPosition, cursorHelper);

        if (retrieveChildCursor) {
            final Cursor cursor = getChildrenCursor(mGroupCursorHelper.getCursor());
            if (cursor != null) {
                cursorHelper.changeCursor(cursor, false);
            }
        }
    }

    return cursorHelper;
}

Also remove the code in the MyCursorHelper.deactivate method since the CursorLoader takes care of closing obsolete cursors.

A: Ok, so talking to someone at Google, Expanded Lists should probably have been deprecated a long time ago. If you really need to use cursor loaders and expanded lists, extend the base adapter. If you don't really need it, go ahead and not use cursor loader.
Feel free to correct me :)

A: call destroyLoader() on onGroupCollapsed(). But it doesn't solve problem completely. Looking on CursorTreeAdapter realization make me sure to not use it with CursorLoader.
It's really better to extend BaseExpandableAdapter. This way allow to avoid unnecessary (in case of using loaders) usage of content observers. In my custom adapter i'm keep created loaders in sparse array and destroy them on group collapse. Works well :)

A: I think when we use initLoader, it will make stack full,
try using restartLoader instead.
@Override
    protected Cursor getChildrenCursor(Cursor groupCursor) {
        // TODO Auto-generated method stub
        Bundle b = new Bundle();
        //b.putString("Artist", "\""+groupCursor.getString(groupCursor.getColumnIndex(artist.ARTIST))+"\"");
        b.putString("Artist", groupCursor.getString(groupCursor.getColumnIndex(artist.ARTIST)));
        getLoaderManager().restartLoader(groupCursor.getPosition(), b, MpArtist.this);
        return null;
    }

A: Try this:
@Override
public void onLoadFinished(Loader<Cursor> loader, final Cursor data) {
    // ...
    final int id = loader.getId();
    new Handler().post(new Runnable() {
        @Override
        public void run() {
            ((CursorTreeAdapter) mAdapter).setChildrenCursor(id, data);
        }
    });
 }


text:
Q: Seaborn histogram with horizontal coloring I'm trying to plot a several histograms with plt.subplots() like this:
chart_len  = 15
chart_height = 25

fig, axs = plt.subplots(len(weight_classes),figsize=(chart_len,chart_height))

sns.set_theme(style="darkgrid",font_scale=2.5)
colors = sns.color_palette('GnBu_d',len(weight_classes)+1)

for i, wc in enumerate(activity_wc):
        data = activity_wc[wc]
        bins = [i for i in range(0,data['total_strikes_attempted'].max(),5)]

        sns.histplot(data,x='total_strikes_attempted', bins=bins, ax=axs[i], kde=True, stat='probability', color=colors[-(i+2)])

This retrieves this image:
histogram subplots
What I'd like though would be for the bars to use the palette, so they would change colors horizontally. Does anyone know how to do this?

A: You ax.containers[0] contains all the histogram bars. You can loop through them and set individual colors. The norm (mapping the x-values to the range 0-1) can be based on the first and last bin boundaries.
Basically, the code would look like:
ax = sns.histplot(...)
norm = plt.Normalize(bins[0], bins[-1])
cmap = sns.color_palette('GnBu_d', as_cmap=True) # use 'GnBu_r_d' for the reversed map
for bar in ax.containers[0]:
    bar.set_color(cmap(norm(bar.get_x())))

Supposing activity_wc is the result of activity.groupby('weight_class'), the plot can be obtained more directly from the original dataframe. sns.displot with row='weight_class' would take care of the grouping and creating a grid of subplots. Note that the figsize would be controlled by height= with the height of an individual subplot, and aspect= with the aspect ratio of one subplot (width divided by height).
Here is an example starting from dummy data. Note that the bins are starting just smaller than zero to avoid rounding errors, and that one bin edge is added to make sure the highest value falls into the last bin. (Use sns.displot(..., facet_kws={'sharex':False}) to have x-tick labels for each subplot.)
import matplotlib.pyplot as plt
import numpy as np
import seaborn as sns
import pandas as pd

weight_classes = ['Flyweight', 'Bantamweight', 'Featherweight', 'Lightweight', 'Welterweight',
                  'Middleweight', 'Light Heavyweight', 'Heavyweight']
activity = pd.DataFrame({'weight_class': np.random.choice(weight_classes, 1000),
                         'total_strikes_attempted': np.concatenate([np.random.binomial(120, p, 100)
                                                                    for p in np.linspace(0.2, 0.9, 10)])})
sns.set_theme(style="darkgrid", font_scale=0.8)

bins = np.arange(-0.00001, max(activity['total_strikes_attempted']) + 5, 5)
g = sns.displot(data=activity, x='total_strikes_attempted',
                row='weight_class', row_order=weight_classes,
                kind='hist', stat='probability', kde=True, palette='GnBu_d',
                height=1.6, aspect=3)
norm = plt.Normalize(bins[0], bins[-1])
cmap = sns.color_palette('GnBu_d', as_cmap=True) # use 'GnBu_r_d' for the reversed map
for ax in g.axes.flat:
    ax.margins(x=0) # less white space left and right
    for bar in ax.containers[0]:
        bar.set_color(cmap(norm(bar.get_x())))
plt.tight_layout()
plt.show()


text:
Q: Android alternative to java.awt (BufferedImage and Raster) for my final year project I am developing an android app that can capture the image of a leaf and identify what type of tree it came from.  I have a nearly completed PC version (developed in java) and i am starting the process of porting it to android.  Although BufferedImage and Raster make up a key part of my program, this is a problem because java.awt is missing in android, so this means i have to alter the library.
I am using a library that was developed by my lecturer, the method below converts a BufferedImage to an IntImage(a type that is used throughout the package) using Raster.
I'm basically asking are there any android alternatives to java.awt that i can use?
Here's the code:
public static int[][] readAsInts(String fileName) throws IOException {
    int[][] pixels;

    System.out.println("File: " + fileName);

    String [] types = ImageIO.getReaderFileSuffixes();
    for (int l = 0; l < types.length; l++) {
        System.out.println("Type " + l + ": " + types[l]);
    }
    File f = new File(fileName);
    BufferedImage bi;
    bi = ImageIO.read(f);

    int cols = bi.getWidth();
    int rows = bi.getHeight();

    System.err.println("Number of bands: " + bi.getRaster().getNumBands());
    Raster rast = bi.getRaster();

    pixels = new int[rows][cols];
    for (int r = 0; r < rows; r++) {
        rast.getSamples(0, r, cols, 1, 0, pixels[r]);
    }
    return pixels;
} // readAsInts

Thanks guys!
EDIT: For anyone who doesn't know the raster stores the pixel values for the BufferedImage, along with the number of bands (red, green, blue, alpha), so this algorithm takes the pixel values ad stores them in a 2d array (pixels).

A: Sounds like you just want to work with bitmaps and be able to manipulate the pixels themselves in an array. The Bitmap class comes to mind along with its getPixels method. Remember though that you have much more limited memory on a mobile device. It's easy to run into out of memory problems when working with large bitmaps.
Another route would be to use the NDK. I don't have much experience there, but AndroidBitmap_lockPixels and AndroidBitmap_unlockPixels are probably a good place to start.
Lastly, yet another option that should perform pretty well is to use RenderScript.
If all you're looking to do is load an image into an int array though, Bitmap.getPixels should be quite sufficient.

A: You can convert a BufferedImage to a PNG or JPEG, then send it via HTTP to Android which can then convert the PNG or JPEG back to a Bitmap and use it.
When Android needs to send any image, send it as PNG or JPEG via network, and then convert the PNG to BufferedImage and use it in your program.


text:
Q: Swift - How can I select multiple rows in tableview without segue My development environment is swift3, xcode8.
I'm making a list app like Apple's message app.
When I select the list in the table view, I go to the detail page (through the seg) and now I want to implement multiple delete functions, but there's a problem. When I edit mode, I can see the selection window, but if I select that selection window, just go to the detail page.
Maybe before going to the detail page through Seg. I think I should make it a multiple choice. What should I do?

A: Make sure you conform something like below code;
class TableviewController:UITableViewController{
override func viewDidLoad() {
    super.viewDidLoad()
    var isMultipleSelectionActive = false
    var selectedItems: [String: Bool] = [:]
    tableView.allowsMultipleSelectionDuringEditing = true
    tableView.setEditing(true, animated: false)
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
    cell.textLabel?.text = "\(indexPath.row)"
    return cell
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 10
}

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    let selectedItem = items.objectAtIndex(indexPath.row)
    //add to selectedItems
    selectedItems[selectedItem] = true
}

func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
    let selectedItem = items.objectAtIndex(indexPath.row)
    // remove from selectedItems
    selectedItems[selectedItem] = nil
}

func getStatusOfSelectedItems() {
    for item in selectedItems {
        println(item)
    }
}

//You should override shouldPerformSegueWithIdentifier and return false if isMultipleSelectionActive is true

override func shouldPerformSegue(withIdentifier identifier: String?, sender: Any?) -> Bool {
    if let identifierName = identifier {
        if identifierName == "NameOfYourSegueIdentifier" {
             if isMultipleSelectionActive {
                  return false
             }
        }
    }
    return true
}
}

A: This code used to select the multiple row
class TableViewController: UITableViewController
{
    var lastSelectedIndexPath = NSIndexPath(forRow: -1, inSection: 0)

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
    {
        let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)

        // Configure the cell...
        cell.textLabel!.text = "row: \(indexPath.row)"

        if cell.selected
        {
            cell.selected = false
            if cell.accessoryType == UITableViewCellAccessoryType.None
            {
                cell.accessoryType = UITableViewCellAccessoryType.Checkmark
            }
            else
            {
                cell.accessoryType = UITableViewCellAccessoryType.None
            }
        }

        return cell
    }

    override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
    {
        let cell = tableView.cellForRowAtIndexPath(indexPath)

        if cell!.selected
        {
            cell!.selected = false
            if cell!.accessoryType == UITableViewCellAccessoryType.None
            {
                cell!.accessoryType = UITableViewCellAccessoryType.Checkmark
            }
            else
            {
                cell!.accessoryType = UITableViewCellAccessoryType.None
            }
        }
    }


text:
Q: CSS not rendering in FastAPI Jinja2Template UPDATE: This solved.  I didn't write the correct CSS!

I am trying to render a few things in HTML.  Multiple things are causing problems but I've included the most basic part I want to get working.  If I can get this to work, I can get the rest to work.
Very simple app structure:
app
  api.py
  static
    styles.css
  templates
    index.html

This is the contents of index.html:
<html>
    <h1>
        Title here
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <link href="{{ url_for('static', path='/styles.css') }}" rel="stylesheet">
    </h1>
</html>

This the the CSS I'm using:
h1 {
    color: red
    text-align: center
}

Relevant code in api.py:
from fastapi.templating import Jinja2Templates
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles

app = FastAPI()

templates = Jinja2Templates(directory="templates")
app.mount("/static", StaticFiles(directory="static"), name="static")

@app.get("/", response_class=HTMLResponse)
def read_mean_cpu(request: Request, device_id):
    return templates.TemplateResponse("index.html", {"request": request}))

Any idea why the CSS isn't taking?


text:
Q: Why do we use radio waves for communication when gamma rays are more powerful? NASA and other space programs primarily use radio waves to transfer information from spacecraft back to earth. Why don't they use gamma rays, which are more powerful?
Since radio waves have less energy than gamma rays, isn't it more likely for radio waves to get blocked by clouds, whereas gamma rays can pass through clouds?

A: Gamma rays are "more powerful" than radio waves only in the sense that the photon energy of the former is much higher; "gamma" radiation is usually taken to mean electromagnetic radiation arising from decays of atomic nucleusses and other nuclear processes; they have a wavelength of well less than a nanometer, whereas AM radio waves have wavelengths of hundreds of meters. A typical gamma photon energy is of the order of $1{\rm MeV}$; an optical photon is of the order of a few ${\rm eV}$ and a radio wave of the order of $10^{-8}{\rm eV}$.
Radio waves are easy to make at high powers - tens of kilowatts - with alternating electric currents produced by primitive electronic technology. They are also easy to modulate, i.e. to have a signal encoded onto them- with the same technology using sophisticated modulation schemes. The effects of such waves of even these powers on biological systems is very mild. Gamma rays of this power are hugely expensive to produced with human technology; only nuclear processes will make them. They can only be modulated by mechanical means - deflexion from mirrors and shutters, so would be useless for high speed communication - of the order of ${\rm GBps}$ which we nowadays routinely achieve with radio technology. Gamma rays of this power are utterly lethal to any biological system in their path. Moreover, their high photon energy means that they interact with and are swiftly (in comparison with radio broadcast distances) absorbed by air. They would be useless for terrestrial communications from this last point of view also. Radio waves, with their low photon energy, have very little interaction with clear air.

A: First, available gamma rays sources are not "more powerful" compared to electromagnetic wave transmitters, i.e., they emit much less energy/time.
Second, gamma rays are extremely dangerous for the human and all other living beings. You would not survive next to such a source even when exposed only for a very short time.
Third, the signal modulation and detection of gamma rays is more cumbersome than that of radio waves.


text:
Q: Write to file skipped on first run I am new to C# and have code that will obtain the userName from the LogIn and begin a program in the background if this is the users first time loging into the system. However, today I noticed when running the program and checking my log file that the program skips adding data to the file that is also created on the initial run. Any run after the initial run, the userName is included into the .log file and if the userName does not match what is in the .log file the file is overwritten to include the new userName. Can someone please help me figure out what happened or if I'm missing something?
Thank you in advance.
 using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    using System.IO;
    using System.Diagnostics;

    namespace User
    {
        public partial class Form1 : Form
        {
            public const string dir = @"C:\Numara";
            public const string path = dir + @"\Audit.log";
            public const string TrackIT = @"C:\Program Files\Numara Software\Numara Track-It!\Track-It! Server\Audit32.exe";

            public Form1()
            {
                InitializeComponent();
            }

            private void Form1_Load(object sender, EventArgs e)
            {
                //returns user name
                //label1.Text = System.Environment.UserName.ToString();
                string userName = System.Environment.UserName;  //user name

                if (!Directory.Exists(dir))
                    //directory does not exist
                    //create it
                    Directory.CreateDirectory(dir);  //creates directory

                //by this point directory is created

                //now check file
                if (!File.Exists(path))
                    //file does not exist, so create it
                    File.Create(path);

                //Read data from the .log file
                string line = System.IO.File.ReadAllText(path);

                //if the name of the logged in user
                //is the same as the user name of the text file
                //then exit program

--------- the debugging stops here and skips to end the program on the first run---------

                if (line == userName)
                    Application.Exit();

                else
                //clear fields and write new name to file and begin audit
                {
                    //clears fields
                    using (FileStream stream = new FileStream(@"C:\Numara\Audit.log", FileMode.Create))
                    {
                        using (TextWriter writer = new StreamWriter(stream))
                        {
                            //writer.Write("");
                            writer.Write(userName);
                        }
                        // writes new name to file
                    }

                      StreamReader textIn =
                      new StreamReader(
                      new FileStream(path, FileMode.OpenOrCreate, FileAccess.Read));

                    //begins audit

                    Process.Start(TrackIT, "/Q");
                    Application.Exit();
                    }
                }
            }
        }

A: File.Create creates a file and returns a FileStream, so it does not close it. Next you want to read it, but it is locked by the File.Create. So exception appears which is not handled and your application quits. Second times the file is already created, so it skips creating and locking it.
So you need to close the file by putting it into using block:
using (File.Create(path))
{
}

Also, you should put all the stuff into try catch blocks to handle IO exceptions - you can never know if one occurs.

A: You are doing battle with a nasty bug in the 64-bit debugger.  Any exceptions in the Load event are swallowed without a diagnostic.  The workaround is Project + Properties, Compile tab, Platform Target = x86.  Now the debugger will stop at the exception.  Fixing it is your next task.
Just in case: avoid catching exceptions that you shouldn't handle.  Using try/catch is not typically a real solution.  Just a band-aid that spackles the injury.

A: I would check the value of the userName variable and the line variable on that first run. You could output that to your log file also. My guess is that if the System.Environment.Username variable is empty, you end up in this case where you simply exit.
Another possibility is that you're not properly handling an exception raised from File.Create(). According to the online docs for File.Create(): http://msdn.microsoft.com/en-us/library/aa328775(v=vs.71).aspx there are 7 different exceptions that are thrown. Try catching and logging these exceptions to see if this could be the case.


text:
Q: why does tail in circular queue point to empty element? I want to know why does tail in the circular queue have to point to an empty element?
As we all know, the capacity of circular queue is (N-1), because it has to leave an empty space for queue to judge if the queue is full. But in my perspective, that is because of the tail pointer has to point to an empty element, if it can be point to the last element, not the empty one, it can full all spaces in the queue.
So I want to know why we design the circular queue as this format, thanks a lot!

A: Sorry that I notice where I am wrong......
IF the tail pointer points to the last element, not the last (element+1), if the tail == front, we can not know if the queue is empty or only has one element filled. So it will cause some issues.

A: Where the tail pointer points to the next element to populate (and with no "always empty" element), there are two conditions we cannot tell apart. Those are the "queue full" and "queue empty" conditions both of which would have head and tail with the same value.
             H,T
        +---+---+---+---+---+
empty:  | - | - | - | - | - |
        +---+---+---+---+---+
        +---+---+---+---+---+
full:   | 5 | 1 | 2 | 3 | 4 |
        +---+---+---+---+---+
             H,T

That much you already know, based on your question.
However, were you to use the tail pointer to point to the last element populated, you would still not be able to distinguish between the two conditions.
That's because a one-element queue would have head and tail equal so, in order to represent an empty queue, the tail would be one before the head (if you didn't do that, the "queue empty" and "queue with one item" conditions would be indistinguishable). Unfortunately, that's also the case if you are full:
          T   H
        +---+---+---+---+---+
empty:  | - | - | - | - | - |
        +---+---+---+---+---+
        +---+---+---+---+---+
full:   | 5 | 1 | 2 | 3 | 4 |
        +---+---+---+---+---+
          T   H

The bottom line is that a head and tail is not quite enough information to uniquely identify all conditions regardless of which scheme you choose, which is why there is an empty cell.
You can do it the way you want (tail points to last populated cell rather than next cell to be populated) but you'll still need the empty cell to distinguish the empty and full cases.

Of course, you can solve the problem by introducing a count to the data structure as well. Once you have that, you can easily distinguish the cases (in both scenarios).


text:
Q: jQuery: on vs live I am curious why when I replace .live() with .on() my events don't work after inserting AJAX's response via html() method. Assume I have html structure:

   alert
   update

and jQuery code something like:
$('.alert-link').on("click", function(){
 alert('abc');
 return false;
});

and ajax-update will trigger request, which response will be:
alert
update
and I will insert it into parent(). Then pressing again alert-link will result in redirecting to / but if I change .on() to .live() then again alert will be shown. What am I missing here? I have read that .on() is replacement both for .delegate() and .live().

A: Your particular conversion to .on() didn't work properly because you were using the static form of .on() instead of the dynamic form of .on().  Instead of the static form:
$('.alert-link').on("click", function(){

you need to use the dynamic form like this:
$(someStaticParentObject).on("click", '.alert-link', function(){

This will bind the event handler to someStaticParentObject and then use delegated event handling for any child events that originate on an item that matches the selector '.alert-link'.  Your version was immediately binding to whatever '.alert-link' items existed at the time you installed the event handler (static binding) and was not using delegated event handling to handle events from objects that aren't yet created.
See these previous answers for a good explanation of .live() vs. .on() and why .live() can lead to performance issues in some cases:
Does jQuery.on() work for elements that are added after the event handler is created?
How does jQuery's new on() method compare to the live() method in performance?
What's the difference between jQuery.bind() and jQuery.on()?
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Why not take Javascript event delegation to the extreme?
In a nutshell:
$(".item").live('click', fn);

is functionality equivalent to:
$(document).on('click', '.item', fn);

The two main drawbacks of .live() are:

*

*It evaluates the selector ".item" immediately which is purely wasted cycles because the result isn't used at all.

*.live() is hardwired to the document object.  It uses delegated event handling to be able to handle objects that come and go, but all .live() event handlers are assigned to the document object.  If you have a lot of them, it can be a big performance bottleneck because every event that bubbles up to the document has to be evaluated against the selectors of all .live() event handlers.  .on() on the other hand can be bound not only to the document object, but also to an ancestor that is much closer to the actual origin of the events and when there are lots of delegated event handlers, it can be a LOT more efficient to find the events closer so that only the events that are close to the object are processed through the .on() selectors, thus improving performance.  For example, the above handlers could be done like this:
$("#container").on('click', '.item', fn);

where #container is a parent of the dynamic .item objects.

A: .on combines and replaces .bind, .live, and .delegate.  The syntax $('selector').on('event', callback) is the moral equivalent of bind, not live.
Add a filtering selector to your call to on:
$('container').on('click', 'child-filter', callback);

In this case,
$('.a').on("click", ".alert-link", function(){
    alert('abc');
    return false;
});

This was changed because it is more efficient to attach a delegate handler to a more localized container element than the old .live style of attaching the handler to the root of the DOM.
In other words, even though alert-link elements will only appear inside of a small a div, with .live, jQuery listens to every single click event on the page and compares it to the delegated selector.  By being more targeted, jQuery only has to process clicks on elements within a.

A: It is indeed a replacement for .delegate and .live, but you have to pass in some additional parameters:
var container = $('.a').on('click', '.alert-link', function() {
    alert('abc');
    return false;
}).on('click', '.ajax-update', function() {
    // something that uses AJAX to update .a, like:
    container.load('some-url');
    return false;
});

For more information, see the documentation.


text:
Q: How to show results based on name/category? I have a database with with these values.
+----+--------+-----------+
| id | value  | category  |
+----+--------+-----------+
|  1 | value1 | category1 |
|  2 | value2 | category1 |
|  3 | value3 | category2 |
|  4 | value4 | category3 |
+----+--------+-----------+

And I want the output to be like this:
Category1:
value1
value2

Category2:
value3

Category3:
value4

I know I can use WHERE category = category1 .. etc, but how do I make the script automatically group all values and show them this way?

A: Use the function GROUP_CONCAT() to get a comma separated list of values, and the GROUP BY clause to gather the values for each category:
SELECT
    `category`,
    GROUP_CONCAT(`value`) as `values`
FROM `tablename`
GROUP BY `category`
ORDER BY `category`


text:
Q: How to load more search results when scrolling down the page in React.js? I would like to load more searching results when scrolling down the page.
I work with google API book and I would like to load just 10 searching results and if user scroll to the last search element than next 10 results load automatically. How to do that? I need a code example how proper solution should look like. Thanks for help.
My App.js file is as follow:
 import React, { useState } from "react";
 import axios from "axios";
 import './App.css';
 import 'bootstrap/dist/css/bootstrap.min.css';

const App = () => {
const [searchTerm, setSearchTerm] = useState("");
const [books, setBooks] = useState({ items: [] });
const onInputChange = e => {
    setSearchTerm(e.target.value);
};

let API_URL = 'https://www.googleapis.com/books/v1/volumes';

const fetchBooks = async () => {

    if (document.getElementById("choose_search").value === "title") {

        const result = await axios.get(`${API_URL}?
q=${searchTerm}&maxResults=40`);
        setBooks(result.data);
    }
    else {
        const result = await axios.get(`${API_URL}?
q=inauthor:${searchTerm}&maxResults=40`);
        setBooks(result.data);
    }

};

const onSubmitHandler = e => {
    e.preventDefault();
    fetchBooks();
};

return (

            <form onSubmit={onSubmitHandler} id="submit">

                    <input
                        type="search"
                        placeholder="Search books"
                        value={searchTerm}
                        onChange={onInputChange}
                    />
                    <button type="submit" class="btn btn-
  success">Search</button>

        </form>

            <select id="choose_search" class="form-control-sm">
                <option value="" disabled selected>Select search
 type</option>
                <option value="title">Title</option>
                <option value="author">Author</option>
                </select>

            {books.items.map((book, index) => {
                return (

{book.volumeInfo.title}

                                <img
                                    id="img_book"
                                    alt={`${book.volumeInfo.title} book`}
                                    src=
 {`http://books.google.com/books/content?id=${
                                        book.id

  }&printsec=frontcover&img=1&zoom=1&source=gbs_api`}
                                />

                                {typeof book.volumeInfo.description ===
 'string' && book.volumeInfo.description.length > 0 ?
 book.volumeInfo.description : }

Preview: {typeof
  book.volumeInfo.previewLink === 'string' &&
  book.volumeInfo.previewLink.length > 0 ? Link : 'No data'}

Published date:
  {typeof book.volumeInfo.publishedDate === 'string' &&
  book.volumeInfo.publishedDate.length > 0 ? book.volumeInfo.publishedDate
  : 'No data'}

Free download:
  {typeof book.accessInfo.pdf.downloadLink === 'string' &&
  book.accessInfo.pdf.downloadLink.length > 0 ? Link : 'Not avaliable'}

Ebook version:
  {typeof book.saleInfo.isEbook === 'boolean' && book.saleInfo.isEbook ===
  true ? 'Yes' : 'No'}

                );
            })}

   );
   };
   export default App;

A: This is called infinite scroll.
If you don't wanna build this from the scratch, you can use external libs:
https://www.npmjs.com/package/react-infinite-scroller
https://www.npmjs.com/package/react-infinite-scroll-component
If you wanna build it yourself, you can follow these tutorials:
https://alligator.io/react/react-infinite-scroll/
https://upmostly.com/tutorials/build-an-infinite-scroll-component-in-react-using-react-hooks

A: Without plugins:
componentWillMount(){
  window.addEventListener('scroll', this.loadMore);
}

componentWillUnmount(){
    window.removeEventListener('scroll', this.loadMore);
}

loadMore(){
    if (window.innerHeight + document.documentElement.scrollTop === document.scrollingElement.scrollHeight) {
        // Do load more content here!
    }
}


text:
Q: How to set hostname in global service in Docker Swarm I have a service deployed to my Docker Swarm Cluster as global service (ELK Metricbeat).
I want to each of this service to have a hostname the same as the hostname of the running node (host)?
in another word, how I can achieve the same result in the yml file such as:
 docker run -h `hostname` elastic/metricbeat:5.4.1

this is my yml file:
metricbeat:
  image: elastic/metricbeat:5.4.1
  command: metricbeat -e -c /etc/metricbeat/metricbeat.yml -system.hostfs=/hostfs
  hostname: '`hostname`'
  volumes:
    - /proc:/hostfs/proc:ro
    - /sys/fs/cgroup:/hostfs/sys/fs/cgroup:ro
    - /:/hostfs:ro
    - /var/run/docker.sock:/var/run/docker.sock
  networks:
    - net
  user: root
  deploy:
    mode: global

I have tried:
  hostname: '`hostname`'
  hostname: '${hostname}'

but no success.
Any solution?
Thank you in advance.

A: For anyone coming here :
services:
  myservice:
    hostname: "{{.Node.Hostname}}-{{.Service.Name}}"

No need to alter entry point ( at least on swarm on deploy )

A: I resolved the issue by mounting the host hostname file under /etc/nodehostname and changing the service container to use an entrypoint that read the file and replace a variable (name) in metricbeat.yml
docker-entrypoint.sh
export NODE_HOSTNAME=$(eval cat /etc/nodehostname)

envsubst '$NODE_HOSTNAME' </etc/metricbeat/metricbeat.yml.tpl > /etc/metricbeat/metricbeat.yml


text:
Q: "Missing file icon" is shown in the system tray when running showMessage with NoIcon on LXDE I'm building an application which uses notifications, and which has an icon in the system tray
I'm using showMessage with the icon parameter set to NoIcon and when the message is displayed the system tray icon changes from the icon that I have set for the application to this icon:

This icon is used by my system to show that the file is missing
I've tried setting the icon parameter to Information instead which shows the letter "i" in both the message and in the system tray (while the message is shown), so there is no problem in this case
When using NoIcon can I avoid seeing the missing icon while the message is shown and instead see my application icon in the system tray?
Grateful for help!

My setup:

*

*Lubuntu 16.04 (uses LXDE)

*PyQt: 5.7.1 (same as the Qt version)

Code:
self.tray_icon.showMessage(
    "Application Name",
    "Message",
    icon=QtWidgets.QSystemTrayIcon.NoIcon,
    msecs=10*1000
)