text:
Q: time needed to access struct vs. "loose" variable I have a question regarding the timing when accessing / reassigning variables either from a matlab struct or a matlab variable (any array):
Imagine the scenario that you have one function that creates ten variables (arrays of different dimensions and sizes). This function is getting called within another function that will need these variables produced.
Now, because getting ten variables from a function looks messy, I thought about storing these ten variables in a struct instead, and change my initial function so that it outputs only one struct (with ten fields) instead of ten variables.
Because timing is crucial for me (it's code for an EEG experiment), I wanted to make sure, that the struct approach is not slower, so I wrote the following test function.
function test_timingStructs

%% define struct
strct.a=1; strct.b=2; strct.c=3;

%% define "loose" variables
a = 1; b = 2; c = 3;

%% How many runs?
runs = 1000;

%% time access to struct
x = []; % empty variable
tic
for i=1:runs
    x = strct.a; x = strct.b; x = strct.c;
end
t_struct = toc;

%% time access to "loose variables"
x = []; % empty variable
tic
for i=1:runs
    x = a; x = b; x = c;
end
t_loose = toc;

%% Plot results
close all; figure;
bar(cat(2,t_struct,t_loose));
set(gca,'xticklabel', {'struct', 'loose variable'})
xlabel('variable type accessed', 'fontsize', 12)
ylabel(sprintf('time (ms) needed for %d accesses to 3 different variables', runs), 'fontsize', 12)
title('Access timing: struct vs "loose" variables', 'fontsize', 15)

end

According to the results, accessing a structure to get the values of a field is considerably slower than just accessing a variable. Can I make this assumption based on the test that I have done?
Is there another way to neatly "package" the ten variables without losing time when I want to access them?

A: In theory, yes, the access to data within a struct is going to be slower than access to data stored in a variable. This is just the overhead that the higher level datatype incurs.
BUT
In your tests, you are only measuring the access time of the data within the two data structures. When you are using variables, simply assigning one variable to another takes very little time because MATLAB uses copy-on-write and does not actually make a copy of the data in memory until it is modified.
As a result, the test that  you have written isn't very useful for determining the actual cost of using a struct because I'm sure your function does something with the data that it receives. As soon as you modify the data, MATLAB will make a copy of the data and peform the requested operation. So to determine what the performance penalty of a struct is, you should time your actual function rather than the no-op function that you're using.
A slightly more realistic test
I have written a test below which compares the struct and variable access where the called function does and does not modify the data.
function timeaccess

    sz = round(linspace(1, 200, 100));

    [times1, times2, times3, times4] = deal(zeros(size(sz)));

    for k = 1:numel(sz)

        n = sz(k);

        S = struct('a', rand(n), 'b', rand(n), 'c', rand(n));
        times1(k) = timeit(@()access_struct(S));
        S = struct('a', rand(n), 'b', rand(n), 'c', rand(n));
        times2(k) = timeit(@()access_struct2(S));
        a = rand(n); b = rand(n); c = rand(n);
        times3(k) = timeit(@()access_vars(a, b, c));
        a = rand(n); b = rand(n); c = rand(n);
        times4(k) = timeit(@()access_vars2(a, b, c));
    end

    figure

    hax1 = subplot(1,2,1);
    ylabel('Execution Time (ms)')
    xlabel('Size of Variables');

    hold on

    plot(sz, times2 * 1000, 'DisplayName', 'Struct w/o modification')
    plot(sz, times4 * 1000, 'DisplayName', 'Variables w/o modification')

    legend(findall(hax1, 'type', 'line'))

    hax2 = subplot(1,2,2);
    ylabel('Execution Time (ms)')
    xlabel('Size of Variables');
    hold on

    plot(sz, times1 * 1000, 'DisplayName', 'Struct w modification')
    plot(sz, times3 * 1000, 'DisplayName', 'Variables w modification')

    legend(findall(hax2, 'type', 'line'))

    saveas(gcf, 'data_manipulation.png')
    legend()
end

function [a, b, c] = access_struct(S)
    a = S.a + 1;
    b = S.b + 2;
    c = S.c + 3;
end

function [a, b, c] = access_struct2(S)
    a = S.a;
    b = S.b;
    c = S.c;
end

function [d, e, f] = access_vars(a, b, c)
    d = a + 1;
    e = b + 1;
    f = c + 1;
end

function [d, e, f] = access_vars2(a, b, c)
    d = a;
    e = b;
    f = c;
end

The results
As you can see, the struct is slower for just assigning a variable to another variable, but as soon as I perform an operation (here I have the very simple operation of adding a constant to each variable), the effect of the access time is negligible.

Summary
Based on the test above, I would assume that the time difference between the two is going to be negligible for your use case. Even if the struct is a little slower, it may be a cleaner design and result in more readable / maintainable code and may be worth the difference in performance.
If you're very concerned about performance, it may be worth looking into a C/C++ mex function to do some of the heavy lifting for you or switch to a more performant language than MATLAB.


text:
Q: JavaMail download attachment from mail How can I download attachment from a mail with Content-Type: multipart/alternative;
Multipart multiPart = (Multipart) message.getContent();

int numberOfParts = multiPart.getCount();
for(int j = 0; j < numberOfParts; j++)
{
    MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(j);

    if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition()))
    {
        part.saveFile( "C:\\Users\\Demo\\Desktop\\" + part.getFileName());

    }
 }

A: There's a wide variety of possible MIME structures for email.  A general solution can be quite complex since it would need to take into account signed and encrypted messages, among other issues.  Different mailers will use different MIME structure, and of course some mailers will have bugs in how they use MIME.  You need to decide which cases you need to support.
In general, multipart/alternative is used to contain different versions of the main message body, and so can be skipped because it doesn't contain any attachments.  Typically, a message with attachments will have a top level multipart/mixed content with the first body part containing the main message body.  The first part may be a simple text part, a multipart/alternative with text/plain and text/html parts, or a multipart/related with a text/html part and associated images.
Attachments will usually, but not always, have a Content-Disposition of attachment.  Attachments will usually, but not always, have a file name.
So, a good approach to start with is to only consider messages with a top level multipart/mixed content and then consider the parts after the first part to be attachments whether they say so or not.  And as I said above, signed and encrypted messages will make this more complex.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Validating word count tinymce I'm working on validating my tinymce editor. At the moment I have it validating by character count which works, but I would like to turn it into sort of like a word count since this is supposed to be the body of an article. So basically they cannot submit an article that is just a few words.
At the moment I have this
setup : function(ed) {
     ed.onInit.add(function(ed, evt) {
     tinymce.dom.Event.add(ed.getBody(), 'focusout', function(e, t) {
             var con = tinyMCE.activeEditor.getContent();
             var len = con.replace(/(<([^>]+)>)/ig,"").length;
             if(len <=100){
                $('.storyError').text('An artical has to have at least 100 words!');
             }else{
                    $('.storyError').text(' ');
             }
          });
      });
  }

after my init that is and this does work, I would just like to count the words instead of the characters. Some help would be much appreciated!

A: here you go, just replace the selector and take the text however you need :
    var count = 0;
    function fn(){
        count++;
        return ' ';
    }
    var x= $('textarea').text().trim();
    console.log(x);
    x= x.replace(/[\s]+/ig,fn);
    //x is now filtered out of extra spaces too !
    var words = count+1;
    count = 0;
    console.log(words);

JSFiddle
in your case it will be :
    var count = 0;
    function fn(){
        count++;
        return ' ';
    }

    setup : function(ed) {
             ed.onInit.add(function(ed, evt) {
             tinymce.dom.Event.add(ed.getBody(), 'focusout', function(e, t) {
             var con = tinyMCE.activeEditor.getContent().trim();
             con = con.replace(/[\s]+/ig,fn);
             //var len = con.replace(/(<([^>]+)>)/ig,"").length;
             var words = count+1;
             count = 0;
             if(words <=100){
                $('.storyError').text('An artical has to have at least 100 words!');
             }else{
                $('.storyError').text(' ');
             }

          });
      });
    }

or to make everything in one line use this (but it won't filter extra spaces out):
var words = con.trim().split(/\s+/).length;

A: It's pretty easy:

*

*Create some dummy element in DOM.

*Let this element hold your data.

*Use Node.textContent or Node.innerText to extract textual content from your data (without tags etc.)

*Split text and count words.

Working example:
var data = '
First paragraph with strong
',
    dummy = document.createElement( 'div' );

dummy.innerHTML = data;

console.log( ( dummy.textContent || dummy.innerText ).split( /\s+/ ).length );
>>> 4 // no "strong", "p" etc, just text

More about Node.textContent on MDN.

A: for tinymce 4.1.4
    $('#ContentPlaceHolder1_txtTitle').tinymce({
            theme: "modern",
            plugins: "wordcount code charmap paste",
            toolbar1: "bold italic underline strikethrough | removeformat | subscript superscript | charmap | cut copy paste | undo redo | code visualblocks visualchars",
            paste_auto_cleanup_on_paste: true,
            paste_remove_styles: true,
            paste_remove_styles_if_webkit: true,
            paste_strip_class_attributes: true,
            menubar: false,
            toolbar_items_size: 'large',
            forced_root_block: "",
            max_word: 5,
            setup: function (ed) {
                ed.on('keyup', function (e) {
                    var writtenWords = $('.mce-wordcount').html();
                    writtenWords = writtenWords.replace("Words: ", "");
                    var maxWord = ed.settings.max_word;
                    var limited = "";
                    var content = ed.getContent();

                    if (writtenWords >= maxWord) {
                        $('.mce-wordcount').css("color", "red");
                        limited = $.trim(content).split(" ", maxWord);
                        limited = limited.join(" ");

                        ed.setContent(limited);
                    } else {
                        $('.mce-wordcount').css("color", "green");
                    }
                });
            }
        });

A: Your solution lies here
https://github.com/AdamScheller/charwordcount
Ok Here is the complete solution.

*

*Download the Zip File From the above Link. It is given in the right side bottom

*Extract the zip folder in the plugins directory which is inside tinymce. So now you shoyld have a directory in your plugins directory named (charwordcount-master)

*Then
just call the plugin in your code where you are initializing the editor. I am writing the whole head section here

    <meta charset="utf-8">
    <title>charwordcount TinyMCE plugin example</title>

this is it now you have both the character and word count capability and it will show in the status bar of the editor. It will be applicable for every textarea.
I hope this makes it clear enough otherwise there is also an example in the zip folder it will be in the newly installed folder
\plugins\charwordcount-master\charwordcount-master\example
if you have any problem just let me know. This solution will work 100% as I had spend lot of time looking for the solution.
Saurabh Gupta

A: if you are also faced this problem means required validation is not working when you are using tinymce html editor, so i have one solution, please follow it and i hope your problem  solve, Check below code
install package of tinymce jquery in your application with the use of nuget package
create one model like this
Model
    [Required(ErrorMessage = "Please enter About Company")]
    [Display(Name = "About Company : ")]
    [UIHint("tinymce_jquery_full"), AllowHtml]
    public string txtAboutCompany { get; set; }

CSHTML OR VIEW

       @Html.LabelFor(model => model.txtAboutCompany, new { @class = "required" })
       @Html.EditorFor(model => model.txtAboutCompany)
       /span>

And this is jquery
$("#BusinessProfile").click(function () {
        var aboutC = $("#txtAboutCompany").val()
        var pinfo = $("#txtProductinfo").val();
        if (aboutC == "" && pinfo == "") {
            $("#AC").append("").val("").html("Please enter about company")
            $("#PI").append("").val("").html("Please enter product information")
            $("#bpform").valid();
            return false;
        } else if (aboutC == "") {
            $("#PI").append("").val("").html("")
            $("#AC").append("").val("").html("Please enter about company")
            $("#txtAboutCompany").focus();
            $("#bpform").valid();
            return false;
        } else if (pinfo == "") {
            $("#AC").append("").val("").html("")
            $("#PI").append("").val("").html("Please enter product information")
            $("#txtProductinfo").focus();
            $("#bpform").valid();
            return false;
        }
        else {
            $("#AC").append("").val("").html("");
            $("#PI").append("").val("").html("");
            //return true;
            $("#bpform").validate();
        }
    });


text:
Q: Move a control from a method in Windows Form High level question, is it possible to move a control from a method? Example, I have a label and a button click event, can the label move from one position (X,Y) to another from the button click to something like (X+20,Y+20)?
I haven't had any luck with changing the .Position property of the label, and I couldn't find anything online so I thought I would ask. Thanks!
EDIT: Was asked to show some code so here ya go. The label1.Position can't be selected/edited, and label1.Move is an event handler, for when the user moves the label?
private void MoveTextButton_Click(object sender, EventArgs e)
    {
        label1.Position = (x,y);
        //label1.Move
    }

A: Just change Location like :
   private void MoveTextButton_Click(object sender, EventArgs e)
   {
       label1.Location = new Point(label1.Location.X + 20, label1.Location.Y + 20);
   }


text:
Q: How does BBEdit define "Predefined symbols" when syntax coloring? The text editor BBEdit offers syntax coloring options for various categories of source code, including plain text, comments, strings, language keywords, etc. One of the categories is "Predefined symbols," which is defined in the BBEdit documentation as

Predefined symbols are terms which are not language keywords, but which are predefined by a language's reference implementation, or which are part of a language's standard library/framework support, or which have other special meaning to developers writing code in that language.

When I edit Python files in BBEdit, I find which symbols get colored with this style to be unpredictable. For example, builtin constants NotImplemented or Ellipsis do not get colored as Predefined symbols, whereas words like index or count, which to my knowledge have no inherent special meaning in Python, do.
How is BBEdit deciding which symbols to highlight in this style? Is this viewable somewhere? Better yet, editable?

A: The Python language model is defined in /Applications/BBEdit.app/Contents/PlugIns/Language Modules/Python.bblm/Contents/Info.plist. I compared the symbols in the BBLMKeywordList and BBLMPredefinedNamesList sections of the document to the list of Python reserved keywords and builtins.
Several Python keywords/builtins do not appear in the syntax coloring list, including async, await, __debug__, Ellipsis, NotImplemented, and some more obscure stuff. I think these are all Python3 features, and I know async and await were not added as reserved keywords until v3.7, so perhaps BBEdit's syntax coloring for Python has not been updated in a while to reflect new tokens.
But, of more interest to me, there are also about a hundred items that do appear in the syntax coloring lists but are not Python keywords or builtins:

*

*Comparison and membership methods: __cmp__, __contains__, __eq__, __ge__, __gt__, __le__, __lt__, __ne__

*Iterator methods: __iter__, __next__

*Sequence methods: count, index (but not mutable sequence methods e.g. extend, reverse, insert…)

*String methods: capitalize, casefold, center, count, encode, endswith, expandtabs, find, format, format_map, index, isalnum, isalpha, isascii, isdecimal, isdigit, isidentifier, islower, isnumeric, isprintable, isspace, istitle, isupper, join, ljust, lower, lstrip, maketrans, partition, replace, rfind, rindex, rjust, rpartition, rsplit, rstrip, split, splitlines, startswith, strip, swapcase, title, translate, upper, zfill (but not bytes, bytesarray, or memoryview methods)

*Set methods: add, clear, copy, difference, difference_update, discard, intersection, intersection_update, isdisjoint, issubset, issuperset, pop, remove, symmetric_difference, symmetric_difference_update, union

*Dict methods: copy, fromkeys, get, items, keys, popitem, setdefault, update, values

*Context manager methods: __enter__, __exit__

*Numeric modules and types: Complex, decimal, Decimal, Fraction, fractions, Integral, Number, numbers, Rational, Real (but not cmath, random, or statistics)

*Module and class attributes: __bases__, __class__, __dict__, __mro__, __qualname__, __subclasses__

*Commonly used convention: self (but not cls)

An overwhelming majority of these tokens are methods and attributes defined on the Built-in Types page of the python docs — but as noted above, many other such methods are not included (like those for MutableSequences or binary sequences such as bytes). I don't know the logic by which the particular tokens included were chosen.
There is a README file located at /Users/[username]/Library/Application Support/BBEdit/Read Me.txt that describes how to add custom language models to BBEdit, which includes a note

**Note**: Do not open the BBEdit application package to extract or modify the language modules in there. That way lies madness.

But despite this probably sensible warning, I would nonetheless like to remove all these extra tokens that are not keywords or builtins of the language from getting syntax-colored, so I guess I'm about to find out just how much madness lies that way…


text:
Q: Asp.net database content cache I am having an ASP.NET website, where most of the content for home page contents coming from database which can be managed by the Admin using the CKEditor.
My problem is, every time user refresh or open the home page it loads from the database. Is there any good method to cache these contents for certain time or till Admin change the contents.
What is the best approach for this.

A: You can cache the the data instead of hitting the database or you can use ASP.NET caching and cache by page, control...etc, there are a lot of options, take a look at the articles below:
.NET Data Caching
Caching with ASP.NET


text:
Q: Can I turn off the message at the bottom from mails generated by Ubuntu One-Thunderbird integration? After installing Ubuntu One, I tested it in Thunderbird by sending myself a file. I then got a marketing message at the address I sent it to promoting Ubuntu One. Is that the price to be paid for the free version, or can this be turned off?

A: Well, I have asked to the Thunderbird team. This cannot be turned off easily, but if you have idea to make it looks better, the relevant code is available here: http://mxr.mozilla.org/comm-release/source/mail/components/compose/content/cloudAttachmentLinkManager.js#330 and developers will be open to comments or tweaks about this code.


text:
Q: Evaluating and rearranging an equation I am trying to evaluate the right hand side of the following equation and then rearrange the whole thing in terms of x.
Q=xT+3x*Integral(1-e^(b*t)dt

The integral has a lower limit of 0 and an upper limit of T. Here is what I keep getting when I evaluate the r.h.s
3 (1 - E^-[b]t) T x + xT

Is my evaluation of the r.h.s accurate? Also, How do I rearrange everything interms x? From what I have read so far, it looks like I have to use Solve and Reduce. I would appreciate any help I can get.

A: After correcting several syntax errors and useing Solve:
x /. Solve[y == x T + 3 x*Integrate[1 - E^(b*t), {t, 0, T}], x][[1]]

$$\frac{b y}{4 b T-3 e^{b T}+3}$$


text:
Q: Creating a vertical separator with a label over it I've seen this somewhere before and it worked really nicely.  But I can't remember where.
Anyway, here's my desired form.
Enter a message:
+--------------------------------------------+
|                                            |
|                                            |
+--------------------------------------------+
                      |
                      |  Enter recipients:
                      |  +------------------+
 [Send to everyone]  OR  |                  |
                      |  +------------------+
                      |
                      |  [Send to these users]

A: You mean like on StackOverflow?
Just inspecting the DOM will tell you what you need to know: The line is an absolutely-positioned element with a left-border, and the "or" has a background colour the same as the body to cover up the line around it.

A: See this jsfiddle for an example. The idea is you offer the user two options in the HTML...
Choose one of the following options:

...and then style the first
 so it will float:left and have a border-right. Add some :after content to create the "or".


text:
Q: TPS54231 input voltage sensitivity quite high? I've spent this evening blowing up TPS54231s. Even a couple of TPS54331s.

(note that C31 is currently DNP)
The input voltage is specified as 17-24 VDC, and this circuit's worked admirably well at 17 volts for a couple weeks now. This evening I've been testing it at 24 volts. With an adjustable bench supply (not a fantastic one - it's a surplus laptop power supply and a Chinese eBay adjustable buck converter), it works ok at 24 volts (to be fair, however, at startup the source supply is drooping a tiny bit, so it may not be a fantastic test of maximum voltage capability).
The trouble starts when I plug in a 24 volt surplus laptop power supply. The TPS54231s instantly die and short out the input. Now, I admit I haven't tried to characterize this input supply's startup characteristics by capturing it on my scope. I'm starting to run low on replacement chips and I'm done with that for now. But the steady-state voltage is correct under load and not - 24V. The TPS54231's absolute maximum input voltage is 30V. Could it be at all likely that the input supply is spiking beyond that - however briefly - and that's toasting these chips?
Assuming that's true, would replacing the S1M with a 24V TVS diode solve the problem?
I really don't want to reduce the input supply voltage spec.

A: The TPS54331 is rated at a max input voltage of 30 volts and you are connecting a nominally 24V DC supply and you say the TPS54331 is dying virtually straight away.
Who can say what inductance is in series with the 24V DC output inside the power supply - can you see the internal circuits? I mention inductance because an inductor is pretty common inside power supplies both to reduce noise and reduce EMI.
So you connect the power supply and current flows through the 10 uF capacitor (C1) to charge it up. That current is flowing through the output inductor (speculation maybe) in the power supply and when the capacitor is fully charged to 24V there is still energy in that inductor which will carry on charging the capacitor to maybe twice 24 V (worst case) just like this: -

The above shows what can happen when 3V is applied to an LC circuit that has low damping (zeta is low). The red curve would be the resultant voltage across C1 - it is nearly double the input voltage. Now imagine what would happen when 24V is applied.
I'm not scare mongering - this has happened to me so I know it's possible.
Solution - put a 27V zener across the power terminals of the regulator.

A: In addition to the answer from Andy:
I read the datasheet for the TPS54231 and it has this very interesting note:

The device is designed to operate from an input-voltage supply range between 3.5 V and 28 V. This input supply should be well regulated.

Now this is particularly unusual for a voltage regulator (that the input should be well regulated in the first place).
That leads me to believe that the input stage is very susceptible to fast transients (and notably, line transient response is not characterised although load transient response is).
I would populate the 47μF device and, as you surmise, find a transient suppressor in place of the input diode.
Note that some transient suppressors can have as much as 5V between guaranteed stand-off and guaranteed breakdown, so a careful look around might well be necessary.

A: I just want know about before you provide the input supply have verified the input supply polarity. When polarity is reversed due to the diode it get short circuit.


text:
Q: Why does unordered-containers have their own implementation of Array I'm reading on HAMT's, and looked at a reference implementation in unordered-containers, but noticed that they have their own implementation of arrays. Why is this? Is it for speed? Or is it for some custom API that they require?

A: After looking at the code I can see a few optimizations.  It does not have support for the "Ix" index translation that most Haskell Arrays have.  It has specialized primitives such as insert' that insert into the middle and dynamically resize the array, something STArray does not support, as well as delete' which does shrinks the array.
So the answer is both speed and custom API.


text:
Q: how to empty ul autocomplete JqueryMobile I have a website that uses an ul element to do autocomplete (using JQueryMobile).
First time that I load the page, I can enter some text to ul input (ul with data-role listview) and it's save in the db.
Then, I redirect into other site, but when I turn again to the same web, the data that I entered in ul input are still there! And it show me an error when I send it to db (error because I need to empty fields before I send).
How can I empty the ul fields when I recharge the web? I tried with
$("ul").html(" "); //not work
$("#id_div").remove(); //destroy the web and I can't enter again
$("#id_div").empty(); //same as above

Thanks and sorry for my bad english!
EDIT:
I have differents functions:
$( document ).on( "pageinit", "#confirm", function() {

    if(typeof localStorage.emails === 'undefined' || localStorage.emails === null){
        var mail = [];
        localStorage.emails = JSON.stringify(mail);
    }

    $( "#confirm_email1" ).on( "listviewbeforefilter", function ( e, data ) {
        var $ul = $( this ),
        $input = $( data.input ),
        value = $input.val(),
        html = "";
        $ul.html( "" );
        if ( value && value.length > 1 ) {

            var emails = JSON.parse(localStorage.emails)
            for(var i=0;i < emails.length;i++){
                html += "<li>" + emails[i] + "</li>";
            }
            $ul.html( html );
            $ul.listview( "refresh" );
            $ul.trigger( "updatelayout");
            $('li').click(function(){
                var mail = $(this).text();
                $input.val(mail);
                $ul.html( "" );
                $ul.listview( "refresh" );
                save_email1="";
                enviar_email1=mail;
            });

            save_email1 = $input.val();
            enviar_email1 = save_email1;
        }
    });

Using this function I create localStorage to add dinamically the li elements to autocomplete.
Then, I use this other one:
function enviarReserva(){

    if(save_email1!==""){
        var emails = JSON.parse(localStorage.emails);
        emails.push(save_email1);
        localStorage.emails=JSON.stringify(emails);
    }

    var horafi = parseInt(horaReserva)+1;

    var check_soci1;

    if((enviar_email1!='' ) && (document.getElementById("soci_nosoci1").checked!=true)){
        check_soci1="no";
    }else{
        check_soci1="yeh";
    }

    $.ajax ( {
        beforeSend: function() { $.mobile.showPageLoadingMsg(); }, //Show spinner
        complete: function() { $.mobile.hidePageLoadingMsg() }, //Hide spinner
        url: "someURL?email1="+enviar_email1+"&check1="+check_soci1,
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            alert(data);
            actualitzarReserves();
            $.mobile.changePage("#mon",{transition:'none'});
            pag = 0;
            $('.pagina').html(pag);
            chargeWallet();
        },
        error: function (data, textStatus, jqHXR) {
            window.location.href="index.html";
        }
    });
}

This function check if the ul is empty or not and if the check is selected. Then, the PHP return something if check_soci is no or something else if check_soci is yeh.
My problem is that the second time that I enter the same web, the ul is not empty by default and although I empty the input it sends to PHP that the check_soci is no. ERROR!!


text:
Q: How can I force subversion to commit an outdated file? I would like to "overwrite" my last commit with the previous version. I tried to checkout the version 631, do some changes, and commit it as version 633. But svn doesn't agree, because version 632 exists.
What is the easiest way to do it? It is a multi-file commit. I don't want to make it manually.

A: Instead of checking out 631, do a REVERT to 631. Then you can change and check in.

A: The question is a bit old, but the answer may be useful for future reference:
Well, actually, one is not supposed to commit outdated files to SVN. The server itself refuses those files for security reason.
One thing to do is to make an update from the last version, but keeping your "outdated" files during the merge process automatically:
svn up --accept mine-full
In other words, this will perform the update, but ignore any incoming merge.

A: If you can't do a REVERT to version 631, do the following:

*

*Save your changes someplace outside your work area.

*Update your work area to version 632 (HEAD).

*Reapply the changes to your work area.

*Commit.

A: I also want to have this feature. Why isn't there a command similar to svn commit --force-overwrite-new-version?
Copy SVN revision 631 to SVN revision 633, and then you can commit your changes to SVN revision 634.
svn copy remote_url@631 remote_url
svn commit

P.S. Neither does git have this feature. There is no such command as git merge foo --force-overwrite.
Sometimes the requirement changes, so some code that is committed becomes useless. It happens really often, so overwriting code is vitally useful. I wonder why neither svn nor git has this feature. What a stupid design!!!

A: Copy the file with the old changes elsewhere, do an svn update of the file to check in. When it is complete overwrite the newly updated recent file with your old file, and then do an svn commit.


text:
Q: An expandable and collapsible tree Please help me how to create an expandable and collapsible tree with JavaScript with JSON feed data shown in the following format.Need some help with this problem.
var dataSource = ({
            "Items": ({
                "Pen": ({}),
                "Pencil": ({
                    "Natraj": "Natraj Pencil",
                    "Afsara": "Afsara Pencil",
                    "Erason": "natraj Erason"
                }),

                "Book": ({
                    "Novel": "ShakeSpear Novel"
                }),
            })
        });

A: Here's a JSFiddle. I would recommend creating objects in javascript and then converting those objects/arrays to JSON if needed...
var dataSource = [];

dataSource.push({
    Items: [{
        Pen: [],
        Pencil: [
            {Natraj: "Natraj Pencil"},
            {Afsara: "Afsara Pencil"},
            {Efason: "natraj Erason"}
        ],
        Book: [
            {Novel: "Shakespear Novel"}
        ]
    }]
});

console.log(JSON.stringify(dataSource));


text:
Q: How to use GET method of Invoke-WebRequest to build a query string Is there a standard way to make use of Invoke-WebRequest or Invoke-RestMethod in PowerShell to get information from a web page using a query string?
For example, I know that the following when used with a well formed JSON end point will work:
$Parameters = @{
  Name = 'John'
  Children = 'Abe','Karen','Jo'
}
$Result = Invoke-WebRequest -Uri 'http://.....whatever' -Body ( $Parameters | ConvertTo-Json)  -ContentType application/json -Method Get

along with the equivalent Invoke-WebMethod.  An important aspect of this is the content type and ConvertTo-JSON which manages the transformation of the parameters specified in the -Body part in to a standard form, including the array aspect of the "Children" field.
What is an equivalent way to do this with a website which uses, say, a comma delimited convention for managing array arguments in the URL or an approach such as "Children[]=Abe&Children[]=Karen&Children=Jo"?
Is there a content type that I'm missing and is there an equivalent ConvertTo-?? that I can use?  My guess is that someone has had to do this before.
For context this is an often used
 way of encoding an array parameter in the URL and is commonly seen in PHP web sites.
passing arrays as url parameter
Edit
Removed references to PHP except for specific context and adjusted the title to refer to a query string. The problem is about encoding a query string not PHP per se.

A: It seems that the server running PHP is irrelevant here. I think you're asking how to send key/value pairs as query string parameters.
Simple Case
If that's the case, you're in luck. Both Invoke-RestMethod and Invoke-WebRequest will take a [hashtable] in the body and construct your query string for you:
$Parameters = @{
    Name = 'John'
    Children = 'Abe','Karen','Jo'
}
Invoke-WebRequest -Uri 'http://www.example.com/somepage.php' -Body $Parameters -Method Get # <-- optional, Get is the default

Passing Complex Objects
Now seeing that the issue is that you want a query string parameter to have multiple values, essentially an array, this rules out the data types you can pass to the body parameter.
So instead, let's build the URI piece by piece first by starting with a [UriBuilder] object and adding on a query string built using an [HttpValueCollection] object (which allows duplicate keys).
$Parameters = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
$Parameters['Name'] = 'John'
foreach($Child in @('Abe','Karen','Joe')) {
    $Parameters.Add('Children', $Child)
}

$Request = [System.UriBuilder]'http://www.example.com/somepage.php'

$Request.Query = $Parameters.ToString()

Invoke-WebRequest -Uri $Request.Uri -Method Get # <-- optional, Get is the default

A: The following appears to work reasonably well as a "first cut".  Thanks to @briantist for the key point which was to use the .NET HttpValueCollection.  It seems we have to "roll our own" way of building the query string.
The below code snip shows a simple way to transform the hash table containing parameters and values in to a well formed query string by simply traversing the hash table.  One limitation is that nesting is not permitted (a parameter value cannot be a complex type such as a hash table).
# Setup, parameters is now a PowerShell hash table
# we convert that on the fly to an appropriate URL
$Parameters = @{
    Name = 'John'
    Children = 'Abe','Karen','Jo'
}
$Uri = 'http://example.com/somepage.php'
$AddSquareBracketsToArrayParameters = $true

$HttpValueCollection = [System.Web.HttpUtility]::ParseQueryString([String]::Empty)
foreach ($Item in $Parameters.GetEnumerator()) {
    if ($Item.Value.Count -gt 1) {
        # It is an array, so treat that as a special case.
        foreach ($Value in $Item.Value) {
            # Add each item in the array, optionally mark the name of the parameter
            # to indicate it is an array parameter.
            $ParameterName = $Item.Key
            if ($AddSquareBracketsToArrayParameters) { $ParameterName += '[]' }
            $HttpValueCollection.Add($ParameterName, $Value)
        }
    } else {
        # Add the scalar value.
        $HttpValueCollection.Add($Item.Key,$Item.Value)
    }
}
# Build the request and load it with the query string.
$Request  = [System.UriBuilder]($Uri)
$Request.Query = $HttpValueCollection.ToString()

# Now fire off the request.
Invoke-WebRequest -Uri $Request.Uri


text:
Q: Mavericks OS X Server : Wiki : Copy & Paste Tables? How can I transfer a table in a wiki page to another page? (...without copy&paste for each cell separately)
I use OS X Server on Mavericks. In the wiki I would like to copy a table from one wiki to another wiki. I went into edit mode for the source and destination page. Then I marked the table, pressed Cmd+C and in the destination page pressed Cmd+V. The result is a table with another table "over it" and both are messed up. I tried source page not in edit mode, but it doesn't work.
What methods can be used to copy a table that's on a wiki page to another page?
EDIT:
It looks like copy & paste works well within one Safari instance, but fails, when I try to copy the content out of a VMWare Fusion VM. (Copy in the guest and paste in the host.)
An example for the result:

I will try to access the Server instance in the VM from outside the VM (didn't want that so far) and see whether copy&paste works, when I use a single instance of Safari to do that.
EDIT#2:
I tried it using a single Safari instance and it worked well. I can enter edit mode in the two wiki pages, select all content from the source page, press Cmd+C and in the destination page press Cmd+V and the content is added nicely and beautifully. So it seems the clipboard transfer out of the VM breaks it for Safari.
I will play with this during the next days - for now it works for me.


text:
Q: How do I get the value of multiple IDs in a Laravel API request I have Laravel acting as an API serving a request from an Emberjs app.
The app requests multiple ID's
vipExperiences?ids=6&ids=4

In my Laravel controller, $request->input('ids') returns just the last ID (i.e. 4) where I would expect an array or something with both.
How do I best get it to return multiple ID's?

A: *

*If you are able to modify the query strings, add brackets to the names
Simply change your query strings to look like vipExperiences?ids[]=6&ids[]=4 then when you call $request->input('ids') you'll get the array you are looking for.

*If you can't edit it you should be able to do something like this
$url = explode('?', $request->fullUrl());
$querystrings = explode('&', $url[1]);

foreach ($querystrings as $param) {
   list($name, $value) = explode('=', $param, 2);
   $params[urldecode($name)][] = urldecode($value);
}
// dd($params);


text:
Q: CakePHP 3 - use multiple database connections *without ORM* I have a CakePHP 3.4.6 web application. Due to the fact it's working with legacy (not written in Cake convention) database tables, we have opted to hand-code all of our SQL queries rather than trying to set up Table and Entity classes. I realise some people will disagree with this, but that's not the point of the question.
I have 3 databases: app_db, users_db, extra_db.
I've configured connections to each one in config/app.php such that:
'Datasources' => [
    'default' => [], // 'app_db' credentials
    'users_db' => [], // 'users_db' credentials
    'extra_db' => [], // 'extra_db' credentials
];

I have a custom Model file located at src/Model/MyModel.php. An example of it being used to do a query on one of the databases (app_db) works like this:
namespace App\Model;

use Cake\Datasource\ConnectionManager;

class MyModel
{
    protected $connection;

    public function __construct()
    {
        $this->connection = ConnectionManager::get('default');
    }

    public function getData()
    {
        $sql = ''; // some SQL query
        $stmt = $this->connection->prepare($sql);
        $stmt->execute();
        return $stmt->fetchAll('assoc');
    }
}

This works because it gets the connection for default which maps to app_db.
But, I now want to run a query which needs to get data from app_db and JOIN with data from users_db.
How do I configure this in the Model so that the SQL will communicate with the other databases?

A: Simple way would be, to have another method, which will change connection.
public function switchConnection($connection=''){
 $this->connection = ConnectionManager::get(connection);
}

end call it for change connection
MyModel->switchConnection('app_db');

next time you run getData, it will communicate with app_db instead of default.


text:
Q: How is it possible to use raw_input() in a Python Git hook? I am writing a pre-commit hook for Git that runs pyflakes and checks for tabs and trailing spaces in the modified files (code on Github). I would like to make it possible to override the hook by asking for user confirmation as follows:
answer = raw_input('Commit anyway? [N/y] ')
if answer.strip()[0].lower() == 'y':
    print >> sys.stderr, 'Committing anyway.'
    sys.exit(0)
else:
    print >> sys.stderr, 'Commit aborted.'
    sys.exit(1)

This code produces an error:
Commit anyway? [N/y] Traceback (most recent call last):
  File ".git/hooks/pre-commit", line 59, in ?
    main()
  File ".git/hooks/pre-commit", line 20, in main
    answer = raw_input('Commit anyway? [N/y] ')
EOFError: EOF when reading a line

Is it even possible to use raw_input() or a similar function in Git hooks and if yes, what am I doing wrong?

A: You could use:
sys.stdin = open('/dev/tty')
answer = raw_input('Commit anyway? [N/y] ')
if answer.strip().lower().startswith('y'):
    ...

git commit calls python .git/hooks/pre-commit:
% ps axu
...
unutbu   21801  0.0  0.1   6348  1520 pts/1    S+   17:44   0:00 git commit -am line 5a
unutbu   21802  0.1  0.2   5708  2944 pts/1    S+   17:44   0:00 python .git/hooks/pre-commit

Looking inside /proc/21802/fd (on this linux box) shows the state of the file descriptors for the process with PID 21802 (the pre-commit process):
  /proc/21802/fd:
  lrwx------ 1 unutbu unutbu 64 2011-09-15 17:45 0 -> /dev/null
  lrwx------ 1 unutbu unutbu 64 2011-09-15 17:45 1 -> /dev/pts/1
  lrwx------ 1 unutbu unutbu 64 2011-09-15 17:45 2 -> /dev/pts/1
  lr-x------ 1 unutbu unutbu 64 2011-09-15 17:45 3 -> /dev/tty
  lr-x------ 1 unutbu unutbu 64 2011-09-15 17:45 5 -> /dev/null

Thus, pre-commit was spawned with sys.stdin pointing at /dev/null.
sys.stdin = open('/dev/tty') redirects sys.stdin to an open filehandle from which raw_input can read.

A: In shell you can:
read ANSWER < /dev/tty


text:
Q: WPF Binding Paths Someone please help me understand how my View is reaching my ViewModel.
My "BookView" has a Listview control that retrieves its data from a binding to a property in the "BookViewModel" using no namespaces. But the ViewModel is in a whole separate folder in the project so I wondering how it is finding it.
<UserControl x:Class="ContactBook.Views.BookView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
             xmlns:local="clr-namespace:ContactBook.Views"
             mc:Ignorable="d"
             d:DesignHeight="450" d:DesignWidth="800" Background="White">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
            <ListView Grid.Column="0"
                ItemsSource="{Binding Path=ContactsVM.Contacts}"
                SelectedItem="{Binding Path=ContactsVM.SelectedContact}">
            </ListView>
        </Grid>
    </Grid>
</UserControl>

This is my view model with the ContactVM property in it.
public class BookViewModel : ObservableObject
    {
        public ContactsViewModel ContactsVM
        {
            get { return _contactsVM; }
            set { OnPropertyChanged(ref _contactsVM, value); }
        }

        public BookViewModel()
        {

        }
    }

These 2 files are in different folders in the project.
image


text:
Q: Post Check Box in PhP i got this annoying problem i can't figure out how to solve
After a quick research i found those links bellow, which i could partially make work
verifying if checkbox is checked in php
How to read if a checkbox is checked in PHP?
This is my html:

<form method="post">

<!-- CHECK BOX TIPO DE PRODUTO (INTEIRO/PEDAÇO) !-->
<input type="checkbox" name="stipo" id="stipo" value="1" onchange="document.getElementById('tipo').disabled = !this.checked;">Tipo
<select name="tipo" id="tipo" disabled="false">
 <option value="Inteiro">Inteiro</option>
 <option value="Pedaço">Pedaço</option>
</select><br>

<input type="submit" href="/consulta/consulta_produto.php" class="loader" value="Consultar">

</form>

and this is my php:

if ($_POST['stipo'] == 1){
echo "123";
} else {
echo "456";
}

Because at the Html code im using form like this:

<form method="post">
</form>

and making the post with a submit button like that:

<input type="submit" href="/consulta/consulta_produto.php" class="loader" value="Consultar">

It doesn't work due to the Href at the submit button.
However, if i do the Html code like this:

<form action="/consulta/consulta_produto.php" method="post">

<input type="submit" class="loader" value="Consultar">

</form>

It will work. But, the problem of the form above is that my script stop working. I Cant use the method above because i need Href into the submit button, because when i submit the form, im loading the next page inside a Div
Just in case it helps, this is my Javascript and why i need the Href

<script type="text/javascript">
$(function() {
    $('.loader').click(function(event) {
        event.preventDefault(); // stop the link loading the URL in href
        $('#content').load($(this).attr('href'));
    });
});
</script>

Anyone got some idea on how to make the POST method works with href instead of action on the form?


text:
Q: Jordan Canonical Form of matrix I am having trouble figuring out computing Jordan Canonical Form. Can someone explain how to get there with this example matrix?
$A=\begin{bmatrix}1&1&1\\0&2&0\\0&0&2\end{bmatrix}$
Also, what would the transformation matrix $D$ be, if $D^{-1}AD$ is in Jordan Form.

A: We have:
$$A = \begin{bmatrix}1&1&1\\0&2&0 \\ 0&0&2\end{bmatrix}$$
We find the eigenvalues of $|A - \lambda I| = 0$, hence:
$$\lambda_1 = 1, \lambda_{2,3} = 2$$
That is, we have a single root and a double root eigenvalue, algebraic multiplicity.
To find the eigenvectors, we set up and solve $[A - \lambda_i I]v_i = 0$.
For $\lambda_1 = 1$, we get the eigenvector:
$$v_1 = (1,0,0)$$
For $\lambda_{2,3} = 2$, we get the eigenvectors (normally, we do not get two linearly independent eigenvectors):
$$v_2 = (1,0,1), v_3 = (1,1,0)$$
We now can write $P$ using the eigenvectors as columns. We have,
$$P = [v_1 | v_2 | v_3 ] = \begin{bmatrix}1&1&1\\0&0&1 \\ 0&1&0\end{bmatrix}$$
We can write the Jordan Normal Form (notice that we do not have any Jordan blocks), $J$, using the corresponding eigenvalues:
$$J = P^{-1} A P$$
However, we can also write this straight off from the eigenvalues and knowing we do not need any Jordan blocks.
$$J = \begin{bmatrix}1&0&0\\0&2&0 \\ 0&0&2\end{bmatrix}$$
Lastly, we should verify:
$$A = P J P^{-1}$$
I purposely left things so you can fill in the details of the calculations.


text:
Q: htaccess file: Prevent redirecting addon domain pages I have a main ssl domain https://www.a.com and a normal addon domain http://www.b.com on the same server. I use this .htaccess rule for a.com to redirect an old page in that website to a new one:
Redirect permanent /my_page.php /my_page

It works just fine. When i access a.com/my_page.php it redirects to a.com/my_page. The problem is that the addon domain b.com has the same page name inside its folder, so when i access b.com/my_page.php it also redirects to b.com/my_page. I need to prevent this redirection for the addon domain.
Note: I have tried to use this redirection rule instead but it didn't work at all:
RewriteRule https://www.a.com/my_page.php https://www.a.com/my_page

And this one too didn't work:
RedirectMatch 301 ^a.com/my_page.php$ https://www.a.com/my_page

A: After some reading and studying i was able to fix this using the RewriteRule instead. Here's the new code:
RewriteCond %{HTTP_HOST} ^.*a.com$ [NC]
RewriteCond %{REQUEST_URI} ^/my_page\.php$ [NC]
RewriteRule ^(.*)$ https://www.a.com/my_page [L,R=301]


text:
Q: How to assign privileges to employees by using checkbox selections in asp.net C# I am creating a web application in asp.net c#.
The project is for assigning tasks to different employees in the system. The project requires that, there are three types of employees, and the privileges corresponding to them are basic, superviser and manager.
The "basic" privilege only has the option to view his/her profile. The "superviser" can create jobs, and when "manager" approves the job, it would become available, and the "superviser" can assign the job to an employee.
As said above, aach of the privileges have a set of avaiable "Actions". My requirement is the following:-
After an employee is created by the admin, the employee need to be given the privileges. The admin can select the privileges (say for example, for basic employee-->view profile, view the work assigned; for superviser--> view profile, create jobs, assign employee to jobs; for manager--> view profile, create job, approve job, assign work to employee; for admin--> all privileges). The admin should be able to "check" the checkboxes associated with each privilegs, and based on these selections, privileges should be assigned to each employee.
How do we do this.
NB:- I dont want to use the "Roles" feature in ASP.NET C#. This is because, only privileges created by the programmer can be used. I want the admin to create roles, by giving a role name, and selecting various privileges.
I have had a look at the features of default asp.net roles and privileges, but my requirement is on the other side of the court.
**The project has different users, and I don't want to categorize them as either "basic emp", "hr", "pm", etc. Instead I would prefer to have a seto of checkboxes, and select the required privileges by using the check boxes.
An employee who has been given the privileges by selection of checkboxes can access the corresponding pages.
For example:
I have a set of checkboxes having associated data as:-
-view profile
-edit profile
-create project
-edit project
-upload resume
If I select the checkboxes corresponding to them, the corresponding web pages will be accessible to them.
How is this possible?**

A: You have to create your own security system. In case of asp.net webform . Create a lookup table containing all the pages name that appears in the question have mention something like this
           Name           Id   Page
           Edit Profile   1    editProfile.aspx
           Update Resume  2    UpdateResume.aspx

Now maintain the relation ship of user and associated pages like this in use table
           User Id AllowedPageid
             1         1
             2         1
             2         2

Now create a security class which can take the URL of the page and have a method to return true and false
          bool IsAllowed(int UserId , string pageURL)
          {
                 // Get the page name and check the DB of User is allowed to access the page
          }

Make sure you call this method in every Page_Load method to check if it return false redirect to NoAuthorization page


text:
Q: How to autodisplay an url when a style.display get on "block"? I'm trying to create a function (maybe an onload()?) to autodisplay an url instead of having to click the link . I want it to happen when the display gets on style.display="block"
enter image description here


text:
Q: Datanucleus Programmatic API Class Enhancement I'm using Eclipse 3.7 (OSGI), and i can do the manual Enhancement (with the Datanucleus Eclipse Plugin & datanucleus-enhancer-2.1.0-release imported as plugin dependency)
I'm trying now to use the API Class Enhancement: http://www.datanucleus.org/products/accessplatform/jpa/enhancer.html#api
With ASM 3.1 in the classpath and this code:
DataNucleusEnhancer enhancer=new DataNucleusEnhancer("JDO","ASM");
enhancer.setVerbose(true);
enhancer.addClasses(...);
enhancer.enhance();

I get:
You have selected to use ClassEnhancer "ASM" yet the JAR for that enhancer does not seem to be in the CLASSPATH!
org.datanucleus.enhancer.NucleusEnhanceException: You have selected to use ClassEnhancer "ASM" yet the JAR for that enhancer does not seem to be in the CLASSPATH!
    at org.datanucleus.enhancer.DataNucleusEnhancer.init(DataNucleusEnhancer.java:224)
    at org.datanucleus.enhancer.DataNucleusEnhancer.addClasses(DataNucleusEnhancer.java:406)

With the code suggested in the tutorial:
JDOEnhancer enhancer = JDOHelper.getEnhancer();
enhancer.setVerbose(true);
enhancer.addClasses(...);
enhancer.enhance();

I get:
javax.jdo.JDOFatalUserException: There are 0 services entries for the JDOEnhancer; there were no valid JDOEnhancer implementations found in the CLASSPATH. The file META-INF/services/javax.jdo.JDOEnhancer should name the implementation class.

Is there a way to achieve API Class Enhancement?

A: See this link http://www.datanucleus.org/products/accessplatform_3_0/enhancer.html#runtime
Especially sentence: "Runtime Enhancement requires the following runtime dependencies: ASM, and DataNucleus Core libraries."
So you are probably missing ASM dependency.
Try add this dependency:
    <dependency>
      <groupId>org.ow2.asm</groupId>
      <artifactId>asm</artifactId>
      <version>4.2</version>
    </dependency>


text:
Q: Docker run arguments/commands with Elastic Beanstalk Dockerrun.aws.json With docker-compose you can write something like this to add arguments to the image when it runs:
# docker-compose.yml
splash:
    image: scrapinghub/splash:latest
    command: --max-timeout 3600 --slots 3

In Dockerrun.aws.json there is a command that you can specify, however it does not seem to work the same as docker-compose. You cant just add arguments like that.
So I've tried this, but it does not work:
# Dockerrun.aws.json
{
    "image": "scrapinghub/splash",
    "command": ["--max-timout 3600"]
}

So question is, how do I get the behavior from docker-compose to my Dockerrun.aws.json file?

A: I highly recommend container-transform, a CLI tool that will transform docker-compose files to dockerrun format.
Edit:
If you would have followed the link, you would see an example of how container transform handles the command property. You need to break it up,
"command": ["--max-timeout", "3600"]


text:
Q: How do you export/import "index-pattern" types in Kibana Kibana 4.3 has great features for importing/exporting dashboards, searches, and visualizations. However, the related index-patterns are not contained in the the generated export.json file. When importing an export.json file into another kibana index, Kibana reports errors Could not locate that index-pattern-field (id: <index-pattern name>).
How do you migrate kibana's index-patterns from one Elasticsearch instance to another?
Thanks,
Nathan

A: From the official documentation (emphasis added)

Exported dashboards do not include their associated index patterns. Re-create the index patterns manually before importing saved dashboards to a Kibana instance running on another Elasticsearch cluster.

Since index patterns are saved in the .kibana index as well like anything else, what you can do instead of having to recreate them manually, is to save them using an adhoc tool, such as (e.g.) elasticdump, like this:
elasticdump \
  --input=http://host1:9200/.kibana \
  --input-index=.kibana/index-pattern \
  --output=http://host2:9200/.kibana \
  --output-index=.kibana/index-pattern \
  --type=data

You could also use snapshot/restore on your .kibana index

A: For anyone trying to migrate an AWS elasticsearch instance from one cluster to a new one... (hope this helps...)
I had a similar problem to the OP (I was trying to migrate data from one AWS Elasticsearch instance to a new one, using the AWS instructions).
For some reason, restoration of the cluster would fail with the following cryptic error.
"cannot restore index [.kibana] because it's open"

After much googling and head scratching, I decided it would be easier to migrate the .kibana index separately to the rest of the indices
I tried @Val's awesome suggestion to use elasticdump , however, @Val's example didn't work for me.
I ended up basing my command on the example from the elasticdump readme,
  elasticdump \
  --input=https://search-some-prod-instance.ap-southeast-2.es.amazonaws.com/.kibana \
  --output=https://search-other-prod-instance.ap-southeast-2.es.amazonaws.com/.kibana \
  --type=data

After running this command, the indices from my old kibana were now available in the new kibana. (finally :p)
nb: I also used the kibana "management->saved objects export / import" to migrate my visualisations, searches, dashboards, etc...


text:
Q: iOS: circular dependency to call method in each other class I'm trying to implement circular dependency between my AppDelegate and my ViewController to call methods from my AppDelegate to my ViewController but it's not working.
See my code as follow:
AppDelegate.h:
@class ViewController;

@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong,nonatomic) ViewController *mainView;

@end;

AppDelegate.m:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    return YES;
}

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    [self.mainView doSomething];
    return YES;
}

ViewController.h:
#import <UIKit/UIKit.h>

@class AppDelegate;

@interface ViewController : UIViewController
@property (strong,nonatomic) AppDelegate *delegate;

-(void)doSomething;

@end;

ViewController.m:
- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
}

- (void)doSomething
{
    NSLog(@"doing something");
}

I don't have any errors or warnings but the method doSomething has never been call. Any of you knows why or what I'm doing wrong?
I'll really appreciate your help.

A: This has nothing to do with circular dependencies.
As you've been told, the method doSomething is never called because you are saying
[self.mainView doSomething];

...at a time when self.mainView has never been given a value. Merely declaring a property
@property (strong,nonatomic) ViewController *mainView;

...does not point the variable mainView at your actual ViewController instance; it is nil, and a message to nil generates no error and causes nothing at all to happen.
You could fix this by having the ViewController set a reference to itself by adding one line to your code:
- (void)viewDidLoad {
    [super viewDidLoad];
    self.delegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
    self.delegate.mainView = self; // <--
}

But don't! The simple truth is that your entire approach here is wrong. There should be no need whatever to keep a reference to your ViewController inside your app delegate. Your app has, at every moment, a view controller hierarchy. The app delegate should know where the ViewController is within that hierarchy.
Here we are in your app delegate when a link message comes in:
- (BOOL)application:(UIApplication *)app
        openURL:(NSURL *)url
        options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {

At that moment, it is the app delegate's job to know where the ViewController is in the view controller hierarchy, and even to arrange the view controller hierarchy so that the ViewController's scene is showing if it wasn't already, in response to the link message.
How you do that depends on the structure of your view controller hierarchy. You start at the top of the hierarchy, which, for the app delegate, is [[self window] rootViewController], and work your way down to the existing view controller you want to talk to.
You have not told us your view controller hierarchy structure, so it's impossible to help in detail. But let's say, for example, that your app revolves around a navigation controller interface. Then, for the app delegate, [[self window] rootViewController] is the navigation controller, and so you can cast to that class: (UINavigationController*)[[self window] rootViewController]. Then, if the ViewController is the navigation controller's root view controller, you take its viewControllers[0] to reach it, and again you cast as needed:
UINavigationController* nav = (UINavigationController*)[[self window] rootViewController];
ViewController* vc = (ViewController*)nav.viewControllers[0];

Now you can send the doSomething message to vc. But that's just an illustration; the precise details will depend on where the ViewController really is, within the view controller hierarchy. And of course you might also want to pop view controllers so that the ViewController's scene is actually showing, since you likely cannot guarantee that it is showing at the time the link message comes in.
Another completely different way of handling this situation is to use the NSNotificationCenter to post a notification for which the ViewController instance has registered. That is often a solution when you do not know exactly where in the view controller hierarchy your view controller is. But in this situation, you should know that.

A: Try the below code :
AppDelegate.m :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.

    [[ViewController sharedInstance] doSomething];
    return YES;
}

ViewController.h
+ (ViewController *)sharedInstance;
- (void)doSomething;

ViewController.m
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

+ (ViewController *)sharedInstance {
    UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
    return [storyboard instantiateViewControllerWithIdentifier:@"ViewController"];
}

- (void)doSomething {
    NSLog(@"ViewController is doing something");
}

Output :
ViewController is doing something

A:
I don't have any errors or warnings but the method doSomething has never been call. Any of you knows why or what I'm doing wrong?

It happens because you haven't initialised an instance of ViewController. So, you have a nil at mainView. When you try to send a message "doSomething" to mainView you send message to nil. At Objective-C when you send a message to nil nothing is happens.
You should initialise an instance before you try to invoke the method. For example, at didFinishLaunchingWithOptions with such code:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.mainView = [ViewController new];
    return YES;
}

It will works if you create views programatically. If you use a storyboards or xib you should use another methods.
Now you should see "doing something" at console when openURL is invoked.
BTW, you have a retain cycle between app delegate and view controller. So, your mainView will never release even if you make it explicitly nil. To avoid a retain cycle you should use attribute weak at ViewController.h:
@property (nonatomic, weak) AppDelegate *delegate;

A: You can do that by the below code but excuse me for doing it with Swift:
class AppDelegate: UIResponder, UIApplicationDelegate {

var window: UIWindow?
var mainVC: ViewController?

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    mainVC = ViewController()
    mainVC?.doSomething()
    setupMainViewController()
    return true
}

func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    mainVC?.doSomething()
    return true
}

func setupMainViewController(){
    guard window != nil else{
        window = UIWindow(frame: UIScreen.main.bounds)
        window?.rootViewController = mainVC
        window?.makeKeyAndVisible()
        return
    }
    window?.rootViewController = mainVC
}

and the MainViewController will be:
class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()
    doSomething()
}

func doSomething(){
    print("do something with \(self)")
}

A: I appreciate all the other answers, I come here with a different approach. Generally, I used in my projects.
NSNotificationCenter defaultCenter Please check the code below.
Viewcontroller.m
@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    //self.delegate = (AppDelegate*)[[UIApplication sharedApplication]delegate];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];

    // HERE REGISTER NOTIFICATION WHEN SCREEN IS APPEAR

    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(doSomething:)
                                                 name:@"TestNotification"
                                               object:nil];
}

// HERE ADDS NOTIFICAIOTN AS PARAMETERS

- (void)doSomething :(NSNotification *) notification
{
    NSLog(@"doing something");

    // IF YOU PASSED VALUE WITH THE NOTIFICAIONT THEN IT WILL SHOW HERE
    NSDictionary *userInfo = notification.userInfo;
    id myObject = [userInfo objectForKey:@"someKey"];
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:animated];

    // HERE REMOVE NOTIFICATION OBSERVER
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

AppDelegate.m :
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    return YES;
}

- (BOOL)application:(UIApplication *)app
            openURL:(NSURL *)url
            options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
    //WITHOUT SENDING ANY DATA
    [[NSNotificationCenter defaultCenter]
    postNotificationName:@"TestNotification"
    object:self];

    // IF YOU WANT TO SEND ANY INFROMATION THEN PLEASE USE THIS METHODS
    NSDictionary *userInfo =
   [NSDictionary dictionaryWithObject:myObject forKey:@"someKey"];
   [[NSNotificationCenter defaultCenter] postNotificationName:
                   @"TestNotification" object:nil userInfo:userInfo];
    return YES;
}

Here you do not need to check the visible view controller and no allocation required. if your screen is in the top then your methods are called otherwise not.
Good luck! :-)


text:
Q: How to Bind Port In java Class I am using Swing and now i want to Allocate one Special port for the Java class which is running in my swing. so how do i bind that port so every time when user run that so there wont be creating new object it will show message that process is already running!! I need to Bind that port to the Process how to do it?
Socket s = new Socket();
s.bind(new InetSocketAddress(9000));

i have bind this address but how to bind it in current class object.?

A: try to use static variable - this object will be created only once
private static Socket s = new Socket();

static {
    try {
        s.bind(new InetSocketAddress(9000));
    } catch (IOException e) {
        e.printStackTrace();
    }
}


text:
Q: How can I search in a big data collection on server side without publishing everything in meteor I'm a newbie to Meteor. I need to build up a text search system with typeahead-like feature using Meteor js. My collection on the server side has about 1 million words, so it's impossible to publish them all (my page will take forever to load so I'm assuming the collection is so large that the sync takes forever). However, each time, my system needs to search within the whole collection. Anyone has suggestions about how to do this? Thanks a lot

A: This is server logic. You have to calculate your stuff with a server method:
Meteor.methods({'myGreatTextSearch': (someParameters) => {
  // TEXT AGGREGATION here
  return stuff
})

You can get 'stuff' on the client with
Meteor.call('myGreatTextSearch', someParameters)


text:
Q: How to make a Muiv5 TreeView with Checkbox for an array of objects? I am using muiv5 treeview component to build a treeview dropdown. The component doesn't have checkbox support for selection/deselection but after bit of searching I was able to find a kind of similar solution but the data that needs to be passed to tree view is an object and it has a parent node. I don't need a parent node. Basically my structure is an array of objects and not an object.
Here is a link to codesandbox project Click here
The rich object is

const data: RenderTree = {
  id: 'root',
  name: 'Parent',
  children: [
    {
      id: '1',
      name: 'Child - 1',
    },
    {
      id: '3',
      name: 'Child - 3',
      children: [
        {
          id: '4',
          name: 'Child - 4',
        },
      ],
    },
  ],
};

but my data is

const data = [
    {
      id: '1',
      name: 'Child - 1',
    },
    {
      id: '3',
      name: 'Child - 3',
      children: [
        {
          id: '4',
          name: 'Child - 4',
        },
      ],
    },
],

I don't want a root parent node to display


text:
Q: Mockito how to unit test a static method which has many objects to be mocked inside I have to unit test a static method which looks like this:
public static boolean someProcess(List<String> arg1, Properties props, String[] arg3, String arg4, String arg5) throws Exception {
    boolean success = false;
    Job1 job1 = new Job1(arg3, props.getProperty("prop1"), props.getProperty("prop2"), arg1.get(0), arg4, "asdf", arg5);

    if(doJobAndCheckStatus(arg1, job1)) {
        String someId = job1.someId;
        Job2 job2 = new Job2(arg3, someId, arg4, arg5);

        if(doJobAndCheckStatus(arg1, job2)) {
            Job3 job3 = new Job3(arg3, someId, arg4, arg5);

            if(doJobAndCheckStatus(arg1, job3)) {
                String id2 = job3.id2;
                Job4 job4 = new Job4(arg3, id2, props.getProperty("prop3"), arg4, arg5);

                if(doJobAndCheckStatus(arg1, job4)) {
                    String id3 = job4.id3;
                    Job5 job5 = new job5(arg3, id3, arg4, arg5, props.getProperty("prop4"));

                    if(doJobAndCheckStatus(arg1, job5)) {
                        success = jobCompletedSuccessfully(arg1);
                    }
                }
            }
        }
    }
    return success;
}

public static boolean doJobAndCheckStatus(List<String> arg1, JobParent job) {
    job.processJob();
    ....
}

As shown above, in this static method, there are 5 JobX classes to initialize. All these Job classes are complex objects which will connect to external systems.
My idea of unit testing this method is:

*

*Mock all the JobX classes which are used in the someProcess method.

*Configure all the mocked classes to return the status of "success" when their processJob methods are called.

*This someProcess method should return true if every job is completed successfully

My questions are:

*

*Does my idea make sense at all? What's there to test for this
particular method at all?

*Best way to test this method? How to get all the mocked JobX classes into effect?

Any enlightenment will be highly appreciated!


text:
Q: How do I escape awk's built-in variables when used within heredoc Following is the command I am trying to execute :
while read api; do
echo $api
ssh username@ip <<ENDSSH
grep $api /myserver/logs/server.log | awk '{print $8}'| sort -n | awk 'BEGIN{i=0} {s[i]=$1; i++;} END{print "=== PERCENTILES ==="; print "50: " s[int(NR*0.50-0.5)]; print "70: " s[int(NR*0.70-0.5)]; print "80: " s[int(NR*0.80-0.5)]; print "90: " s[int(NR*0.90-0.5)]; print "95: " s[int(NR*0.95-0.5)]; print "99: " s[int(NR*0.99-0.5)]; print "100: " s[int(NR-1)]; print "Count:" NR; print "==================="}'
ENDSSH
done <apiList >output.out

I want to run this for multiple apis on a remote host and collect the output in an output file locally.
list of files is locally stored.
Initially I was using <<'ENDSSH' then $api wasn't getting evaluated.
now I changed that to <

How do I tell the remote host to evaluate NR?

A: In shell, backslash \ can be used to quote, e.g. ... print "Count:" \$NR; ....


text:
Q: Is there a way to multiply all the elements of an array using thrust? Let's say I have an array and I want to multiply all the elements of that array and store it in a variable. How do I do it? I want to multiply all the elements in A and store the result in S. Doing this gives me zero.
thrust::device_vector<double> A(10);
thrust::sequence(A.begin(), A.end(), 1);
double S = thrust::reduce(thrust::host, A.begin(), A.end(),
                             0, thrust::multiplies<double>());

A: There are two problems here:

*

*The use of the thrust::host execution policy makes no sense (in fact no execution policy makes sense if you are using thrust vectors as inputs). I would expect some sort of segfault or runtime error if you actually tried to run this code. Use tag based execution instead, i.e. just remove the first argument, and thrust will infer the execution policy from the types.

*The fourth argument in the thrust::reduce in call your code is the initial value of the product. You are setting it to 0. This means any product calculated by that code will be zero. Presumably you want the initial value to be one.

Fixing both of those glaring problems gets me this:
#include <thrust/device_vector.h>
#include <thrust/reduce.h>
#include <thrust/sequence.h>

#include <iostream>
#include <iomanip>

int main()
{
    thrust::device_vector<double> A(10);
    thrust::sequence(A.begin(), A.end(), 1.0);

    for(auto p = A.begin(); p != A.end(); ++p) {
        double v = *p;
        std::cout << v << std::endl;
    }

    double S = thrust::reduce(A.begin(), A.end(), 1.0, thrust::multiplies<double>());

    std::cout << "S = " << std::fixed << std::setprecision(1) << S << std::endl;

    return 0;
}

Compiling and running it gets me this:
$ nvcc -std=c++11 -o prodprob prodprob.cu

$ ./prodprob
1
2
3
4
5
6
7
8
9
10
S = 3628800.0

The correct answer should be 10! = 3628800, so I judge this as working correctly.


text:
Q: C++ vector(math) destination, check range based on movement I am moving an entity to a new position vector, however when it reaches it's destination, it's jumping around the destination.
I want to check on a range of the destination based on the movement speed, can anyone help with how I could go about this?
Here is the function:
void Enemy::onUpdate(Graphics& graphics)
{
        //function called every tick
    Vector dest(190.f, 250.0f);
    Vector destination = dest - posVec;

    Vector normalise = Vector::unitVector(destination);

    mPosVec = mPosVec + normalise * mVelocity;//mVelocity = 4.f

    mX = mPosVec.x;
    mY = mPosVec.y;

        //clamp range
        //if(something)
}

Thanks.


text:
Q: Rails - ActiveRecord get database name from an Instance I have a model distributed into many databases. Here is an example:
class Timetablerange < ActiveRecord::Base
  self.table_name = "TimetableRange"

  def self.integration(integration)
    self.establish_connection(integration.to_sym)
    return self
  end

end

So when I want to fetch an instance from one database:
Timetablerange.integration(:integration_id).find(1)

I need to get the database_name from an instance without using:
Timetable.connection.current_database

Since it can be different if I use this:
instance_a = Timetablerange.integration(:integration_1).find(1)
instance_b = Timetablerange.integration(:integration_2).find(1)

At this time Timetable.connection.current_database = :integration_2 but instance_a was loaded from :integration_1.
I've tried to use:
instance_a.connection_handler.connection_pools

And it lists all the connections. But how can I now witch database was instance_a loaded from?
Thanks so much for the help!

A: If you are using mysql you probably can use:
Timetable.connection.execute("select database()").first.first

The other databases might have a query to get the current db too.


text:
Q: c# where to place "using" for every page? If I have a
using MyProject.language;

literary needs to place on every single page.
My question is, is there a place that I can place the "using" just once, for every page of the project.
Thanks.

A: Using statements have to be in the file where you are actually using the namespace. There is no such thing as a one-place-for-all-usings in C#, unlike C++. The only 'exception' to this are ASP / ASP-MVC files, which automatically add all the using statements defined in the web.config namespaces node. C# / .cs files do not make use of this facility however and still need every namespace manually defined.

A: Since you mentioned page, you can configure ASP.NET to reference the namespace everywhere. This only affect the views themselves and not the code behind
<pages>
  <namespaces>
    <add namespace="System.Web.Mvc" />
    <add namespace="System.Web.Mvc.Ajax" />
    <add namespace="System.Web.Mvc.Html" />
    <add namespace="System.Web.Routing" />
    <add namespace="Microsoft.Web.Mvc" />
    <add namespace="xVal.Html" />
    <add namespace="Telerik.Web.Mvc.UI" />
  </namespaces>
</pages>

If you use the Razor view engine of ASP.NET MVC, you can add a reference for all views like this
<system.web.webPages.razor>
  <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
  <pages pageBaseType="System.Web.Mvc.WebViewPage">
    <namespaces>
      <add namespace="System.Web.Mvc" />
      <add namespace="System.Web.Mvc.Ajax" />
      <add namespace="System.Web.Mvc.Html" />
      <add namespace="System.Web.Routing" />
    </namespaces>
  </pages>
</system.web.webPages.razor>

If you are in a plain C# project or in the code behind of a page, you should know that any class that is located in a namespace will automatically reference all object in any parent namespace. Assuming a namespace Company.Software.Somethings.Data, any classes in the Data namespace will automatically reference the classes in

*

*Company.Software.Somethings

*Company.Software

*Company

A: You can not do that, as this works only for one file.


text:
Q: Mistakenly inserted date in month field sql how to change Unfortunately I inserted a date as dd-mm-yyyy in sql but it assumed it as mm-dd-yyyy Now more than 50 fields are like this how can I change this? I found an exception as invalid date when I was taking report by date that more than 12. Now I want to change all of the inserted fields without losting it

A: UPDATE tableName
SET dateColumn = MONTH(dateColumn) + "-" + DAY(vdateColumn) + "-" + YEAR(dateColumn)

I hope this work even though I didn't test it myself. Please use a WHERE clause to limit the update only to the impacted rows.

A: UPDATE yourTable
SET yourDateColumn = Convert(datetime,yourDateColumn,101)

Let me know if this fixes your issue.

A: Nothing worked but finally I reset it manually by c# console
Console.WriteLine("Changing Orderdate");
        Console.WriteLine("~~~~~~~~~~~~~~~~~~");
        List<string> date = new List<string>();
        List<string> no = new List<string>();

        int i = 0;

        SqlCommand cmd = new SqlCommand("select DATEPART(yyyy,orderdate) as y, DATEPART(mm,orderdate) as m, DATEPART(dd,orderdate) as d, bno from bill", con);

        con.Open();
        SqlDataReader dr = cmd.ExecuteReader();
        while (dr.Read())
        {
            date.Add(dr["y"].ToString() + "-" + dr["d"].ToString() + "-" + dr["m"].ToString());
            no.Add(dr["bno"].ToString());
        }
        con.Close();

        foreach (var a in date)
        {
            Console.WriteLine("Inserting: " + date[i] + " With " + no[i]);
            SqlCommand cmd2 = new SqlCommand("update bill set orderdate = '" + date[i] + "' where bno = " + no[i], con);
            con.Open();
            cmd2.ExecuteNonQuery();
            con.Close();
            i++;
        }
        Console.WriteLine("Order date changing completed \n\n");

Thank you for sharing your precious time thanks friends


text:
Q: Accessing Oracle Database from C# I have a C# program that uses System.Data.OracleClient to access an oracle database.
The code uses OracleCommand, OracleDataReader objects. And it uses the TNS names to refer to specific oracle servers (as defined in the tnsnames.ora file).
It runs fine on my computer. And then I copied the binary to another computer, and upon running it encounters the error:
TNS:could not resolve the connect identifier specified.
The other computer has the same version of oracle client installed, and the identical copy of tnsnames.ora dropped in the oracle network/admin folder. And the other computer also has SQLDeveloper installed, and I am able to connect to the oracle servers by using those TNS names from inside its SQLDeveloper.
Why then is the c# program complaining about not able to resolve TNS identifier?
The connection string I use (as hardcoded into my c# program) is ;
"Data Source=TNS Name; User ID=user; Password=pass;"
Thanks

A: Open a command window, type tnsping yourdbname and hit enter, you should get back a bunch of info, but what you want to look for is

Used parameter files:
C:\Oracle\product\10.1.0\Client_1\network\admin\sqlnet.ora

Or something similar, this is the "Default" Oracle client on the system, make sure that this is the same path that you have the tnsnames.ora in (in my case we use sqlnet.ora)
Sometimes multiple Oracle product installs make multiple potential ORA_HOMEs, you can at least confirm the "active" client, so that way you are certain the files are in the right spot.
Also, can you connect to the db using SQLPlus?

A: Is it failing to locate or load the tnsnames.ora file?  Try running ProcessMonitor (http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx) and then running your c# program.  You can see if it fails to locate the .ora file.

A: You can also force all things Oracle to look in a fixed location for network files by setting the environment variable TNS_ADMIN to the location of your tnsnames.ora and sqlnet.ora files (by default ORACLE_HOME/network/admin).
Then you don't have to worry about guessing which network/admin folder is being used by the particular Oracle process you're running at the moment.

A: Ultimately my issue was that I had multiple instances of Oracle installed on my machine, and needed to update a third tnsnames.ora file that I was not aware of.
For what it's worth, I got a false positive response when running tnsping [dbName]. It was useful information, but it needed further investigation. Only when I went to check Windows Environment Variables did I notice another Oracle path and found the third tnsnames.ora


text:
Q: Is there a fast way to save images files on python? I made a program to filter an images with only 20 colors, and i want to save the process that the program is making until it finished, i've successfully saved the images however it takes a lot of time.
Lets say the user gives me an image of 800x600, it will take about 15 seconds or less to my program to finish editing the image, but if i save after every step, it will take around 10 min.. and that is because after every save, the program is waiting for the file to be ready altho it doesn't need the image it can move on and let winodws handle it.
I've tried doing it with threading and i get the same result, about 1s per image..
from PIL import Image
from PIL import ImageGrab

im = Image.open('braw.png') # Can be many different formats.
rgb_im = im.convert('RGB')

pix = rgb_im.load()

height, width = im.size
image = ImageGrab.grab()
path = os.getcwd()

def read_color(height,width, COLORS):
    for x in range(height):
        for y in range(width):
            r,g,b = rgb_im.getpixel((x,y))
            color = closest_color(r, g, b, COLORS)
            back_work(color,x,y)
            save_frame(x, '/frames')

def save_frame(x, location):
    try:
        rgb_im.save(path + location+'/ark_ai' + str(x) + '.jpeg')
    except OSError:
        sleep(0.5)

def back_work(color, x, y):
    pix[x,y] = color

I've expected the program to keep saving images after every loop even tho its not done, is there a faster way of doing so that i am not aware of?

A: It looks like you're saving every time you update a pixel, which means you're saving 480,000 images, with a total of 691 GB written to the disk. Granted, not all of that will be saved to the hard drive at once, since you're overwriting 99% of the files. Nonetheless, that's a lot of file I/O, and there simply isn't much you can do to speed that up.
Why don't you try saving after each column is updated, rather than each pixel? That would reduce the amount of saving you do by a factor of 600. And the output should be the same, since you're only skipping saving the frames that would have been overwritten anyway.
def read_color(height,width, COLORS):
    for x in range(height):
        for y in range(width):
            r,g,b = rgb_im.getpixel((x,y))
            color = closest_color(r, g, b, COLORS)
            back_work(color,x,y)
        save_frame(x, '/frames')


text:
Q: Does there exist a base of $M(n, \mathbb{R})$ of elements of $SO(n)$? I was wondering whether or not there exist a base of $M(n, \mathbb{R})$ as a vector space over $\mathbb{R}$ made solely by matrices in $SO(n)$, or equivalently if $Span(SO(n))=M(n)$ for each natural $n$. Even partial answers, such as one answering to the same question with $O(n)$ replacing $SO(n)$, would be greatly appreciated.

A: Any matrix $A$ in the span of $SO(2)$ has $A_{21} = -A_{12}$.

A: Note that if $p$ is an orthogonal projection then $I - 2 p$ is an isometry. Since $I$is also an isometry, you can write any orthogonal projection as a linear combination of isometries, and so any $T \cdot \pi$, where $T$ is an isometry and $T$ is a projection. It should be clear now how to get all the $E_{ij}$'s.


text:
Q: How to get data from a jTextField or jFormattedTextField in another java class I'm trying to use to different classes on netbeans, one is my GUI (also, i'm starting at programming and just learned what is one GUI), and in this one, I have some jTextField's and JFormattedTextField's, the other one, I want to use as back-end, for starters, I want to delete a information that I already have on my DB.
The error I get is this:

error: cannot find symbol
if(jFormattedTextFieldCPF.getText().equals("")){
symbol:   variable jFormattedTextFieldCPF
location: class Modos

Here's the first part of my code:
private void jButtonExcluirActionPerformed(java.awt.event.ActionEvent evt) {

    MODO = 1;// it sends which action the button have to do
    funcao.funcoes(MODO);

    // TODO add your handling code here:

}

In the class Modos I only have a function called funcoes, where there will be more actions to do on my DB, like, edit, add, search...
public void funcoes(int MODO) {

    if (MODO == 1){

                PreparedStatement stm;
    try {
        /*jFormattedTextFieldCPF.setEnabled(true);
        jTextFieldNOME.setEnabled(false);
        jTextFieldIDADE.setEnabled(false);
        jFormattedTextFieldDATA.setEnabled(false);
        jTextFieldAPELIDO.setEnabled(false);
                    */
        stm = conecta.conn.prepareStatement("delete from cad_pessoa where cad_cpf=?");

        if(jFormattedTextFieldCPF.getText().equals("")){

            JOptionPane.showMessageDialog(null, "Por favor completar o campo CPF");
            conecta.conn.rollback();
        }

        else {

        stm.setString(1, jFormattedTextFieldCPF.getText()); //pega o nome que será deletado
        stm.execute(); //executa o SQL
        conecta.conn.commit();

        JOptionPane.showMessageDialog(rootPane, "Excluído!");

        /*jFormattedTextFieldCPF.setText("");
        jTextFieldNOME.setText(""); //deixa o campo vazio
        jTextFieldIDADE.setText("");
        jFormattedTextFieldDATA.setText("");//deixa o campo vazio
        jTextFieldAPELIDO.setText(""); //deixa o campo vazio

        jFormattedTextFieldCPF.setEnabled(false); //deixa o campo indisponivel
        jTextFieldNOME.setEnabled(false);
        jTextFieldIDADE.setEnabled(false);
        jFormattedTextFieldDATA.setEnabled(false);
        jTextFieldAPELIDO.setEnabled(false);
        jButtonINSERIR.setEnabled(true);
        jButtonALTERAR.setEnabled(false);*/

        // as a comentary cuz everything is a jFrame and gives an error
        }

    } catch (SQLException ex) {
        Logger.getLogger(Pessoa.class.getName()).log(Level.SEVERE, null, ex);
        JOptionPane.showMessageDialog(null, "Erro:01\n" + ex.getMessage());

    }

    }

Sorry for the long question, To simplify, I want to get the info on the jFormattedTextField in another class.

A: You can declare a static variable of type jTextField, inside your method initialize this static variable with the same object jFormattedTextField after modifications, declare a static get method to get this variable from another class and call it.
 class WhereYourJTextExists{
  private  jTextField jText ;
  private static jTextField jToPass;

  public static  jTextField getJToPass(){
   return jToPass;
  }
  public void yourTaskHere(){
  // .... do some tasks with jText
  // initialize your variable with the jTextField
  jToPass= jText;
  }
  }
  // ----------------------------------
  class OtherClass{
  public void needJtextHere(){
  jTextField recievedJtext = WhereYourJTextExists.getJToPass();
  //...do your job with the recived jTextField
  }
  }

A: Decouple your code.  Pass all the information that funcoes needs in order to do it's job and have it throw one or more exceptions as needed, for example...
public void funcoes(int MODO, String cpf) throws SQLException {

    if (MODO == 1) {
        if (cpf.equals("")) {
            // This could be a custom exception, which would make it easier
            // to detect and display a custom error message
            throw new SQLException("Por favor completar o campo CPF");
        } else {
            try (PreparedStatement stm = conecta.conn.prepareStatement("delete from cad_pessoa where cad_cpf=?")) {
                stm.setString(1, jFormattedTextFieldCPF.getText()); //pega o nome que será deletado
                stm.execute(); //executa o SQL
                conecta.conn.commit();
            }
        }
    }
}


text:
Q: how to install react-pannellum library to react/ionic I need to implement 3d panorama view in my react ionic app but I'm getting an error when I try install using either of the followings:
npm install --save react-pannellum
npm install --save pannellum

> npm WARN config global `--global`, `--local` are deprecated. Use
> `--location=global` instead.
>
> npm ERR! code ERESOLVE
>
> npm ERR! ERESOLVE unable to resolve dependency tree
>
> npm ERR! While resolving: test-pannelum@0.1.0
>
> npm ERR! Found: react@18.2.0
>
> npm ERR! node_modules/react
>
> npm ERR!   react@"^18.2.0" from the root project
>
>
> npm ERR! Could not resolve dependency:
>
> npm ERR! peer react@"17.0.2" from react-pannellum@0.2.13
>
> npm ERR! node_modules/react-pannellum
>
> npm ERR!   react-pannellum@"*" from the root project
>
>
> npm ERR! Fix the upstream dependency conflict, or retry
>
> npm ERR! this command with --force, or --legacy-peer-deps
>
> npm ERR! to accept an incorrect (and potentially broken) dependency
> resolution.

A: npm install --save react-pannellum --force


text:
Q: Remove an element from a list that contains only NA? I want to remove all elements in this list that contain only NA:
  List_data <- list("Green", "Yellow", c(NA,NA,NA), TRUE, 51.2)

A: For a purrr approach:
library(purrr)

List_data %>%
  map(discard, is.na) %>%
  compact()

Noting you can remove compact() and get "either" solution.

A: You can also do:
List_data[!sapply(List_data, function(x) all(is.na(x)))]

or as @snoram pointed out:
 List_data[sapply(List_data, Negate(anyNA))]

which can also be expressed as:
 List_data[!sapply(List_data, anyNA)]

A: EDIT2: As per akrun's comment following may also help here.
List_data[vapply(List_data, function(x) any(!is.na(x)), logical(1))]

EDIT: As per Onyambu's comment following may help in order to remove complete element which has NA in it, thanks to Onyambu for guiding here.
List_data[!sapply(List_data, function(x) all(is.na(x)))]

Could you please try following:
lapply(List_data, function(x) x[!is.na(x)])

A: If you mean remove the entire element (and not leave the empty name behind), try:
Filter(function(a) any(!is.na(a)), List_data)

Edit: using Onyambu's suggestion (thanks!) of Negate(anyNA), this would be
Filter(Negate(anyNA), List_data)

though admittedly this changes the logic from "something not-NA exists" (first code) to "no NA exists" (second code), definitely a logical change.


text:
Q: Can Robinson's Q prove Presburger arithmetic consistent? I made an assertion in What are some examples of theories stronger than Presburger Arithmetic but weaker than Peano Arithmetic? that Q has higher consistency strength than Pres, Presburger arithmetic; i.e., Q proves the consistency sentence for Pres.
But in fact, I only know something weaker, that Q can formalise the provability predicate for Hilbert systems, and so prove, say, that Peano arithmetic proves Pres consistent.
Is there a direct proof of consistenct of Pres in Q?

A: I believe that Theorem 1 of Bezboruah and Shepherdson 1976 [1] covers your question, at least in spirit. Their theory $T_0$ is a finite theory extending $Q$. Quoting their paper:

Theorem 1. Let $L$ be any formal system with a recursive set of axioms, a finite number of finitary and recursive rules of inference including modus ponens and having $A \to A$ as a theorem for all sentences $A$. Let
  $$Con_L =_{df}\quad \lnot(\exists y,z)(Th_L(y) \land Th_L(z) \land neg(z,y))$$
  where $\text{Th}_L$, $\text{neg}$ are given in Definition 3 below. Then $\text{Con}_L$ is not provable in $T_0$.

The authors, however, express the common doubt that consistency proofs in Q are philosophically meaningful.

"We must agree with Kreisel that this is devoid of any philosophical interest and that in such a weak system this formula cannot be said to express consistency but only an algebraic property which in a stronger system (e.g. Peano arithmetic P) could reasonably be said to express the consistency of Q."

The (well known?) difficulty here is that Q can formalize the provability predicate but cannot verify the Hilbert-Bernays derivability conditions for it.
1: A. Bezboruah and J. C. Shepherdson, "Gödel's Second Incompleteness Theorem for Q", The Journal of Symbolic Logic Vol. 41, No. 2 (Jun., 1976), pp. 503-512, JStor.


text:
Q: How to use path class? public static void main(String[] args) {
    java.nio.file.Path p = Paths.get("E:/test/Hellow.txt");

    try {
        FileOutputStream f = new FileOutputStream(p.getParent() + "hellow2.txt");
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

Hi, How to use path class?
I want input file E:/test/Hellow.txt to be output to E:/test/Hellow2.txt
But I'm getting E:\testHellow2.txt as the output file name. How do I fix this?

A: You should resolve the parent directory of the source file with the new file name the copy should get.
Have a look at this example:
public static void main(String[] args) {
    // provide the source file (must exist, won't check for that here)
    Path sourceFile = Paths.get("D:/ZZ--temp/Hellow.txt");
    // then try to copy source to target
    try {
        Path copy = Files.copy(sourceFile,
                /* get the parent directory of the source file
                 * and resolve it with the file name of the copy
                 */
                sourceFile.getParent().resolve("Hellow2.txt"),
                StandardCopyOption.REPLACE_EXISTING);

        if (Files.exists(copy)) {
            System.out.println("Successfully copied"
                    + sourceFile.toAbsolutePath().toString()
                    + " to "
                    + copy.toAbsolutePath().toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

It really copies the file and outputs the following on my machine (paths not equal to yours!)
Successfully copiedD:\ZZ--temp\Hellow.txt to D:\ZZ--temp\Hellow2.txt


text:
Q: Dailymotion embed: foreground and background parameters not working? I'm trying to change the the foreground and background colors of an embedded Dailymotion video like this:
<iframe src="http://www.dailymotion.com/embed/video/xjo5zb?background=0000FF&foreground=00FF00&highlight=FF0000" width="480" height="270" frameborder="0" allowfullscreen></iframe>

The values for foreground and background don't have any effect. I also noted that choosing a dark(er) color for highlight changes the background color to light grey.
Using just one or two of the parameters doesn't make any difference.
Am I missing something obvious?

A: you are right, these parameters (foreground and background) have been deprecated in dailymotion new player. They don't have any effect on the player skin any more.
Also, you are still right, skin colors are automatically adjusted (dark or clear) based on the highlight color.
The documentation will be fixed very soon regarding those changes.