text:
Q: GCC inline assembly intel syntax "Error: invalid use of register" I decided to try using inline assembly in c for my basic operating system (using intel syntax because I am used to that with NASM). And I came across something I could not fix, I tried looking everywhere but nothing has worked. while trying the code shown after the error messages, GCC displays these messages:
main.c: Assembler messages:
main.c:8: Error: invalid use of register

The code being:
int main(){
    asm("mov ah, 0x00\n\t");
    asm("mov al, 0x13\n\t");
    asm("int 0x10\n\t");
    asm("mov bx, 0xA000\n\t");
    asm("mov es, bx\n\t");
    asm("mov di, 0\n\t");
    asm("mov byte [es:di], 0x0f\n\t"); // Problem line of error.
    while(1){
        asm("nop");
    }
    return 0;
}

Can someone help me?

A: Lots to mention about this.  First, you are using Intel syntax, which is fine (at least with GCC, it's harder with clang).  You can use -masm=intel when you compile it, or as a hack switch to .intel_syntax noprefix inside your asm template, then switch back to .att_syntax at the end of your asm string so the rest of the compiler's code still works.  (How to set gcc to use intel syntax permanently?)
Next, you have lots of asm() blocks.  It's probably better to have one, so you can specify inputs / outputs / clobbers / gotos for the entire block.  That can be done pretty easily, since C concatenates adjacent strings.
Your code has NASM-style [es:di] in it.  In GAS's dialect of Intel syntax, the segment name goes outside the brackets: es:[di].  I also note that [di] isn't going to be appropriate unless you are on a 16-bit architecture; the thing in square brackets must be the size of a pointer on the platform...
...However you are also using int 0x10, which is a BIOS interrupt, so I am guessing that 16-bits is actually what you intend here.
All that said, you do need to get in the habit of specifying clobbers.  That is, specify which registers your code modifies, and whether it modifies the condition code register and memory.  The compiler is making decisions about which variables to hold in registers, etc., and has no idea what your assembly code does.  You have to tell it you are modifying, for instance, ax, so it knows and can save/restore it.
GCC doesn't really know about segmentation (it's a portable compiler that assumes a flat memory model, not specializing in x86-16), so it's not really safe to leave es with a different base than ds.  e.g. GCC might choose to use rep stosd to initialize a struct or array.  It's safe here because your code after the asm is minimal.
Here's my rewrite of your code.
int main()
{
    asm volatile(
        ".intel_syntax noprefix\n\t"
        "mov ah, 0x00\n\t"
        "mov al, 0x13\n\t"
        "int 0x10\n\t"
        "mov bx, 0xA000\n\t"
        "mov es, bx\n\t"
        "mov di, 0x00\n\t"
        "mov byte ptr es:[di], 0x0f\n\t"
        ".att_syntax"                      // undo .intel_syntax
        : /* output operands */
        : /* input operands */
        : "ax","bx","di","cc", "memory" /* clobbers */
    );
    while(1){
        // asm("nop");  // unneeded: empty infinite loops are already legal in C.
    }
    return 0;
}

If your code modifies or even reads memory that you also access via C pointers, you would also include "memory" in the clobbers line.  See the documentation for inline assembly for gcc, and How can I indicate that the memory *pointed* to by an inline ASM argument may be used?
volatile is not strictly necessary here because with no output operands, the asm statement is implicitly volatile.  But it's a good idea to include volatile to make it clear (to human readers) that there's a visible side effect (the BIOS call, and storing to video memory).  So if you did include an output operand, it wouldn't get optimized away.
Addendum:
In general, use -masm=intel to compile, instead of using .intel_syntax in the listing.  That lets the compiler use the right syntax when substituting operands.


text:
Q: My function does not return anything no matter what I try def iq_test(numbers):
    i = 0
    length = len(numbers)
    numbers = numbers.split()
    ints = []
    even = []
    odd = []
    try:
        for i in range(i, length, i + 1):
            number = int(numbers[i])
            ints.append(number)
            if ints[i] % 2 == 0:
                even.append(ints[i])
            else:
                odd.append(ints[i])

    except:
        pass
    if len(even) > len(odd):
        return i
    else:
       return i

iq_test("1 2 2")

No matter how many times or ways I try to fix this it doesn't seem to return i. Whenever I do print(i) it gives me the exact thing I wanted and the function works well, but when it's return i I get nothing, how can I fix this?
Edit: this function is supposed to take in some numbers (in string format), one of those numbers will be different in evenness (one is even and the rest are odd and vice versa), I want to return the index of that number.

A: I have modified your code and it's working :
def iq_test(numbers):
     i = 0
     numbers = list(map(int,numbers.split()))
     even = []
     odd = []
     try:
         for i in range(len(numbers)):
            if numbers[i] % 2 == 0:
               even.append(i)
            else:
               odd.append(i)
     except:
         pass
     finally:
         if len(even) > len(odd):
            return odd[0]
         else:
            return even[0]
print(iq_test("1 1 2"))

Points I have modified :

*

*instead of creating another list for converting list elements to an integer you could just use the map function

*you should store the index of the even and odd value instead of the value itself

*And if there is something in the code that is necessary to do even if the error occurs you could use the finally block

A: def iq_test(numbers):
        numbers = numbers.split()
        length = len(numbers)
        ints = []
        even = []
        odd = []
        try:
            for i in range(0, length):
                number = int(numbers[i])
                ints.append(number)
                if ints[i] % 2 == 0:
                    even.append(ints[i])
                else:
                    odd.append(ints[i])
            if len(even) > len(odd):
                return even[0]
            else:
                return odd[0]
        except:
            pass

    ReturnedNumber = iq_test("1 2 2")
    print("Returned number from function:",ReturnedNumber)

redpajama_set_name: RedPajamaStackExchange


text:
Q: jquery cycle: Showing half og the next and previous slide? I am trying to create an image slider (with a header and description text for each image) with the jQuery cycle plugin. The basics are pretty straightforward and working. But I want to show half the previous and next image (only the image, not the header and text) from the current slide.
Any ideas on how to do this?

A: Not really a straightforward answer to your question, but before you end up in hours of trying to modify an existing plugin to do things it wasn't intended to do, i found out it is usually faster and more inspiring to use jQuery to create your own slider.


text:
Q: password is always passw0rd? Why? Per telecomworld:

FreePBX Operator Panel (FOP)
The secret code for performing transfers and hangups in the Flash
  Operator Panel is passw0rd (zero not the letter O)

I'm on Elastix 2.5 and am just curious about this -- it seems a questionable choice to set any password to a static value.  The MySQL password is set to this value for either FreePBX or PIAF (PBX In A Flash).
Why?
In Elastix 2.5 running elastix-admin-passwords --change invokes:
#!/bin/bash
clear
echo "This script resets your MySQL password. IT MUST BE passw0rd!"
echo "Script also changes your admin password for Elastix MT access."
read -p "To continue, press Enter. Otherwise, press Ctrl-C to abort."
echo " "
elastix-admin-passwords --change
echo " "
echo "Done. Access Incredible PBX at http://`/sbin/ifconfig eth0 | grep "inet " | cut -f 2 -d ":" | cut -f 1 -d " "`"
echo " "

I'm as much interested in how that came about as to whether or not it's a "good" idea.

A: With many programs (including MySQL), the default and sometimes only way to authenticate a user is to ask the user for a password. It works the same even if that user is actually another program: the server will still ask it for a password, and the program must know the answer.
The easiest way to ship a product with all the programs knowing the right passwords is to use a bunch of hard-coded (as in, part of the ISO image—the same for every install) ones—then you can just put them in the various config files (or worse, in the various programs' source code). An alternative is to generate unique, random passwords for each install and have the installer put them in the appropriate config files, but that's more work (though far more secure!).
A second reason for default passwords is to make writing documentation easy. "Log in at http://machine-ip-address/, user admin, password admin" is easy. (This doesn't apply to program-to-program passwords, of course).
The key thing about these passwords is that default passwords are always insecure. It does not matter if the default password is password, p455w0rd, or even j@'kNDv&178VGzsv; it is insecure. Its been published widely on the Internet, it is known to anyone who cares to do a slight bit of research, and it's probably on any password-guesser's wordlist. So it really doesn't matter security-wise what the default passwords are, and thus passw0rd (instead of password) is probably just a joke. The person who chose it knows its insecure (since its a default password), and makes a joke of "must contain letters and numbers" security requirements by putting a clearly insecure letters-and-numbers password.
So, yes, when technically possible, you should change default passwords. When it's not technically possible, you should ask why and think long and hard: is it really a good idea to run this software? And if you do decide to run it, make certain to control access some other way.

A: "passw0rd" was famously derived by the genius-level idea of corrupting the lowercase letter "o" in the trailing half of the single-word string "password" into a zero "0", thus resulting in the string "passw0rd".
The corruption hints the user of the need to choose an obfuscated password that would not necessarily occur to an intruder, or be found through a dictionary attack. The string "passw0rd" itself does not, however, achieve this, as the substitution "o" -> "0" is unfortunately common enough for password-cracking programs to attempt it, in addition to many similar variations.


text:
Q: Malloc outside of main() or any other function (i.e. at global scope) I wanted a heap allocated buffer common to a class (to use as a scratchpad during computations).  At some point I may free and then reallocate the buffer if it is not large enough.  I wanted the buffer to exist without having to call a "myclass::initialize();" in main();  I came up with the following code that compiles and works well for my purpose.
My questions are:  Why does this code compile correctly?  Why is malloc() allowed to be outside of main() or any other function?  Is the compiler interpreting this somehow and removing the malloc?
Code compiled on linux 64bit using "g++ example.cpp" and checked with valgrind
// example.cpp
#include <cstdio>
#include <cstdlib>

class myclass {
public:
   static char* pbuf;                     // buffer
   static unsigned int length;            // buffer length
   const static unsigned int chunk_size;  // allocation chunck size
};

// set constants and allocate buffer
const unsigned int myclass::chunk_size = sizeof(long unsigned int) * 8;
unsigned int myclass::length = chunk_size;  // start with smallest chunk
char* myclass::pbuf = (char*)malloc(sizeof(char)*myclass::length);

int main() {

   // write to buffer (0 to 63 on 64bit machine)
   for (int i = 0; i < myclass::length; i++) {
       *(myclass::pbuf+i) = i;
   }

   // read from buffer (print the numbers 0 to 63)
   for (int i = 0; i < myclass::length; i++) {
     printf("%d\n", *(myclass::pbuf+i));
   }

   free(myclass::pbuf); // last line of program
}

Thanks for the answers.  Sound like this is more common than I thought.  "Functions calls are allowed in static initializers". This leads me to a slightly modified version catching a possible malloc error:
#include <cstdio>
#include <cstdlib>

class myclass {
public:
   static char* pbuf;                     // buffer
   static unsigned int length;            // buffer length
   const static unsigned int chunk_size;  // allocation chunck size
   static void* malloc_buf(unsigned int);
};

// set constants and allocate buffer
const unsigned int myclass::chunk_size = sizeof(long unsigned int) * 8;
unsigned int myclass::length = chunk_size;  // start with smallest chunk
//char* myclass::pbuf = (char*)malloc(sizeof(char)*myclass::length);
char* myclass::pbuf = (char*)myclass::malloc_buf(sizeof(char)*myclass::length);

void* myclass::malloc_buf(unsigned int N) {
    void* buf = malloc(N);
    if (!buf) exit(EXIT_FAILURE);
    return buf;
}

int main() {

   // write to buffer (0 to 63 on 64bit machine)
   for (int i = 0; i < myclass::length; i++) {
       *(myclass::pbuf+i) = i;
   }

   // read from buffer (print the numbers 0 to 63)
   for (int i = 0; i < myclass::length; i++) {
     printf("%d\n", *(myclass::pbuf+i));
   }

   free(myclass::pbuf); // last line of program
}

A: It's just doing static initialization (initialization before main is called). Static initializers are allowed to call functions.

A: main() is just another function - which is why it has such specific requirements placed on it to allow it to be called properly.
Other things can and do happen before it gets called.  Static initialization among them.


text:
Q: Photos not appearing in dash home, photo lense If I load up ''Dash Home'' then click on the ''Camera'' photo lense, to view photos or search for photos it says theres no photos that match my search.
But if I search under the ''home/house'' icon photos are found.
Movies and Music work perfect.
Any one know how to solve it.
Thanks


text:
Q: Array Range and IsEmpty If Then Statement VBA. Overwrites everything instead of selectively inserting I'm brand new to VBA.  Got about 4 weeks under my belt so far. And this is the last portion of a long list of macros for completing data cleanup and analysis for a report. Maybe this isn't the best way to do this? I'm still new to this, so I'm open to other suggestions. But it needs to be a macro. This is basically what it looks like (the highlighted fields are filled with a vlookup, which is why I have two different arrays because they're not contiguous):
link to snip of the worksheet
The number of rows varies depending on the report. Sometimes its 4000 rows, sometimes its more, sometimes its less. But I've made sure that every column would be the same. We're trying to automate as much of it as we can so that we might be able to get some less-technical people to be able to run through the entire process. The first time I went through the process it took me 6 hours (although I was taking notes too).   For the senior person here it takes about 2 hours for each one, depending. We have somewhere around 300 of these to do before the end of the year.
Anyways, this code works, but it overwrites all of my iferror/vlookup results that I inserted.  I'm guessing my 'For Each If Then' statement is to blame.  But I've been working on this for a couple days, trying different ways to achieve this goal and this is closest that I've gotten.  Any help would be greatly appreciated.  I'm sure its something super simple...
Sub AutomateAllTheThings6()
Dim arr3() As String
Dim arr11() As String
Dim rng3 As Range
Dim rng11 As Range
Dim sourcerng As Range
Dim lastRow As Long
    Call OptimizeCode_Begin
        lastRow = Range("D1:D" & Range("D1").End(xlDown).Row).Rows.Count
        Set rng3 = ActiveSheet.Range("BH2:BJ2" & ":BH" & lastRow)
        Set rng11 = ActiveSheet.Range("BL2:BV2" & ":BL" & lastRow)
        Set sourcerng = ActiveSheet.Range("BE2:BF2" & ":BE" & lastRow)
        arr3() = Split("UNKNOWN,UNKNOWN,UNKNOWN", ",")
        arr11() = Split("UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, 00/00/0000, 00/00/0000, 00/00/0000, 00/00/0000, NEEDS REVIEW", ",")
            For Each cell In sourcerng
                If IsEmpty(cell) Then
                    rng3.Value = arr3
                    rng11.Value = arr11
                End If
            Next
    Call OptimizeCode_End
End Sub

A: You are refering to the whole range with:

rng3.Value = arr3

So when any are found blank the whole range gets set, not just that row.  We can do just that row by using Intersect
Intersect(rng3, ActiveSheet.Rows(cell.Row)).Value = arr3

Also, Your ranges are in error

Set rng3 = ActiveSheet.Range("BH2:BJ2" & ":BH" & lastRow)

would refer to range BH2:BJ2:BH100
Cahnge to:
Set rng3 = ActiveSheet.Range("BH2:BJ" & lastRow)

so:
Sub AutomateAllTheThings6()
Dim arr3() As String
Dim arr11() As String
Dim rng3 As Range
Dim rng11 As Range
Dim sourcerng As Range
Dim lastRow As Long
    Call OptimizeCode_Begin
        lastRow = ActiveSheet.Range("D1").End(xlDown).Row
        Set rng3 = ActiveSheet.Range("BH2:BJ" & lastRow)
        Set rng11 = ActiveSheet.Range("BL2:BV" & lastRow)
        Set sourcerng = ActiveSheet.Range("BE2:BF" & lastRow)
        arr3() = Split("UNKNOWN,UNKNOWN,UNKNOWN", ",")
        arr11() = Split("UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, 00/00/0000, 00/00/0000, 00/00/0000, 00/00/0000, NEEDS REVIEW", ",")
            For Each cell In sourcerng
                If IsEmpty(cell) Then
                    Intersect(rng3, ActiveSheet.Rows(cell.Row)).Value = arr3
                    Intersect(rng11, ActiveSheet.Rows(cell.Row)).Value = arr11
                End If
            Next
    Call OptimizeCode_End
End Sub

A: You can also use such version with arrays. Although in my code results are not pasted into arrays, the computing is done based on them, what makes code execute much faster than when operating on cells in range.
Option Explicit
Option Base 1

Sub AutomateAllTheThings6()

Dim arr3() As String, arr11() As String
Dim rng3 As Range, rng11 As Range, sourceRng As Range
Dim vSource As Variant
Dim nCounter1 As Long, nCounter2 As Long, lastRow As Long

    Call OptimizeCode_Begin

    Const firstRow As Long = 2

    With ActiveSheet
        lastRow = .Range("D1:D" & Range("D1").End(xlDown).Row).Rows.Count
        Set rng3 = .Range("BH" & firstRow & ":BJ" & lastRow)
        Set rng11 = .Range("BL" & firstRow & ":BV" & lastRow)
        Set sourceRng = .Range("BE" & firstRow & ":BF" & lastRow)
    End With

    vSource = sourceRng

    arr3() = Split("UNKNOWN,UNKNOWN,UNKNOWN", ",")
    arr11() = Split("UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, UNKNOWN, 00/00/0000, 00/00/0000, 00/00/0000, 00/00/0000, NEEDS REVIEW", ",")

    For nCounter1 = LBound(vSource) To UBound(vSource) 'loop through all rows in source range
        For nCounter2 = LBound(vSource, 2) To UBound(vSource, 2) 'loop through all columns in the row
            If IsEmpty(vSource(nCounter1, nCounter2)) Then 'if cell is empty
                rng3.Rows(nCounter1) = arr3
                rng11.Rows(nCounter1) = arr11
                Exit For
            End If
        Next nCounter2
    Next nCounter1

   Call OptimizeCode_End

End Sub


text:
Q: Rails 3 - doesn't load pages (nginx doesn't start) I'm sorry for my noob question, but i really don't understand what is wrong!
I want to run my app on vds. So, for that i use next:
Ubuntu 10.04
PostgreSQL 9.1
Rails 3.1.3
Ruby 1.9.3p27
Nginx 1.0.11 (installed/compiled by passenger)
Phusion passenger 3.0.11
Capistrano

So, i tried my configuration with small simple Rails app which has been created by Scaffold. So, this app works ok (it uses SQlite and shows all page).
Then i tried to launch my app which uses PostgreSQL. So, i uploaded it via capistrano and then printed
$ cap deploy:start
* executing `deploy:start'

And also on my server i print
service nginx restart

So, when i visit ip i only get main rails index page of my old app (if i launched very simple app before) or it shows that can't connect to server (otherwise), nothing more.
Also i tried that:
rails c production
> app.get("/")

Then i get:
User Load (4.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
  CACHE (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."id" IS NULL LIMIT 1
  User Load (0.0ms)  SELECT "users".* FROM "users"
 => 500

Also, when i try start or restart nginx for my app it doesn't want to work:
$ initctl list | grep nginx
nginx stop/waiting
$ service nginx start
nginx start/running, process 30746
$ initctl list | grep nginx
nginx stop/waiting

What is wrong?
My configurations files:
Nginx.conf:
user  root;

worker_processes  1;

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;

events {
    worker_connections  1024;
}

http {
    passenger_root /usr/local/rvm/gems/ruby-1.9.3-head/gems/passenger-3.0.11;
    passenger_ruby /usr/local/rvm/wrappers/ruby-1.9.3-head/ruby;

    include       mime.types;
    default_type  application/octet-stream;

    #log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
    #                  '$status $body_bytes_sent "$http_referer" '
    #                  '"$http_user_agent" "$http_x_forwarded_for"';

    #access_log  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    server {
        listen       80;
        server_name  localhost;

        # root and passenger i added.
        root /vol/www/apps/ror_tutorial/current/public                      #/current because of Capistrano
        passenger_enabled on;

        #charset koi8-r;

        #access_log  logs/host.access.log  main;

        # location / {
        #                       root   html;
        #                       index  index.html index.htm;
        #                    }

        #error_page  404              /404.html;

        # redirect server error pages to the static page /50x.html
        #
        error_page   500 502 503 504  /50x.html;
        location = /50x.html {
            root   html;
        }

        # proxy the PHP scripts to Apache listening on 127.0.0.1:80
        #
        #location ~ \.php$ {
        #    proxy_pass   http://127.0.0.1;
        #}

        # pass the PHP scripts to FastCGI server listening on 127.0.0.1:9000
        #
        #location ~ \.php$ {
        #    root           html;
        #    fastcgi_pass   127.0.0.1:9000;
        #    fastcgi_index  index.php;
        #    fastcgi_param  SCRIPT_FILENAME  /scripts$fastcgi_script_name;
        #    include        fastcgi_params;
        #}

        # deny access to .htaccess files, if Apache's document root
        # concurs with nginx's one
        #
        #location ~ /\.ht {
        #    deny  all;
        #}
    }

    # another virtual host using mix of IP-, name-, and port-based configuration
    #
    #server {
    #    listen       8000;
    #    listen       somename:8080;
    #    server_name  somename  alias  another.alias;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

    # HTTPS server
    #
    #server {
    #    listen       443;
    #    server_name  localhost;

    #    ssl                  on;
    #    ssl_certificate      cert.pem;
    #    ssl_certificate_key  cert.key;

    #    ssl_session_timeout  5m;

    #    ssl_protocols  SSLv2 SSLv3 TLSv1;
    #    ssl_ciphers  HIGH:!aNULL:!MD5;
    #    ssl_prefer_server_ciphers   on;

    #    location / {
    #        root   html;
    #        index  index.html index.htm;
    #    }
    #}

}

config/deploy.rb
set :user, "root"
set :rails_env, "production"

default_run_options[:pty] = true                                              # Must be set for the password prompt from git to work
set :repository,  "git://github.com/Loremaster/sample_app.git"

set :application, "ror_tutorial"
set :deploy_to, "/vol/www/apps/#{application}"

set :scm, :git
set :branch, "master"

server "188.127.224.136", :app,
                          :web,
                          :db, :primary => true

# if you're still using the script/reaper helper you will need
# these http://github.com/rails/irs_process_scripts

# If you are using Passenger mod_rails uncomment this:
namespace :deploy do
   task :start do ; end
   task :stop do ; end
   task :restart, :roles => :app, :except => { :no_release => true } do
     run "#{try_sudo} touch #{File.join(current_path,'tmp','restart.txt')}"
   end
end

A: Make sure you have your root route set in your routes file, and delete the index.html from the public folder, otherwise it will always render on your landing page.

A: I don't know anything about nginx, but just a hint:
Have you set up your PostgresSQL server properly?

A: I found what is wrong - i forgot about ';' in this string:
Nginx.conf:
root /vol/www/apps/ror_tutorial/current/public


text:
Q: removing a particular character in a string in linux sh scripts I am making a method for custom job creation in a crontab manager where it prompts the user for hours/min/month/date etc and then creates the first half of the crontab command using * when necesary or the user given value. My problem is with the asterix * character. Being a special character is causes unwanted behaviour. My solution was to use \*  and try to remove the \ from the completed string after its been put together and before I add the command part. I cannot figure out how to remove all the \ from the string; ive tried $string//\  and $string//"\" and other variations of it. Ive also tried newstring=$("oldstring" | \  ) and variations of it. Initially i was just building a string with a * or a variable containing it ($string$star$string). Also tried the ${string}*${string} approach. I am now stuck as to how to remove every \ from a string that looks somethinglike*: 00  \* \* 09 \*
the whole method is this:
echo "When would you like the job to occur? A for all"

echo "On which hour? A for every hour"
read hour

echo "On which minute? A for every minute"
read min
space=" "
if [ "$min" = "A" ]
then
minstring="Every minute"
minout="\*"
else
minstring=$min
minout=$min
fi

if [ "$hour" = "A" ]
then
hourstring="Every Hour"
hourout="\*"
else
hourstring=$hour
hourout=$hour
fi

timestring=$hourstring$space$minstring
frequency=$minout$space$hourout$space

echo "For which month 01-12. Or any other character for every month"
read month
monthout=$month
case $month in

01)
monthstring="January"
;;
02)
monthstring="February"
;;
03)
monthstring="March"
;;
04)
monthstring="April"
;;
05)
monthstring="May"
;;
06)
monthstring="June"
;;
07)
monthstring="July"
;;
08)
monthstring="August"
;;
09)
monthstring="September"
;;
10)
monthstring="October"
;;
11)
monthstring="November"
;;
12)
monthstring="December"
;;
*)
monthstring=" Every month "
monthout="\*"
;;
esac

echo "On partiular dates(date) or days of the week(dow) Or everyday(A)"
read choice
case $choice in
date)
echo "Which dates: "
read date

datestring="Date(s) ${date}"

frequency+="$date$space$monthout$space\*$space"
;;
dow)
echo "Which days. 1 for monday:"
read days
daystring="days ${days}"
frequency+="\*$space$monthout$space$days$space"
;;
A)
daystring="Every Day"
frequency+="\*$space$month\*$space"
;;
*)
echo "invalid input"
;;
esac

echo "Enter your command for: $timestring"
echo $monthstring
echo "On $daystring"
read command

fullcommand=$frequency$command
echo $fullcommand

A: # example, trim with "tr"
str='00  \* \* 09 \*'
echo str \""$str"\"
trim=$(echo "$str" | tr -d '\134')
echo trim \""$trim"\"


text:
Q: Subtract two columns and sum the result at run time I have two tables in MySQL which have a lot of data. I want to subtract two columns and show sum of the generated column...
Here is what I have
CREATE TABLE fin_invoice(
id MEDIUMINT NOT NULL AUTO_INCREMENT,
invoice_no INT,
total INT,
PRIMARY KEY (id)
) ENGINE=MyISAM;
INSERT INTO fin_invoice (`id`, `invoice_no`, `total`) VALUES (NULL, '1000', '1000'),
(NULL, '1001', '2000'),(NULL, '1002', '3000'),(NULL, '1003', '1200'),(NULL, '1004',     '2000'),
(NULL, '1005',   '1202'),(NULL, '1006', '220');

and table two is
CREATE TABLE fin_money(
id MEDIUMINT NOT NULL AUTO_INCREMENT,
fk_invoice INT,
amount INT,
PRIMARY KEY (id)
) ENGINE=MyISAM;

INSERT INTO `fin_money` (`id`, `fk_invoice`, `amount`) VALUES (NULL, '1', '100'),
(NULL, '2', '200'),(NULL, '3', '300'),(NULL, '4', '500'),(NULL, '5', '600'),
(NULL, '6',   '800'),(NULL, '7', '50');

table two(fin_money) is connected to table1(fin_invoice) with foreign key fk_invoice.so the relation is fin_invoice.id=fin_money.fk_invoice
i want to get this
+----+-------------+--------+------+---------+
| id |  total      | amount | bal  | running |
+----+-------------+--------+------+---------+
|  1 |        1000 |    100 |  900 |     900 |
|  2 |        2000 |    200 | 1800 |    2700 |
|  3 |        3000 |    300 | 2700 |    5400 |
|  4 |        1200 |    500 |  700 |    6100 |
|  5 |        2000 |    600 | 1400 |    7500 |
|  6 |        1202 |    800 |  402 |    7902 |
|  7 |         220 |     50 |  170 |    8072 |
+----+-------------+--------+------+---------+

where bal=total-amount and running is the sum of bal and running of previous id.like 900+0=900 and 1800+900=2700 and so on.

A: This should do it using a local variable to create a running total:
SELECT fi.id,
  fi.total,
  fm.amount,
  fi.total-fm.amount bal,
  @runTotal:=@runTotal+fi.total-fm.amount runTotal
FROM fin_invoice fi
  JOIN fin_money fm ON fi.id = fm.fk_invoice
  JOIN (SELECT @runTotal:= 0) r;

Here's the SQL Fiddle.
And the results:
ID  TOTAL   AMOUNT  BAL    RUNTOTAL
1   1000    100     900    900
2   2000    200     1800   2700
3   3000    300     2700   5400
4   1200    500     700    6100
5   2000    600     1400   7500
6   1202    800     402    7902
7   220     50      170    8072


text:
Q: Data not inserting in firebase database with JS Im trying to make a login form and i want that info to be save to my firebase database.
I have written the code but the data doesn't get added to my firebase
Here is the code html code

<input type="password" id="password"  placeholder="Ur password" required
style="background-color: white; border: none; top: 55%; left: 41.5%; position: absolute; width: 15%; height: 3%;">

<button id="register"  style="position: absolute; left: 48%; color: green; top: 60%; border-radius: 2%; border-color: green;" >Continue</button>

Here is the code i used to connect to firebase
<script src="https://www.gstatic.com/firebasejs/9.1.1/firebase-app.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.1.1/firebase-auth.js"></script>
<script src="https://www.gstatic.com/firebasejs/9.1.1/firebase-database.js"></script>

and here is the code im using to add the data to firebase:
<script id="main">
        const firebaseConfig = {

            ***The config info is here but i removed it for privacy reasons***

  };

  const app = initializeApp(firebaseConfig);
  var username, password;
  function ready (){
      username = document.getElementById('username').value;
      password = document.getElementById('password').value;
  }

  document.getElementById('register').onclick = function(){
      ready();
      firebase.database().ref('user/'+ username).set({
          user: username,
          pass: password
      })
  }

A: Are you sure the function is being triggered? If your button is in a form then it might trigger the default form submission. Also the set() method returns promise so try refactoring the function like this:
document.getElementById('register').onclick = async function() {
  // async function                           ^^^^^
  console.log('Register button clicked')
  ready();

  // add await
  await firebase.database().ref('user/'+ username).set({
    user: username,
    pass: password
  })

  console.log('Date Added To Firebase')
}

If the button is in a form as mentioned earlier, try setting the type like this:
<button id="register" type="button" ></button>


text:
Q: Compare array and delete duplicate I want to compare 2 array of different dimension and then eliminate the duplicate and put the result on array called tmp
Here is the code
ArrayList<String> list = new ArrayList<String>();
HashSet<String> tmp = new HashSet<String>();

try
{
    String query1="SELECT ID FROM Apps;";
        ResultSet rs = con.createStatement().executeQuery(query1);
        while(rs.next())
        {
            list.add(rs.getString("ID"));
            tmp.add(rs.getString("ID"));
        }

        for(int i=0;i < check.size();i++)//ciclo  le checkbox selezionate
        {
                check.get(i);
                String query="UPDATE Apps SET Authorized='1' WHERE ID=" +check.get(i);//vado ad eseguire la query di update
                pr=con.prepareStatement(query);
                pr.executeUpdate();
                tmp.add(check.get(i).toString());
        }

        System.out.println(tmp);

The content of the two arrays is:
check -> [1, 2]
list -> [1, 2, 3, 4, 5]

The result I want is tmp -> [3,4,5]
but the console show tmp -> [1,2,3,4,5]

A: You could add everything to a hashSet
    HashSet<String> h = new HashSet<String>();

    // Adding elements into HashSet usind add()
    h.add("Cats");
    h.add("Cats"):
    h.add("Dogs");

    System.out.println("List:" + h);

Output
List:[Dogs, Cats]

The hash set won't store any of the duplicates.

A: You can remove duplicates like this:
    public static void main(String[] args) {

    Set<Integer> tmp = new HashSet<>();
    List<Integer> check = new ArrayList<>();
    check.add(1);
    check.add(2);
    List<Integer> list = new ArrayList<>();
    for(int i = 1; i <= 5; i++){
        list.add(i);
    }

    tmp.addAll(list);
    tmp.removeAll(check);
    System.out.println(tmp);
}

A: Try this
public static void main(String[] args)
  {
    List<String> one = new ArrayList<>();
    one.add("one");
    one.add("two");
    one.add("three");
    one.add("in one");
    one.add("in two");

    List<String> two = new ArrayList<>();
    two.add("zero");
    two.add("one");
    two.add("two");
    two.add("four");
    two.add("not in one");
    two.add("in one");
    two.add("in two");

    // Depending on your needs create new or modify existing like one.addAll(two) and stream() from that.
    List<String> unique = one;
    unique.addAll(two);
    unique = unique.stream().distinct().collect(Collectors.toList());

    System.out.println("Unique list: " + unique.stream().collect(Collectors.joining(",")));
    // Unique list: one,two,three,in one,in two,zero,four,not in one
  }


text: Q: zarr get_coordinate_selection equivalent in xarray Is there an equivalent for zarrstore['param'].get_coordinate_selection()  in xarray?. Trying to use more xarray to replace the zarr, as I use zarr in the code mostly for this function.


text:
Q: getting error - Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first I want to play audio as an alert but I'm getting an error like "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.
HTML Code:
<audio id="alarm" src="alarm.mp3"></audio>

JavaScript Code:
function alarm() {
    var value = document.getElementById("rvoltage").innerHTML;
    if (value > 230) {
        document.getElementById('alarm').play();
    }
}

A: That is due to the fact that many browsers do not allow HTML elements to autoplay music and videos on page-load to save bandwidth etc. You could create a button and play the music on a click event or hack your way around it to make it play on any click event on your page.

Autoplay with sound is allowed if:
  User has interacted with the domain (click, tap, etc.).
  On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously play video with sound.
  On mobile, the user has [added the site to their home screen].

https://developers.google.com/web/updates/2017/09/autoplay-policy-changes


text:
Q: Take the Binary From Text Area and then Converting to Hexa I want to take a binary in the text area and convert it to hex. When calculated using the calculator, result is "E0AC882AA428B6B8", but with my code result is "30".
String str = txtXOR.getText();
char[] chars = str.toCharArray();

StringBuffer hex = new StringBuffer();
int x = chars.length;

for(int i = 0; i < x; i++){
  hex.append(Integer.toHexString((int)chars[i]));
  txtXORToHexa.setText(Integer.toHexString((int) chars[i]));
}

Could someone point out where I have gone wrong?

A: You should use Integer#parseInt(String s, int radix) with base 2 to parse the binary string and then use toHexString to get the Hex String:
String binaryStr = txtXOR.getText();
int number = Integer.parseInt(binaryStr, 2);
String hexStr = Integer.toHexString(number);
txtXORToHexa.setText(hexStr);

In case you must support very large number you can use BigInteger:
String binaryStr = txtXOR.getText();
BigInteger number = new BigInteger(binaryStr, 2);
String hexStr = number.toString(16);
txtXORToHexa.setText(hexStr);


text:
Q: Não conigo ler o array codificada com PHP em json Não estou conseguindo no jQuery Ajax ler este array codificado com PHP:
[{"voo_Cod":"1","voo_CidadeOrigem":"1","voo_CidadeDestino":"2","voo_Data":"2015-07-13 07:00:00","voo_Preco":"200"}]

Meu código no jquery,

Meu código em PHP:
 <?php
// header('Content-Type: application/json; charset=utf8');
require_once("./authSession.php");
require_once("./conf/confBD.php");
include_once("../html/cabecalho_main_Pessoal.html");

$nomeUser = ($_SESSION['nomeUsuario']);
 //teste
//print_r($_POST);// you will get an array of all the values

try{
    $conexao = conn_mysql();
}catch(PDOException $excep){
    echo "Erro!: " . $excep->getMessage() . "\n";
    die();
}

if(!empty($_POST['cidadeOrigem'])){
    $cidOrigem   =  utf8_encode(htmlspecialchars($_POST['cidadeOrigem']));
    $CidDestino  =  utf8_encode(htmlspecialchars($_POST['cidadeDestino']));
    //$passageiros =  utf8_encode(htmlspecialchars($_POST['Passageiros']));
    echo "Contém arquivos";
}else{ echo "Não contém arquivos";}

// Captura os voos disponiveis no banco de dados instrução SQL básica (sem   restrição de nome),
    $SQLSelect = 'SELECT * FROM voos WHERE voo_CidadeOrigem=? AND   voo_CidadeDestino= ?';

    //prepara a execução da sentença
    $operacao   =  $conexao -> prepare($SQLSelect);

    $pesquisar  =  $operacao -> execute(array($cidOrigem, $CidDestino));

    //$resultados =  $operacao -> fetchAll();//resultado antigo

    $resultados = $operacao->fetchAll(PDO::FETCH_ASSOC);//resultado com array associativo

    // fecha a conexão (os resultados já estão capturados)
    $conexao = null;

$dados_result = json_encode($resultados);
echo $dados_result;

?>

Minha reposta cria um loop, com as variáveis indefinidas.

Voo Data e Horario undefined Preco undefined

Contém arquivos
[{"voo_Cod":"1","voo_CidadeOrigem":"1","voo_CidadeDestino":"2","voo_Data":"2015-07-13 07:00:00","voo_Preco":"200"}]

No console log, exibe o codigo abaixo
 <!DOCTYPE html>

   <meta charset="UTF-8">
   <title>SISTEMA DAW TURISMO</title>

   <link rel="stylesheet" type="text/css" href="../CSS/estiloCabecalho.css">

   <link rel="stylesheet" type="text/css" href="../CSS/estilo_login_teste.css">

   <link rel="stylesheet" type="text/css" href="../CSS/estilo_cadastro.css">

   <link href="../css/starter-template.css" rel="stylesheet">

SISTEMA DAW TURISMO

Home

Reservas

Alterar Cadastro

Passagens

Hotéis

Listar Reservas

Sair

A: Se entendi bem o problema pode talvez ser no PHP, para isto adicione o cabeçalho no seu PHP assim:
dadosJSON.php:
<?php
header('Content-Type: application/json; charset=utf8');

//Resto do seu código PHP abaixo

Troque o charset conforme a necessidade
E eu recomendo usar uma boa indentação e sempre usar o var quando declarar variaveis, também recomendo sempre setar o .length em uma variavel e não dentro do loop e ao invés de alert use console.log para depurar o código:
    $(function() {
        $("#form").on("submit", function(event) {
            event.preventDefault();

            $.ajax({
                url: "dadosJSON.php",
                type: "post",
                data: $(this).serialize(),
                success: function(d) {
                    alert(d);

                    if (console) {
                        console.log(d);
                    }

                    if(d[0] && d[0].erro){
                        $("h2").html(d[0].erro);
                    } else {
                        var html = "", j = d.length;
                        for(var i=0; i < j; i++){
                            html += " Voo Data e Horario " + d[i].voo_Data;

                            html += " Preco " + d[i].voo_Preco;
                        }
                    }
                    $("body").html(html);
                }
            });
        });
    });

Note que agora o alert(d) vai mostrar [Object object]
Pra visualizar os dados enviados ao console use as teclas de atalho Command + Option + J (Mac) ou Ctrl + Shift + J (Windows/Linux).

Atualização
Conforme o output do console.log o arquivo dataJSON.php está retornando o corpo de um HTML.
Não se pode misturar HTML com JSON desta maneira, veja que você adicionou isto:
include_once("../html/cabecalho_main_Pessoal.html");

O que provavelmente é um HTML, mas a sua resposta tem que ser JSON, misturar HTML com JSON irá fazer com que o interpretador não consiga fazer o "parse" do json, então remova o que não vai usar.
Veja também que as mensagens de erro devem ser json, tente assim:
<?php
header('Content-Type: application/json; charset=utf8');
require_once("./authSession.php");
require_once("./conf/confBD.php");

$nomeUser = ($_SESSION['nomeUsuario']);
 //teste
//print_r($_POST);// you will get an array of all the values

try{
    $conexao = conn_mysql();
}catch(PDOException $excep){
    echo json_encode(array("Erro!: " . $excep->getMessage() . "\n"));
    die();
}

if(!empty($_POST['cidadeOrigem'])){
    $cidOrigem   =  utf8_encode(htmlspecialchars($_POST['cidadeOrigem']));
    $CidDestino  =  utf8_encode(htmlspecialchars($_POST['cidadeDestino']));
    //$passageiros =  utf8_encode(htmlspecialchars($_POST['Passageiros']));
} else {
   echo json_encode(array("Não contém arquivos"));
   die();
}

// Captura os voos disponíveis no banco de dados instrução SQL básica (sem   restrição de nome),
    $SQLSelect = 'SELECT * FROM voos WHERE voo_CidadeOrigem=? AND   voo_CidadeDestino= ?';

    //prepara a execução da sentença
    $operacao   =  $conexao -> prepare($SQLSelect);

    $pesquisar  =  $operacao -> execute(array($cidOrigem, $CidDestino));

    //$resultados =  $operacao -> fetchAll();//resultado antigo

    $resultados = $operacao->fetchAll(PDO::FETCH_ASSOC);//resultado com array associativo

    // fecha a conexão (os resultados já estão capturados)
    $conexao = null;

$dados_result = json_encode($resultados);
echo $dados_result;
die();
?>

A: A Resposta do @Guilherme é plausível, aparentemente é este o problema.
Como ele já pode ter resolvido seu problema, eu reescrevi seu código sem usar o $.ajax porque ele não é a melhor solução, eu não entendi muito bem o que seu código faz por completo, mas fiz algo meio semelhante e em GET, mas pode modificar pra POST se preferir, caso outro dia você queira adaptar ao seus projetos ou se alguém quiser utilizar algo mais limpo em jQuery
HTML:

<form id="exemplo">
<input type="submit" value="Simbora" />
</form>

SCRIPT:

PHP:
<?php
$data = (object)array("voo_Cod"=>"1",
                      "voo_CidadeOrigem"=>"1",
                      "voo_CidadeDestino"=>"2",
                      "voo_Data"=>"2015-07-13 07:00:00",
                      "voo_Preco"=>"200");

echo json_encode($data);

//Erro
/*
$erro = (object)array("erro"=>"Houve algum problema");

echo json_encode($erro);*/


text:
Q: Key out of range when adding element to a head of sorted set in java I'm trying to retreive head of the sorted set, assign it to the same variable and later on add some values to it but I receive java.lang.IllegalArgumentException: key out of range.
My code below
import java.util.SortedSet;
import java.util.TreeSet;

class StackOverflow{
    public static void main(String args[]){
        SortedSet<Integer> some_set = new TreeSet<Integer>();
        some_set.add(5);
        some_set.add(3);
        some_set.add(12);
        some_set.add(15);

        some_set = some_set.headSet(10);
        some_set.add(10);

        System.out.println(some_set);
    }
}

I read there is something like restricted range which is set by using headSet but I coudn't find the way to prevent this. Is there a way to have unlimited upper bound when using headSet or maybe set it after the assignment? The only solution I came up with is
import java.util.SortedSet;
import java.util.TreeSet;

class StackOverflow{
    public static void main(String args[]){
        SortedSet<Integer> some_set = new TreeSet<Integer>();
        some_set.add(5);
        some_set.add(3);
        some_set.add(12);
        some_set.add(15);

        SortedSet<Integer> temp_some_set = new TreeSet<Integer>(some_set.headSet(10));
        some_set = temp_some_set;
        some_set.add(10);

        System.out.println(temp_some_set);
    }
}

But this creates unwanted new sorted set with the elements from the head of previous set which slows the progam down when I have to do such operation houge amount of times.

A: I believe your usage of headSet is not correct.
It should be used to obtain the subset of values from the main set. Docs - here
I believe you are to use the last() method for your usecase.


text:
Q: Abstract class with inheritance classes and functions writing into separate vectors c++ Card game; I'm using abstract class for the "hands" which hold cards. The "hands" need to be slightly different but they share majority of the functions. So there is a Hand and a MasterHand which will inherit from the Hand and have an additional function. Everything goes through the deck which deals cards. My aim is to formulate the function within the Hand class in a way which allows writing into handV of the instance of the Abstract class that is called- regardless of it being Hand of MasterHand.. I've tried different methods but couldn't make any of them work.
class AbstractClass
{
    virtual ~AbstractClass(){}
    virtual void getCard(Card::card)=0 ;

};

class Hand:public AbstractClass
 {
 public:
    vector<Card::card> handV;
    virtual void getCard(Card::card k) override
    {
        writeIntoVector(k);
    }
    void writeIntoArray(Card::card g)
    {
        handV.push_back(g);
    }
};
class HandMaster:public Hand
{
    public:
    vector<Card::card> handV;
// now here I would like to use the functions from Hand, but make them write into HandMaster.handV rather than Hand.handV
};

class Deck
{
    void passCard(AbstractBase &x)
    {
        x.getCard(deck.back());
    }
};

int main
{
    AbstractBase* k=&h;
    Hand* p = static_cast<Hand*>(k);  // so I was trying to do it via casting in different convoluted ways but failed
    MasterHand h2;
    AbstractBase* m=&h2;
    d.passCard(*k); // here I'd like the card to be passed to Hand.handV
    d.passCard(*m); // here I'd like the card to be passed to MasterHand.handV
}

A: I added and simplified some of the code. But I will point you to some resources on polymorphism to get you started. I also remove the AbstractClass entirely since from an OOP perspective, you have objects that are Hands and another Master hand object.
https://www.tutorialspoint.com/cplusplus/cpp_polymorphism.htm
#include <vector>
#include <iostream>
//dummy class
struct Card{
    int x;
};

class Hand{
 public:
    Hand(){}
    std::vector<Card> handV;
    virtual ~Hand(){}
    virtual void getCard(Card k)
    {
        handV.push_back(k);
    }
    virtual void showHand()
    {
        for(std::vector<Card>::const_iterator it = handV.begin();
            it != handV.end();
            it++)
        std::cout << it->x << " ";
    }
};
class HandMaster: public Hand
{
    public:
    HandMaster(){}
    //add additional methods
};

class HandOther: public Hand
{
    public:
    HandOther(){}
    //add additional methods
};

class Deck
{
public:
    std::vector<Card> deck;
    Deck(){
        Card c;
        for(int i = 1; i <= 52; ++i){
            c.x = i;
            deck.push_back(c);
        }
    }
    void passCard(Hand *x)
    {
        x->getCard(deck.back());
        deck.pop_back();
    }
};

int main()
{
    Deck d;
    Hand* p = new Hand();
    HandMaster *m = new HandMaster();
    HandOther * o = new HandOther();
    for(int i =0; i < 5; ++i){
        d.passCard(p);
        d.passCard(m);
        d.passCard(o);
    }
    std::cout << "\nHand:";
    p->showHand();
    std::cout << "\nHandMaster:";
    m->showHand();
    std::cout << "\nHandOther:";
    o->showHand();

    std::cout << "\n";
    delete o;
    delete p;
    delete m;
}


text:
Q: Differential equation matching distances between points I am new to Differential Equations and am looking for some help regarding the following:
Find a differential equation the solutions to which describe the following curve: the sum of the tangential slope at point (x,y) on the curve and the slope between point (x,y) and (3,2) is exactly 1. Find the equation of the curve that passes through (0,0), while matching the criterion above.
I understand the theory, and I built the following solution:
$y'=1-\frac{(y-2)}{x-3}$.
An online differential equations calculator gave the solution
$y=\frac{x^2-2x+c_1}{2(x-3)}$.
As the curve has to pass through $(0,0)$, $c_1$ comes out 0, which leaves me with $y=\frac{x^2-2x}{2(x-3)}$.
While I think I have the right answer, what is bothering me is that I was not able to get from $y'$ to $y$ manually. It is my first week dealing with this topic, and I would like to gain this insight.
Many thanks!

A: On this one you can use an integration factor.
We have  $y'+a(x)y=b(x)$, where $a(x)=\frac1{x-3}$ and $b(x)=1+\frac2{x-3}$.
Use $e^{\int a(x)\operatorname dx}=x-3$.
Multiply through and rewrite, using the product and chain rules.
Get $\frac{\operatorname d}{\operatorname dx}((x-3)y)=x-3+2=x-1$.
Integrate: $\int\frac{\operatorname d}{\operatorname dx}((x-3)y)=\int( x-1)$.
Then by FTC, we get $(x-3)y+C=\frac{x^2}2-x$.
So $y=\frac{x^2-2x}{2(x-3)}+C$.


text:
Q: Group Managed Service Account (gMSA): get authorized hosts / install-adserviceaccount unknown error After having successfully created a Group Managed Service Account (gMSA) using the command below:
add-adserviceaccount -name gmsaAccount -PrincipalsAllowedToDelegateToAccount gmsaGroup -DNSHostName gmsaAccount.test.local

I am having trouble to have this account installed on the targeted hosts (members of gmsaGroup group). I wonder if the problem is not related to the hosts associated with the service account.
Is there a way (powershell command?) to verify which hosts are associated and authorized with a group managed service account.
I tried get-adserviceaccount -identity gmsaAccount | fl * but nothing related to hosts or principalsAllowedToDelegateToAccount is displayed.
For information, when i try to run the install-adserviceaccount on a target Windows2012R2 host, i get a useless "unknown error" message (no error code).

A: *

*Do you have at least one 2012 DC?

*Did you prep the domain with Add-KDSRootKey?

*After you added the computers to gmsaGroup, were they rebooted to get a new token that reflects the new group membership?

*When you create the account, I think you need to use "PrincipalsAllowedToRetrieveManagedPassword" instead of "PrincipalsAllowedToDelegateToAccount"

The cmdlet to create a new gMSA is "New-ADServiceAccount" not "Add-ADServiceAccount"
Process overview http://blogs.technet.com/b/askpfeplat/archive/2012/12/17/windows-server-2012-group-managed-service-accounts.aspx


text:
Q: PFConfig synchronous call quick question about PFConfig.
Unfortunately, I cannot get my current config in background so I need to call it when the app starts synchronously.
If the network is not available the app freeze on some version of iOS, I was wondering if there is some timeout I can set on the synchronous call.
Thanks

A: My main advice is to do the call asynch and design your UI to deal with it.  For example, a first-run-only view controller that says "hi" while it gets ready to run (and a requirement that user must have a network on first run -- highly probable if they just downloaded the app).
In other words, I think its a mistake to force the config call to be synchronous, but here's one way to do it...
- (PFConfig *)yuckyGetConfig {
    __block PFConfig *config;
    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);

    [PFConfig getConfigInBackgroundWithBlock:^(PFConfig *config, NSError *error) {
        config = config;
        dispatch_semaphore_signal(semaphore);
    }];

    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
    return config;
}

The idea is that dispatch_semaphore_wait is equivalent to a while loop (but executing far fewer instructions) until the getConfig block has executed.  (This idea thanks to @Rob, here, though the rest of his advice is particular to the document api).


text:
Q: Open Graph on mobile (iOS) I would like to realize an iPhone app with Facebook OpenGraph to push user activities directly in Facebook (for this part, it's OK). BUT, I would like to show friends activities for the same verb. In dev Facebook documentation, I don't find API to get friends activities...
Any ideas ?

A: GET /me/{namespace}:{action-type}
GET /me/{namespace}:{action-type}/{object-type}
Don't forget to ask for the permissions firends_actions:namespace
Namespace = namespace of your app

A: Find friends with the app (this gives you a nice tidy list)
Option 1. Use Fql.query so you can apply filters and get back only what you need...
Fql.query POST
SELECT uid, name, pic from user where uid in (select uid2 from friend where uid1=me()) and is_app_user=1", @"query

option 2. Use opengraph and get back a mother list of friends with their ID any fields you want to read (installed status shown)
GET me/friends&fields=installed

Then use the Friends list to download their {action-type} executions
Option1. Enumerate through your friends activity with this and then bare it all:
GET /friend_id/{namespace}:{action-type}

option 2. Force the user to browse the list of friends with the app...
They choose the friend and then ->
GET /friend_id/{namespace}:{action-type}

They get a list of that users last 25 actions.
It's how instagram works when you browse.
The thing we all want is to just have a feed with the last 25-50 actions by friends. Just like the activity plugin. At this point it seems like there is no way to get it. I spent hours searching and everyone ends up saying you need to do it manually on your own server. I wouldn't be surprised if this activity function is added to the graph sdk eventually. It's a reasonable request.


text:
Q: Replacing Text in PHP? I'm need of a tiny help.I have a get statement on my process form like this
<?php echo $_GET['search']?>

Now how do i put "+" sign in between the spaces.Because what my current code does is  just gets the data from the text of another form.
I would be glad if you could help.
Thanking You,

A: <?php echo str_replace(' ', ' + ', $_GET['search']) ?>

A: You can use the str_replace function this way:
$new_text = str_replace(' ', ' + ', $_GET['search']);

A: What about input that looks like
hello  world

(two spaces between the words)? Do you want to get hello +  + world ?
If not, I suggest to remove the white spaces from the beginning and the end of the string first and use a regular expression to substitute several following white spaces with one +:
preg_replace('#\s+#', ' + ', trim($_GET['search']))

A: This will allow you to modify a regex to match more than just spaces.
function insertPlusSign($str)
{
    $func = create_function('$c', 'return $c . '+' . $c;');
    return preg_replace_callback('/ /', $func, $str);
}

A: You could also use urlencode, which also encodes the string to be used in a query part of a URL
echo urlencode('word1 word2 word3 word4 wiérdText@');
// Output: word1+word2+word3+word4+wi%E9rdText%40

A: $newText=str_replace(' ', ' + ', $_GET['search']);
str_replace will replace the text as desired and save the new updated string in $newText


text:
Q: why getElementsByName is giving undefined value in javascript? Hi I have a dropdownlist as a column within a gridview. gridview has multiple rows.
In Page Source of this Page I see same Id for all the drodownlists of each row, but name is differenet. So I want to get the selected value of a dropdownlist in any nth row. So I'm trying to do the same by getElementsByName. But its giving undefind value.
Why its giving undefined value and how to achieve the desired results
var DropDown= document.getElementsByName('grvRewardRulesDetails$ctl03$StartHourDropDown');

A: Try
document.getElementByID('<%= StartHourDropDown.ClientID %>')

Your DropDownList(DDL) is inside a GridView.
Then you must try some other things. Try calling the Javascript on the onchange event of DDL
This link should help
http://forums.asp.net/t/1550471.aspx

A: Solved Issue.
getElementsByName returns array not a single value.


text:
Q: Displaying mysql data in html table PHP I have to make data from a MySQL table display in an HTML table.
I've got the code to where it will display the first of seven rows from the MySQL table, but it is repeating the row nine times, instead of displaying all seven rows.
What have I done wrong?
<?php
require 'database.php';

//get all product data
$query = 'SELECT * FROM products';
          $products = $db->query($query);
          $products = $products->fetch();
?>

    <!doctype html>

    <meta charset="utf-8">
    <title>SportsPro</title>

    <form id="Header" name="Header" method="post">
    <?php include 'header.php'; ?>
    </form>
    <form id="Content" name="Content" method="post">

    Code
    Name
    Version
    Release Date

    <?php foreach ($products as $product) { ?>

    <?php echo $products['productCode']; ?>
    <?php echo $products['name']; ?>
    <?php echo $products['version']; ?>
    <?php echo $products['releaseDate']; ?>
    <input type = "submit" value = "Delete" align = "right" >

    <?php } ?>

Add Product

    </form>
    <form id="Footer" name="Footer" method="post">
    <?php include 'footer.php'; ?>
    </form>

A: Why are you using $products?
FIX:
<?php
foreach ($products as $product) {  //See *$products as $product*, so no need to use $products below instead use $product
    echo "
";
    echo "". $product['productCode']. "	";
    echo "". $product['name']. "	";
    echo "". $product['version']. "	";
    echo "". $product['releaseDate']. "	";
    echo "<input type = \"submit\" value = \"Delete\" align = \"right\" >	";
    echo "
"
}
?>

A: You have to replace,
$products = $products->fetch();

with
$products = $products->fetchAll();

Inside td tags, you have,
<?php echo $products['productCode']; ?>

Change it to like below for all lines,
<?php echo $product['productCode']; ?>


text:
Q: GridViewRow FindControl query C# I am building a simple C# web app which will act like an online database for resources.
In my table, I have a category and author column.
When I click a category value in the table, the table will refresh showing only the categories that was selected.
To do this I used the following code:
GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;

Label category = (Label)clickedRow.FindControl("lbl_category");

String selectedCategory = category.Text.ToString();

string query =
("SELECT * FROM main WHERE category='" + selectedCategory + "' ORDER BY ID ASC");

This works fine for the first time I click a category/author. But after the table has refreshed, and select another category or author then the table shows the wrong record.
How can I solve this?
You can view the page here:   Try clicking at category 'Health' and then 'Puvent, Kevin'. The outcome is different to the one that was expected. I think
The question will probably make more sense once you see the page :)
EDIT - This is the gridview binding code:
<asp:TemplateField HeaderText="Category" ItemStyle-Width="15%">
<ItemTemplate>
<asp:Label ID="lbl_category" Text='<%# Bind("category")%>' runat="server" style="display:none;"></asp:Label>
<asp:LinkButton ID="lbl_linkCategory" Text='<%# Bind("category")%>' runat="server" OnClick="linkCategory" CommandArgument='<%# Bind("category")%>' />
</ItemTemplate>
</asp:TemplateField>

A: When you click on a category this changes the controls underneath. The control numbers changes. You reference that number and it is wrong, it needs to be constant and an ID of the table "main". You will have to find a way to assign the corresponding number to selectedCategory properly. You could do that by adding an attribute to the category-label, or check on what has been clicked. Like Finance => selectedCategory = 2, Health = 3, Family = 4 etc. Hopes it helps.

A: Using if (!IsPostBack) in Page_Load seemed to have solved the problem :)


text:
Q: django ifequal I need to make a links section for a django project that show only the non active links, ie. if i'm at home, the section only shows the about link and not the home link.
Im using something like this in my template:
{% ifequal item.url request.path %}
<a href = "{{item.url}}" > {{item.name}} </a>
{% endifequal %}

it works fine but, if for example I visit "/section/page/" the "section" link still showing and i don't want to this happen.
it was wordering if i can use something like:
{% ifequal item.url+* request.path %}

any body can give me a clue to solve this problem?
thanks in advance

A: I believe this website has the information you need.  Basically you create a custom template tag that allows you to use a regexp to match the url to the active link, just like you would with your urls.
You might have to modify it slightly to get the exact functionality you want, but this should give you a good start.


text:
Q: Importance of broker.id in kafka? We have broker.id property in kafka properties file.
What is the importance of broker.id and what if we assign same integer number to broker.id on all the kafka instance running on different vm.

A: From the Apache Kafka documentation:

The broker.id property is the unique and permanent name of each node in the cluster.

Broker id must be unique because this value is used in core Kafka algorithms (leader/followers).
On the flip side, each Kafka broker registers itself by Zookeeper using that broker.id value. This is an another reason why this value has to be unique: otherwise you'll get something like
java.lang.RuntimeException: A broker is already registered on the path /brokers/ids/0. This probably indicates that you either have configured a brokerid that is already in use, or else you have shutdown this broker and restarted it faster than the zookeeper timeout so it appears to be re-registering.


text:
Q: The last Saturday of a given month / year In Unix, I want to find the date (day of month) of the last Saturday of a given month and year. I know cal will give me the calendar for a given month / year. What is a good way to get the last Saturday?
Update: I'd like a solution that I could use to apply to any day of the week. For example, I could use the same method to find the date of the last Sunday or Wednesday as well.

A: Use awk for that. Consider this:
cal 5 2013 | awk 'NF>6{a=$7} END{print a}'

OUTPUT:
25

A: If you didn't want to just pipe/parse cal output, you could use an algorithm to determine the weekday of a date, then get the weekday for December 31st and move backward the number of days needed to make it a Saturday.
But parsing cal is probably simpler.

A: I have another answer for this question, which is a bit lengthy Bash script and not so efficient, but easy to understand. The basic idea is it to loop over the days 22 till 31 for the given month and year and check the day of the week for each of these days by date +'%u'. The last day for which this returns the wanted week day (e.g. Saturday) is stored in the variable RESULT_DAY,  which will contain the result after the loop.
#!/bin/bash

DAY_OF_WEEK=6 # 1=Monday, ..., 7=Sunday
THE_YEAR=2016
THE_MONTH=10

RESULT_DAY=0

YEAR_MONTH_STR=${THE_YEAR}"-"${THE_MONTH}  # Example value: "2016-10"

for DAYNO in 22 23 24 25 26 27 28 29 30 31
do
  DATE_TO_CHECK=${YEAR_MONTH_STR}"-"${DAYNO}
  DATE_RESULT=$(date --date=$DATE_TO_CHECK '+%u')
  if [ $? -eq 0 ]
  then
    if [ $DATE_RESULT -eq $DAY_OF_WEEK ]
    then
      RESULT_DAY=$DAYNO
    fi
  fi

done

RESULT_DATE_COMPLETE=${YEAR_MONTH_STR}"-"${RESULT_DAY}

echo -e "\nResult date (YYYY-MM-DD): "$(date --date=$RESULT_DATE_COMPLETE +'%Y-%m-%d (%A)')

We check for date's result code by checking $? for value "0", so we can ignore illegal days (e.g. 31st of February, which does not exist).
The 22nd day of a month is the earliest date we have to consider, because in the shortest month (February in non-leap years) this is the earliest day for the last occurrence of a e.g. Saturday.


text:
Q: Folder redirection php Ok so what I am trying to do is have multiple folders pull from one folder. So if I have this structure:
/test1/some_folder
/test2/some_folder
/test3/some_folder

I would want all of those folders named some_folder to read from a master directory. I dont need them to be able to go that specific url just need it to include the files from the main directory in each of those. Imagine I was setting up shared functions and just wanted to store them in one place but be able to include them on any site. I didnt know what to google (tried folder redirection but didnt seem right) so if anyone can offer a suggestion as to what to google or wants to provide an answer it would be appreciated.

A: Add all of them to include_path
See also: set_include_path()

A: If it's possible, your best bet is just using a symlink. Even most version control packages understand those. Be sure to set FollowSymlinks to true for Apache.


text:
Q: How use * ngIf to display a button if the key exists in ionic storage I working on a App that  pulls simple online,  json below.
json
this.itemList = {
  "list": [
    {
      title: "Power Audit",
      text: "666",
      textTwo: "",
      Type: "auditform-main",
      link: this.linkOne
    },
    {
      title: "FLHA Three",
      text: "999",
      textTwo: "",
      Type: "form-main",
      link: this.linkFive
    }
  ]
};

and then  an ion-card displays the the data.

Here is the html.
<ion-card  *ngFor="let data of itemList.list let i = index">
  <ion-card-content>

    Download {{data.title}}

      Check For storage key {{data.title}}

      Delete from storage {{data.title}}

</ion-card-content>

I have methods to (1) save the data to ionic storage, (2) Check if storage key exists, (3) Delete the storage key.
What I am trying to accomplish is hide the delete button if the storage key does not exist.  I have tried an *ngIf statement using the checkForKey() method but this just goes into an infinite loop.  I have also tried ngShow, but this also has not worked for me.  Any help would be greatly appreciated.
ts
saveData(data) {
  this.storage.set( data.Name, JSON.stringify( data.Sections )).then(() => {
    this.listKeys();
  });
};

checkForKey(data) {
  this.storage.get(data).then(value => {
    if(value){
      console.log("true");
      return true
    }else{
      console.log("false");
      return false
    }
  }).catch(err=>{
    console.log(err)
  })
}

async deleteKeyValue(value: string) {
  const alert = await this.alertController.create({
    header: 'Confirm Deletion!',
    message: 'Delete this item ?',
    buttons: [
      {
        text: 'Cancel',
        role: 'cancel',
        cssClass: 'secondary',
        handler: () => {
          console.log('Confirm Cancel: blah');
        }
      }, {
        text: 'DELETE',
        cssClass: 'delete',
        handler: () => {
          this.storage.remove(value).then(() => {
            this.listKeys();
          });
        }
      }

    ]
  });
  await alert.present();
}

A: You must never do this kind of method calls (i.e. checkForKey(data)) inside the Angular apps HTML template. Due to the change detection life cycle, it calls that method indefinitely and in the end, it directly leads to memory leaks and crashes the app.
You need to bring all the relevant data upfront here itemList.list and then use *ngIf like so:

 ....

Note: data.isTrue - this is just a fiction property. Just changes it according to your app.

A: What I ended up doing was using  *ngIf="i == data.task" in line thirteen.  So if the storage key does not exist
listKeys() {
  this.storage.keys().then((k) => {
    this.loop = k;
  });
}

no div *ngFor="let i of loop" shows up.
<ion-card *ngFor="let data of itemList.list let i = index">
  <ion-card-header>
    <ion-card-title  class = "linkCenter">{{data.task}}</ion-card-title>
  </ion-card-header>

  <ion-card-content>

ID: {{data.formID}}

Date: {{data.date}}

Auditors: {{data.auditors}}

Inspection Type: {{data.inspectionType}}

    <ion-button *ngIf= "data.downloadable == true" fill="outline" color="medium" (click)="saveData(data.link)" >Download</ion-button>

          <ion-button fill="outline" color="primary" (click)="openForm(data.Type, data.task)">  Open  </ion-button>
          <ion-button fill="outline" color="blackgreen" [disabled]="data.update == false" (click)="syncData()">Sync</ion-button>
          <ion-button fill="outline" color="danger" [disabled]="data.delete == false" (click)="deleteAudit( i )">Delete</ion-button>

  </ion-card-content>
</ion-card>


text:
Q: Java: Replace only exactly matching URL I want to replace only exactly matching link given in String.
My code is as follows:
String originalString = "ABC"
            + "Contact";

String replacedString = originalString.replace("http://example.com/", "link1");
System.out.println("Replaced String:" + replacedString);

replacedString = "ABCContact"

requiredString = "ABCContact"

I get Output as replacedString but required Output should be as requiredString.
Thanks in advance.

A: Replace the URL with the quotes:
String replacedString = originalString.replace("\"http://example.com/\"", "\"link1\"");
replacedString = replacedString.replace("\"http://example.com/contact/\"", "\"link2\"");

A: The problem is that http://example.com/contact/ contains http://example.com/.
Use this instead:
String replacedString = originalString.replace("http://example.com/contact/", "link2");
String replacedString2 = replacedString.replace("http://example.com/", "link1");

replacedString2 is the required output

A: working regex ishttp:\\/\\/example.com.*?(?=\\\\) in java. it matches all occurences of http://example.com and until the next backslash


text:
Q: Use stylelint to check if vendor prefixes exist I am looking for a way to prevent a Webpack/SCSS/Postcss/CSS pipeline to create css files without vendor prefixes.
We use autoprefixer to apply vendor prefixes. In the past this build had been accidently disabled and the IE 11 build was broken.
I understand that Stylelint has rules that check if there is a vendor prefix and then throw an error etc. Is there a way I can achieve the opposite with stylelint. I am open to write/extend a rule or plugin for that feature.
Alternatively: Any other solution not requiring Stylelint would be acceptable for me - as long as it has been proven to work.


text: Q: How to create a website link without the leading http:// I'm creating a merge document. My only remaining problem is with websites. InDesign doesn't seem to want to create a link unless "http://" is included with the address, but the world knows that http:// is the beginning of the address, and since http:// is pretty ugly, I'd like to create linked text without the http://.


text:
Q: Colors change when rendering from After Effects I have a video composition in AE CC and want to export it. However, when the video is exported, the colors look different than what displays in AE. Interestingly enough, this problem only happens with codecs without alpha (RGBA) that only work with RGB. I need to export this to a RGB codec.
I have tried all sorts of stuff with working spaces in both the project settings and export settings and am quite sure the problem has to be elsewhere.
This is how AE displays the video and this is how I want my exported video to look: https://www.dropbox.com/s/5nb80vt8721mm8g/AE.jpg
and this is how the exported file looks: https://www.dropbox.com/s/9uudws2miux6pxu/Export.jpg
Note the difference is not only in the darkness, but also in the tone of the colors.
I'm using Media Player Classic and Windows Media Player 12, since I got to be able to play this in PowerPoint. At the moment, I'm exporting to H.264, but I also tried a lot of other codecs - DXV, XviD, WMV, ...
I would be very grateful if somebody could help me with this.
Note: Due to some specific plugins, I cannot export this to a premiere project, so that's not a solution either.
Thanks,
Ondrej

A: The colours were pretty much right when I did the following:

*

*In the render queue window, click "Lossless" to open the output
settings of that video

*Click Format Options… in the Video Output settings  Choose H.264.

*Render the video.

It occurred to me that Quicktime player tends to show washed colours unlike other players.

A: After some time, these are my conclusions:

*

*the issue is related to the source and export video codecs operating in different color spaces (YUV vs. RGB); the color problem is based in this and also resides in the fact that H.264 cannot work with an alpha channel.

*although exporting the video to QuickTime with some alpha-capable codec like Animation or Lagarith, the resulting video with 1 hour is way too big for me

*I ended up exporting to H.264 after all and will be applying some color changing effects in Premiere during final processing steps.

This is not the ideal workflow to say the least. I will have to take a look and find a way to avoid using After Effects for this.
Thanks for the comments, people.
Ondrej


text:
Q: Can OCKCarePlanStore queries in Apple's CareKit be run off the main queue? On GitHub, the documentation for CareKit includes a sample app called "Sample". Within Sample, the file QueryActivityEventsOperation.swift includes a line of code with the following comment:
// <rdar://problem/25528295> [CK] OCKCarePlanStore query methods crash if not called on the main thread

I've been searching, but I can't find this Radar issue documented anywhere. Does anyone know if OCKCarePlanStore query methods are still limited to running in the main queue?

A: OCKCarePlanStore queries can be run off any queue. As seen on GitHub, the thread is only checked twice: when creating the store and in one of the unit tests.
This means that the only call restricted to the main thread is initWithPersistenceDirectoryURL:. Any other method can be called on any thread.


text:
Q: Asset pipeline precompile issue when deploying to heroku I have built a Rails 4 and I am now trying to deploy to Heroku.
When I run the git push heroku master command, the process shuts down when Heroku runs rake assests:precompile. I get the following error message:
Sass::SyntaxError: Invalid CSS after "... "bootstrap" */": expected "{", was ""
I am at a loss of where to find this error in my code. I have included the bootstrap-sass gem in my gem file, but I have also included the entire css folder from the download provided by Bootstrap in my assets/stylesheets folder.
Below is what I have required in my application.css.sass file:
*= require font-awesome
*= require_tree .
*= require_self
*/

@import "bootstrap-sprockets";
@import "bootstrap";

As a final note, I have also precompiled locally using the rake assets:precompile command. In addition, I have set config.assets.compile equal to true in my application.rb file, as well as uncommenting config.assets.css_compressor = :sass.
Any guidance would be greatly appreciated.

A: Remove the */ from your code (right below *= require_self). That is what the error is referring to (though it isn't very clear).


text:
Q: How to make regular expression only accept special formula? I'm making html page for special formula using angularJS.
<input ng-model="expression" type="text" ng-blur="checkFormula()" />

function checkFormula() {
  let regex;

  if (scope.formulaType === "sum") {
    regex = "need sum regular expression here"; // input only like as 1, 2, 5:6, 8,9
  } else {
    regex = "need arithmetic regular expression here"; // input only like as 3 + 4 + 6 - 9
  }

  if (!regex.test(scope.expression)) {
    // show notification error
    Notification.error("Please input expression correctly");
    return;
  }

  // success case
  if (scope.formulaType === "sum") {
     let fields = expression.split(',');
     let result = fields.reduce((acc, cur) => { return acc + Number(cur) }, 0);
     // processing result
  } else {
     // need to get fields with + and - sign.
     // TODO: need coding more...
     let result = 0;
     // processing result
  }
}

So I want to make inputbox only accept my formula.
Formulas are two cases.
1,2,3:7,9

or
4-3+1+5

First case, means sum(1,2,3,4,5,6,7,9) and second case means (4-3+1+5).
But I don't know regular expression how to process it.
I searched google, but I didn't get result for my case.
So I want to need 2 regex match.

A: 1,2,3:7,9

Fot this pattern, you can try this one:
^\d+(?::\d+)?(?:,\d+(?::\d+)?)*$

*

*^\d+(?::\d+)?

matches string starts with a number(e.g. 1) or two numbers separated by a column (e.g. 1:2)

*

*(?:,\d+(?::\d+)?)*$

repeats the previous pattern with a comma in front of it as many time as possible until meets the end of the string (e.g. ,2:3,4:5,6)

4-3+1+5

Fot this pattern, you can try this one:
^\d+(?:[+-]\d+)*$

*

*Like the previous one, this is much simpler

*^\d+

starts with a number(e.g. 12)

*

*(?:[+-]\d+)*$

repeats the previous pattern with a - or + in front of it as many time as possible until meets the end of the string (e.g. +2-3+14)

Also, if you need at least one pair of numbers.
Such as 1,2 is allowed but just 1 is not. You can just change the * before $ to +:
^\d+(?::\d+)?(?:,\d+(?::\d+)?)+$

^\d+(?:[+-]\d+)+$

And if you allow white spaces in between them:
^\d+(?:\s*:\s*\d+)?(?:\s*,\s*\d+(?:\s*:\s*\d+)?)+$

^\d+(?:\s*[+-]\s*\d+)+$


text:
Q: How can i create a new object in a class?(c++) Good evening every body~
As the title, How can i create a new object in a class? and i want to give it a number.
How can i do that?
Thank you very much~

A: class MyClass {
    int yourNumber;
};

or what do you mean?


text:
Q: Kubuntu 16.04 no wifi driver not ethernet port Hey guy how do I install the wifi drivers without internet to my laptop that recently installed kubuntu and wifi does not work. My laptop has not ethernet port and I do want to run kubuntu, help please.

A: Do you have a smartphone with an active internet connection? If you have, then you can use your phone's internet through USB cable. You only need to turn on USB tethering and connect it to your Kubuntu PC. Or another way is to connect through Bluetooth by turning on Bluetooth tethering.
To install wifi driver, first of all, check which brand's adapter you have through the command lsusb, you will get the list of all the USB devices installed on your computer.

Here, in my case, I have a Realtek adapter, so I have installed the RTL driver.
You may have Broadcom or maybe another adapter.


text:
Q: Angular: How to handle null value in angular material table I wanted to apply css class based on the status. Eg: if status is Pass, css class .dot .pass should be assigned to span in html. How I can handle the null value if api return status: null. I'm getting this error message ERROR TypeError: Cannot read property 'css' of undefined. I belived this was caused by null value in status.
status.constant.ts
export const STATUSES_KEY = {
  notChecked: 'NOT_CHECKED',
  pass: 'PASS',
  na: 'NA',
  fail: 'FAIL'
};

export const STATUS_STYLING = {
  [STATUSES_KEY.notChecked]: {
    text: 'Not Checked',
    css: 'dot notChecked',
  },
  [STATUSES_KEY.pass]: {
    text: 'Pass',
    css: 'dot pass',
  },
  [STATUSES_KEY.fail]: {
    text: 'Fail',
    css: 'dot fail',
  }
};

app.ts
  generateStatusClass(status: string) {
    if (status) {
      return STATUS_STYLING[status].css;
    } else {
      return;
    }
  }

app.html

A: In your generateStatusClass(status: string) method you are checking if status is truthy, but not if there is a value for the status in your dictionary (for example na is not present). Change the code to something like this;
 generateStatusClass(status: string) {
    if (status && STATUS_STYLING[status]) {
      return STATUS_STYLING[status].css;
    } else {
      return;
    }
  }

Also, I am not sure if class={{...}} works. You might want to change this to ngClass, like this;


text:
Q: How to combine 2 columns with different names to fill the nulls of the first with the values of the second? i have this df:
           country  customer_id   invoice   price   stream_id   times_viewed    year    month   day total_price StreamID    TimesViewed
0   United Kingdom  13085.0        489434    6.95       85048           12.0    2017       11   28          NaN      NaN            NaN
1   United Kingdom  NaN            489597    8.65       22130            1.0    2017       11   28          NaN      NaN            NaN
2   United Kingdom  NaN            489597    1.70       22132            6.0    2017       11   28          NaN     NaN              NaN
3   United Kingdom  NaN            489597    1.70       22133            4.0    2017       11   28          NaN     NaN             NaN
4   United Kingdom  NaN            489597    0.87       22134            1.0    2017       11   28          NaN     NaN             NaN

The columns stream_id and StreamID are in fact the same thing. The df i have is much larger and it was created by chunks. The problem came that when reading those chunks, some of them had the column name as stream_id and some others had StreamID instead, so when putting all the chunks together using pd.concat the final result look like this.
What i would like to do is to fill the null values of StreamID with the values of stream_id when this last one is not null. I'm not sure if this is the right approach or there is a more efficient way of solving this problem.
The same problem occurred with the times_viewed and the TimesViewed columns, so the same solution would apply for this one too.
I tried using np.where like this:
df['new_col'] = np.where(df['StreamID'].isnull(), df['stream_id'], df['StreamID'])

But i'm not sure if this is right or if there is a better way to do it. Could someone please help me solve this?
Thank you very much in advance.

A: I finally got it solved by progressively renaming the wrong column names after checking they exist, then added each df created from each file to a temporary list that got concatenated in the end, giving the final result:
import glob
import pandas as pd

files = sorted(glob.glob(os.getcwd() + "/data_dir/*.json"))

df_list = []

for i in files:

    temp_df = pd.read_json(i)

    if 'StreamID' in temp_df.columns or 'total_price' in temp_df.columns or 'TimesViewed' in temp_df.columns:

        temp_df.rename(columns = {'StreamID': 'stream_id', 'total_price': 'price', 'TimesViewed': 'times_viewed'}, inplace = True)

    df_list.append(temp_df)

df = pd.concat(df_list, axis = 0)

It totally solved the issue of duplicated columns with wrong names. Hopefully, this will help someone.


text:
Q: PERL Can't locate object method "echo" via package "IO::File" at ./echo.pl I'm learning Perl by following the book "Learning Perl the Hard Way" by Allen B. Downey. It instructs me to execute the following code "echo.pl":
#! /usr/bin/perl

use strict;

sub echo {
    my @params = @_;
    print "@params\n";
}

echo ARGV

Testing the code returns:
$./echo.pl TEST NOW
Can't locate object method "echo" via package "IO::File" at ./echo.pl
line 10.

It should return:
TEST NOW

What is wrong?

A: echo ARGV

is interpreted by Perl as "indirect object notation", i.e. the same as
ARGV->echo

ARGV
 is a special file handle, its methods come form IO::File - but there's no echo method there.

A: The book is online here. This program is on page 4 (going by the page numbers). It is:
sub echo {
    print "@_\n";
}
echo @ARGV

So this is just a typo. You have ARGV where you wanted @ARGV.
That book is from 2003. A lot has changed in Perl since then. You might well be better off looking at Modern Perl instead.

A: what you are looking for should be this.
#!/usr/bin/perl
use warnings;
use strict;

sub echo {
     my @params = @_;
     print "@params\n";
}

echo(@ARGV);


text:
Q: set source ip for remote rsyslog I am using rsyslog-8.22 on my product. Is there a way for me to set the source ip when forwarding a message to a remote server ?
I need this since the remote server is running a firewall which is opened to a specific interface, I'd like to be able to specify this IF when forwarding messages.
Thanks,
Ran


text:
Q: Stata spmap legend key symbol and legend text off not aligned I am creating a filled geographical map. I think I have what I want, but for some unexplained reasons, the legend key and the legend text are not in the same line. Would anyone know what is the issue? I have put a blue line at the bottom of the legend to show that the legend text and key symbols are not aligned.
See here in this map
Additionally, I found it very odd that I had to start the labelling from "2" instead of "1". What could be the reason for that?
This is the code used to generate the map:
spmap predictions using "$shape/district polygons.dta", ///
id(id)  ///
title("TEST predictions") ///
label(data("district predictions.dta")  ///
    xcoord(x_coord) ycoord(y_coord) label(DISTRICT) ///
    pos(0) size(*0.9))  ///
clmethod(custom)    ///
clbreaks(0 (5000) 30000)    ///
fcolor($colorscale_stata)   ///
legorder(lohi)  ///
legend(pos(11) col(1) rowgap(0.3) size(*1.6) margin(l = 0.6 b = -0.2)   ///
    symysize(*0.9)  alignment(top)  ///
    label(2 "0 to 5000")    ///
    label(3 "5000 to 10000")    ///
    label(4 "10000 to 15000")   ///
    label(5 "15000 to 20000")   ///
    label(6 "20000 to 25000")   ///
    label(7 "25000+")   ///
    title("PREDICTIONS", pos(11) size(4)))

A: Possibly because label 1 is intended for missing data


text:
Q: Printer error (EX_TIMEOUT) Epson TM-T88V-I with epson.ePOSBuilder
*

*Epson model TM-T88V-i.

*Connected to LAN.

*Ping response OK.

*Printing status sheet OK.

*I have access to printer configuration page.
http://192.168.x.x/PrinterConfigurationPage/

*In configuration page - section devices raise error in test print button for the printer "local_printer", error: "EX_TIMEOUT A time-out ocurred".
reference (ePOS-Print API/XML):
https://download.epson-biz.com/modules/community/index.php?content_subject=ePOS-Print%20API/XML
simple test web site:
print.html
<script type="text/javascript" src="js/epos-print-3.0.0.js"></script>

code
function printTest() {
    // open print dialog
    $('#print').dialog('open');

    //
    // build print data
    //

    // create print data builder object
    var builder = new epson.ePOSBuilder();

    builder.addText('Test Print\n');
    builder.addFeedLine(1);

    // append paper cutting
    builder.addCut();

    //
    // send print data
    //

    // create print object
    var url = 'http://192.168.x.x/cgi-bin/epos/service.cgi?devid=local_printer&timeout=6000';
    var epos = new epson.ePOSPrint(url);

    // register callback function
    epos.onreceive = function (res) {
        // close print dialog
        $('#print').dialog('close');
        // print failure
        if (!res.success) {
            // show error message
            $('#receive').dialog('open');
        }
    }

    // register callback function
    epos.onerror = function (err) {
        // close print dialog
        $('#print').dialog('close');
        // show error message
        $('#error').dialog('open');
    }

    // send
    epos.send(builder.toString());

}

Request to service.cgi :
<?xml version="1.0" encoding="utf-8"?>
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
    <s:Body>
        <epos-print xmlns="http://www.epson-pos.com/schemas/2011/03/epos-print">
            <text>Test Print!!
</text>
            <feed line="1"/>
            <cut/>
        </epos-print>
    </s:Body>
</s:Envelope>

Response: epson api manual (status: 0x00000001 = No response from the TM printer)
<?xml version="1.0" encoding="UTF-8" ?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Body>
        <response success="false" code="EX_TIMEOUT" status="1" xmlns="http://www.epson-pos.com/schemas/2011/03/epos-print" />
    </soapenv:Body>
</soapenv:Envelope>

when i change the service url a other device
var url = 'http://192.168.x.x/cgi-bin/epos/service.cgi?devid=other_printer&timeout=6000';

Request correct
Sucess="False" code="DeviceNotFound" status="0"

Windows Application example the same response:
Public Class Form1

    ' URL of ePOS-Print supported TM printer
    Private address As String = "http://192.168.x.x/cgi-bin/epos/service.cgi?devid=local_printer&timeout=10000"

    ' XML namespace
    Private soap As XNamespace = "http://schemas.xmlsoap.org/soap/envelope/"
    Private epos As XNamespace = "http://www.epson-pos.com/schemas/2011/03/epos-print"

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

        ' Create print document
        Dim req As XElement = _
            <s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
                <s:Body>
                    <epos-print xmlns="http://www.epson-pos.com/schemas/2011/03/epos-print">
                        <text lang="en" smooth="true">Intelligent Printer
</text>
                        <cut/>
                    </epos-print>
                </s:Body>
            </s:Envelope>

        ' Send print document
        Dim client As WebClient = New WebClient()
        client.Headers.Set("Content-Type", "text/xml; charset=utf-8")
        AddHandler client.UploadStringCompleted, AddressOf UploadStringCompletedEventHandler
        client.UploadStringAsync(New Uri(address, UriKind.Absolute), req.ToString())

    End Sub

    ' Receive response document
    Private Sub UploadStringCompletedEventHandler(sender As Object, e As UploadStringCompletedEventArgs)

        If (e.Error IsNot Nothing) Then
            MessageBox.Show(e.Error.Message)
        Else
            'Parse response document
            Dim res As XElement = XElement.Parse(e.Result)
            Dim c = From el In res.Descendants(epos + "response") Select el.Attribute("success")
            MessageBox.Show(c.First().Value)
        End If

    End Sub

End Class

A: Two possibilities:
Your printer has a device id that is different from local_printer - check the configuration page.
Or the ePOSPrint() function does not allow sending the url directly. What I have on my first test page (I'm working on building an app for the same printer right now) looks different than on yours:
var epos = new epson.ePOSPrint();
epos.address = 'http://192.168.0.1/cgi-bin/epos/services.cgi?devid=local_printer&timeout=6000';

Note the empty () and how the url is delivered after initialization.

After checking, it looks like some other test code I have does submit the url as parameter to the function like you have it, so my only guess is that the device id local_printer is incorrect.