text:
Q: Numerical approximation of $\int_0^t\int_0^s\vert u-v\vert^{2H-2}((t+s)-(u+v)^{-d/2})$ I want to have a numerical approximation of the following integral
$$\int_0^t\int_0^s\vert
 u-v\vert^{2H-2}\left((t+s)-(u+v)^{-d/2}\right)\, {\rm d}v\,{\rm d}u$$
with $t=2,],s=1,\,d=1,\,2H-2=-0.5$. Since the integrand explodes in many regions the method
NIntegrate[Abs[u - v - (1)]^-.75/((u + v ))^(1/2), {u, 0, 2}, {v, 0, 1}]**

fails, giving me the following message

NIntegrate::zeroregion: Integration region {{0.5,1},{1.,0.999999999999999999999999999999975153439150570957241015732418974750}} cannot be further subdivided at the specified working precision. NIntegrate assumes zero integral there and on any further indivisible regions.

Can anybody tell me how I can get a good approximation to this type of integral?

A: Up to the help on NIntegrate,
NIntegrate[ RealAbs[u - v]^(2 H - 2) ((t + s) - (u + v)^(-d/2)) /. {2 H -
 2 -> -1/2, t -> 2, s -> 1, d -> 1}, {u, 0, 2}, {v, 0, 1},
 WorkingPrecision -> 12, AccuracyGoal -> 8, Exclusions ->{u==v}]

7.37875949086

Addition.
NIntegrate[ RealAbs[u - v]^(2 H - 2) ((t + s) - (u + v)^(-d/2)) /.
{2 H - 2 -> -1/2, t -> 2, s -> 1, d -> 1}, {u, 0, 2}, {v, 0, 1},
 WorkingPrecision -> 15, AccuracyGoal -> 11,PrecisionGoal->11,Exclusions->{u==v}]

7.37875672406846B

A: The IMT singularity handler works better when the singularity is parallel to an axis, so it's not surprising this appears to be a difficult integral.  The message is only a warning, but it's hard to know beforehand whether a warning implies an error.  Let's look at the OP's TeX'ed integral.
int = NIntegrate[
  Abs[u - v]^(2 H - 2) ((t + s) - (u + v)^(-d/2)) /.
   {H -> 3/4, t -> 2, s -> 1, d -> 1}, {u, 0, 2}, {v, 0, 1}]

NIntegrate::zeroregion: Integration region...cannot be further subdivided at the specified working precision. NIntegrate assumes zero integral there and on any further indivisible regions.

(*  7.378756495073663`  *)

The reliability of the result depends on the assumption that there is a negligible contribution to the value of the integral in the integration region that cannot be divides because it is as small as possible at machine precision.  Since the integrand is approaching infinity in this region, it is not an obviously safe assumption.  However, it turns out that the result is accurate, with an error likely within the PrecisionGoal which is 6 digits by default.
To see that, evaluate the integral by other means or with higher precision and observe how stable the result is.  Here are a couple of different working precisions.  At the higher one, the default multidimensional rule is much slower than the cartesian product of Gauss-Kronrod. All these integrals evaluate without errors or warnings.
(int16 = NIntegrate[
    Abs[u - v]^(2 H - 2) ((t + s) - (u + v)^(-d/2)) /.
     {H -> 3/4, t -> 2, s -> 1, d -> 1}, {u, 0, 2}, {v, 0, 1},
    WorkingPrecision -> $MachinePrecision]) // AbsoluteTiming
(*  {0.472966, 7.378756517051061}  *)

int32 = NIntegrate[
   Abs[u - v]^(2 H - 2) ((t + s) - (u + v)^(-d/2)) /.
    {H -> 3/4, t -> 2, s -> 1, d -> 1}, {u, 0, 2}, {v, 0, 1},
   Method -> "GaussKronrodRule", WorkingPrecision -> 32] // timeIt
(*  {21.1778, 7.3787567240684493164029272938681}  *)

We can also get a fast, error-free evaluation at MachinePrecision using "SingularityDepth":
(intSD = NIntegrate[
    Abs[u - v]^(2 H - 2) ((t + s) - (u + v)^(-d/2)) /.
     {H -> 3/4, t -> 2, s -> 1, d -> 1}, {u, 0, 2}, {v, 0, 1},
    Method -> {"GlobalAdaptive", "SingularityDepth" -> 8}]) // AbsoluteTiming
(*  {0.085006, 7.378756757328596`}  *)

All of these results agree to seven or eight digits:
({int, intSD, int16} - int32)/int32
(*  {-3.10343*10^-8, 4.50755*10^-9, -2.8055863*10^-8}  *)

Finally, as implied in the opening sentence, things might be easier with a change of variables that aligns the singular like with an axis.  Let's let $w = u - v$, that is, $u = w+v$.  We also identify the singularity $w=0$ in the integration limits.  Then the integral becomes this, which is a little faster than the original integral and produces no warnings:
(intb = NIntegrate[
    Abs[w]^(2 H - 2) ((t + s) - ((w + v) + v)^(-d/2)) /.
     {H -> 3/4, t -> 2, s -> 1, d -> 1}, {v, 0, 1}, {w, -v, 0, 2 - v}]) // AbsoluteTiming
(*  {0.031386, 7.378756783881534`}  *)

A: Mathematica can do this analytically without too much difficult
integrand = Abs[u - v]^h ((t + s) - (u + v)^(-d/2));

Block[{d = 1, h = -(1/2), t = 2, s = 1},
 FullSimplify[Integrate[integrand, {u, 0, t}, {v, 0, s}]]]
(* 8 Sqrt[2] - (5 π)/6 - Log[2 + Sqrt[3]] *)

N[%, 20]
(* 7.3787567240684493164 *)

It can also cope with symbolic values for s and t


text:
Q: How to use The highest Warning Level (Wall) for Visual Studio 2017 when it's incompatible for the std headers? But I want to use it with "Warnings treated as errors" = Yes
There seems to be a lot of useful check in the compiler flag but it isn't compatible with the standard headers. I want to use this compiler flag to check my code, but not the std headers. Is there a way to do this?
Or just disable warnings for any code I didn't write?
Edit:
Added pictures of the settings in visual studio and an example of what happens when I try to build. With just including iostream!
Example when trying to compile a basic C++ program with these settings

A: You can disable the warnings in the headers (or change warning level for them) by changing the warning level before each inclusion, see here: How to suppress warnings in external headers in Visual C++. However that is not so handy because it needs to be done for every inclusion.
However if you'd use precompiled headers (which might be actually good for compilation speed), you can put all the system/STL headers you care about into the precompiled header file, and disable them via pragmas just there. Or you would need to create wrappers for the standard headers where you'll disable the warnings and include the wrapper headers instead.
And as discussed, the "/Wall" sometimes goes too far (e.g. the padding is quite usual thing you sometimes even can't do anything about), and even with the "/W4" the documentation mentions that it might be too detailed (however at the same time recommends it for new projects, so I generally use "/W4 /WX" for new projects). However some of the "/Wall" warnings still might find subtle bugs (like missing case in switch etc.). You might as well enable just some of the extra warnings selectively.

redpajama_set_name: RedPajamaStackExchange


text: Q: Why is my empty sparsbundle so big (1,5 GB)? I just followed the instructions here to create a encrypted sparseimage for Time Machine backups. The empty sparsebundle ended up being 1.4 GB (and after enabling encryption it grow to 1.6GB). Why is an empty sparseimage so big?


text:
Q: how a microcontroller or microprocessor is called as 8 bit, 16 bit? In what basis a micro controller or a microprocessor is classified as 8bit and 16bit?

A: On the basis of the word length. Most instructions will operate on word-sized chunks of data, the data bus is almost always one word wide and most registers have the width of one word.
8-bit microcontrollers have byte-sized (8-bit) words, so while e.g. computing the sum of two bytes is fast and easy with just a single instruction, summing two 16-bit values requires more thought from the programmer and will require multiple instructions.
16-bit microcontrollers have 16 bit words, so they effectively operate on two bytes at the same time. For example, summing 16-bit values will take just a single instruction on a 16-bit processor, yet you can still sum 8-bit values as usual if you want to.
32 bit and 64 bit words are also common in especially higher end processors, and some digital signal processors even have more unconventional word sizes.


text:
Q: Tesseract OCR: very inaccurate result Below is my very simple program to test Tesseract performance. The result I got was not as expected though the picture was a high quality and very clear screenshot (not a complex picture with colors). Please take a look at my code and the result below. I'm not sure if I did something wrong or the Tesseract engine can not handle this?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using tessnet2;

namespace ImageProcessTesting
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        int up_lef_x = 1075;
        int up_lef_y = 0070;

        int bo_rig_x = 1430;
        int bo_rig_y = 0095;

        int width = bo_rig_x - up_lef_x;
        int height = bo_rig_y - up_lef_y;

        var bmpScreenshot = new Bitmap(width, height, PixelFormat.Format32bppArgb);
        var gfxScreenshot = Graphics.FromImage(bmpScreenshot);

        gfxScreenshot.CopyFromScreen(
                                    1075,
                                    0070,
                                    0,
                                    0,
                                    Screen.PrimaryScreen.Bounds.Size,
                                    CopyPixelOperation.SourceCopy);

        // bmpScreenshot.Save("C:\\Users\\Exa\\Screenshot.png", ImageFormat.Png);

        var image = bmpScreenshot;
        var ocr = new Tesseract();
        ocr.Init(@"C:\Users\Exa\Desktop\tessdata", "eng", false);
        var result = ocr.DoOCR(image, Rectangle.Empty);
        string result_str = "";
        foreach (Word word in result)
            result_str += word.Text;
        MessageBox.Show(result_str);

    }
}
}

A: 96DPI screen shots are typically not adequate for OCR. As written in Tesseract wiki:

There is a minimum text size for reasonable accuracy. You have to consider resolution as well as point size. Accuracy drops off below 10pt x 300dpi, rapidly below 8pt x 300dpi. A quick check is to count the pixels of the x-height of your characters. (X-height is the height of the lower case x.) At 10pt x 300dpi x-heights are typically about 20 pixels, although this can vary dramatically from font to font. Below an x-height of 10 pixels, you have very little chance of accurate results, and below about 8 pixels, most of the text will be "noise removed".

However, if you know what exact font it is, you can try re-train tesseract to get better result.


text:
Q: Add Fileinput to Treemap I can't add the file input to my map. It says I am missing something and that the Items []is not instantiated. I can't seem to figure it out
public class BigCities {

    private Map<String, Set<CityItem>> countryMap;
    private File file;

public BigCities(String fileName) {
    countryMap = new TreeMap<>();
    file = new File(fileName);
    readFile(fileName);
}

private void readFile(String fileName) {
    // Opg 3c implementeres her.

    CityItem cityItem;

    try(BufferedReader br = new BufferedReader(new FileReader(fileName))) {
        StringBuilder sb = new StringBuilder();
        String line = br.readLine();
        String[] items;

        while (line != null) {

            sb.append(line);
            sb.append(System.lineSeparator());
            line.split(";");
            line = br.readLine();
            cityItem = new CityItem(items[1], items[2], items[3]);
        }
        String everything = sb.toString();
        System.out.println(everything);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
   }

public String toString() {
    return countryMap.toString();
}

/**
 * @param args
 */
public static void main(String[] args) {

    //Vaelg ANSI eller UTF8 afhaengig af hvad der virker bedst paa din computer:
    BigCities bc = new BigCities("EuroCities ANSI.txt");
    //BigCities bc = new BigCities("EuroCities UTF8.txt");
    System.out.println(bc);
}

}

I Don't know what I am missing to add the input, but hopefully someone has some input.
I Am new to programming and therefore I find it confusing, since I feel like I am following all the right methods.

A: You never initialize the items array, so when trying to access it, you're getting null, or it may just be caught by the compiler and will give you an error there.
I suspect that you mean to assign the split to items, so change the line
line.split(";");

to
items = line.split(";");


text:
Q: AutoConvert Bengali Number to English Number while typing in PHP Form In Input form,
How I can make an input box where..
When a user tries to input the Bengali Number and It will automatically convert it to English Number?
Suppose the input box is look like below:
<input type="text" name="number" size="45"/>
Ex: If user typing ১২৩৪৫৬৭৮৯০ in the input box, it will convert to 1234567890 automatically.
How to do that!!!
I tried it lots of time to fix but I cannot do it. I think the community will help me. Advance thanks!!!

A: If you need this while the user is tying, you're looking for a JavaScript solution. If you need this on the backend, working with unicode is a bit more complicated for PHP since a lot of the built-in functions aren't designed for working with unicode, so you'd need to reach for the mb_* functions and need the mbstring extension enabled. There's probably ways to do this without on the PHP side. But I'd suggest doing this just in JavaScript. The amount of hoops you'd need to jump through to get this working on the PHP side isn't worth it. But I've attached both a frontend and backend solution so you can choose which you need. You can also combine these solutions such as if the user has JavaScript disabled, or an old browser etc.
<!doctype html>

<form method="POST">

<input type="text" name="number" size="45">

Copy from here into the text box: ০১২৩৪৫৬৭৮৯

Here's another text box, but without the JavaScript events so you can do this on the backend

<input type="text" name="number2" size="45">

<button type="submit">Submit</button>

</form>

<?php
if(!empty($_POST)) {

    // using a switch, so we can "break" without invoking "exit".
    // Invoking exit is bad since it affects code flow and prevents you from running stuff afterwards.
    // Another approach is to put this into a function and use return etc.
    switch(true) {
        default:
            // Validation and security check to prevent errors with unexpected input types
            if (!isset($_POST['number'])) {
                echo 'Missing name=number field.';
                break;
            }
            if (!isset($_POST['number2'])) {
                echo 'Missing name=number2 field.';
                break;
            }
            // security check to prevent errors with unexpected input types
            if (is_array($_POST['number'])) {
                echo 'Unexpected array field: name=number.';
                break;
            }
            if (is_array($_POST['number2'])) {
                echo 'Unexpected array field: name=number2.';
                break;
            }

            if ($_POST['number'] === '' && $_POST['number2'] === '') {
                echo 'Blank input was given. Please enter something into one of the text boxes';
                break;
            }

            $n = $_POST['number'];
            $n2 = $_POST['number2'];
            echo "
\n";
            echo "Original Input:\n";
            echo "first field: " . htmlentities($n) . "\n";
            echo "second field: " . htmlentities($n2) . "\n";
            echo "\n";
            echo "After filtering in PHP:\n";
            // credit for strtr_utf8: https://stackoverflow.com/questions/1454401/how-do-i-do-a-strtr-on-utf-8-in-php
            function strtr_utf8($str, $from, $to) {
                $keys = array();
                $values = array();
                preg_match_all('/./u', $from, $keys);
                preg_match_all('/./u', $to, $values);
                $mapping = array_combine($keys[0], $values[0]);
                return strtr($str, $mapping);
            }
            // credit for mb_range: https://gist.github.com/rodneyrehm/1306118
            mb_internal_encoding('UTF-8');
            function mb_range($start, $end) {
                // if start and end are the same, well, there's nothing to do
                if ($start == $end) {
                    return array($start);
                }

                $_result = array();
                // get unicodes of start and end
                list(, $_start, $_end) = unpack("N*", mb_convert_encoding($start . $end, "UTF-32BE", "UTF-8"));
                // determine movement direction
                $_offset = $_start < $_end ? 1 : -1;
                $_current = $_start;
                while ($_current != $_end) {
                    $_result[] = mb_convert_encoding(pack("N*", $_current), "UTF-8", "UTF-32BE");
                    $_current += $_offset;
                }
                $_result[] = $end;
                return $_result;
            }
            function replaceBengaliNumeralsToArabicNumerals($str)
            {
                return strtr_utf8($str, implode('',mb_range("\u{09E6}", "\u{09EF}")), implode('',range(0,9)));
            }

            $replaced_n = replaceBengaliNumeralsToArabicNumerals($n);
            $replaced_n2 = replaceBengaliNumeralsToArabicNumerals($n2);
            echo "first field:" . htmlentities($replaced_n) . "\n";
            echo "second field:" . htmlentities($replaced_n2) . "\n";
            echo "
";
    }
}

?>

I suppose we could also include Eastern Arab Numerals:

let numbers = {
    '০': 0,
    '১': 1,
    '২': 2,
    '৩': 3,
    '৪': 4,
    '৫': 5,
    '৬': 6,
    '৭': 7,
    '৮': 8,
    '৯': 9,
    '': 0,
    '': 1,
    '': 2,
    '': 3,
    '': 4,
    '': 5,
    '': 6,
    '': 7,
    '': 8,
    '': 9
};
function normalizeUnicodeNumbers(str) {
    return [...str].map(function(c){
        return numbers.hasOwnProperty(c) ? numbers[c] : c;
    }).join('');
}

<input type="text" name="number" size="45">

Copy from here into the text box: ০১২৩৪৫৬৭৮৯𑁦𑁧𑁨𑁩𑁪𑁫𑁬𑁭𑁮𑁯


text:
Q: how to Integrate cloudinary media library widget inside ckfinder or ckeditor We have implemented ckfinder inside ckeditor and from browse server button ckfinder opens local storage folders.we are using cloudinary for images storage so,I want to open cloudinary folders when user click on browse server button. please help
Thanks in advance
I googled ckfinder provide any support for cloudinary but did not find anything.
in ckfinder website there are only 3 plugin mentioned which is azure, amazon s3 and dropbox
please see below code sample
string folderName = string.Concat("/", ResourceConstants.ResourceFileRootPath, "/", objconfigure.SiteID);
                            string baseUrl = string.Format("{0}://{1}/{2}", System.Web.HttpContext.Current.Request.Url.Scheme, System.Web.HttpContext.Current.Request.Url.Authority, ResourceConstants.ResourceFileRootPath);
                            config.AddBackend("default1", new LocalStorage(System.Web.HttpContext.Current.Server.MapPath(folderName)), baseUrl);
                            config.AddResourceType("Images", builder => builder.SetBackend("default1", "/"));

I want to assign cloudinary folders and path in config.addbackend function.
in browse server button click I want to display folders from cloudinary


text:
Q: Insert into table with foreign keys? On my Addcar view I have form allow me to insert data into my database (into table Car).
In the table Car I Have colonne (Idcat) it's foreign key related to the Categorie table.
So in my add forms I should have a dropDownlist that allow user to chose what's categorie of car he want to add.
this is part of my view :

        <%: Html.LabelFor(model => model.Idcat) %>

        <%: Html.DropDownListFor(model => model.Idcat, ViewBag.cat as SelectList)%>
        <%: Html.ValidationMessageFor(model => model.Idcat) %>

This is my controller action :
        public ActionResult addcar()
    {

        ViewBag.cat = new SelectList(entity.categorie, "Idcat", "Nom");

        return View();
    }

This work fine until i clic on create he show me this error There is no ViewData item of type 'IEnumerable <SelectListItem>' with key 'Idcat'. at This Line <%: Html.DropDownListFor(model => model.Idcat, ViewBag.cat as SelectList)%>

A: In the ASP.Net MusicStore Tutorial there is an example where you choose from a given list of genres. The list of genres is passed to the view via the viewbag that is filled by the controller:
MusicStore Tutorial
This is probably exactly what you are looking for.

A: Model binding really only binds individual elements.  So it's fine binding Idmarque.  It is no help displaying a drop down list of possible values.  To me it seems like something lacking in the framework, because it makes you stop using EditorForModel.  You have to decide how you want to handle getting the dropdownlist.  Are you ok with having an Html Helper that will query the database and draw a list of options?  Or would you prefer to have your controller call a model method to get a list of options, and pass that into the view as part of a view model?  Probably want to avoid passing a datareader since you may have open connection issues if you do that.


text:
Q: How to group by with only Time format in Linq i want to know that how to using the group by with only time format about datetime type.
select CONVERT(VARCHAR(10), a.tempDay, 108) as returnDay, b.qty from table1     as a inner join table2 as b on (a.id = b.id)
where a.id = 100
group by CONVERT(VARCHAR(10), a.tempDay, 108), b.qty

Actually, tempDay is DateTime type.(yyyy-MM-dd HH:mm:ss) in this case, i just want to groupping with only "HH:mm:ss" format with Linq.

A: var datesByTime = from d in dates
                  group d by d.TimeOfDay.ToString(@"hh\:mm\:ss") into g
                  select new { Time = g.Key, Dates = g.ToList() };

dates is collection of DateTime,  DateTime has property TimeOfDay which returns TimeSpan of that date, all you have to do Group By TimeOfDay.
You need also .ToString(@"hh:mm:ss") to remove milliseconds.


text:
Q: Issue when I deploy my wordpress website on GAE I followed all the steps to deploy my wordpress website on GAE (Running WordPress in App Engine)
When I am entering my address:wp-dot-YOUR_PROJECT_ID.appspot.com
I am automatically redirected to: wp-dot-YOUR_PROJECT_ID.appspot.com/admin/configure.jsp
Which is definitely not my website. And if I change the path, I have an error 404.
Have you already faced this issue?
thank you

A: I notice that you refer to you site as wp-dot-YOUR_PROJECT_ID.appspot.com when it should actually be YOUR_PROJECT_ID.appspot.com.
On first uploading, navigating to YOUR_PROJECT_ID.appspot.com should redirect to YOUR_PROJECT_ID.appspot.com/wp-admin/install.php of this doesn't happen automatically try navigating to the install.php page.


text:
Q: Rails webpack and vue How can I define a root component with Vue, that wraps my entire code, so all other components are descendants from that root?
Basically I would like to achieve something like:
In application.html.erb
<!DOCTYPE html>
<html>
  <head>
    <title>My App</title>
    <%= csrf_meta_tags %>

    <%= stylesheet_pack_tag    'application' %>
  </head>

  <body>
    <div id="root">
      <%= yield %>
    </div>
    <%= javascript_pack_tag 'application' %>
  </body>
</html>

and then on my webpack entry point
...

import Vue from 'vue';

var app = new Vue({
  el: '#root'
 })

However, when I do this I got a Vue warning that says:

[Vue warn]: You are using the runtime-only build of Vue where the
  template option is not available. Either pre-compile the templates
  into render functions, or use the compiler-included build.

So, from what I understood, this happens because I need to put my vue components inside .vue files but then, if I do that, how can I still use the yield statement to implement the rest of the views the "rails way"?
In the end, I guess, it all resumes to how can I organize my frontend using vuejs, webapack only(no asset pipeline) in rails and but still use some of the rails features like yield to render the "normal" views?
P.S: I already saw the hello world example that comes when you start a new project with webpack, but it's to simple...

A: Try adding vue: 'vue/dist/vue.js' to your webpack aliases file. I've had to do the same when I'm rendering component templates that don't fit the normal model for vue templates (i.e dynamic based content).
This post by Evan You (Vue's creator) explains about the runtime only build (which this is) via this link specifically, the bit we're looking at is this:

Runtime only build: since it doesn't include the compiler, you need to
  either pre-compiled templates in a compile step, or manually written
  render functions. The npm package will export this build by default,
  since when consuming Vue from npm, you will likely be using a
  compilation step (with Browserify or Webpack), during which vueify or
  vue-loader will perform the template pre-compilation.

This means the version we normally use doesn't have the compiler so we need to include it via the alias which then gives us access to:

Standalone build: includes both the compiler and the runtime. This
  functions basically exactly the same Vue 1.x does.

As this has the compiler in, it allows your template to be compiled which it needs to be because it's not part of the standard Vue file templating.
Well, that is at least my take on the whole thing :)


text:
Q: Python Global Not Behaving As Expected The following prints out "None" instead of "whatever". I don't understand why.
dirr = None

def method():
    global dirr # you have to declare that you'll use global variable 'dirr'
    dirr = "whatever"

print `dirr`

A: You should call 'method' one time.
dirr = None

def method():
    global dirr # you have to declare that you'll use global variable 'dirr'
    dirr = "whatever"

method()
print (dirr)

The result is:
whatever


text:
Q: Encapsulate repeated assertions in a function I have several integration tests where some of the assertions are the same. For maintainability concerns, I'd like to regroup the common assertions of each test under a unique function.
  test "login with invalid information" do
    get login_path
    assert_template 'sessions/new'
    post login_path, params: { session: { email: "", password: "" } }
    assert_template 'sessions/new'
    assert_not flash.empty?
    get root_path
    assert flash.empty?
  end

  test "login with valid information followed by logout" do
    get login_path
    assert_template 'sessions/new'
    post login_path, params: { session: { email: @user.email, password: "password" } }
    .

  end

For instance, the
get login_path
assert_template 'sessions/new'

bit are repeated inside the two tests. How can I make this more maintainable?

A: The part that you describe as "repeated" should not be asserted on each test. If the first test fails at asserting the template, then the other tests using the same assertion will also fail. This means you should extract that test logic into a single test, something like test 'login rendered template' and remove those get & assert_template from the other tests:
test "login rendered template" do
  get login_path
  assert_template 'sessions/new'
end

test "login with invalid information" do
  # template assertion already done in previous test
  post login_path, params: { session: { email: "", password: "" } }
  # [...]
end

This is an example of a bad practice in testing your app. A single test should make assertion(s) about a specific logic/feature and not be repeated. If you see pieces of code/assertions repeated in your test suite, it should probably be extracted to a single test.


text:
Q: forwarded ref with button OR anchor types - typescript I want to create a button component in react with typescript.
This component should be rendered as an a-tag or a button-tag in html. So I added the property as: "a" | "button" to the component to let the programmer decide which one should be used.
So you should be able to do:
<Button as="button" type="submit">I am a button</Button>
<Button as="a">I am a link</Button>

It is necessary that the button forwards the ref! Keep that in mind for the next steps.
So the button component should look something like that:
import { forwardRef } from "react";

type ButtonPropsBasics = {
  outlined?: boolean;
  children?: React.ReactNode;
  className?: string;
};
type ButtonPropsAsButton = React.HTMLAttributes<"button"> & {
  as: "button";
} & ButtonPropsBasics;

type ButtonPropsAsAnchor = React.HTMLAttributes<"a"> & {
  as: "a";
} & ButtonPropsBasics;

type ButtonProps = ButtonPropsAsButton | ButtonPropsAsAnchor;

const Button = forwardRef<HTMLAnchorElement | HTMLButtonElement, ButtonProps>(
  function ForwardedButton(props, ref) {
    const {
      outlined,
      children,
      className,
      as: Component = "a",
      ...rest
    } = props;

    return (
      <Component
        ref={ref}
        className={outlined ? "border-2 border-black" : ""}
        {...rest}
      >
        {/* some other components here */}
        {children}
      </Component>
    );
  }
);

export default Button;

The problem here is that the ref types do not match the given html element.
So I don't know how to say "if the as is an anchor, then use HTMLAnchorElement as type of the forwardedRef otherwise use the HTMLButtonElement.
Any ideas?
See full example here: https://codesandbox.io/s/flamboyant-flower-gh9qtv?file=/src/Button.tsx

A: You can use this (merge ref with rest props):
import { forwardRef } from 'react';

type ButtonProps = {
  outlined?: boolean;
  children?: React.ReactNode;
  className?: string;
  as: 'button' | 'a';
  type?: 'button' | 'submit' | 'reset';
};

const Button = forwardRef<HTMLAnchorElement | HTMLButtonElement, ButtonProps>(
  function ForwardedButton(props, ref) {
    const { outlined, children, className, as: Component = 'a', ...rest } = props;
    const btnProps = { ...ref, ...rest };

    return (
      <Component className={outlined ? 'border-2 border-black' : ''} {...btnProps}>
        {/* some other components here */}
        {children}
      </Component>
    );
  },
);

export default Button;

or this (don't forget /* eslint-disable react/display-name */):
/* eslint-disable react/display-name */
import React, { forwardRef } from 'react';

type ButtonProps = {
  outlined?: boolean;
  children?: React.ReactNode;
  className?: string;
  as: 'button' | 'a';
  type?: 'button' | 'submit' | 'reset';
};

export type ButtonRef<C extends React.ElementType> = React.ComponentPropsWithRef<C>['ref'];

const Button = forwardRef(
  <C extends React.ElementType>(props: ButtonProps, ref: ButtonRef<C>) => {
    const { outlined, children, as: Component = 'a', ...rest } = props;

    return (
      <Component ref={ref} className={outlined ? 'border-2 border-black' : ''} {...rest}>
        {/* some other components here */}
        {children}
      </Component>
    );
  },
);

export default Button;

or this (more generic polymorphic)
/* eslint-disable react/display-name */
import React from 'react';

type AsProp<C extends React.ElementType> = {
  as?: C;
};

type PropsToOmit<C extends React.ElementType, P> = keyof (AsProp<C> & P);

type ComponentProp<
  C extends React.ElementType,
  Props = Record<string, unknown>,
> = React.PropsWithChildren<Props & AsProp<C>> &
  Omit<React.ComponentPropsWithoutRef<C>, PropsToOmit<C, Props>>;

type ButtonRef<C extends React.ElementType> = React.ComponentPropsWithRef<C>['ref'];

type ComponentPropWithRef<
  C extends React.ElementType,
  Props = Record<string, unknown>,
> = ComponentProp<C, Props> & { ref?: ButtonRef<C> };

type ButtonProps<C extends React.ElementType> = ComponentPropWithRef<
  C,
  { outlined?: boolean; children?: React.ReactNode; className?: string }
>;

const Button = React.forwardRef(
  <C extends React.ElementType = 'span'>(props: ButtonProps<C>, ref?: ButtonRef<C>) => {
    const { outlined, children, as: Component = 'a', ...rest } = props;

    return (
      <Component ref={ref} className={outlined ? 'border-2 border-black' : ''} {...rest}>
        {/* some other components here */}
        {children}
      </Component>
    );
  },
);

export default Button;

A: We found a solution for the problem. So we have to say that we want an IntrinsicElements of type a if  prop as="a".
This allows us to add all props to the given HTML tag and declines al other props which are not supported by this anchor. Same for the button tag.
Here the full Code of the Button.tsx:
import { forwardRef } from "react";

type ButtonPropsBasics = {
  outlined?: boolean;
  children?: React.ReactNode;
  className?: string;
};

type ButtonProps = ButtonPropsBasics &
  (
    | (JSX.IntrinsicElements["a"] & { as?: "a" })
    | (JSX.IntrinsicElements["button"] & { as: "button" })
  );

const Button = forwardRef<HTMLAnchorElement | HTMLButtonElement, ButtonProps>(
  function ForwardedButton(props, ref) {
    const {
      outlined,
      children,
      className,
      as: Component = "a",
      ...rest
    } = props;

    return (
      <Component
        ref={ref as any}
        className={outlined ? "border-2 border-black" : ""}
        {...(rest as any)}
      >
        {/* some other components here */}
        {children}
      </Component>
    );
  }
);

export default Button;

This allows us to use the following"
<Button as="button" type="submit" outlined={true}>I am an button</Button>
<Button as="a" href="/">I am a link</Button>

But does NOT allow:
{/* 'href' is not allowed as prop of button */}
<Button as="button" href="/">I am a button</Button>

See the full example here: https://codesandbox.io/s/nervous-grass-bnvsmn?file=/src/Button.tsx


text:
Q: How to Resume Twitter Sample Stream V2 using Tweetinvi I want to resume Twitter sample stream V2 after doing some calculations.
Initially I'm streaming few tweets (e.g. 100 or 1000 tweets), after receiving those I'm stopping the stream (using "sampleStreamV2.StopStream()" method provided by Tweetinvi Sample Stream V2) and doing some calculations. But after stopping not able to resume the stream using Tweetinvi.


text:
Q: How can I create a custom styled EntryElement with MonoTouch.dialog? I am trying to create a custom entry element using monotouch.dialog. I understand how to subclass a StringElement to style my own string elements - see example below:
public class CustomStyledStringElementPlain : MonoTouch.Dialog.StyledStringElement
{
    public CustomStyledStringElementPlain (string _caption, UIColor _backgroundcolour, UITextAlignment _alignment) : base(string.Empty,string.Empty)
    {
        TextColor = UIColor.White;
        Font = UIFont.FromName ("Helvetica-Bold", 14f);
        Caption = _caption;
        Alignment = _alignment;
        BackgroundColor = _backgroundcolour;
    }
}

However, when subclassing EntryElement, I am not able to access properties for the BackgroundColor for example (which is the main thing I want to change!) Here is what I have so far... Any pointers or advice on how I could change the background color or otherwise style entry elements would be much appreciated!
public class CustomStyledEntryElementPlain : MonoTouch.Dialog.EntryElement
{
    public CustomStyledEntryElementPlain (string _caption, UIColor _colour, UITextAlignment _alignment) : base(string.Empty,string.Empty)
    {
        ReturnKeyType = UIReturnKeyType.Done;
        Caption = _caption;
    }
}

A: To customize a MonoTouch.Dialog Element, you can override the GetCell method and set the appearance you want on the cell object. Something like this:
public override UITableViewCell GetCell(UITableView tableView) {
    var cell = base.GetCell(tableView);
    cell.BackgroundColor = _colour;
    return cell;
}


text:
Q: which is the condition I should use for proper working? I am new in developing and new to Stack Overflow too. This is my first question. I'm stuck in a problem that I am describing below:
$(document).ready(function() {
    $(".header").click(function() {
        if ($(".header-content").is(':visible')) {
            $(".header-content").slideUp(600);
        }
        else {
            $(this).next(".header-content").slideDown(600);
        }
    });

I uploading images of my project.
first Image is when we load the page.
Second images is when i click on second div named tracking
I want to write code for this functionality in which.
1. when I load the page all div with class header should be like same as in first image.

*when i click on any area of any one of from thee div. the class named header-content should be display block initially it is set display:none in css.

*when i click on other div except from open div it should closed the open div first and open the current div which was clicked.

*and at last when i click on same div twice it should close that div.
I hope you can understand my problem now.
Thanks for the help in advance.

A: Your posted question already asked here so many times. So, use ask question only if you do not find what you're looking for.
As from I get your question, you want to toggle .header-content classed element on click on .header.
In case you can use Toggle function of jQuery. like below:
$(document).ready(function(){
    $(".header").click(function(){
        $(".header-content").toggle("slow");
    });
});

You can use duration of this toggle effect using parameter. Replace "slow" accordingly.


text:
Q: Cannot install netbeans on Gentoo I'm trying to install Netbeans on my Gentoo system and I just cannot get it to work. When I'm compiling it It fails due to not being able to locate org.apache.maven.project.MavenProject.

[nb-javac] class file for org.apache.maven.project.MavenProject not found

I'm suspecting it has something to do with the installation not being able to find several files. However these are reported as warnings. The missing files have a version in their filenames, the files that are on the disk have a version number that is slightly off. So that explains why these cannot be found.
The full output of the install can be found here: http://pastebin.com/43NS2ktz

A:
tryggve ~ # eix maven
* app-admin/eselect-maven
     Available versions:  ~0.1 0.2 0.2-r1
     Homepage:            http://www.gentoo.org/
     Description:         Manages Maven symlinks

* dev-java/maven-bin
     Available versions:
        (1.1)   1.1-r1 ~1.1-r3
        (2.0)   2.0.11 ~2.0.11-r2
        (2.2)   2.2.1 ~2.2.1-r2
        (3.0)   ~3.0.4-r1
        {{elibc_FreeBSD}}
     Homepage:            http://maven.apache.org/
     Description:         Project Management and Comprehension Tool for Java

Install maven and use the first package to select the proper version.


text:
Q: Not able to display editable multiline field fully - Maximo Anywhere How do I display multiline text in editable textbox on device screen? At the moment, if the text is not editable then it shows the full text in multiline. The same value is displayed in 2 textboxes, one is editable and one is non-editable.
 <groupitem id="WorkExecution.groupitem_1">
    <text cssClass="richText" editable="false"
     id="WorkExecution.groupitem_1_abc" resourceAttribute="abc"/>
 </groupitem>
 <groupitem id="WorkExecution.groupitem_2">
     <text cssClass="richText" editable="true"
      id="WorkExecution.groupitem_2_xyz" placeHolder="Tap to enter"
      resourceAttribute="xyz"/>
</groupitem>

e.g. if the value reads -
IBM® Maximo® Anywhere gives you remote access from most mobile devices to Maximo Asset Management processes – work and asset management. It is built with an interface that is customizable, so you can create your own assets.
then the value of abc is displayed properly in multiline format whereas value of xyz is displayed in a single line and not in multiline.
Do I need to apply any CSS here?

A: In the OOB app.xml if you look at the view
<view editableView="WorkExecution.NewWorkLogView" id="WorkExecution.WorkLogDetailView" label="Work Log Entry">

You will see the multi line editable detail attribute near the bottom
            <groupitem id="WorkExecution.WorkLogDetailView_workOrder_groupitem_5">
                <text cssClass="richText" editable="false" id="WorkExecution.WorkLogDetailView_workOrder_groupitem_5_details_Details" label="Details" resourceAttribute="details"/>
            </groupitem>

As you already have the editable and css attributes set, my guess is that on your view it is not defined as an editableView.

A: For a editable multiline widget you need to use the textarea widget.  See our WorkLog details page in 7.5.2 for an example.
<groupitem id="WorkExecution.NewWorkLogView_workOrder_groupitem_5">
                        <textarea editable="true" id="WorkExecution.NewWorkLogView_details_0" label="Work Log Details" placeHolder="Tap to enter" resourceAttribute="details"/>
                    </groupitem>


text:
Q: Error while executing Windows Ubuntu Installer executable I have burnt a DVD from the Ubuntu 11.10 image file - ubuntu-11.10-desktop-i386.iso
I wanted to install Ubunto inside my Windows installation( I am doing this installation on a Windows-7 32 bit as a administrator login). I inserted this DVD in my drive, and started the WuBi(Windows Ubunti Installer) executable, it says installation started, the progress bar shows the progress, but just before it ends, it gives error as mentioned in the snapshot image below. As a result of this error, I have to say Ok and the installation is unsuccessful as I cannot start Ubuntu under windows.
Does anyone know what could be going wrong here. How fix it?
Have uploaded the log file as mentioned in the error message here


text:
Q: Descomponer un factorial en sus factores primos con javascript Estoy resolviendo un problema que consiste en descomponer el factorial de un numero en sus factores primos.

function decomp(n) {
    let multiplicadores = ''
    let factorial = 1;
    for (let i = 2; i <= n; i++) {
        factorial *= i
    }
    const numero = factorial
    for (let j = 2; j <= factorial; j++) {
        let contador = 0
        while (factorial % j == 0) {
            factorial /= j
            contador++
        }
        if (contador == 1) multiplicadores += `${j} * `
        if (contador > 1) multiplicadores += `${j}^${contador} * `
    }
    return `Resultado de descomponer ${n}! = ${numero}: ${multiplicadores.substr(0, multiplicadores.length - 3)}`
}
console.log(decomp(5));
console.log(decomp(12));
console.log(decomp(25));

Pero tengo un problema al probar con números muy grandes ej: 25! me regresa:

2^31 * 17^2 * 969743 * 25772783

cuando el resultado debería ser:

2^22 * 3^10 * 5^6 * 7^3 * 11^2 * 13 * 17 * 19 * 23

Desconozco el tamaño de números con el que trabaja javascript pero cuando hago los cálculos para el 25! me da como resultado:

1.5511210043330986e+25

Si se supone que este número representa el 25!, dicho numero solo debería poder simplificarse por 2 hasta 22 veces, pero al hacer la división:

1.5511210043330986e+25/Math.pow(2,22) = 3698160658676859400

Se comprueba que el número "aun pudiera simplificarse por 2".

A: El problema que ocurre al aplicar la función con números grandes probablemente se deba a la forma en que los ordenadores representan los números de punto flotante;
Por ejemplo en el caso de 25!, este fue transformado a 1.5511210043330986e+25 al ser muy grande, dejando de ser el mismo numero al ignorarse una parte sus dígitos.
Para mas información véase:
¿Por qué mis programas no pueden hacer cálculos aritméticos correctamente?
Lo que se podría hacer es emplear otro enfoque para resolver el problema; en lugar de iterar y obtener primero el resultado del factorial para luego descomponerlo, se podría hacer la descomposición de cada numero que compone el factorial dentro de la iteración:
En el siguiente código se almacenan los factores y su contador de apariciones en el objeto factores.
Luego en un bucle se obtiene el factorial del numero en fact y se va descomponiendo cada numero desde x en forma descendiente y contando la aparición de cada factor.
Luego se recorre el objeto factores, (donde las keys son las bases y sus valores los exponentes) para colocar las cadenas resultantes en multiplicadores verificando si apareció una o mas de una vez.
Por el utlimo se retorna el resultado en el formato requerido:
return `El resultado de descomponer ${num}! = ${fact} : `+multiplicadores.join(' * ');

El código queda de la siguiente forma:

function dfactorial(x) {

    var multiplicadores = [];
    var factores={};
    var num=x;
    var fact=1;

    while(x>1){
      fact*=x;
      var y=x;
      var fac=2;
      while(y>1)
        if(y%fac==0){
          y/=fac;
          factores[fac]==null ? factores[fac]=1 : factores[fac]++;
        }else
          fac++;
      x--;
    }
    Object.keys(factores).forEach(key =>
      multiplicadores.push(factores[key]>1 ? `${key}^${factores[key]}` : key)
    );
    return `El resultado de descomponer ${num}! = ${fact} : `+multiplicadores.join(' * ');
  }

  console.log(dfactorial(5));
  console.log(dfactorial(12));
  console.log(dfactorial(25));

De esa forma se puede descomponer el factorial de un número en sus factores primos.

A: Propongo el siguiente algoritmo, si bien se basa en la idea de @the-breaker, la diferencia es que en este no se calcula el factorial usando la multiplicación de todos los números desde 1 hasta N, sino que lo calcula multiplicando los factores primos hallados, ya que me parece que es la aproximación más adecuada al problema planteado.
La idea planteada es que se pueden descomponer los elementos que comprenden un factorial en sus factores primos:
7! = 2 * 3 * 4 * 5 * 6 * 7
7! = 2 * 3 * (2 * 2) * 5 * (2 * 3) * 7
7! = 2^4 * 3^2 * 5 * 7

Luego se calcula el factorial multiplicando estos factores primos (elevados cada uno a su respectivo exponente).
Usando la premisa divide y vencerás, vamos a dividir el problema en tareas pequeñas y puntuales necesarias para obtener la solución. Por lo tanto estas serán las funcionalidades específicas:

*

*Función que indique si un número es primo o no.

*Función que descomponga un número compuesto en factores primos.

*Método para agrupar factores comunes con su exponente.

*Cálculo del factorial usando los factores primos.

Con estas 4 funcionalidades podemos armar un algoritmo eficiente. Tal vez exista una manera aún más eficiente de hacer el trabajo, pero esta es la que se me ocurrió a mi.
Función para determinar si un número es primo.
Esta es una función de esas que siempre debemos tener guardada como herramienta básica, existen algunos algoritmos que buscan optimizar esta función, pero eso ya está fuera del alcance del objetivo básico que nos planteamos aquí.

const isPrime = (x) => {
  const CRIBA = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];
  if( x < 2) {
    return false;
  } else if(CRIBA.indexOf(x) > -1) {
    return true;
  } else if(CRIBA.some((primo) => { return (x % primo === 0) })) {
    return false;
  } else {
    if(x <= CRIBA[CRIBA.length - 1] * 2) {
      return true;
    } else {
      let test = true;
      for(let i = CRIBA[CRIBA.length - 1] + 1; i <= Math.floor(x/2); i++) {
        if(x % i === 0) {
          test = false;
          break;
        }
      }
      return test;
    }
  }
}

console.log(`7 es primo: ${isPrime(7)}`);
console.log(`11 es primo: ${isPrime(11)}`);
console.log(`6 es primo: ${isPrime(6)}`);
console.log(`37 es primo: ${isPrime(37)}`);

Esta función usa una lista con números primos conocidos. Muchos algoritmos se basan en lista de números primos ya calculados para intentar obtener valores de primos más altos con una eficiencia superior a la iteración desde 2 hasta N/2. En este caso he usado una criba con 10 números primos, pero se puede ajustar a gusto.
¿Porqué hasta la mitad del número? La respuesta es simple: nos ahorramos algunas iteraciones, ya que un número compuesto no puede tener un factor primo mayor a la mitad de su valor.
¿Porqué un valor menor que el doble del mayor primo de la lista es un número primo? Muy sencillo, si P es el mayor primo de la lista y N es menor o igual que 2P, entonces esto indica que la validación N % p === 0 dio falso para todos los p de la lista, y como hemos dicho que un número compuesto no puede tener un factor primo que sea mayor a la mitad de su valor, entonces debe ser primo.
Solamente se itera cuando un valor dado es mayor que 2P, además se itera desde P+1 hasta N/2.
Descomposición en factores primos
Teniendo una forma de determinar si un número es primo o no, podemos ahora descomponer en factores primos. El siguiente algoritmo toma un valor N y prueba si el mismo es primo o no. Si lo es, devuelve una lista con N como elemento único. Si N es compuesto, realiza una división de N por cada primo posible entre 2 y N/2. Por cada división exacta que se logre, se agrega el primo a la lista y se divide N por el primo, y se realiza una nueva división. La iteración de cada división se detiene cuando la división es inexacta y se pasa a verificar el siguiente primo de la lista. El valor de N se va actualizando en cada paso hasta obtener todos los primos.

const isPrime = (x) => {
  const CRIBA = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];
  if( x < 2) {
    return false;
  } else if(CRIBA.indexOf(x) > -1) {
    return true;
  } else if(CRIBA.some((primo) => { return (x % primo === 0) })) {
    return false;
  } else {
    if(x <= CRIBA[CRIBA.length - 1] * 2) {
      return true;
    } else {
      let test = true;
      for(let i = CRIBA[CRIBA.length - 1] + 1; i <= Math.floor(x/2); i++) {
        if(x % i === 0) {
          test = false;
          break;
        }
      }
      return test;
    }
  }
}

const primeFactors = (x) => {
  if(isPrime(x)) return [x];
  let p = [];
  let value = x;
  for(let i = 2; i <= Math.floor(x/2); i++) {
    if(isPrime(i)) {
      while(value % i === 0) {
        value = value / i;
        p.push(i);
      }
    }
  }
  return p;
}

console.log(primeFactors(6).join(' - '));
console.log(primeFactors(12).join(' - '));
console.log(primeFactors(17).join(' - '));
console.log(primeFactors(256).join(' - '));

Agrupar factores comunes
Usaremos el método reduce(); para contar los factores primos y agruparlos en un array de objetos. Cada objeto tendrá la forma {<clave>: <valor>, ... }, donde la <clave> será el factor primo y el <valor> será el exponente (cantidad de veces que aparece).

const groupFactors = (factors) => {
   return factors.reduce((all, f) => {
     if(f in all) {
       all[f]++;
     } else {
       all[f] = 1;
     }
     return all;
   }, {});
}

console.log(groupFactors([2,2,2,3,3,5]));

Calcular Factorial usando los factores primos
Ahora simplemente debemos calcular el factorial usando los factores primos hallados, para ello recorreremos el objeto creado con los factores agrupados y realizaremos las operaciones matemáticas correspondientes.

const groupFactors = (factors) => {
   return factors.reduce((all, f) => {
     if(f in all) {
       all[f]++;
     } else {
       all[f] = 1;
     }
     return all;
   }, {});
}

const obj = groupFactors([2,2,2,3,5]); // esto es 5!

let factors = [];
let factorial = [];

Object.keys(obj).forEach((k) => {
  factors.push(`${k}${obj[k] > 1 ? `^${obj[k]}`: ''}`);
  factorial.push(k ** obj[k]);
});

console.log(`El factorial de 5 es ${factorial.reduce((acc,curr) => acc * curr)}`);
console.log(`La descomposición en factores primos de 5! es:`);
console.log(`${factors.join(' * ')}`);

Ensamblando todo
El paso final es escribir una función que realice toda la tarea en un solo llamado, todas nuestras funciones deben estar diponibles para realizar esta tarea, por lo tanto el código podría verse así:

const isPrime = (x) => {
  const CRIBA = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];
  if( x < 2) {
    return false;
  } else if(CRIBA.indexOf(x) > -1) {
    return true;
  } else if(CRIBA.some((primo) => { return (x % primo === 0) })) {
    return false;
  } else {
    if(x <= CRIBA[CRIBA.length - 1] * 2) {
      return true;
    } else {
      let test = true;
      for(let i = CRIBA[CRIBA.length - 1] + 1; i <= Math.floor(x/2); i++) {
        if(x % i === 0) {
          test = false;
          break;
        }
      }
      return test;
    }
  }
}

const primeFactors = (x) => {
  if(isPrime(x)) return [x];
  let p = [];
  let value = x;
  for(let i = 2; i <= Math.floor(x/2); i++) {
    if(isPrime(i)) {
      while(value % i === 0) {
        value = value / i;
        p.push(i);
      }
    }
  }
  return p;
}

const groupFactors = (factors) => {
   return factors.reduce((all, f) => {
     if(f in all) {
       all[f]++;
     } else {
       all[f] = 1;
     }
     return all;
   }, {});
}

const factorialPrimeFactors = (x) => {
  // casos no válidos
  if(x < 1) {
    console.log(`El factorial de ${x} no está definido`);
    return;
  }
  if(x == 1) {
    console.log(`El factorial de ${x} es ${x}.`);
    return;
  }

  let primos = [];
  for(let i = 2; i <= x; i++) {
    primos.push(... primeFactors(i));
  }

  const obj = groupFactors(primos);

  let factors = [];
  let factorial = [];

  Object.keys(obj).forEach((k) => {
    factors.push(`${k}${obj[k] > 1 ? `^${obj[k]}`: ''}`);
    factorial.push(k ** obj[k]);
  });

  console.log(`El factorial de ${x} es ${factorial.reduce((acc,curr) => acc * curr)}`);
  console.log(`La descomposición en factores primos de ${x}! es:`);
  console.log(`${factors.join(' * ')}`);
}

factorialPrimeFactors(17);
factorialPrimeFactors(120);
factorialPrimeFactors(25);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Espero que esto te de otra visión del problema y una solución alternativa al cálculo de un número factorial.
EDICIÓN
Gracias al comentario de @abulafia sobre optimización, edito la función que determina si un número es primo.
La idea planteada por @abulafia es simple:

Ningún número compuesto puede tener un factor primo mayor que su raíz cuadrada si ya hemos comprobado que hasta su raíz cuadrada no lo tiene. Por lo tanto si hasta llegar a la raíz cuadrada de un número, no hemos hallado ningún factor que lo divida, el número es primo.

Esto reduce significativamente las iteraciones que se realizan para determinar si un número es primo o no.
Usando la Criba de Eratóstenes, (la cual aplico de una forma trucada en mi algoritmo), e iterando hasta N/2 como sugerí en mi implementación tenemos por ejemplo, que si deseamos verificar si 103 es un número primo, entonces:

*

*Calculamos la mitad de 103 (al no ser exacto se toma sólo la parte entera del resultado), lo cual nos da la proximación de 51.

*Iteramos desde 2 hasta 51.

*En 50 iteraciones descubrimos que 103 es primo.

Usando la optimización comentada por @abulafia, ahora vamos a iterar solamente hasta la raíz cuadrada de 103, que nuevamente aproximaremos por defecto. El resultado real es 10,148891565, pero usaremos 10. Así las iteraciones son mucho menos para descubrir que 103 es primo:

*

*Calculamos la raíz de 103 y la aproximamos por defecto.

*Iteramos desde 2 hasta 10.

*En 9 iteraciones descubrimos que 103 es primo.

Nos hemos ahorrado 41 iteraciones. Es mucho más óptimo. El código de la función quedaría como el siguiente:

const isPrime = (x) => {
  const CRIBA = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29];
  if( x < 2) {
    return false;
  } else if(CRIBA.indexOf(x) > -1) {
    return true;
  } else if(CRIBA.some((primo) => { return (x % primo === 0) })) {
    return false;
  } else {
    if(x <= CRIBA[CRIBA.length - 1] ** 2) {
      return true;
    } else {
      // itero solo para números mayores que P^2, siendo P el mayor primo de mi lista
      let test = true;
      let count = 0;
      for(let i = CRIBA[CRIBA.length - 1] + 1; i <= Math.floor(Math.sqrt(x)); i++) {
        count++;
        if(x % i === 0) {
          test = false;
          break;
        }
      }
      console.log(`Iteraciones realizadas: ${count}`);
      return test;
    }
  }
}
console.log('Comprobaremos si 1741 es un número primo (lo es)');
console.log('La aproximación de su raíz es 41');
console.log('Debemos realizar 40 iteraciones usando la Criba de Eratóstenes');
console.log('Sin embargo, dado que uso una versión trucada del mismo:');
console.log(`¿1741 es primo? ${isPrime(1741)}`);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Con esto tenemos un algoritmo más eficiente para determinar si un número es primo o no.


text:
Q: Changing property type in class that implements interface with object type property I'm writing a TemplateEngine that will allow me to use my own markup in text based files. I'm wanting to add controls as plugins as the application matures. Currently i've got a structure like the following:
interface IControl
    string Id
    object Value

class Label : IControl
    string Id
    string Value

class Repeater : IControl
    string Id
    List<IControl> Value

Now you'll see the strange part right away in the Repeater class with the Value property. I was hoping that having the Value type as object in the interface would allow me the flexibility to expand the controls as i go along. The compiler doesn't like this and for good reason i guess.
Bottom line: I'm trying to get all control classes to implement the same interface but have different types for the Value property.
Does anyone have any suggestions how to accomplish this?
Note: Please don't go into suggesting things like use Spark View Engine for templating. There is a reason i'm creating extra work for myself.

A: Normally the Repeater would implement something different, like an IItemsControl for example.
EDIT 1
(removed for brevity)
EDIT 2
Ah okay, you can always use explicit interface implementation of course:
interface IControl
{
    string Id { get; set; }
    object Value { get; set; }
}

class Label : IControl
{
    public string Id { get; set; }
    public string Value { get; set; }

    object IControl.Value
    {
        get { return this.Value; }
        set { this.Value = (string)value; }
    }
}

class Repeater : IControl
{
    public string Id { get; set; }
    public IList<IControl> Value { get; set; }

    object IControl.Value
    {
        get { return this.Value; }
        set { this.Value = (IList<IControl>)value; }
    }
}

A: you could also use generics:
interface IControl<T>
{
    string ID{get;set;}
    T Value{get;set;}
}

class SomeControl : IControl<string>
{
    public string ID{get;set}
    public string Value{get;set;}
}

class SomeOtherControl : IControl<int>
{
    public string ID{get;set}
    public int Value{get;set;}
}

I like this better than the explicit interface idea if it's just one return value that needs to change. However, I think if you had several properties that each would return a different type, you wouldn't want to have IControl. At least, I wouldn't. In that case I would recommend the explicit interfaces.
Of course, this wouldn't work if you didn't have access to the source of IControl.
Edit: had a typo. Fixed

A: No, the compiler doesn't allow same name fields to be of different data types other than what is defined in the interface in derived classes.
The properties (since no fields are allowed in interface) should be implemented in the deriving classes and they need to have same data type. So, you cannot probably do it with properties without explicit declaration.
However, if you make Value to be returned by a function, then it works, but you need to check the return type because the return types should match for the function, otherwise you will get error that interface's function was not implemented.
    interface IControl
    {
        object Value();
    }
    class A : IControl
    {
        string m_value = string.Empty;
        public object Value() { return m_value; }
    };
    class B : IControl
    {
        List<IControl> m_value = new List<IControl>();
        public object Value() { return m_value; }
    };
    ....
    object o = new B().Value();
    if (o is List<IControl>)
        MessageBox.Show("List");

[Update]
You have to be careful if explicitly defining the body of the properties. Having one name for two properties would be dangerous if implementation is not done carefully.
These two properties if contain different definition, it would be unexplainable for the final use of the interface and classes.
        public IList<IControl> Value
        object IControl.Value

See this example:
    ...
    class Repeater : IControl
    {
        List<IControl> m_Value = new List<IControl>();
        public IList<IControl> Value
        {
            get { return this.m_Value; }
            set { this.m_Value = (IList<IControl>)value; }
        }
        object IControl.Value
        {
            get
            {
                return this.m_Value;
            }
            set
            {
                this.m_Value = new List<IControl>();
                this.m_Value.Add(new Label());
                this.m_Value.AddRange((List<IControl>)value);
            }
        }
    }
    ...
    Repeater b = new Repeater();
    IControl i = b;
    List<IControl> list = new List<IControl>();
    list.Add(new Repeater());
    i.Value = list;

You can observe that the list container in Repeater will have different values when data is added via IControl (because of the explicit definition of IContainer.Value).


text:
Q: Calling functions from multiple files within a single load statement using jQuery I'm trying to achieve the most basic include with jQuery, that is loading functions from multiple files when the DOM is ready, but apparently it turned out not to be so trivial:
index.html
<script type="text/javascript" src="res/scripts.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
        alert("Hello world!");
        foo();
        bar();
    });
</script>

scripts.js
function foo(){
        alert("Hello from foo!");
}

function bar(){
        alert("Hello from bar!");
}

With alert("Hello world!"); being the only statement that executes as expected. The folder locations are checked, as worked with the previous strategy (window.attachEvent)
I've tried moving the .ready()statement to the scripts.js file but that didn't helped much.
Any advice would me really appreciated. Thanks much in advance.
UPDATE
Currently I'm handling the function loading this way:
// Based on "Flexible JavaScript events" by John Resig: http://goo.gl/xLn4S
function addEvent( obj, type, fn ) {
    if ( obj.attachEvent ) {
        obj['e'+type+fn] = fn;
        obj[type+fn] = function(){obj['e'+type+fn]( window.event );}
        obj.attachEvent( 'on'+type, obj[type+fn] );
    } else
        obj.addEventListener( type, fn, false );
}

function removeEvent( obj, type, fn ) {
    if ( obj.detachEvent ) {
        obj.detachEvent( 'on'+type, obj[type+fn] );
        obj[type+fn] = null;
    } else
        obj.removeEventListener( type, fn, false );
}

addEvent(window, 'load', foo);
addEvent(window, 'load', bar);

A: $(document).ready() is executed after the dom is complete which can happen before the external javascript files are downloaded so foo and bar may not be defined yet.

A: I think it's just a typo. It's alert not altert:
function foo(){
        alert("Hello from foo!");
}

function bar(){
        alert("Hello from bar!");
}

Tools like Firebug can help with things like that.

A: First, add a unique number to the url you use to retrieve your javascript, as in:
<script type="text/javascript" src="res/scripts.js?111010101"></script>

to assure the browser retrieves the most current version of scripts.js. Then, every time the page is retrieved, generate a new unique version number. (At least during development)
Next, you need to assure that script.js has been loaded and correctly evaluated before you try to call its functions.
One way to do this would be to trigger a new, custom event at the bottom of script.js, on which you would set a handler to execute (in document.ready()).
Another way would be to load the script within the document.ready() handler before you tried to call any of its functions.
EDIT to add example:
<script type="text/javascript">
  document.ready(function(){
    alert('Hello World!');
    $.getScript('res/scripts.js', function() {
      foo();
      bar();
    });
  });
</script>


text:
Q: How do I move "Application menu" within the widows title bar on the left side while "minimize, maximize, close" buttons are placed on the right side? I'm looking for a way to move the application menu in the window's title bar on the left side as it is illustrated on the next image.

Optionally, I will be happy if there is some way to force such application menu to appear for non-GTK windows as Firefox, Chromium, GIMP, etc.

A: You can achieve the preferred ordering of window control buttons by running the following:
gsettings set org.gnome.desktop.wm.preferences button-layout appmenu:minimize,maximize,close

The : works as a "separator". You can put any button to the left or right of the : to make it appear on the left or right of the title-bar.

In order to place something in the left corner of the window title bar for all GTK and non GTK windows, you can modify the above command in this way (reference):
gsettings set org.gnome.desktop.wm.preferences button-layout menu:appmenu,minimize,maximize,close

Here is how the final result looks like for GTK and non GTK windows:


text:
Q: How to import JSON file from a remote host into Ansible variable? I am using ansible.builtin.slurp to do this. Here is the relevant part of my Ansible role:
- name: Load config
  slurp:
    src: "/etc/mlnx_snap/mlnx_snap.json"
  register: imported_config
- name: Debug
  debug:
    var: imported_config

I expect to have debug print my file, however, something different happens.
Here's the file content:
root@ratchet01-snic:~# cat /etc/mlnx_snap/mlnx_snap.json
{
    "ctrl": {
        "sqes": 0x6,
        "cqes": 0x4,
        "cq_period": 3,
        "cq_max_count": 6,
        "nr_io_queues": 32,
        "mn": "Mellanox BlueField NVMe SNAP Controller",
        "sn": "MNC12",
        "mdts": 4,
        "oncs": 0,
        "offload": false,
        "max_namespaces": 0,
        "quirks": 0x0
    },
    "backends": [ {
        "type": "spdk_bdev",
        "paths": [{}]
    } ]
}

And here is what the debug output looks like:
Debug...
  retchet01-snic.mtr.labs.mlnx ok: {
    "changed": false,
    "imported_config": {
        "changed": false,
        "content": "LyoKICogcHJ...CiAgICB9IF0KfQo=",
        "encoding": "base64",
        "failed": false,
        "source": "/etc/mlnx_snap/mlnx_snap.json"
    }
}

Content is actually thousands of characters long, I just shortened it for readability.
Imagine I have a following task further in this role:
- name: Do x
  module_name:
    var_name: value
  when: imported_config.ctrl.quirks >= 0

How do I correctly import the JSON file so that such a task could work? What am I doing wrong?

A: Use from_yaml. JSON is a subset of YAML. For example
    - set_fact:
        content: "{{ imported_config.content|b64decode|from_yaml }}"
    - debug:
        msg: "{{ content.ctrl.quirks >= 0 }}"

gives
  msg: true

A: The following helped get the raw text of JSON file:
- name: Debug
  debug:
    var: imported_config.content|b64decode

To further decode it into a variable, I would need to use this:
- name: Debug
  debug:
    var: imported_config.content|b64decode|from_json

That, however, fails for me due to invalid JSON format (it contains comments for some weird reason despite them not being allowed in JSON). But that is out of the initial scope of this question.


text:
Q: is there picturebox in java SE application(using netbeans) is there picturebox in java SE application(using netbeans).  i dont want to use label and Imageicon. can someone help me .

A: No, there is not. The JDK itself doesn't offer that many ready components - if you want something more - either create it yourself (by creating a class extending JComponent or JPanel for instance) or have a look at what external Swing libraries have to offer. You can bend and swing the JLabel + ImageIcon approach to your will easily. Btw this is probably the fifth consecutive question you're asking for a trivial topic. You'd do better to read a good Java book for beginners like "Core Java" or google a bit, instead of flooding SO with your questions. It will be a much more productive approach for you as well...


text:
Q: Automatically creating hyperlink to another sheet by text I would like to know how to create a hyperlink from one excel sheet to another, automatically through a script, based on equal text values that both cells in their respective sheets have.
If this can be done without a script, using a formula of some kind (like VLOOKUP) this would be preferable.
thanks for your time.

A: *

*Hyperlink on same sheet using a value in A1:

=HYPERLINK("#" & ADDRESS(MATCH(A1, B1:B5, 0), 2), "Link")

*

*Hyperlink to a specific different sheet using a value in A1:

=HYPERLINK("#'My Database'!" & ADDRESS(MATCH($A1, 'My Database'!$A:$A, 0), 1), "Link")

*

*Hyperlink to a sheet listed in cell A1

=HYPERLINK("#'" & A1 & "'!A1", "Link")

*

*Hyperlink to a random position in a column that must be found on a random sheet listed in cell C3, matching the value in A1, a 3D INDEX/MATCH/Hyperlink:

=HYPERLINK("#" & CELL("address", INDEX(INDIRECT(C3 & "!A:A"), MATCH(A1, INDIRECT(C3 & "!A:A"), 0))), "Link")
There's a sample sheet found here where you can see these applied:
3D Hyperlink Examples


text:
Q: Position elements relative of a static sibling I am working on a Calender where I have multiple events in parallel. I can allow the following elements in an event class to inherit their position form the event-start.
I would like the browser to handle the positioning of multiple elements.
When I set the position of the following elements to absolute
then the next event-start which has position:relative;, does see the element with absolute and get the same potion which means all events land in the same row.
Inherited Position with even-start a relative position.

Positions relative.

Here is a fiddle without the inherit functionality.
https://jsfiddle.net/4uk8yur5/2/
I would like to, through css set the position of the events-start elements relative to the static events.


text:
Q: Mapbox IOS example "Annotation views" not displaying Custom UIView I am new to Mapbox and I am trying to learn how to work with Custom Annotated Views. I created a new xcode project (using xcode 11.5, IOS 13.5 and Storyboard option), installed the pods, and setup the access tokens following the installation guide: https://www.mapbox.com/install/ios/
I then copied and pasted the code from the Annotation example: https://docs.mapbox.com/ios/maps/examples/annotation-views/ into ViewController.swift
When I run the code I get this on the simulator:
ActualFunctionality
But I want: ExpectedFunctionality
After adding print statements, it appears that .layoutSubviews() is never being called within the created CustomAnnotationView's. Any help or insight would be greatly appreciated.
EDIT:
ViewController.swift
import Mapbox
import UIKit

class ViewController: UIViewController, MGLMapViewDelegate {

    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        print("{ERFORMED")
    }
    override func viewDidLoad() {
        super.viewDidLoad()

        let mapView = MGLMapView(frame: view.bounds)
        mapView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        mapView.styleURL = MGLStyle.darkStyleURL
        mapView.tintColor = .lightGray
        mapView.centerCoordinate = CLLocationCoordinate2D(latitude: 0, longitude: 66)
        mapView.zoomLevel = 2

        mapView.delegate = self
        view.addSubview(mapView)

        // Specify coordinates for our annotations.
        let coordinates = [
            CLLocationCoordinate2D(latitude: 0, longitude: 33),
            CLLocationCoordinate2D(latitude: 0, longitude: 66),
            CLLocationCoordinate2D(latitude: 0, longitude: 99)
        ]

        // Fill an array with point annotations and add it to the map.
        var pointAnnotations = [MGLPointAnnotation]()
        for coordinate in coordinates {
            let point = MGLPointAnnotation()
            point.coordinate = coordinate
            point.title = "\(coordinate.latitude), \(coordinate.longitude)"
            pointAnnotations.append(point)
        }

        mapView.addAnnotations(pointAnnotations)
    }

    func mapView(_ mapView: MGLMapView, viewFor annotation: MGLAnnotation) -> MGLAnnotationView? {
        // This example is only concerned with point annotations.
        guard annotation is MGLPointAnnotation else {
            return nil
        }

        // Use the point annotation's longitude value (as a string) as the reuse identifier for its view.
        let reuseIdentifier = "\(annotation.coordinate.longitude)"

        // For better performance, always try to reuse existing annotations.
        var annotationView = mapView.dequeueReusableAnnotationView(withIdentifier: reuseIdentifier)

        // If there's no reusable annotation view available, initialize a new one.
        if annotationView == nil {
            annotationView = CustomAnnotationView(reuseIdentifier: reuseIdentifier)
            annotationView!.bounds = CGRect(x: 0, y: 0, width: 40, height: 40)

            // Set the annotation view's background color to a value determined by its longitude.
            let hue = CGFloat(annotation.coordinate.longitude) / 100
            annotationView!.backgroundColor = UIColor.green

        }

        return annotationView
    }

    func mapView(_ mapView: MGLMapView, annotationCanShowCallout annotation: MGLAnnotation) -> Bool {
        return true
    }
}

class CustomAnnotationView: MGLAnnotationView {
    override func layoutSubviews() {
        super.layoutSubviews()

        print("LAYOUT SUBVIEWS")
        // Use CALayer's corner radius to turn this view into a circle.
        layer.cornerRadius = bounds.width / 2
        layer.borderWidth = 2
        layer.borderColor = UIColor.white.cgColor
    }

    override func setSelected(_ selected: Bool, animated: Bool) {
        super.setSelected(selected, animated: animated)

        // Animate the border width in/out, creating an iris effect.
        let animation = CABasicAnimation(keyPath: "borderWidth")
        animation.duration = 0.1
        layer.borderWidth = selected ? bounds.width / 4 : 2
        layer.add(animation, forKey: "borderWidth")
    }
}

AppDelegate.swift
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        return true
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.
        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

    func application(_ application: UIApplication, didDiscardSceneSessions sceneSessions: Set<UISceneSession>) {
        // Called when the user discards a scene session.
        // If any sessions were discarded while the application was not running, this will be called shortly after application:didFinishLaunchingWithOptions.
        // Use this method to release any resources that were specific to the discarded scenes, as they will not return.
    }

}

SceneDelegate.swift
import UIKit

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?

    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
        guard let _ = (scene as? UIWindowScene) else { return }

//        if let windowScene = scene as? UIWindowScene {
//
//            let window = UIWindow(windowScene: windowScene)
//
//            let annotated = Annotation_vc()
//            let navigation = UINavigationController(rootViewController: annotated)
//
//            window.rootViewController = navigation
//
//            self.window = window
//            window.makeKeyAndVisible()
//        }
    }

    func sceneDidDisconnect(_ scene: UIScene) {
        // Called as the scene is being released by the system.
        // This occurs shortly after the scene enters the background, or when its session is discarded.
        // Release any resources associated with this scene that can be re-created the next time the scene connects.
        // The scene may re-connect later, as its session was not neccessarily discarded (see `application:didDiscardSceneSessions` instead).
    }

    func sceneDidBecomeActive(_ scene: UIScene) {
        // Called when the scene has moved from an inactive state to an active state.
        // Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
    }

    func sceneWillResignActive(_ scene: UIScene) {
        // Called when the scene will move from an active state to an inactive state.
        // This may occur due to temporary interruptions (ex. an incoming phone call).
    }

    func sceneWillEnterForeground(_ scene: UIScene) {
        // Called as the scene transitions from the background to the foreground.
        // Use this method to undo the changes made on entering the background.
    }

    func sceneDidEnterBackground(_ scene: UIScene) {
        // Called as the scene transitions from the foreground to the background.
        // Use this method to save data, release shared resources, and store enough scene-specific state information
        // to restore the scene back to its current state.
    }

}

Xcode setup:
Deployment
Build
info
info.plist

A: Annotation views should be added after the map has completely loaded
See https://github.com/mapbox/mapbox-gl-native/issues/16492 for more details


text:
Q: 3A Current Distribution

simulate this circuit – Schematic created using CircuitLab
I am using a 5V 3A wall adapter. I have stripped the output end and connected it to a terminal block. I am rerouting the current to two places: a standard breadboard and the Raspberry Pi. When I use the multimeter to measure the current I see readings of 0 and then sudden spikes to 2A.
Why am I not seeing anything close to 3A? I am measuring the current directly from the adapter's PWR and GND wires. Please let me know if any additional info can help.
I also get PWR warning issues from the Raspberry Pi but I believe this may be a result of the fluctuating current readings OR the fact I am using 26 AWG cable (rated max 300 mA when the Pi needs 1A).

A: The Pi needs 500mA DC, not 1A (depending on the model, actually).
The way you have connected the current meter sounds wrong - using a multimeter as an ammeter you must put the device in SERIES along the PWR output wire, not to ground.
You have probably damaged your multimeter or blown it's ammeter fuse.
The next thing is, place a large (100uf -> 1000uF) capacitor just where the Raspberry Pi is connected, to help it deal with pulsed current requirements.
You should also place a large capacitor on the breadboard where the power connection comes into it. This technique is called power supply decoupling.
You should indeed increase the size of the wire carrying current to the Raspberry Pi by the way, even just two strands of AWG26 run together but twisted at each end would do fine.
You should not "see" 3A unless you actually have a 3A load. The Pi like I said will only draw about 500mA DC in normal conditions. Unless you have something else to act as a 2.5A load, you will never see the wall wart putting out 3A. Another thing is, don't trust crappy wall warts. The next thing is, if you short circuit the output (like with an ammeter from PWR to GND..) the Wall Wart may go into protection mode to protect itself, and thus brown-out the R-Pi.


text:
Q: sending feedback form through email I want to send a user feedback form through email. when they press submit button form should go to the mentioned id.
How to achieve this? is it possible?

A: The best way of going about this would be to create some kind of contact form, on your actually site, just don't have the direct URL visible to everyone, then rather than sending the actual form to a client/customer/whatever, just send them the link to the form and allow them to fill it in on the site and submit it, if you do it in php then the email can be sent directly to you personally.
This will talk you through creating the form:
http://php.about.com/od/phpapplications/ss/form_mail.htm
You may also want to research validation to other any nasty suprises through hackers or injections, and try to make it as secure as possible.
Hope this helps.


text:
Q: Checking an output for specific extentions in if statement I am trying to write a script where I have an if statement that has to check if a specific folder contains a package with specific extensions. If so, it then has to unpack it.
if [ installation = "1" ]; then
    if ls /usr/local/src grep -qF ".tar.gz"; then
        tar -zxvf $package #it has to unpack the package
    elif ls /usr/local/src grep -qF ".tar.bz2"; then
        tar -xvfj $package #it has to unpack the package
    fi
    ./configure
elif [ installation = "2" ]; then
    dpkg -i $package #it has to install the deb package
fi

Can it be written in this way?
The $package is not used, but I've written it to show you what I mean. I don't know how to let it know that it has to unpack/install the founded folder with the extension .tar.gz or .tar.bz2 or .deb

A: something like this?
 #!/bin/bash

cd /usr/local/src
    if [ installation = "1" ]; then
        for package in *.tar.gz
        do
            tar -zxvf "${package}"
        done

        for package in *.tar.bz2
        do
            tar -xvfj "$package" #it has to unpack the package
        done
        ./configure
    elif [ installation = "2" ]; then
        dpkg -i "$package" #it has to install the deb package
    fi

A: You could use something like this.
if [ installation = "1" ]; then
    for package in *.tar.*
    do
        tar -xvf ${package} # Unpack (Let tar detect compression type)
    done
    ./configure
elif [ installation = "2" ]; then
    dpkg -i ${deb_package} #it has to install the deb package
fi

There is no need to manually detect the compression type through ls/grep hacks.

The only case when you have to specify a decompression option while
  reading the archive is when reading from a pipe or from a tape drive
  that does not support random access. However, in this case GNU tar
  will indicate which option you should use. For example:
$ cat archive.tar.gz | tar tf -
tar: Archive is compressed.  Use -z option
tar: Error is not recoverable: exiting now

If you see such diagnostics, just add the suggested option to the
  invocation of GNU tar:
$ cat archive.tar.gz | tar tzf -

-- 8.1.1 Creating and Reading Compressed Archives


text:
Q: Hibernate Reverse Engineer Database I am using MyEclipse to generate Hibernate code for a PostgreSQL database. The issue is that this is the only reason I'm using MyEclipse. I would like to use some kind of command line tool to easily generate this code. I've seen some mention of such tools but I can't find anything solid. It seems like what I want to do is pretty simple. I hate to fire up this IDE and go through all this stuff just to do some simple code gen.
What's the best way to do this simply?

A: Yes, you can do it using ant from command line like this.


text:
Q: At what point does the performance gap between GPU & CPU become so great that the CPU is holding back a system? I know that generally speaking for gaming performance the GPU is the primary factor which holds back performance, with everything else such as RAM/motherboard/PSU/CPU being secondary in importance to the graphics card.
But at some point the other components ARE going to be significant in holding back the whole system!
For instance nobody would be silly enough to play modern games with 512MB RAM and the very latest graphics cards (such as an HD7970) as I bet the performance increase over such a system with only 512MB but a mid range card would be non-existent! Thus it would be a "waste" for such a person to buy any high end graphics card without resolving first the system's other problems. The same point applies to other components, such as if it only had a Pentium II a current high end graphics card would be wasted on it!
So my core question is how do you determine at what point for your system is spending on extra GPU power be completely "wasted"? (also, a slightly more nuanced question is trying work out at what point might the extra graphics power not be "wasted" but would be "sub optimal" value for money, when the expenditure should then be split around graphics card and other components. As obviously a gamer shouldn't always just spend on upgrading the graphics card! But needs to balance it out)

A: Simple. If you open up process explorer or GPU shark, you can see the bottleneck in that moment.

If the GPU is capped at 100% load, then it's the GPU. If the GPU is at
  <100, and the CPU is either on 25% or 100% (if it's single-threaded it
  will be 25%), then it's the CPU.

But it's simple to max out a GPU. Just get a "gaming CPU", for example the Core i5 2500K is the king of that field. With it's cheap price, and kickass power, it will surely max out any GPU.

A: There are no lookup tables to determine what GPU is the best fit for your system. You mentioned 'Arma 2' as something being very CPU intensive. Let's go one step further and take a look at Dwarf Fortress. Although the game is not coded to support it, in terms of processing power, it could run on a machine with no GPU at all, as long as the system can output text to a display. Cards cannot really be ranked on a vague term as processing power anyway. To give a very general indication, some cards excel at handling complex scenes, while others may cope better with large textures and high display resolutions, or offer a fancier set of features.
While it is very hard to gauge performance in advance, you can do some testing on an operational rig to determine whether a GPU upgrade is going to be useful. Theoretically, if your GPU usage never reaches 100%, a faster model would probably just have more idle time, whereas full usage indicates an upgrade would allow the GPU to do more work. This reasoning holds for the central processing unit as well. There are plenty of ways of getting these statistics during load, an example guide can be found here.
There's a catch. Having a GPU do more work does not necessarily result in a perceived or useful performance increase. For example, it could boost the average framerate from 250 fps to 500 fps, but not prevent frequent framedrops that are caused by a bottleneck elsewhere. The GPU could also be doing busy work, throwing most of the calculations away. Keep an eye out for other stats as well. Knowing the CPU, HDD, RAM etcetera are not bottlenecks, will help you determine whether the GPU is.


text:
Q: Given this model, how to delete a nested array item with updateOne (mongoose)? I am trying to remove an array item with "updateOne" method but my query is not matching the right record in the model structure that I have. Given an email, I would like to find the array item with the provided email and pulls it out, remove it. (There is no array item with the same email)
My model is like so:
var mongoose = require('mongoose');

var teamMemberModelSchema = new mongoose.Schema({
     _id: false,
    "email": {
        "type": String,
        "required": true,
        "minlenght": 5,
        "maxheight": 50
    },
    "name": {
        "type": String,
        "required": true,
        "minlenght": 5,
        "maxheight": 256
    },
    "role": {
        "type": String,
        "required": true,
        "minlenght": 20,
        "maxheight": 256
    },
    "twitter": {
        "type": String,
        "required": true,
        "minlenght": 1,
        "maxheight": 100
    },
    "facebook": {
        "type": String,
        "required": true,
        "minlenght": 1,
        "maxheight": 100
    },
    "linkedin": {
        "type": String,
        "required": true,
        "minlenght": 1,
        "maxheight": 100
    },
});

var teamModelSchema = new mongoose.Schema({
    "title": {
        "type": String,
        "required": true,
        "minlenght": 5,
        "maxheight": 20
    },
    "headline": {
        "type": String,
        "required": true,
        "minlenght": 5,
        "maxheight": 30
    },
    "description": {
        "type": String,
        "required": true,
        "minlenght": 5,
        "maxheight": 80
    },
    "members": [teamMemberModelSchema]
}, { collection: 'team' });

teamModelSchema.set('collection', 'team');
mongoose.model('team', teamModelSchema)

And the approach that I am trying is the following:
module.exports.removeMember = function (req, res) {
  const email = req.params.email;
  const query = { "members.email": email };
  const pull = { $pull: { "members.$.email": email } };

  try {
    var message = teamMsg.teamMemberRemoveSuccess;

    TeamModel.updateOne(query, pull);

    responseUtilities.sendJSON(res, false, { message: message });
  } catch (err) {
    console.log(err.message);
    responseUtilities.sendJSON(res, err, { message: err.message });
  }
};

It executes with no errors, but nothing is updated.
I have tried some others alternatives with "FindOneAndUpdate" and "FindOneAndRemove" but, I could not find a solution.
Any ideas?

A: give this query a try:
db.collection.update(
    { 'members.email': 'email@address' },
    { $pull: { members: { email: 'email@address' } } },
    { multi: true }
)

A: You can use findOneAndUpdate with $pull  operator for this task.
For removing items from an array of documents you can check MongoDb docs
You need to use await or then block to query. I used await, and made the function asynchronous by adding async keyword. We also need empty query object.
I also added the new: true option, to return the updated object to check if the item is deleted.
You need to handle the case where no document matches, I added a TODO for you.
module.exports.removeMember = async function(req, res) {
  const email = req.params.email;
  const query = {};

  const pull = {
    $pull: {
      members: {
        email: email
      }
    }
  };

  const options = {
    new: true
  };

  try {
    var message = teamMsg.teamMemberRemoveSuccess;

    const result = await TeamModel.updateOne(query, pull, options);

    console.log(result);

    if (!result) {
      //TODO: return 400-Bad Request or 404 - Not Found
    } else {
      responseUtilities.sendJSON(res, false, { message: message });
    }
  } catch (err) {
    console.log(err.message);
    responseUtilities.sendJSON(res, err, { message: err.message });
  }
};

A: Try using the update() method and async/await:
module.exports.removeMember = async function (req, res) {

    const email = req.params.email;
    console.log(`email = ${email}`)   // Make sure correct value is coming thru

    const query = { "members.email": email };
    const pull = { $pull: { "members.$.email": email } };
    const options = { multi: true }

    try {

        var message = teamMsg.teamMemberRemoveSuccess;

        await TeamModel.update( query, pull, options );

        responseUtilities.sendJSON(res, false, { "message": message });

    } catch (err) {
        console.log(err.message);
        responseUtilities.sendJSON(res, err, { "message": err.message });
    }
};


text:
Q: Checking whether the usage of Fubini's theorem is possible Let's define
$$\Gamma(z) = \int \limits_{0}^{\infty} e^{-t} \, t^{z-1} \, dt, \qquad z \in \mathbb{C}, \quad \text{Re}(z) > 0.$$
It's just a standard Gamma function.
Now let's consider closed curve $C \in \mathbb{C}$ smooth in pieces.
I wonder if it is possible to use Fubini's theorem in the following integral
$$\oint \limits_{C} \int \limits_{1}^{\infty} e^{-t} \, t^{z-1} \, dt \, dz.$$
If yes, why?

A: Hint: to apply Fubini's Theorem it is enough to check integrability on the product space. Here $|t^{z-1}|=t^{\Re z -1}$. If $C$ is a closed path contained in $\{z: Re z >0\}$ the there exists $r>0$ such that $\Re z >r$ for all $z$ on $C$. Can now check integrability?
Suppose $C$ is given by $\gamma:[0,1] \to \mathbb C$. Then $\int_0^{1}\int_1^{\infty} |e^{-t}t^{z-1}||\gamma '(s)|dtds=\int_0^{1}\int_1^{\infty} |e^{-t}t^{x-1}||\gamma '(s)|dtds$ where $x=\Re z$. Hence $\int_0^{1}\int_1^{\infty} |e^{-t}t^{z-1}||\gamma '(s)|dtds\leq \int_0^{1}\int_1^{\infty} |e^{-t}t^{r-1}||\gamma '(s)|dtds$ where $r$ is as described above. Since $\gamma$ is assumed to be piecewise smooth it follows that $|\gamma'(s)|$ is bounded. If $M$ is a bound for this then we get $\int_0^{1}\int_1^{\infty} |e^{-t}t^{z-1}||\gamma '(s)|dtds \leq M\Gamma (r) <\infty$.


text:
Q: How to investigate scope in directive? I have this plunker to show my problem: http://plnkr.co/edit/bNha1xOrnhnyhvXtXSnX?p=preview
angular.module('docsTransclusionExample', [])
.controller('Controller', ['$scope', function($scope) {
  $scope.arr = [1,2,3,4];
}])

.directive('myDialog', function() {
  return {
    restrict: 'E',
    scope: {
        arr: '='
    },
    templateUrl: 'my-dialog.html',
    link: function (scope) {
      var lengthOfArray = scope.arr.length;
      scope.test = 'The array length is ' + lengthOfArray;
    }
  };
});

In the plunker, everything works as i would like: I set the scope.arr array, and investigate it in the link. This gives me the possibility to add more things to the scope (test), and print this out. Using a template like this:
{{arr}} - {{test}}

.. i get this result:
[1,2,3,4] - The array length is 4

SO: In this example, the array is set on the controller directly above. But in my real implementation of this, the array is a json object, fetched from a server. The result is that i keep getting 'undefined' as the result. I think it might be because of the (little) delay from when the directive asks for the data, until it actually gets delivered, meanwhile the link in the directive have nothing to work with.
Any good ideas i can try out?
Update:
I've made this Plunker to show the problem:
http://plnkr.co/edit/bNha1xOrnhnyhvXtXSnX?p=preview
Run it, and then in the result window, it should say something like this:
The array length is 5
(content of array...)

Now then, if you go into script.js (or any other file), and add a linebreak at the bottom or something, Plunker will reload the page. And then, sometimes, the script will fail to read the array, and the output will only be:
(content of array...)

I've tried to add watch, but not sure if i'm doing it correctly.. as it doesn't seem to work.
Another funny thing is that more often than not, this works as it should on Plunker. But on localhost, this never works.
Update 2
I've managed to solve this using the $watch. Plunker updated to correct solution: http://plnkr.co/edit/bNha1xOrnhnyhvXtXSnX?p=preview
.directive('myDialog', function() {
  return {
    restrict: 'E',
    scope: {
       contentOfList: '='
    },
    templateUrl: 'my-dialog.html',
    link: function (scope) {
      scope.counter = 0;
      scope.$watch('contentOfList', function() {
         scope.counter = scope.counter + 1;
         var lengthOfArray = scope.contentOfList.categoryList[0].rows.length;
         scope.test = 'The array length is ' + lengthOfArray;
        });
    }
  };
});

A: If you do not define it first, you will likely hit an undefined error, since arr is only created after making the call. Did you try creating an empty array, and then populate it?
Something like:
angular.module('docsTransclusionExample', [])
.controller('Controller', ['$scope', '$http', function($scope, $http) {
  $scope.arr = [];
  $http.get("somedata.json").success(function(result) {
      $scope.arr = result;
  });
    }]);

http://plnkr.co/edit/1yt3OSdrrbdTpa6FnWT8?p=preview
Hope it helps

A: There are two ways to solve this issues
 1) You should fetch the data before controller init like during resolve function in routeprovider if you are using routing
2) You should use watch to watch for changes and set the property inside that
  scope.$watch('arr',function(newvalue,oldvalue){
            if(newvalue===oldvalue){return};
            scope.test=newvalue.length
          },true);


text:
Q: Alamofire build fails with 138 errors I just imported Alamofire into a Swift project (via cocoapods) and my build fails because of Alamofire. XCode says there are 138 errors in Alamofire.
Here is a pick of just one error (given in the Alamofire.swift file).
value of optional type String not unwrapped :
extension NSURL: URLStringConvertible {

    public var URLString: String {

        return absoluteString // error shows here

    }

}

Most errors are "swift compiler errors"
I have tried the following :

*

*closing and reopening XCode

*pod remove repo master / pod setup / pod install

*rm -rf MyProject.xcworkspace / pod install

but no success so far.
I am running the latest cocoapods pre-release (0.39.0.beta.4) and XCode 6.4
Any suggestions ?

A: Well, you are using Xcode 6.4, which uses Swift 1.2
Since the master branch of Alamofire now uses Swift 2.0 you'll need to update to Xcode 7
Alternatively you can supply the version '1.3.1' in your podfile, as this was the last version using Swift 1.2.

A: In Pod file insert Below code....It works for me.
xcode version should be 7.3+
swift should be 2.2  (In preferences-> location-> select command line tool-> xcode 7.3).
source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.3'
use_frameworks!

target 'Your Target Name' do
pod 'Alamofire', '~> 3.0'
end

I hope it will work for you.

A: I was using Swift2.0 but i used Alamofire 1.2.2 which caused compiler problems. After i switched to Alamofire 2.0 in the Pod Files, everything worked fine.
pod 'Alamofire', '~> 2.0'