text:
Q: \r keep printing time on same line even after another print is made i have a thread that calculates the time every 1 second to get the total elapsed time. This works great but i need to make it stay on the same line even after printing another line. Currently it is doing this:
[~] 00:00:02
ok #this is a test print to see if it stays on the same line and of course it dosen't.
[~] 00:00:08

def total_elapsed_time(start):
    while True:
        elapsed_time = time.time() - start
        print(colorama.Fore.LIGHTBLUE_EX + "[~] " + time.strftime("%H:%M:%S", time.gmtime(elapsed_time)), end="\r")
        time.sleep(1) #updates every second

this is my code. Ive been reading about \r \n and \r\n and \r does the job partially but i still need it to stay on the same line always. I'm not sure if this is even possible although i have seen it done in other languages so i think it is.

A: You can use \r to rewrite the bottom line.
If you want to print something else (like "ok") "above" the timestamp:

*

*erase the bottom line with the timestamp first (you may have to overwrite it with spaces and then use \r again if the next thing isn't long enough), then

*print the other thing (the "ok"), then

*write the timestamp again below it on a new line.

For example,
>>> from datetime import datetime
>>> import time
>>> for c in 'abcdefg':
...   print(datetime.now(), end='\r')  # timestamp
...   time.sleep(1)
...   print(' '*80, end='\r')  # overwrite timestamp line with spaces
...   print(c)  # print something else "above" the next timestamp
...
a
b
c
d
e
f
g
>>>

The end result has no timestamp, but you can see it while it's looping. Try it.
If you don't start out scrolled to the bottom, the timestamp line "moves" but once you print enough lines to fill the terminal, the bottom line will stay in place at the bottom. You can also use this to display progress bars and spinners and things like that.
Note also that you can use the backspace character to back up one character instead of the carriage return to back up to the beginning of the line.


text:
Q: Admin Form Integration for Custom Model Fields in Django I need a model field composed of a numeric string for a Django app I'm working on and since one doesn't exist I need to roll my own.  Now I understand how "get_db_prep_value" and such work, and how to extend the Model itself (the django documentation on custom model fields is an invaluable resource.), but for the life of me I can't seem to figure out how to make the admin interface error properly based on input constraints.

How do I make the associated form field in the admin error on incorrect input?

A: Have a look at the Form and field validation section in the Django documentation, maybe that's what you're looking for?
You would have to make a new type of form field for your custom model field.

A: All you need to do is define a custom modelform which uses your new field, and then tell the admin to use that form to edit your models.
class MyModelForm(forms.ModelForm):
    myfield = MyCustomField()

    class Meta:
        model = MyModel

class MyModelAdmin(admin.ModelAdmin):
    form = MyModelForm

redpajama_set_name: RedPajamaStackExchange


text:
Q: Query my excel worksheet with VBA Is it possible to query a worksheet using VBA?

I want to be able to select all the values in the time column i.e. (00:00) WHERE the day equals for example: Saturday
I there any way to do this, a tutorial would be really helpful.
Thanks

A: You can programmtically create an AutoFilter, then select the matching values:
Dim ws As Worksheet: Set ws = ActiveSheet

With ws
    .AutoFilterMode = False
    .Range("1:1").AutoFilter
    .Range("1:1").AutoFilter field:=2, Criteria1:="=Saturday", Operator:=xlAnd
    With .AutoFilter.Range
        On Error Resume Next ' if none selected
        .Offset(1).Resize(.Rows.Count - 1).Columns(2).SpecialCells(xlCellTypeVisible).Select
        On Error GoTo 0
    End With
    .AutoFilterMode = False
End With


text:
Q: Pop up blocker API- how to check if user has it enabled I need to know when the user clicks on the button that triggers window.open if there is stable API/way to know beforehand if the user actively has a pop-up blocker?
In some cases the user doesn't know/pay attention that they have pop-up blocker (that block the new window). I would like to inform them by some dialog/or something to authorize a new window by clicking on allow.

A:
Well this is your question - I need some stable solution how to know
  when the user click on event which open window ,how to know if he
  have the pop-up blocker enabled . before the window is
  open...thanks!

I am afraid there isn't any method to handle that. I researched upon this same issue a while back and I am sharing what I found.
Why our popups are blocked?
Smart popup blockers will allow a popup if it is directly associated to a user's action. If it's delayed in anyway, there's a good chance it's going to get blocked.
Reference : Andy Stratton (His Blog)
I like this explanation more
The general rule is that popup blockers will engage if window.open or similar is invoked from javascript that is not invoked by direct user action. That is, you can call window.open in response to a button click without getting hit by the popup blocker, but if you put the same code in a timer event it will be blocked. Depth of call chain is also a factor - some older browsers only look at the immediate caller, newer browsers can backtrack a little to see if the caller's caller was a mouse click etc. Keep it as shallow as you can to avoid the popup blockers.
Reference : dthorpe (Stack Overflow Username)
What we can do?
One thing is crystal clear as of now that there isn't any direct way to tweak with pop up blockers from code. I think the reason behind it is, it'll hamper the only reason behind it's existence.
You can go read at the solution presented by Andy on his blog here : Click. If I had to write what he has explained in short I'd directly say that use popups for response section. Andy explains that we can use windows.open in response section after a call is directly made on user's action wont be blocked by popup blockers.
Like xaxxon has explained it is possible to check after execution of windows.open that if it was blocked or not. Generally that is what people do and developers while making any extra service feature keep that in mind. For example I was implementing twitter's digits authentication system. I used to check for message after failure in execution of pop up command and then I could show a message to user to enable pop up window but then I found the solution mentioned above. It makes the whole thing more neat and clean.

A: window.open() will mostly only be blocked if it was not triggered by a click event.
To confirm the window has loaded:

var loaded = false;

function windowLoaded() {
  alert("The popup loaded");
  loaded = true
}

function pause(milliseconds) {
  var dt = new Date();
  while ((new Date()) - dt <= milliseconds) { /* Do nothing */ }
}

document.write("start...");

//open the window
var win = window.open("window.html");

// If window.open returned an object
if(win) {
  win.onload = function() {
    win.RunCallbackFunction = windowLoaded;
  };
  document.write("popup sent...");

  pause(3000);

  // Verify that out window loaded
  if (loaded == false)
    document.write("check you popup blocker!");
  else
    document.write("ok!");

}
else {
  document.write("window.open() was blocked...");
}

A: Window.open(...) returns a handle to the new window if it exists.  If it doesn't have a handle to the new window, that's a pretty good indication the window was blocked.
https://developer.mozilla.org/en-US/docs/Web/API/Window/open
From: https://davidwalsh.name/popup-block-javascript
var windowName = 'userConsole';
var popUp = window.open('/popup-page.php', windowName, 'width=1000, height=700, left=24, top=24, scrollbars, resizable');
if (popUp == null || typeof(popUp)=='undefined') {
    alert('Please disable your pop-up blocker and click the "Open" link again.');
}
else {
    popUp.focus();
}

A: Use this code to check
var popupBlockerChecker = {check:function(b) {
var a = this;
b ? /chrome/.test(navigator.userAgent.toLowerCase()) ? setTimeout(function()      {
a._is_popup_blocked(a, b);
}, 200) : b.onload = function() {
a._is_popup_blocked(a, b);
} : a._displayError();
}, _is_popup_blocked:function(b, a) {
0 == 0 < a.innerHeight && b._displayError();
}, _displayError:function() {
alert("Popup Blocker is enabled! Please add this site to your exception list.");
}};

and the usage will be something like
 var popup = window.open("http://www.google.com.au", '_blank');
 popupBlockerChecker.check(popup);

A: The following is a jQuery solution to popup blocker checking. It has been tested in FF (v11), Safari (v6), Chrome (v23.0.127.95) & IE (v7 & v9).
var popupBlockerChecker = {
    check: function(popup_window){
        var _scope = this;
        if (popup_window) {
            if(/chrome/.test(navigator.userAgent.toLowerCase())){
                setTimeout(function () {
                    _scope._is_popup_blocked(_scope, popup_window);
                 },200);
            }else{
                popup_window.onload = function () {
                    _scope._is_popup_blocked(_scope, popup_window);
                };
            }
        }else{
            _scope._displayError();
        }
    },
    _is_popup_blocked: function(scope, popup_window){
        if ((popup_window.innerHeight > 0)==false){ scope._displayError(); }
    },
    _displayError: function(){
        alert("Popup Blocker is enabled! Please add this site to your exception list.");
    }
};

Usage:-
var popup = window.open("http://www.google.co.in", '_blank');
popupBlockerChecker.check(popup);

Hope it will help.


text:
Q: Javascript: Simulate a click in  Good day,
I'm trying to simulate a click on a browse file element but I couldn't make it work.
I found this:
http://www.randomsnippets.com/2008/03/05/simulate-a-button-click-via-javascript/
and tried and it works in 'button' and 'submit' types:
<input type="checkbox" onClick="document.getElementById('theSubmitButton').click();">Check the box to simulate a button click
<input type="submit" name="theSubmitButton" id="theSubmitButton" value="Button" onClick="alert('The button was clicked.');">

but when I tried to change it to 'file' type:
<input type="checkbox" onClick="document.getElementById('theSubmitButton').click();">Check the box to simulate a button click
<input type="file" name="theSubmitButton" id="theSubmitButton" value="Button" onClick="alert('The button was clicked.');">

It wouldn't work in Firefox and IE8. But the file browser window appears in Google Chrome.
Is there a problem with this approach? How could I make it work in FF and IE8?
Thank you very much!

A: That's a security restriction to prevent malicious javascript from uploading files from a users computer without him wanting that or tricking him in doing so by opening a file selection dialog. You can't do it in javascript, and it's not a bug, it's a feature.

A: It also depends, why you need this? If this is for testing purposes you can use some existing frameworks, like FuncUnit:
http://www.beletsky.net/2010/12/functional-testing-by-javascript-with.html


text:
Q: How scientists estimated that our universe is 4% normal matter, 21% dark matter, and 75% dark energy? Is there a simple way to understand how scientists estimated/calculated the following percentages?

A: The total energy density of the universe can be inferred from the geometry of space-time, which in turn can be inferred from the observed size of microwave background fluctuations.
The amount of normal matter can be extrapolated from direct observation, the amount of dark matter indirectly via gravitation, the rest is dark energy.
See this site from NASA for a basic introduction.

A: I am afraid it is not simple. The normal matter would be the visible matter i.e. something directly observable. As for the Dark Matter, various observations point to its existence. One of them being the galaxy rotation curves. This is when the stars rotating in the galaxy are moving a lot faster than they would if there were only the visible galaxy matter creating the gravitational pull. You can also study galaxy clusters which will give you an idea of how much Dark Matter there is. Dark Energy is even more complicated. The evidence for that stems for observation which show the Universe to be expanding. Based on the expansion rate one can deduce how and how much of this Dark Energy is around to cause such an accelerated expansion.

A: From studying the motions of clusters of Galaxies, you can calculate its motion and therefore estimate its mass.
Then study clusters of clusters of Galaxies and you can estimate the total mass and the rate of expansion.
Then estimate.
After that it is simple psychology:
Normal (visible) Matter  4%, Dark (invisible) Matter 75%, Dark (expansion) Energy 21%
Give something a name and number and people will believe anything.


text:
Q: Are there one (or two) solid bugs in the `curses` shim for Perl? In furtherance to question Perl + Curses: Expecting a UTF-8 encoded multibyte character from getchar(), but not getting any, I'm starting a separate question after more info has been collected:
I am trying out Bryan Henderson's Perl interface to the ncurses library: Curses, henceforth called "curses shim".

*

*Tried with perl-Curses-1.36-9.fc30.x86_64

*Tried with perl-Curses-1.36-11.fc31.x86_64
For a simple exercise, I try to obtain single characters typed on-screen. This is directly based off the NCURSES Programming HOWTO, with adaptations.
When I call the curses shim's getchar(), I expect to receive a character, possibly multibyte (It's a bit more complicated as explained in this part of the library manpage because one has to handle the special cases of function keys and no input, but that's just the usual curlicues).
I'm receiving the correct input. Mostly. This took me some time to actually ascertain. I have experimented quite a bit with the code, been confused from time to time, and also fought with Perl's it's-an-opaque-object-but-not-quite approach to Strings (actually, byte containers).
In the end:
Looks like there is at least one bug in the curses shim:
Strings from curses with a single character between 0x80 and 0xFF and not created correctly by the wide-character aware getchar(). There are additional NUL bytes in there, which confuses Perl, and which also confuse the curses printw function.
Let's see what we have got:
An overview of what we receiving characters q, è, д through Curses::getchar() which transform the win_t 2-byte wide character obtained from wget_wch() into a Perl string:

*

*The "green case" works out.

*The "orange case" fails. But there is (fragile) fix.

*The "yellow case" works out, but probabyl accidentally.

The curses shim function printw is simple and simulates a printf:
In Curses.pm:
sub printw   { addstr(sprintf shift, @_) }

And this indicates another bug in the curses shim:  addstr is the C curses library function for non-wide character processing. I don't know how the calling convention from Perl to C above is solved, but for me that line means that the string generated by sprintf must be necessarily UTF-8 encoded so that printing through addstr works on an UTF-8 enabled terminal. And it will work completely by accident. If Perl had UCS-2 encoded string, it wouldn't. The correct way to output wide chars is addwstr.
Here is some code.
Run as:
perl test.pl 2> OUT; reset

To see the problem in action. Enter p, è or д.
Run as:
perl test.pl --fixit  2> OUT; reset

To see the code in action which fixes the string with the character between 0x80 and 0xFF.
Tail the file OUT while this is running:
tail -f OUT

Also noted:

*

*Contrary to what perldoc say, use bytes does not only apply to its scope. It break out of it and changes behaviour of ord program-wide.

CODE
If you try it, hit BACKSPACE to get out of the loop, because CTRL-C is no longer interpreted.
The terminal must be in UTF-8 mode.
#!/usr/bin/perl

use warnings;
use strict;
use utf8; # Meaning "This lexical scope (i.e. file) contains utf8"

use Curses;                   # On Fedora: dnf install perl-Curses
use Encode qw(decode encode); # https://perldoc.perl.org/Encode.html

# Necessary for proper printing to a terminal expecting UTF-8
# https://perldoc.perl.org/open.html

use open qw(:std :encoding(UTF-8));

# https://perldoc.perl.org/perllocale.html#The-setlocale-function

use POSIX ();
my $loc = POSIX::setlocale(&POSIX::LC_ALL, "");

# ---
# Set STDOUT/STDERR to autoflush for proper debugging
# ---

select STDERR;
$| = 1;
select STDOUT;
$| = 1;

# ---
# Surrounds the actual program: set upand teardown curses
# ---

sub setup() {
   initscr();
   raw();
   keypad(1);
   noecho();
}

sub teardown {
   endwin();
}

# ===
# Functions below is where the action is
# ===

sub announce {
   my $res = printw "Type any character to see it in bold! (or backspace to exit)\n";
   return { refresh => 1 }
}

sub read_one_char {

   # Read a next character, waiting until it is there.
   # >>>>
   my ($ch, $key) = Curses::getchar();
   # <<<<

   if (defined $key) {
      # it's a function key
      printw "Function key pressed: $key";
      printw "\n";
      # we are done if "backspace" was hit
      return { done => ($key == KEY_BACKSPACE()) }
   }
   elsif (!defined $ch) {
      # it's an error
      printw "getchar() failed\n";
      return {}
   }
   else {
      output_with_fix($ch);
      return { ch => $ch }
   }
}

sub output_with_fix {
   my($str) = @_;
   print STDERR "Received new character\n";
   print STDERR " About: " . about($str) . "\n";

   my $curses_str = $str; # will go to curses via curses printw()
   my $stderr_str = $str; # will go to stderr via print()

   my $fixit  = defined($ARGV[0]) && (lc($ARGV[0]) eq "--fixit");
   my $fakeit = defined($ARGV[0]) && (lc($ARGV[0]) eq "--fakeit");

   if ($fixit || $fakeit) {

      my $byte_len;
      my $byte_ord;
      {
         # https://perldoc.perl.org/bytes.html
         use bytes;
         $byte_len = length($str);
         $byte_ord = ord($str);
      }

      if ($byte_ord >= hex('0x80') && $byte_len == 2) {
         print STDERR " UTF-8 (on 2 bytes)? NOT Fixing it!\n";
      }
      elsif ($byte_ord >= hex('0x80') && $byte_len == 1) {
         print STDERR " ISO-8859-1? Fixing it!\n";
         if ($fixit) {
            # Try to "decode it as ISO-8859-1" and hope that Perl fixes whatever is wrong
            # The result is a nice string internally encoded as UTF-8, with its UTF-8 flag properly set
            $curses_str = decode('iso-8859-1',$str);
         }
         else {
            # Fake it to show the above is not a NOP
            $curses_str = $str;
         }
         print STDERR " Fixed curses string to: " . about($curses_str) . "\n";
      }
      elsif ($byte_ord < hex('0x80') && $byte_len == 1) {
         print STDERR " ASCII: Nothing to fix\n";
      }
      else {
         die "Something weird!"
      }
   }

   print STDERR " Interpolated string  : $stderr_str\n";
   print STDERR " Concatenated string  : " . $stderr_str . "\n";
   print STDERR " Sprintf-built string : " . sprintf("%s",$stderr_str) . "\n";

   printw("...printw printing interpolated string  : $curses_str\n");
   printw("...printw printing concatenated string  : " . $curses_str . "\n");
   printw("...printw printing sprintf-built string : " . sprintf("%s",$curses_str) . "\n");

}

sub feedback {
   my ($ch) = @_;
   printw "The pressed key is: ";
   attron(A_BOLD);
   #
   printw($ch);
   #
   attroff(A_BOLD);
   printw("\n");
   return { refresh => 1 }  # should refresh
}

# ---
# main
# ---

sub do_curses_run {
   setup;
   printw "Locale: $loc\n"; # printing OK
   my $done = 0;
   while (!$done) {
      my $bubl = announce();
      refresh() if $$bubl{refresh};
      $bubl = read_one_char();
      $done = $$bubl{done};
      if (!$done && defined $$bubl{ch}) {
         $bubl = feedback($$bubl{ch});
         refresh() if $$bubl{refresh};
      }
   }
   teardown;
}

do_curses_run();

# ===
# ANNEX
# ===

# ---
# annex stuff: printing info about string
# ---

sub about {
   my($str) = @_;

   my $char_len = length($str);
   my $ord      = ord($str);
   my $mark     = (utf8::is_utf8($str) ? "yes" : "no");

   my $byte_ord;
   my $byte_len;
   my $byte_contents;
   {
      # https://perldoc.perl.org/bytes.html
      use bytes;
      $byte_len = length($str);
      $byte_ord = ord($str);
      $byte_contents = sprintf("%vx", $str);
   }

   my $f1 = sprintf("%d bytes", $byte_len);
   my $f2 = sprintf(", %d chars", $char_len);
   my $f3 = sprintf(", utf-8: %s",$mark);
   my $f4 = sprintf(", ord: x%x", $ord);
   my $f4p = sprintf(", byte-ord: x%x", $byte_ord);
   my $f5 = sprintf(", byte-contents (hex, via %%vx): %s", $byte_contents);
   return $f1 . $f2 . $f3 . $f4 . $f4p . $f5;
}

Output for normal operations
Run as perl test.pl 2> OUT
On the terminal, è is not displayed:
Locale: en_GB.UTF-8
Type any character to see it in bold! (or backspace to exit)
...printw printing interpolated string  : p
...printw printing concatenated string  : p
...printw printing sprintf-built string : p
The pressed key is: p
Type any character to see it in bold! (or backspace to exit)
...printw printing interpolated string  :
...printw printing concatenated string  :
...printw printing sprintf-built string :
The pressed key is:
Type any character to see it in bold! (or backspace to exit)
...printw printing interpolated string  : д
...printw printing concatenated string  : д
...printw printing sprintf-built string : д
The pressed key is: д
Type any character to see it in bold! (or backspace to exit)

In OUT:
The lines marked with # are coming from the C-side of curses shim, where I added some printfs:
# Obtained win_t 0x0070
# Not UTF-8 string: 70 00
Received new character
 About: 1 bytes, 1 chars, utf-8: no, ord: x70, byte-ord: x70, byte-contents (hex, via %vx): 70
 Interpolated string  : p
 Concatenated string  : p
 Sprintf-built string : p
# Obtained win_t 0x00e8
# Not UTF-8 string: e8 00
Received new character
 About: 1 bytes, 1 chars, utf-8: no, ord: xe8, byte-ord: xe8, byte-contents (hex, via %vx): e8
 Interpolated string  : è
 Concatenated string  : è
 Sprintf-built string : è
# Obtained win_t 0x0434
# UTF-8 string: d0 b4 00
Received new character
 About: 2 bytes, 1 chars, utf-8: yes, ord: x434, byte-ord: xd0, byte-contents (hex, via %vx): d0.b4
 Interpolated string  : д
 Concatenated string  : д
 Sprintf-built string : д
# Obtained win_t 0x0107

Output for "fixit" operations
Run as perl test.pl --fixit 2> OUT
On the terminal, è is now displayed.
Locale: en_GB.UTF-8
Type any character to see it in bold! (or backspace to exit)
...printw printing interpolated string  : p
...printw printing concatenated string  : p
...printw printing sprintf-built string : p
The pressed key is: p
Type any character to see it in bold! (or backspace to exit)
...printw printing interpolated string  : è
...printw printing concatenated string  : è
...printw printing sprintf-built string : è
The pressed key is:
Type any character to see it in bold! (or backspace to exit)
...printw printing interpolated string  : д
...printw printing concatenated string  : д
...printw printing sprintf-built string : д
The pressed key is: д
Type any character to see it in bold! (or backspace to exit)

In OUT:
The lines marked with # are coming from the C-side of curses shim, where I added some printfs:
# Obtained win_t 0x0070
# Not UTF-8 string: 70 00
Received new character
 About: 1 bytes, 1 chars, utf-8: no, ord: x70, byte-ord: x70, byte-contents (hex, via %vx): 70
 ASCII: Nothing to fix
 Interpolated string  : p
 Concatenated string  : p
 Sprintf-built string : p
# Obtained win_t 0x00e8
# Not UTF-8 string: e8 00
Received new character
 About: 1 bytes, 1 chars, utf-8: no, ord: xe8, byte-ord: xe8, byte-contents (hex, via %vx): e8
 ISO-8859-1? Fixing it!
 Fixed curses string to: 2 bytes, 1 chars, utf-8: yes, ord: xe8, byte-ord: xc3, byte-contents (hex, via %vx): c3.a8
 Interpolated string  : è
 Concatenated string  : è
 Sprintf-built string : è
# Obtained win_t 0x0434
# UTF-8 string: d0 b4 00
Received new character
 About: 2 bytes, 1 chars, utf-8: yes, ord: x434, byte-ord: xd0, byte-contents (hex, via %vx): d0.b4
 UTF-8 (on 2 bytes)? NOT Fixing it!
 Interpolated string  : д
 Concatenated string  : д
 Sprintf-built string : д
# Obtained win_t 0x0107

Addendum
Of course, you need libcursesw.
If you have the Perl process pid, try:
pmap -p PID

which shows the per process having attached:
/usr/lib64/libncursesw.so.6.1
/usr/lib64/perl5/vendor_perl/auto/Curses/Curses.so

Addendum 2
Tried to see what the C code does and added an fprintf directly into the multibyte handling code of curses/Curses-1.36/CursesFunWide.c, recompiled, didn't manage to override the system Curses.so with my own via LD_LIBRARY_PATH (why not? why is everything only working half of the time?), so replaced the system library directly in place (take THAT!).
#ifdef C_GET_WCH
    wint_t wch;
    int ret = wget_wch(win, &wch);
    if (ret == OK) {
        ST(0) = sv_newmortal();
        fprintf(stderr,"Obtained win_t 0x%04lx\n", wch);
        c_wchar2sv(ST(0), wch);
        XSRETURN(1);
    } else if (ret == KEY_CODE_YES) {
        XST_mUNDEF(0);
        ST(1) = sv_newmortal();
        sv_setiv(ST(1), (IV)wch);
        XSRETURN(2);
    } else {
        XSRETURN_UNDEF;
    }
#else

Addendum 3
The win_t (apparently the same as wchar_t) conversion code from CursesWide.c, converts the wint_t (here seen as wchar_t) received from wget_wch() into a Perl string. SV is the "scalar value" type.
See also: https://perldoc.perl.org/perlguts.html
Here with two fprintf inserted to see what is going on:
static void
c_wchar2sv(SV *    const sv,
           wchar_t const wc) {
/*----------------------------------------------------------------------------
  Set SV to a one-character (not -byte!) Perl string holding a given wide
  character
-----------------------------------------------------------------------------*/
    if (wc <= 0xff) {
        char s[] = { wc, 0 };
        fprintf(stderr,"Not UTF-8 string: %02x %02x\n", ((int)s[0])&0xFF, ((int)s[1])&0xFF);
        sv_setpv(sv, s);
        SvPOK_on(sv);
        SvUTF8_off(sv);
    } else {
        char s[UTF8_MAXBYTES + 1] = { 0 };
        char *s_end = (char *)UVCHR_TO_UTF8((U8 *)s, wc);
        *s_end = 0;
        fprintf(stderr,"UTF-8 string: %02x %02x %02x\n", ((int)s[0])&0xFF, ((int)s[1])&0xFF, ((int)s[2])&0xFF);
        sv_setpv(sv, s);
        SvPOK_on(sv);
        SvUTF8_on(sv);
    }
}


text:
Q: How to get index in jstl display table I have display table like below
<display:table name="sample" id="sample" class="display-table" style="width:100%;">

</display:table>

Now I want to get index of loop like for first element 0 for second 1 and 2,3,4... go on. How it is possible with display table.
For just reference we can do like this in JSTL forEach loop with help of varStatus variable like below
<c:forEach items="${sample}" var="clm" varStatus="status">
     ${status.index}
</c:forEach>

So is this possible with display table?

A: display table tag implicitly exposes row number named id_rowNum where id is specified in display table tag.
In your scenario:
    <display:table name="sample" id="sample" class="display-table" style="width:100%;">
        <display:column title="Row Number" >
          <c:out value="${sample_rowNum - 1}"/>
        </display:column>
        ...
    </display:table>

Also make sure to include core tag as:
   <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

You can find more information about implicit objects of display table tag here.


text:
Q: PHP-FPM stops responding suddenly and resumes after 2-3 minutes I have 4 php-fpm servers running on backend to server Php request to Nginx. Everything works fine but sometimes suddenly PHP-FPM stops responding to Nginx and resumes well in normal mode without taking any restart after 3-5 minutes.
Any help or suggestion would be greatly appreciated to locate the issue.
Thanks


text:
Q: Bootstrap Dropdown won't expand on mobile I have a navbar from bootstrap and one of the menus is a dropdown that allows me to select a course.
The first pic is what it looks like on my desktop when I click on courses, working perfectly fine.

When I try to select it on mobile, nothing happens.
This is the navbar code

And the scripts I include.

Any insight on this issue would be much appreciated

A: Here is the link, I think you might find something that will work for you.
Drop-Down Menu not working on mobile devices

A: Here yo go with a solution https://jsfiddle.net/rskte8s5/

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

      <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
        Toggle navigation

      </button>
      Brand

Home (current)

          Course

Accounting & Information System

Aerospace Engineering

Business Information Technology

Computer Science

Electrical & Computer Engineering

Finance

Math

Contact


text:
Q: Creating 3D geometry column by combining existing 2D geometry column with "elevation" column? I want to create a table that contains 3D data.
I currently have 2D data stored as EWKT, which is multipoint geometry in one column, and another column that has elevation from sea level in another column.
Is there a way that I can combine these two columns and output a single column with 3D data?
Example:
Geom column ("010400000001000000010100000000001038011323410000E9631AFC5641")
Elevation column ("1346.9495")
My goal is to combine the Geom column with the Elevation column, to create a 3D geometry column.
My thought is to possibly use subquerries, but I don't know how.
I am using pgAdmin 4.

A: With the elements we have here,
I'll show a way to transform MultiPoints and Point geometrie and add the Z information in your geometry.
create table public.multi_test as (
SELECT ST_GeomFromText('MULTIPOINT((-71.160281 42.258729),(-71.160837 42.259113),(-71.161144 42.25932))') as geom,
1515 as elevation)

I will simulate your dataset as follow, geometry as MultiPoints geometry in your geom column and an "elevation" column with the Z information
At this point, you need to Dump your dataset to split your multipoints in single points and keep the z information at the same time. You can run the following
select St_asText((ST_Dump(multi_test.geom)).geom) as geom
from public.multi_test

Create table public.point_dump as (
select (ST_Dump(multi_test.geom)).geom as geom,
multi_test.elevation as elevation
from public.multi_test)

So we create a dataset of points with the z information in your column "elevation"
from here we can make a new geometry with the Z information by extracting info from your geometry and adding the Z from the column. You can extract X and Y information from a geometry with ST_X, ST_Y. St_MakePoint will create the new point with the Z information
Create table public.points_3d as (
select St_MakePoint(ST_X(geom),ST_Y(geom),elevation) as geom
from public.point_dump)

select St_asText(geom) from public.points_3d

You can resume all these queries in a single query but as we don't have full information, I prefer to explain the way to go.
Similar things are possible with Polygons and Linestrings.
Edit : with a CTE you can do this single query
Create table public.points_3d_v2 as (
with points as (
    select
    (ST_Dump(multi_test.geom)).geom as geom,
    multi_test.elevation as elevation
    from public.multi_test
)
    select ST_MakePoint(ST_X(geom),ST_Y(geom),elevation) as geom,
    elevation from points
)


text:
Q: Suitable tense for specific time I understand that when we use the past continuous tense, our listener usually understands what time we are talking about. Like, "I was working at 10 pm last night."
However, I saw a sentence in a textbook it wrote that "I was in bed asleep at 4.30 this morning."  I wonder why it didn't use past continuous tense; can we say "I was being in bed asleep at 4.30 this morning" or not?  Plus, I'm not sure if the verb to be can be continuous or not for this case.
Moreover for verbs that can't be continuous, if I write a specific time, I have to use past tense not continuous tense, right? For example, "I saw a very big bird at 10 am this morning."  Is it correct to use past tense "saw" in this case?

A: Right, as you say, when we use the past continuous tense there is usually some context that makes it clear to the reader / listener when the event was happening. Your question seems to be mostly about stative verbs (1) to be; and (2) to see.
(1) Be
Verbs that are not typically used in continuous tenses are called stative. Examples are see, be, want, hear. So we say "I was in bed..." not "I was being...". There are some cases when stative verbs like "be" are used in a continuous tense and these cases tend to change the meaning of the verb.
(2) See
As to the correctness of "I saw a very big bird at 10am this morning", this will depend on the context. It is a grammatically correct sentence; it appropriately expresses the idea that at 10am a bird appeared in view.
However, if you wanted to express some kind of continuous observation then you would need a different verb, not see (which is stative). E.g. you might say, "when someone knocked on the door at 10am I was watching a big bird".


text:
Q: VBA Access Specify Field Format for a Date/Time Field I am having issues with changing the Field Format of a existing Data/Time Field.
I want to add a field called "Duration" to a table called "IncidentData" and change the field to show only the hour and minutes information such as "13:44"

A: It is possible to set the format property of the field to Short Time or hh:nn.
alt text http://ltd.remou.com/access/tableformat.png


text:
Q: Using JQuery or JS to add classes to raw unformatted html text I am trying to format the returned text from an API call, however what is being returned is poorly formatted and does not have css elements. Additionally, the only html element is a "

" to break up the body content (had to add the spaces to display on screen).
What I am trying to do is assign a class when each  is detected.
I am however struggling.
What I have so far.

Example of the layout that I am working with.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.

 Vivamus pharetra at justo ut rhoncus. Suspendisse potenti. Morbi accumsan felis in mi aliquet, vitae efficitur nulla consectetur. Praesent in ante id purus consectetur maximus in et erat.

 In eget augue ut tortor iaculis rutrum ultrices et nulla. In euismod ultrices erat, a bibendum metus egestas eget. Morbi eu viverra mauris, ut finibus velit. Etiam at erat rhoncus, porta ante non, placerat nibh.

 Aenean eget lacus vitae neque fermentum pulvinar ut a mi.

I am aiming to have a structure similar to the following as a starting point.

Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Vivamus pharetra at justo ut rhoncus. Suspendisse potenti. Morbi accumsan felis in mi aliquet, vitae efficitur nulla consectetur. Praesent in ante id purus consectetur maximus in et erat.

In eget augue ut tortor iaculis rutrum ultrices et nulla. In euismod ultrices erat, a bibendum metus egestas eget. Morbi eu viverra mauris, ut finibus velit. Etiam at erat rhoncus, porta ante non, placerat nibh.

 Aenean eget lacus vitae neque fermentum pulvinar ut a mi.

JS and JQuery is still very much new to me. Thank you.

A: Sounds like you have some unwanted double  line breaks that you want to replace and convert paragraphs or sections to divs.
I might do something like get the text inside your text wrapper did. Then use Javascript string.split function to to remove the    and convert those paragraphs into arrays then add a new div  with class and replace it back into the main textwrapper div with $.html
like this :

A: You could wrap the poorly formated html in

 and then replace

 with

, which will result in properly formatted html.
$('.text-wrapper').each(function() {
  this.innerHTML = `

      ${this.innerHTML.replace(/

/g, '

')}

`;
});

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions


text:
Q: Android - Custom ListView with internet images. Can't download images I'm trying to display a custom ListView that has a thumbnail image and text in each row.
I have the text stored in one ArrayList<String> and the URLs to each thumbnail stored in another one.
I can get the text to appear in the list, but I can only statically/manually set the image.
My question: How can I make my ImageView download the thumbnail image and display it? Each thumbnail is unique.
Here is my code for populating the ListAdapter:
class CustomAdapter extends ArrayAdapter<String>
{
    CustomAdapter()
    {
        super(MyClass.this, R.layout.listrows, R.id.txtAddress,propertyAddress);
    }

    public View getView(int position, View convertView, ViewGroup parent)
    {
        View row=super.getView(position, convertView, parent);
        ViewHolder holder=(ViewHolder)row.getTag();

        if (holder==null)
        {
            holder=new ViewHolder(row);
            row.setTag(holder);
        }

        //I tried this,
        holder.icon.setImageURI(Uri.parse(imageList.get(position).toString()));
        //But I get a NullPointer

        return(row);
    }
}

Also, my ViewHolder class is pretty normal:
class ViewHolder
{
    ImageView icon=null;
    ViewHolder(View base)   {
        this.icon=(ImageView)base.findViewById(R.drawable.ic_launcher);
    }
}

I would appreciate any help with this.
Thanks!

A: setImageUri is to set a local position. not for the internet.
try to use ImageDownloader.


text:
Q: Is there a CSS selector that applies when matching specific values in the URL? Is there a selector that specifies CSS to only applied when matching a specific URL or part of URL?
For example, here is my CSS stylesheet:
p {
   color: green;
}

url("home.html") {
   color: blue;
}

url("about.html") {
   color: yellow;
}

path("/path/index*") {
   color: indigo;
}

When the user visits home.html I want the home.html selector to be applied. When I'm on the about.html URL I want the about.html to be applied.
CSS media queries allow you to switch to a different set of styles when the width of the view changes. It also lets you specify a different set of styles when the user is going to view on the screen or send it to a printer.
My question again is, "Is it possible to specify a different set of styles depending on the URL or values in the URL." So it's not a question of how to do what I'm asking but if it's possible to.
I am using a CMS and it has a theme that allows you to add your own CSS. There is one stylesheet. That's it. Not two but one.
And I have one page that has specific CSS to that page and only that page. That is the origin of this question. There may be a thousand workarounds but my question is not about the workarounds.
However since this has been answered I do not mind workaround answers related to the question.

A: You could attach a data-url custom attribute to an element's parent tag, either in the HTML or using JavaScript, and then query that data's value in CSS. Here's a working example:

const urlHolder = document.getElementById("url-holder");

document.getElementById("changer").onclick = () => {
  urlHolder.dataset.url = "https://mywebsite.com/about"
};
#url-holder[data-url*="blog"] .url-based{
  background-color: red;
}

#url-holder[data-url*="blog"] .url-based::after{
  content: "You're on the blog page!"
}

.url-based::after{
  content: "You're not on the blog page."
}

.box{
  width: 200px;
  height: 200px;
  border: 2px solid black;
  margin: 5px;
}
<button id="changer" type="button">Change data-url to "https://mywebsite.com/about"</button>

No idea how performant such a solution would be though.

A: To be sad there is no pseudo classes to select element's based on URL.The only way you can do it is by adding class to the body tag or specific element and then override the CSS.

A: It looks like the @document rule was proposed for just this case but it was removed from CSS3 spec and planned for CSS4. From my tests it does not appear to be supported and it's not listed on caniuse at the time of this posting.
The syntax is as follows:
@document url("http://www.example.com/widgets/") {
  body {
    color: white;
    background: tomato;
  }
}
/* The above applies styles only to the page at the given URL  */

@document url-prefix("http://www.example.com/widgets/") {
  /*
  Styles written here are applied to all URLs that
  begin with 'http://www.example.com/widgets/'
  */
}

@document regexp("https:.*") {
  /* Styles written here are applied to all URLs that begin with 'https:' */
}

Test code using @media query for comparison:
var styleTag = document.createElement ("style");
document.head.appendChild (styleTag);
var sheet = styleTag.sheet;
sheet.insertRule ("@media (min-width:600px) { html {color:red}}", 0);
console.log(document.styleSheets.length);

Results:
// no errors, stylesheet is added

Test code testing @document rule:
var styleTag = document.createElement ("style");
document.head.appendChild (styleTag);
var sheet = styleTag.sheet;
sheet.insertRule ("@document url('http://www.google.com') { html {color:red}}", 0);

Results:
/*
Exception: SyntaxError: An invalid or illegal string was specified
@Scratchpad/3:4:0
*/

TIL about @document thanks to @BoltClock
More info

A: if just for only HTML, use jQuery

If use you WordPress:
Add your theme function.php
  function site_stil_script() {

    if ($_SERVER['REQUEST_URI']=='/YOURPAGE/') {
        wp_enqueue_style( 'theme_css', get_template_directory_uri() . '/assets/css/theme-difrent-style.css', array(), '20120208', 'all' );
    } else {
        wp_enqueue_style( 'theme_css', get_template_directory_uri() . '/assets/css/theme-style.css', array(), '20120208', 'all' );
    }
//other lines....
}
add_action( 'wp_enqueue_scripts', 'site_stil_script' );


text:
Q: Exercise 2. Chapter 5. Stein Suppose $F(z)$ is holomorphic near $z=z_0$ and $F(z_0)=F'(z_0)=0$, while $F''(z_0)\neq 0$. Show that there are two curves $\Gamma_1$ and $\Gamma_2$ that pass through $z_0$, are orthogonal at $z_0$, and so that $F$ restricted to $\Gamma_1$ is real an has a minimum at $z_0$, while $F$ restricted to $\Gamma_2$ is also real but has a maximum at $z_0$.
Progress: I know that $F(z)=z^2f(z)$ where $f(z)$ doesn't vanish at $z_0$. Then in a small disk around $z_0$ the function $f$ doesn't vanish. So I can write $F(z)=g(z)^2$ where $g$ is a bijection in a small disk around $z_0$. The hint of this exercise suggests to use this function $g$ and its inverse to get the curves $\Gamma_1$ and $\Gamma_2$, but I don't see how to do it. Any suggestions?

A: You are almost there. $g$ is a bijection of some neighborhood of $z_0$ to a disk $B_r(0)$, therefore you can define
$$
 \Gamma_1(t) = g^{-1}(t) \\
 \Gamma_2(t) = g^{-1}(it)
$$
where $ t \in (-r, r)$. Then $f(\Gamma_1(t)) = t^2$ is real and has a minimum at $t=0$, whereas $f(\Gamma_2(t)) = -t^2$ is real and has a maximum at $t=0$.
$\Gamma_1$ and $\Gamma_2$ are orthogonal at $z_0$ because $g^{-1}$ preserves angles.


text:
Q: How to call SamsungMobilePrint scan function via intent For some reason I would like to call SamsungMobilePrint/Scan directly from an app with startActivity.
Samsung suggested
Intent intent = new Intent("com.sec.print.mobileprint.action.SCAN");
startActivity(intent);

but this leads to a Nullpointer-Exception somewhere within Java.
I am able to call the Print-Fuction directly without problems by doing:
Intent intent = new Intent("com.sec.print.mobileprint.action.PRINT");
Uri uri= Uri.parse(printfileName);    //Test_document.pdf speech.txt
intent.putExtra("com.sec.print.mobileprint.extra.CONTENT", uri );
intent.putExtra("com.sec.print.mobileprint.extra.CONTENT_TYPE", "DOCUMENT");
intent.putExtra("com.sec.print.mobileprint.extra.AUTO_RETURN", "TRUE");
startActivity(intent);

I can also call the whole MobilePrint app by:
Intent intent = getPackageManager().getLaunchIntentForPackage("com.sec.print.mobileprint");
startActivity(intent);

Has anybody been able to call the SamsungMobilePrint/Scan using
Intent intent = new Intent("com.sec.print.mobileprint.action.SCAN"); ?

A: It appears that I finally found a solution. There was an "Extra" missing. Samsung documentation was a little misleading.
It finally works like this:`
Intent launchIntent = new Intent("com.sec.print.mobileprint.action.SCAN");
if (launchIntent != null) {     //null pointer check in case package name was not found
    launchIntent.putExtra("com.sec.print.mobileprint.extra.CONNECTION_TYPE", "WIFI");
    launchIntent.putExtra("com.sec.print.mobileprint.extra.AUTO_RETURN", "TRUE");
}
startActivity(launchIntent);

e.g. a "CONNECTION_TYPE"-Extra is mandatory in this case.


text:
Q: C# - program about while loop I'm a newbie to C# Programming and we're still starting on the loops. For our exercise today, we were tasked to create program using (while loop).
the question is :
Read 5 marks from the user, print the sum and "Passed" if the marks greater or equal to 50 or if among the marks there is only one mark less than 50.
 if the user enters 2 marks less than 50 then the program should print STOP and end the program.
this is my try
unfortunately not complete and I can't do it
May you help me, please ?
int sum=0 , counter = 0, number=0 ;

        while (counter < 5 || number < 50)
        {

            number = Convert.ToInt16(Console.ReadLine());
            sum = sum + number;
            counter++;
        }

        Console.WriteLine(sum + "\nPassed");

A: In the while loop you need && (and) instead of || (or).
After reading a number you can check if it's less than 50 or not and you can also count these.
So after the loop you need to check the lessCounter to decide to print Passed or STOP.
int sum = 0, counter = 0, number = 0, lessCounter = 0;

while (counter < 5 && lessCounter <= 1)
{
    number = Convert.ToInt16(Console.ReadLine());
    sum += number;
    if (number < 50)
        lessCounter++;
    counter++;
}
if (lessCounter <= 1)
    Console.WriteLine(sum + "\nPassed");
else
    Console.WriteLine(sum + "\nSTOP");

A: Thank you all for all your effort and a time, special thanks to Mr.Szkup.
I was able to do it this way:
int number = 0, sum = 0, count = 0;
while (number < 5)
{
    Console.Write("Input Number {0} : " , (number + 1));
    int mark = Convert.ToInt16(Console.ReadLine());
    if (mark < 50)
    {
        count++;
    }
    if (count == 2)
    {
        Console.WriteLine("\nStop\n");
        break;
    }
    sum += mark;
    number++;
}
if (count <= 1)
{
    Console.WriteLine("\nsum = {0}\nPassed\n",sum);
}


text:
Q: Limit Skyrim Special Edition FPS to 60 So I have an issue (a common one) that if Skyrim goes over 60 fps, it will start to show issues with the game (for example colliding items, functions not working).
I am well aware that this is asked for the "old" Skyrim. Most of the people give you a link to a mod that does this for you. But as Skyrim SE is brand new, it still does not have this mod. (Kind of a shame this is still not fixed in the Special Edition)
I have also seen alot of solutions like using nVidia Inspector. But I would prefer to NOT use any third-party software to resolve this issue.
So what I would like to know if there is a solution for this.
Even though I can change the refresh rate to 60Hz (144Hz normally) this will become a chore after a while.
I am open for any Command Line solutions. VB.NET or C# is welcome too.
Any info is appreciated.

A: The graphical enhancement mod ENBSeries can limit your FPS, if you set EnableFPSLimit=true and your desired FPS in FPSLimit=61.0 under [LIMITER] in enblocal.ini.
The base game itself does not offer a (documented or discovered) way of limiting the FPS outside of enabling vsync and setting your monitor refresh rate to the desired amount (after making sure your monitor supports it, of course).


text:
Q: Smartquotes displayed fine in Rails 2, now a problem in Rails 3 My Rails app is working from a mysql database, and when I switched from Rails 2.8, Ruby 1.8 and the mysql gem over to Rails 3.0.7, Ruby 1.9.2 and the mysql2 gem, all of a sudden my pages are rendering with smartquotes (curly quotes) and em-dashes, etc., all looking like gibberish.
I'm assuming this has something to do with UTF-8, but I don't know how to pinpoint it.
Here's what I do know:
(1) config/database.yml has the following:
development:
  adapter: mysql2
  encoding: utf8

(2) config/application.rb has the following:
config.encoding = "utf-8"

Don't know where to go from there.
Any suggestions?

A: You can narrow it down to the db vs the view by doing two things:

*

*rails console # in your terminal in the project directory, then test that your ActiveRecord objects have the correct data.

*ViewSource in your browser to see if the generated source is putting in the correct characters.

Later:
This is probably a duplicate of: mysql2 gem, Rails 3.0.3 and "incompatible character encodings" errors https://github.com/brianmario/mysql2/issues/124
And maybe even the monkeypatch here: http://www.rorra.com.ar/2010/07/30/rails-3-mysql-and-utf-8/


text:
Q: Suddenly stop copying SQLite Database from assets I am copying SQLite Database from assets folder to android app. I am using below mentioned code. And it was working fine and I am doing my code smoothly. Suddenly, it stopped copying database to android app.
public class PreCreateDB {

    public static void copyDB (Context context) {
        try {
            String destPath = "/data/data/"+ context.getPackageName()+ "/databases";
            File f = new File(destPath);
            if (!f.exists()) {
                f.mkdir();
                rawCopy(context.getAssets().open("dbname.db"), new FileOutputStream(destPath + "/dbname.db"));
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void rawCopy(InputStream inputStream, OutputStream outputStream) throws IOException{

        byte[] buffer = new byte[1024];
        int length;
        while ((length=inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }
        inputStream.close();
        outputStream.close();

    }
}

I found db in Device File Explorer and I see the following lines in it (not whole tables). Kindly help
SQLite format 3   @                                                                   .�
   � �                                                                                W--ctableandroid_metadataandroid_metadataCREATE TABLE android_metadata (locale TEXT)
   � �                                                                                en_IN

A: I change my code to the following one, now it's working.
public static void copyDB (Context context) throws IOException {

        try (SQLiteDatabase dbe = SQLiteDatabase.openDatabase("/data/data/com.app.example/databases/dbname.db", null, 0)) {
            dbe.close();
        } catch (Exception e) {
            AssetManager am = context.getAssets();
            OutputStream os = new FileOutputStream("/data/data/com.app.example/databases/dbname.db");
            byte[] b = new byte[100];
            int r;
            InputStream is = am.open("dbname.db");
            while ((r = is.read(b)) != -1) {
                os.write(b, 0, r);
            }
            is.close();
            os.close();
        }

    }


text:
Q: Vite Error "Access is denied", when I make Vue3 apps using vite I tried to use vite to make vue3 apps.
but when I build vue3 apps, build error occurred and
no apps shown in browser.
my PC and node.js version
windows:10
"node":"v16.13.2"
"npm":"v8.1.2"

Basically I started make vue3 apps following the guide  and used CommandPrompt to make apps like below.
$npm create vite@latest my-vue-app -- --template vue
↓
$cd my-vue-app
↓
$npm install
↓
$npm run dev

and package.json like this.
{
  "name": "vue3testapps",
  "private": true,
  "version": "0.0.0",
  "scripts": {
    "dev": "vite",
    "build": "vite build",
    "preview": "vite preview"
  },
  "dependencies": {
    "vue": "^3.2.25"
  },
  "devDependencies": {
    "@vitejs/plugin-vue": "^2.3.0",
    "vite": "^2.6.14"
  }
}

after I command "npm run dev",
"Access is denied" was occurred in CommandPrompt.

I thought node.js and npm is ok because my other project
which is vue verison 2 is no problem and githun issues
arguing about node version, but my version is seems ok.
How can I fix the build problem?
Does anyone help me, please?


text:
Q: Sharepoint update field based on lookup I have a Sharepoint online list "myList" with fields PersonName, OriginCountry and OriginCity and another list of countries and cities called "WorldList" with columns Country and City.
In myList the user will select their city using a lookup to Worldlist.  I want the country field to update based on what is entered into the city field.
What's the best way to do this?
I would like to do this without a webPart, Powerapp or Flow, but will use them if necessary.  I would prefer to use a Flow rather than a Powerapp or webpart.

A: When you set the OriginCity lookup column in myList from WorldList, please add an additional column country as shown below:

If you don't want to show the additional column in list view, you can hide the column.
Then create a flow to update the OriginCountry value using the additional column "OriginCity:Country":

Simple test for your reference:

-------------------------Update----------------------------------
Note, exclude OriginCountry ID, other columns will use the property under "when you created or modified the item" option.


text:
Q: when i use a ENS name ,can't resolve it I'm trying to write my first etherjs code,get eth balance from viatalik.eth:
const balance = await provider.getBalance('vitalik.eth');

but it's failed:
Error: ENS name not configured (operation="resolveName(\"vitalik.eth\")", code=UNSUPPORTED_OPERATION, version=providers/5.7.1)
    at Logger.makeError (d:\sunflowerCode\etherjs\node_modules\@ethersproject\logger\lib\index.js:238:21)
    at Logger.throwError (d:\sunflowerCode\etherjs\node_modules\@ethersproject\logger\lib\index.js:247:20)
    at FallbackProvider.<anonymous> (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:1980:36)
    at step (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:48:23)
    at Object.next (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:29:53)
    at fulfilled (d:\sunflowerCode\etherjs\node_modules\@ethersproject\providers\lib\base-provider.js:20:58)
    at processTicksAndRejections (node:internal/process/task_queues:96:5) {
  reason: 'ENS name not configured',
  code: 'UNSUPPORTED_OPERATION',
  operation: 'resolveName("vitalik.eth")'
}

A: Ethers is able to connect to multiple providers and switch between them. So the getDefaultProvider() function only retrieves the default one.
You can specify the provider RPC URL (see example below) that is already connected to some network (e.g. the mainnet). Or you can connect to a wallet API (e.g. MetaMask in a frontend app), then your app uses the currently selected network of the wallet. If you didn't specify any provider or wallet API, ethers then tries to connect to your local node at http://127.0.0.1:8545 by default.
If your local node is not available or is not connected to the mainnet, it cannot retrieve the mainnet ENS records.
So the solution is to connect to a mainnet provider (or to a wallet that is connected to a mainnet provider), and then you can query the ENS.
const ethers = require("ethers");
const provider = new ethers.providers.JsonRpcProvider("https://mainnet.infura.io/v3/<your_api_key>");
const balance = await provider.getBalance('vitalik.eth');
console.log(balance.toString()); // outputs `1183955717666208782618` at the moment

Docs: https://docs.ethers.io/v5/getting-started/#getting-started--connecting


text:
Q: Java: ExceptionInInitializerError on program startup On start up, my program immediately throw an ExceptionInInitializerError.  The source is from this method:
public static void errorMessage(String input) {
    System.err.println("[ERROR] " + form.format(date) + " - " + Thread.currentThread().getStackTrace()[3].getClassName() + ": " + input);
}

I printed out the different parts of the string and found that the error is only thrown when I call form.format(date).  It says it is null.  The only problem is, both date and form are statically declared right above this method as so:
public static Date date = new Date();
public static DateFormat form = new SimpleDateFormat("HH:mm:ss");

The error suddenly started being thrown after some minor bug fixing.  I have no idea what is wrong or how something could be wrong with this.  I mean, I am calling on statically declared variables in the same class.  Technically, they should not be null, yet they are.  Anyone have any ideas why it is throwing this error?  Here is the console output:
java.lang.ExceptionInInitializerError
at A$$OpSystem.getOperatingSystem(A$.java:98)
at A_.<clinit>(A_.java:19)
Caused by: java.lang.NullPointerException
at A$.errorMessage(A$.java:72)
at A$.loadCursor(A$.java:84)
at A$.<clinit>(A$.java:62)
... 2 more
Exception in thread "main"

By the way, A$.OpSystem.getOperatingSystem is only being shown there because it calls A$.errorMessage...
And I have had this problem before, it was just when a statically declared variable was actually never declared an remained null when it was called.  Now it is not supposed to be null, yet it is.  So I have no idea what is causing it.  Ideas?
But I guess this is a good time to be educated on how static variables actually load...
EDIT: It seems as though no exception is thrown if I move the static Cursor object that calls 'loadCursor' to a different class.  What?
I made a test of this situation but it returns no error?
public class StaticMethodTesting {

public static int i = getInt();

public static int getInt() {
    return getAnotherInt();
}

public static int getAnotherInt() {
    return 0;
}

public static void main(String[]args) {
    System.out.println("Hi");
}
}

A: After examining your exception trace...
at A$.errorMessage(A$.java:72)
at A$.loadCursor(A$.java:84)
at A$.< clinit>(A$.java:62)

It becomes clear that some static field initialization in A$ is executing prior to the initialization of date and form and calling loadCursor, which then logically fails with NullPointerException as date and form are uninitialized.
The issue is that you've placed the the code which initializes your Cursor before that which initializes your date and form objects. Static fields with assignments at declaration time are initialized in declaration order, as per Section §8.3.2.1 of the Java Language Specification.
If you read the detailed initialization process, particularly Section §12.4.2.9, you find...

Next, execute either the class variable initializers and static initializers of the class, or the field initializers of the interface, in textual order, as though they were a single block.

So, you're likely doing something like this:
static Cursor cursor = loadCursor();
static Date date = new Date();
static DateFormat form = new SimpleDateFormat("HH:mm:ss");

static Cursor loadCursor() {
  ...
  errorMessage("...");
  ...
}

loadCursor must not be called before date and form are initialized if you wish for this to work.

The reason your example produces no 'error' (huh?) is because neither method refer to a yet uninitialized field. If you want equivalent behavior which is in no way an error, see the following (which can be seen run here):
import java.util.Random;

public final class Example {

  /* note if the below read: static final int value = rand.nextInt(),
     this would be considered an illegal forward reference to rand */
  private static final int value = next();
  private static final Random rand = new Random();

  private static int next() {
    return rand.nextInt();
  }

  public static void main(final String[] argv) { }
}

The output can be seen to be as follows.
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: java.lang.NullPointerException
        at Example.next(Example.java:11)
        at Example.<clinit>(Example.java:7)

A: I think you'll find the problem is occurring here
Thread.currentThread().getStackTrace()[3].getClassName()

You may need to do something more like
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
String className = stackTrace[Math.min(3, stackTrace.length - 1)].getClassName();

Or similar :P


text:
Q: Mongoose: does a custom _id need to be declared as an index and be unique Here is the common way to define a collection structure with Mongoose :
var UserSchema = new Schema({
    _id: Schema.Types.ObjectId,
    username: String,
    ...
});

And Now I want _id field declared as Number type :
var UserSchema = new Schema({
    _id: Number,
    username: String,
    ...
});

The problem is, do I need to declare more infomation about _id ? Such as :
var UserSchema = new Schema({
    _id: {type: Number, required: true, index: {unique: true}},
    username: String,
    ...
});

I am not sure whether MongoDB would do it automatically.
if you know the answer, could you leave a comment below ? Thank you!

A: Well, after some practice,  I realized that, MongoDB would set _id as PRIMARY KEY (NOT NULL + UNIQUE INDEX) automatically. So, just type:
_id: Number,
...


text:
Q: Is it possible to have custom content types in big commerce? For a bigcommerce site I'm working on we will need to have custom content types or something similar that would accomplish the same goal.
One example is we need a way for the admin to arbitrarily add locations that have the following fields: latitude, longitude, as well as text fields for facts.
I saw that there were ways that you could add ui fields to products
https://developer.bigcommerce.com/stencil-docs/configure-store-design-ui/defining-ui-options
But what I want to create is not a product. I want various types of posts with their own set of fields. Basically the same kind of features I would be able to find in something like Drupal.
Edit: Also I cannot use any outside cms. It can only be the bigcommerce cms alone


text:
Q: Bootstrap 3 multiple menus collapse into one for mobile I have been fighting with menus for a while now. What I want is both a top menu and a side menu. And in order to be useful on mobile devices, both menus need to collapse into something accessible on a phone. Is this actually possible? Or do I have to code different solutions for the different screen sizes?
Thanks

A: html

    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
      Toggle navigation

    </button>
    Brand

Link

Link

        Dropdown

Action

Another action

Something else here

Separated link

One more separated link

    <form class="navbar-form navbar-left" role="search">

        <input type="text" class="form-control" placeholder="Search">

      <button type="submit" class="btn btn-default">Submit</button>
    </form>

Link

        Dropdown

Action

Another action

Something else here

Separated link

content

Home

Profile

Messages

javascript
$('#bs-example-navbar-collapse-1').on('show.bs.collapse', function () {
  $('#bs-example-navbar-collapse-1').append($('#sidebar').html());
  $('#bs-example-navbar-collapse-1 ul').last().removeClass('nav-pills nav-stacked').addClass('navbar navbar-nav');
});
$('#bs-example-navbar-collapse-1').on('hidden.bs.collapse', function () {
  $('#bs-example-navbar-collapse-1 ul:last-child').remove();
});
$(window).on('resize', function () {
  if (window.innerWidth > 768) {$('#bs-example-navbar-collapse-1').collapse('hide');}
});

Example: http://bootply.com/106921
The (navbar) collapse triggers some events: hidden, hide, show and shown. (see: http://getbootstrap.com/javascript/#collapse) use this events to append the content of your side menu to the navbar. Remove it again on hidden: remove last append element jquery
Hide your side menu on small devices with the Responsive utilities (http://getbootstrap.com/css/#responsive-utilities).
The last "problem" collapse hide isn't triggerd on window resize will be solved here: https://github.com/twbs/bootstrap/issues/11653

A: I know this is an older post but still the best answer to a similar question I had present day, I had to modify one small thing though to make it work properly for me. Everything worked as intended except the line
$('#bs-example-navbar-collapse-1 ul:last-child').remove();

This would for some weird reason remove literally the last child of every ul in the menu so to correct it just added an id to the aside ul and used that selector to remove the menu which worked out a bit better especially if combining more than one menu. Thank you very much for the solution though! Bass Jobsen!
  Only going to post the modified lines since Bass already has the answer posted.
in the html:

and in the javsacript:
$('#bs-example-navbar-collapse-1 #sideMenu1').remove();


text:
Q: How do I insert a sentence into a string at a specific location? Let's say there is a line like this:
 Imperial 190  is a premium model, decoration of any promotion and a worthy personal gift. Soft, comfortable tight T-shirt, with a collar protected from deformation. It holds its shape perfectly and is ideal for applying a logo. The absence of side seams allows you to apply the image almost over the entire surface.

Tell me how this can be done? I wanted to do find ('.'), But it won't work, since the dot is also in the link
 Imperial 190

Expected output:
 Imperial 190  is a premium model, decoration of any promotion and a worthy personal gift. **[INSERTED TEXT]**. Soft, comfortable tight T-shirt, with a collar protected from deformation. It holds its shape perfectly and is ideal for applying a logo. The absence of side seams allows you to apply the image almost over the entire surface.

There will be a lot of such insertions.

A: You can first find the index of the first . which occurs after the  and append the text which you want to insert with the help of slicing. However, this depends on the assumption that the main text is always coming after an anchor tag....
text = "Text to be inserted."
to_parse = ' Imperial 190  is a premium model, decoration of any promotion and a worthy personal gift. Soft, comfortable tight T-shirt, with a collar protected from deformation. It holds its shape perfectly and is ideal for applying a logo. The absence of side seams allows you to apply the image almost over the entire surface.
'

index = to_parse.find(".", to_parse.find(""))
to_parse = to_parse[:index+1] + text + to_parse[index+1:]
print(to_parse)

You can adjust the spacing and/or fullstops which come before or after the inserted text as per your requirement by editing the slicing statement.


text:
Q: How to Stop Or Kill Or Terminate a Single Thread in ExecutorService or Job runs in the Thread? a. How to Stop Or Kill Or Terminate a Single Thread in ExecutorService ?
b. How to Stop Or Kill Or Terminate the Job which is running in ExecutorService instead of the
   Thread which is holding the job?
Thanks,
Kathir

A: It depends on what exactly you are doing in you job ( = in your Runnable / Callable -implementation). If you are processing a list of items, you could check for a cancel-flag in between (which should be declared as volatile).
You could also use cancel(true) on your future object (when you are submitting a callable), but this as well would require that you test for Thread.currentThread().isInterrupted() inside your job.

A: We also tracked the thread via socket programming.
Assume a call has been initiated from web app to third party application.
Initiating the request via a thread using socket programming
Whenever user wants to kill the thread, we can do it in socket programming as it holds the exact thread.
In Quartz there is no way we can kill a running thread.


text:
Q: How do I adjust the height of the pikaChoose plugin without ruining the width? I was religiously following this tutorial: http://www.icodeya.com/2012/08/grails-creating-image-gallery-feat.html on how to add an image gallery feature in grails. It works great and all, but I wanted to adjust the height of the main (big) image. I did it successfully, but when I upload an image which exceeds the default width, it ruins the whole layout. Like, a part of the image will overflow from the rest of the layout. I guess it's more of a css problem.. and I suck at CSS. The code is below. A good demo can be seen here:
http://www.pikachoose.com/ Note that if I change the width to 100%, it's the height that becomes inconsistent. :(
*upload an image if there's none and see for yourself.
Anybody wanna help me? :D
I offer free cookies. :) :)
@charset "UTF-8";
/* Just for the example. Fee free to delete these three lines */
body{font-family:Helvetica, sans-serif;}
a{color:white;}
.pikachoose {width: 800px; margin: 20px auto 20px auto;}

/* Style the thumbnails */
.pika-thumbs{ padding: 0 16px; height: 75px; margin-top: 10px; width: 100%;}
    .pika-thumbs li{ width: 144px; height:74px; margin: 5px; padding: 2px; overflow: hidden;
        float: left; list-style-type: none; background: #fafafa; border: 1px solid #e5e5e5; cursor: pointer;}
    .pika-thumbs li:last {margin: 0;}
    .pika-thumbs li .clip {position:relative;height:100%;text-align: center; vertical-align: center; overflow: hidden;}

/* The stage is the wrapper. The image fills 100% the height of the stage */
.pika-stage, .pika-textnav {width: 800px;}
.pika-stage {overflow:hidden; position: relative; background: #fafafa; border: 1px solid #e5e5e5; padding: 10px 10px 40px 10px; text-align:center; height:400px;}
.pika-stage img{height:100%;}

A: From looking at the demo, it looks like the stage for the main image is 800px so just add a max-width for your images that appear on the main stage:
.pika-stage img {
    height: 100%;
    max-width: 800px; /* Same width as the main stage so images don't stretch past */
}


text:
Q: Increasing resolution in AnatomicalData In version 10.3 one can get an image of an anatomical structure, such as a brain, using this code:
AnatomyData[Entity["AnatomicalStructure", "Brain"], "Image"]

Is there any way to increase the resolution of this image?  I've tried obvious methods such as PlotPoints, ImageSize and such, but none work.  The only approach that seems to work is to retrieve a full 3D model:
AnatomyData[Entity["AnatomicalStructure", "Brain"], "Graphics3D"]

But that stores far more information than I need.
I can try exporting the 3D image as 2D, but the ideal solution would be to work entirely in 2D and just get a higher-resolution image.
Any suggestions?


text:
Q: Asynchronous callbacks I've written a function which makes an asynchronous request using jQuery.
var Site = {

    asyncRequest : function(url, containerId) {
        $.ajax({
            url : url,
            onSuccess: function(data){
                $(containerId).html(data);
            }
        });
    }
}

Syntax might be slightly wrong as I'm using notepad, but hopefully you get the idea.
I call the function:
Site.asyncRequest('someurl', container1);
Site.asyncRequest('someurl', container2);

Both requests get sent and processed by the server. Two responses get sent back, which is what I expect. However, I would expect container1 and container2 to contain responses from both requests.
The problem, is that only the last response gets displayed and I can't figure out why. I don't know how the jQuery ajax keeps a track of requests/responses, so maybe this is a problem.
Say I make 5 or 10 requests, how does jQuery ajax know which response is for which request and where does it keep a track of it?
Thank you

A: This appears to be a Javascript scoping issue. Try the following:
var Site = {
    asyncRequest: function(url, containerId) {
        (function(theContainer) {
            $.ajax({
                url: url,
                onSuccess: function(data) {
                    $(theContainer).html(data);
                }
            });
        })(containerId);
    }
};

This creates a separate scope for each function call, so the actual value pointed to by "theContainer" is different for each onSuccess anonymous function.

A: What is happening here is a single closure is getting created, due to the way that function is declared.  See "A more advanced example" here:  http://skilldrick.co.uk/2010/11/a-brief-introduction-to-closures/
Basically, the containerId is being shared among all instances of that onSuccess anonymous function.  I haven't tested this, but I believe if you defined your asyncRequest function outside of Site, this would work.
As far as a more elegant solution to this problem, perhaps someone else will answer better.


text:
Q: Combining SQL Select statements into a single Select Statement? (Simplification.) I'm kind of a noob when it comes to SQL, so forgive me if this obvious.
I wanted to find duplicates of the Customer field, and the FULL records that had them.
Note: I am using MS SQL Server 2005.
I tried to implement the it as a single SQL Select statement before I came up with the following:
SELECT ModTab.* from modTab
    WHERE Customer IN (SELECT Customer
            FROM    ModTab
            GROUP BY Customer
            HAVING COUNT(Customer) > 1
        )
    ORDER BY Customer

Originally I tried a dozen differnt variations on something like:
SELECT ModTab.*
FROM    ModTab
GROUP BY Customer,<ALL other fields...>
HAVING COUNT(Customer) > 1

Is there something like the second approach which accomplishes the same thing?
(Plus the Group by clause seems someone pointless to me?  I'm not realclear on why it's needed or used.)

A: Try this:
select modTab.*
from ModTab
join (
  select Customer, count(*)
  from Modtab
  group by Customer
) B on B.Customer = ModTab.Customer
order b Customer

I believe this also now explains the need for the group by.

A: If using an RDBMS (such as SQLServer) that supports analytic functions, try:
select * from
(select m.*, count(*) over (partition by customer) cnt
 from Modtab m) ilq
where cnt > 1

Otherwise, try:
select m.*
from Modtab m
where exists
(select 1
 from Modtab l
 where m.customer = l.customer and m.id <> l.id)

(Replace id with the suitable primary key field for Modtab.)

A: WITH    numbered
AS ( SELECT   *, row_number() OVER ( PARTITION BY customer ORDER BY customer  ) AS nr FROM ModTab)
Select * from numbered WHERE   nr >1


text:
Q: WooCommerce add Product tag second description + create shortcode could be added in Elementor As I couldn't find any answer to my request on several websites, I hope to get help here to solve my problem. In fact, I would like to know how I can creat a shortcode to display the second description of product tag, which could then be added in page builder. I am using now Elementor Pro.
I found a solution for add the second description of product tag that works perfectly (here : https://businessbloomer.com/woocommerce-add-a-second-content-box-product-category-pages/) with changing product_cat_add_form_fields to product_tag_add_form_fields in the code.
But it is fixed below the product listings. Would be good if it had a [shortcode] and it could then be added in Elementor(on single Product page).
I'm newbie and i don't have too much knowledge about coding...I try to change the 4th function but it still doesn't  work. Hope that someone can help me!
 * @snippet       Add new textarea to Product Tag Pages - WooCommerce
 * @how-to        Get CustomizeWoo.com FREE
 * @author        Rodolfo Melogli
 * @compatible    WooCommerce 3.9
 * @donate $9     https://businessbloomer.com/bloomer-armada/
 */

// ---------------
// 1. Display field on "Add new product Tag" admin page

add_action( 'product_tag_add_form_fields', 'bbloomer_wp_editor_add', 10, 2 );

function bbloomer_wp_editor_add() {
    ?>

        <?php echo __( 'Second Description', 'woocommerce' ); ?>

      <?php
      $settings = array(
         'textarea_name' => 'seconddesc',
         'quicktags' => array( 'buttons' => 'em,strong,link' ),
         'tinymce' => array(
            'theme_advanced_buttons1' => 'bold,italic,strikethrough,separator,bullist,numlist,separator,blockquote,separator,justifyleft,justifycenter,justifyright,separator,link,unlink,separator,undo,redo,separator',
            'theme_advanced_buttons2' => '',
         ),
         'editor_css' => '',
      );

      wp_editor( '', 'seconddesc', $settings );
      ?>

<?php echo __( 'This is the description that goes BELOW products on the Tag page', 'woocommerce' ); ?>

    <?php
}

// ---------------
// 2. Display field on "Edit product Tag" admin page

add_action( 'product_tag_edit_form_fields', 'bbloomer_wp_editor_edit', 10, 2 );

function bbloomer_wp_editor_edit( $term ) {
    $second_desc = htmlspecialchars_decode( get_woocommerce_term_meta( $term->term_id, 'seconddesc', true ) );
    ?>

        <?php echo __( 'Second Description', 'woocommerce' ); ?>

            <?php

         $settings = array(
            'textarea_name' => 'seconddesc',
            'quicktags' => array( 'buttons' => 'em,strong,link' ),
            'tinymce' => array(
               'theme_advanced_buttons1' => 'bold,italic,strikethrough,separator,bullist,numlist,separator,blockquote,separator,justifyleft,justifycenter,justifyright,separator,link,unlink,separator,undo,redo,separator',
               'theme_advanced_buttons2' => '',
            ),
            'editor_css' => '',
         );

         wp_editor( $second_desc, 'seconddesc', $settings );
         ?>

<?php echo __( 'This is the description that goes BELOW products on the Tag page', 'woocommerce' ); ?>

    <?php
}

// ---------------
// 3. Save field @ admin page

add_action( 'edit_term', 'bbloomer_save_wp_editor', 10, 3 );
add_action( 'created_term', 'bbloomer_save_wp_editor', 10, 3 );

function bbloomer_save_wp_editor( $term_id, $tt_id = '', $taxonomy = '' ) {
   if ( isset( $_POST['seconddesc'] ) && 'product_tag' === $taxonomy ) {
      update_woocommerce_term_meta( $term_id, 'seconddesc', esc_attr( $_POST['seconddesc'] ) );
   }
}

// ---------------
// 4. Display field under products @ Product Tag pages

add_action( 'woocommerce_after_shop_loop', 'bbloomer_display_wp_editor_content', 5 );

function bbloomer_display_wp_editor_content() {
   if ( is_product_taxonomy() ) {
      $term = get_queried_object();
      if ( $term && ! empty( get_woocommerce_term_meta( $term->term_id, 'seconddesc', true ) ) ) {
         echo '
' . wc_format_content( htmlspecialchars_decode( get_woocommerce_term_meta( $term->term_id, 'seconddesc', true ) ) ) . '
';
      }
   }
};

//----------------------------------------------------------------------------------
// Here is my custom shortcode
// 4. Display shortcode

add_shortcode( 'custom_display_tag_seconddesc', 'custom_display_tag_seconddesc' );

function custom_display_tag_seconddesc() {
   if ( is_product_taxonomy() ) {
      $term = get_queried_object();
      if ( $term && ! empty( get_woocommerce_term_meta( $term->term_id, 'seconddesc', true ) ) ) {
         return '
' . wc_format_content( htmlspecialchars_decode( get_woocommerce_term_meta( $term->term_id, 'seconddesc', true ) ) ) . '
';
      }
   }
};
//----------------------------------------------------------------------------------


text:
Q: jQuery Web Socket not connecting and not sending I'm trying to convert a PHP function into a jQuery function so that I can use a TCP/IP socket local connection straight from the browser.
I use this:
$socket = @fsockopen('xxx.xxx.xxx.xxx', '8810', $err_no, $err_str);

if(!$socket){
    return 'Errore #'.$err_no.': '.$err_str;
}else{
    fwrite($socket, '["D";"C";"?ST";200]');
    $read = fread($socket, 2024);

     //other stuff...

    return $read;
    fclose($socket);

}

This works fine. I then downloaded the Github jQuery Websocket 0.0.4 from the Google Code site and followed the example but not successfully.
I just simply tried to make a connection and send data this way:
ws = $.websocket("ws://95.110.224.199:8810/");
ws.send('string', '["D";"C";"?ST";200]');

This gives me "undefined is not a function" error.
I then tried to see if the connection was actually establishing (without sending data) this way:
var ws = $.websocket("ws://xxx.xxx.xxx.xxx:8810/", {
    open: function() {console.log('WS:connesso')},
    close: function() {console.log('WS:chiuso')},
});

No luck for me... the console says nothin'...
Any hint or help on this? Any help is appreciated.

A: Maybe you missed the jquery.websocket.js file but you can use a javascript web socket:
ws = new WebSocket('ws://95.110.224.199:8810/');

Or you can put 0.0.0.0 in instead of your ip because some servers do not allow direct ip access:
ws = new WebSocket('ws://0.0.0.0:8810/')
ws.onopen = function(msg) {
    // Logic for opened connection
    console.log('Connection successfully opened');
};
ws.onmessage = function(msg) {
    // Handle received data
};

ws.onclose = function(msg) {
    // Logic for closed connection
    console.log('Connection was closed.');
}
ws.error =function(err){
    console.log(err); // Write errors to console
}

A: WebSockets doesn't allow you to connect to an arbitrary TCP server in the way fsockopen from PHP does. The server must also support the WebSocket protocol, in particular:

*If the server chooses to accept the incoming connection, it MUST
reply with a valid HTTP response indicating the following.
1.  A Status-Line with a 101 response code as per RFC 2616
    [RFC2616].  Such a response could look like "HTTP/1.1 101
    Switching Protocols".

2.  An |Upgrade| header field with value "websocket" as per RFC
    2616 [RFC2616].

3.  A |Connection| header field with value "Upgrade".

4.  A |Sec-WebSocket-Accept| header field.  The value of this
    header field is constructed by concatenating /key/, defined
    above in step 4 in Section 4.2.2, with the string "258EAFA5-
    E914-47DA-95CA-C5AB0DC85B11", taking the SHA-1 hash of this
    concatenated value to obtain a 20-byte value and base64-
    encoding (see Section 4 of [RFC4648]) this 20-byte hash.

    The ABNF [RFC2616] of this header field is defined as
    follows:

    Sec-WebSocket-Accept     = base64-value-non-empty
    base64-value-non-empty = (1*base64-data [ base64-padding ]) |
                             base64-padding
    base64-data      = 4base64-character
    base64-padding   = (2base64-character "==") |
                       (3base64-character "=")
    base64-character = ALPHA | DIGIT | "+" | "/"

(from the WebSocket protocol specification)
I suspect that the server you're trying to connect isn't a special WebSocket server, and thus doesn't reply with a HTTP response to the client's handshake.

A: Are you sure you are accepting connection in right way?
Please take a look at How to call a WebSocket programmatically (using PHP)?, there is something sent to the client at the beginning of exchanging data, maybe that's right direction.
If everything with your server is ok, then this script should work fine http://jsbin.com/qibevu/1/edit if you change echo websocket server to your own.

A: Personally, I recommend the pure javascript new WebSocket('ws://'); it's easy to use and will connect as long as there's a backend socket listening on the same address and port.


text:
Q: Why is splice deleting my entire array? I would only like to delete max if it is in position 0 I'm working on a leet code problem with the following instructions:
You are given an array prices where prices[i] is the price of a given stock on the ith day.
You want to maximize your profit by choosing a single day to buy one stock and choosing a different day in the future to sell that stock.
Return the maximum profit you can achieve from this transaction. If you cannot achieve any profit, return 0.
In my code below, I expect to remove the Max number from the array only if it's in index 0 of the array. When checking the debugger, I see that the entire array is deleted except  index 0. Why is splice not working as intended?
what debugger shows

var maxProfit = function (prices) {
  let theMin = Math.min(...prices)
  let minPosition = prices.indexOf(theMin)
  let theMax = Math.max(...prices)
  let maxPosition = prices.lastIndexOf(theMax)

  if (maxPosition === 0) {
    prices = prices.splice(0, 1)
    if (prices.length === 0) {
      return 0
    }

    maxProfit(prices)
  }

  return theMax - theMin
};

A: splice does not return a modified copy of the array. The array is modified in-place, and what is returned is the deleted subarray, if any.
In effect, your code is:
const deletedElements = prices.splice(0, 1);
prices = deletedElements;

You deleted the first element from the array, then replaced that array with another array which only contains the first element. Thus, it is not that only the first element is returned, as you claim. splice is working exactly as documented.

Also, prices.splice(0, 1) is more legibly written as prices.shift().


text:
Q: How does nuget execute entity framework's seed method via command line `I am using dapper as my ORM, and I've been a long time entity framework user. I'd like to execute a custom seed method of my own similar, to how entity framework code first works via nuget "update-database" but i'm not sure exactly how that works. I've searched through the package and looked at tools folder at the *.ps1 files and see in the help file that is included in the package that
The following Entity Framework cmdlets are used with Entity Framework
Migrations.

    Cmdlet              Description
    -----------------   ---------------------------------------------------
    Enable-Migrations   Enables Code First Migrations in a project.

    Add-Migration       Scaffolds a migration script for any pending model
                        changes.

    Update-Database     Applies any pending migrations to the database.

    Get-Migrations      Displays the migrations that have been applied to
                        the target database

I'm guessing the commandlets live inside of entityframework.powershell.dll?
my question is: is there a way i could toss a powershell file in with my dapper package to allow me to call seed-database within nuget, and then fire off a custom seed method similar to entity frameworks, and is the code for the entity framework commandlets "update-database" out there somewhere for me to see how they trigger the C# seed method.


text:
Q: Hover function для меню Есть структура:

$('li').hover(function(){
  $(this).addClass('active');
}, function(){
  $(this).removeClass('active');
});

Текст 1

Текст 2

Текст 3

Проблема: при наведении на
 второго уровня, активным становится и
 первого уровня.

A: Вы, батенька, наступили на очень большие грабли. Кроме шуток.
CSS наследование называется.
И универсального решения нет.
Но есть ньюансы.
К примеру использовать CSS псевдокласс :hover для выделения. Это будет 100% работать.


text:
Q: Check file type? I need to check a file's type on upload to make sure it's an image. What I'm thinking of doing is checking the MIME file type(from $_FILE) and then checking that against the extension. Something like:
function checkType($file){

    $ext = pathinfo($_FILES[$file]['name'], PATHINFO_EXTENSION);
    $mime = $_FILES[$file]['type'];

    if($mime == "image/jpg" || $mime == "image/jpeg"){

        if($ext == "jpg" || $ext == "jpeg"){
            return true;
        } else{
            return false;
        }

    }

    if($mime == "image/gif"){

        if($ext == "gif"){
            return true;
        } else{
            return false;
        }

    }

    if($mime == "image/png"){

        if($ext == "png"){
            return true;
        } else{
            return false;
        }

    }

}

Is this a good approach? Suggestions?
Also, how would I go about getting the width of the image before it's finally uploaded to the server?

A: You should never rely on the content type provided by $_FILE as it's set by the browser, not by your server.
If you're expecting images, you should use getimagesize() to get the type of the image.
Example:
$imagedata = getimagesize($_FILES['image']['tmp_name']);
$mime = $imagedata['mime'];

You should then make sure that $mime isn't empty and that it contains a mime type that you want.
Here's an example using the Google logo: http://codepad.viper-7.com/9GBDf9

A: No, its bad. Mime type could not match actual file contents. To be sure what kind of uploaded file you received (or if its actually an image) you need to check file contents.
Try function like getimagesize for example. If it will return valid data then you have an image.


text:
Q: Apply patch file to Magento core files I edit some core code of magento. After this I would like to patch all my edited files to the Magento directory.
My question is: How can I implement php patch with magento? Or how to create patch file with PHP.
Please help me.

A: Pathfiles are great way to record & distribute you local modifications. Creating a patch file is relatively easy, and applying a patch is even easier.
Before you begin, how did you retrieve Magento's source file?
If you've checkout the source code with SVN, generating a patch is pretty simple.
shell $> cd path/to/your/working/copy
shell $> svn diff > ~/Desktop/magento.path

However, if you downloaded Magento from an archive (tar,zip), you'll need to have the copy of the original files before comparing your revisions. I like to make a original file backup, cp source.php source.php.org, before I alter anything. Sometimes I forget, and I'll need extract the original source-code to a new directory for comparison. To generate a patch file by comparing two sources, use the diff command
shell $> diff -Naur path/to/original/copy path/to/your/working/copy > ~/Desktop/magento.patch

To apply your newly created patch, use the  patch command.
shell $> cd path/to/new/magento
shell $> patch -p0 < ~/Desktop/magento.patch

Piece of cake.
Now your question implied that you may want PHP to apply patches. If you comfortable with compiling PHP extentions, take a look at xdiff's xdiff_file_patch function. Else, simply run the previous commands through PHP's system or shell_exec methods.


text:
Q: Foreign Keys vs Joins Is it better to use foreign keys in tables or can the same results be achieved with joins?

A: Foreign keys are just constraints to enforce referential integrity. You will still need to use JOINs to build your queries.
Foreign keys guarantee that a row in a table order_details with a field order_id referencing an orders table will never have an order_id value that doesn't exist in the orders table. Foreign keys aren't required to have a working relational database (in fact MySQL's default storage engine doesn't support FKs), but they are definitely essential to avoid broken relationships and orphan rows (ie. referential integrity).

A: FOREIGN KEYs and JOINs  don't do the same thing!

*

*A FOREIGN KEY enforces data integrity, making sure the data conforms to some rules when it is added to the DB.

*A JOIN is used when you extract/query data from the DB by giving rules how to select the data.

*JOINs work if there are FK or not.

*FK's work if you extract data with or without JOINs.
CONCLUSION: FK and JOIN don't allow you to achieve the same goal!


text:
Q: How to returne the last occurrence of a field using bash script in a file containing a JSON Given the file containing this content:
{"CAMPOS":[{"CAMPO_ID":13071,"CAMPO_COD":"JJ1111-000","CAMPO_NAME":"Valor 1"},{"CAMPO_ID":13072,"CAMPO_COD":"JJ1111-004","CAMPO_NAME":"Valor2"},{"CAMPO_ID":13073,"CAMPO_COD":"JJ1111-01","CAMPO_NAME":"diversos valores"}, {"CAMPO_ID":13075,"CAMPO_COD":"JJ1111-02","CAMPO_NAME":"qualquer valor"}]}

How do I return the last occurrence of the CAMPO_ID value?

A: Use jq to process JSON files:
jq '.CAMPOS[-1].CAMPO_ID' file.json

The code is telling jq to select the value under the "CAMPOS" key, -1 means the last element in the array, and from it, it selects the CAMPO_ID key and returns its value.


text:
Q: Not able to add queries to firebase database I am currently showing users who have registered on to my app in the fragment.I am trying to implement queries onto firebase realtime database.It shows me no error neither my app crashes but my queries don't work.I am trying to add some queries on to my database but my my recyclerview show data without any query attached.

code
    public class UsersFragment extends Fragment {
    private RecyclerView recyclerView;
    private UserAdapter mUserAdapter;
    private List<User> mUsers;
    String TAG = "MyTag";
    ValueEventListener mValueEventListener;

    public UsersFragment() {
        // Required empty public constructor
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment

        View view = inflater.inflate(R.layout.fragment_users, container, false);
        recyclerView = view.findViewById(R.id.recycler_view);
        recyclerView.setHasFixedSize(true);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mUsers = new ArrayList<>();

        readUser();
        //RandomUsers();

        //query = .orderByChild("id").startAt(generateRandom()).limitToFirst(6);

        return view;
    }

    private void readUser() {

        final FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();
        DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Users");

        mValueEventListener = new ValueEventListener() {
            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                mUsers.clear();
                for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                    User user = snapshot.getValue(User.class);
                    Log.d("TAG", "mainActivityListener called");
                    //mUsers.add(user);

                    if (!user.getId().equals(firebaseUser.getUid())) {
                        mUsers.add(user);
                    }

                }
                mUserAdapter = new UserAdapter(getContext(), mUsers, false);
                recyclerView.setAdapter(mUserAdapter);
                mUserAdapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {

            }
        };
        reference.addValueEventListener(mValueEventListener);
        Query query=reference.orderByChild("First").equalTo("Arjun");
        query.addValueEventListener(mValueEventListener);

    }
}

A: You are using two valueeventlistener:
reference.addValueEventListener(mValueEventListener);
Query query=reference.orderByChild("First").equalTo("Arjun");
query.addValueEventListener(mValueEventListener);

If you want to filter according to the value of the First attribute, then just do the following:
Query query=reference.orderByChild("First").equalTo("Arjun");
query.addValueEventListener(mValueEventListener);


text:
Q: Error with hex encode in Python 3.3 I am trying modify code from this question to use in Python 3.3 (I installed Pillow, scipy and NumPy):
import struct
from PIL import Image
import scipy
import scipy.misc
import scipy.cluster

NUM_CLUSTERS = 5
print ('reading image')
im = Image.open("image.jpg")
im = im.resize((150, 150))      # optional, to reduce time
ar = scipy.misc.fromimage(im)
shape = ar.shape
ar = ar.reshape(scipy.product(shape[:2]), shape[2])

print ('finding clusters')
codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS)
print ('cluster centres:\n'), codes

vecs, dist = scipy.cluster.vq.vq(ar, codes)         # assign codes
counts, bins = scipy.histogram(vecs, len(codes))    # count occurrences

index_max = scipy.argmax(counts)                    # find most frequent
peak = codes[index_max]
colour = ''.join(chr(c) for c in peak).encode('hex')
print ('most frequent is %s (#%s)') % (peak, colour)

But I get this error:
Traceback (most recent call last):   File
"C:/Users/User/Desktop/pyt33_pic.py", line 24, in <module>
  colour = ''.join(chr(c) for c in peak).encode('hex') LookupError: unknown encoding: hex

What am I doing wrong?

A: In 2.x the codec "hex_codec" is aliased to "hex". This alias is restored in 3.4. A bigger change is that a buffer to bytes encoding requires using codecs.encode in Python 3. Additionally, for string formatting you'll need to decode the result. For example:
>>> peak
array([131, 128, 124], dtype=uint8)

>>> codecs.encode(peak, 'hex_codec').decode('ascii')
'83807c'

Alternatively you can use the format function to individually convert the numbers to hex:
>>> ''.join(format(c, '02x') for c in peak)
'83807c'