text:
Q: sshd allows login with no authentication all accounts This morning I was logging into an Ubuntu 18 machine that luckily we use for testing and is not on the Internet. When my SSH client got to the authentication point I accidentally hit 'ESC' which means that all I did was pass a username to the client and it let me login.
I like you assumed it was because my client has my key but I hadn't typed in the passphrase or anything for my ssh key. To be sure I closed the client and I tried a different user on the host. Sure enough no auth required. Does anyone know why it isn't requiring any authentication?
The three lines at the very bottom of the config file below were put there to make duo 2fa work as were the changes to pam.d/sshd
sshd_config
# Package generated configuration file
# See the sshd_config(5) manpage for details

# What ports, IPs and protocols we listen for
Port 22
# Use these options to restrict which interfaces/protocols sshd will bind to
#ListenAddress ::
#ListenAddress 0.0.0.0
Protocol 2
# HostKeys for protocol version 2
HostKey /etc/ssh/ssh_host_rsa_key
HostKey /etc/ssh/ssh_host_dsa_key
HostKey /etc/ssh/ssh_host_ecdsa_key
HostKey /etc/ssh/ssh_host_ed25519_key
#Privilege Separation is turned on for security
UsePrivilegeSeparation yes

# Lifetime and size of ephemeral version 1 server key
KeyRegenerationInterval 3600
ServerKeyBits 1024

# Logging
SyslogFacility AUTH
LogLevel INFO

# Authentication:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes

RSAAuthentication yes
PubkeyAuthentication yes
#AuthorizedKeysFile     %h/.ssh/authorized_keys

# Don't read the user's ~/.rhosts and ~/.shosts files
IgnoreRhosts yes
# For this to work you will also need host keys in /etc/ssh_known_hosts
RhostsRSAAuthentication no
# similar for protocol version 2
HostbasedAuthentication no
# Uncomment if you don't trust ~/.ssh/known_hosts for RhostsRSAAuthentication
#IgnoreUserKnownHosts yes

# To enable empty passwords, change to yes (NOT RECOMMENDED)
PermitEmptyPasswords no

# Change to yes to enable challenge-response passwords (beware issues with
# some PAM modules and threads)
#ChallengeResponseAuthentication no

# Change to no to disable tunnelled clear text passwords
PasswordAuthentication no

# Kerberos options
#KerberosAuthentication no
#KerberosGetAFSToken no
#KerberosOrLocalPasswd yes
#KerberosTicketCleanup yes

# GSSAPI options
#GSSAPIAuthentication no
#GSSAPICleanupCredentials yes

X11Forwarding yes
X11DisplayOffset 10
PrintMotd no
PrintLastLog yes
TCPKeepAlive yes
#UseLogin no

#MaxStartups 10:30:60
#Banner /etc/issue.net

# Allow client to pass locale environment variables
AcceptEnv LANG LC_*

Subsystem sftp /usr/lib/openssh/sftp-server

# Set this to 'yes' to enable PAM authentication, account processing,
# and session processing. If this is enabled, PAM authentication will
# be allowed through the ChallengeResponseAuthentication and
# PasswordAuthentication.  Depending on your PAM configuration,
# PAM authentication via ChallengeResponseAuthentication may bypass
# the setting of "PermitRootLogin without-password".
# If you just want the PAM account and session checks to run without
# PAM authentication, then enable this but set PasswordAuthentication
# and ChallengeResponseAuthentication to 'no'.
#UsePAM yes
#ChallengeResponseAuthentication yes
#UseDNS no
UsePAM yes
ChallengeResponseAuthentication yes
UseDNS no

/etc/pam.d/sshd
# Standard Un*x authentication.
#@include common-auth
auth  [success=1 default=ignore] pam_duo.so
auth  requisite pam_deny.so
auth  required pam_permit.so
# Disallow non-root logins when /etc/nologin exists.
account    required     pam_nologin.so


text:
Q: Visual studio code PowerShell terminal[unknown] I am using vs-code. After cloning a project my PowerShell terminal showed I am in the [master] branch. I then opened a whole new project which I did not want to push to the git repository and the terminal still had the "[master]". In my attempt to move out of the repository I ran the command rm -r .git and the terminal changed to [unknown]. How can i remove the "[unknown]"?
Image for reference

redpajama_set_name: RedPajamaStackExchange


text:
Q: Required imports for Meteor In meteor project, do I need to import {Meteor},{Mongo}, and{check} in this example?  Why?
collections.js
    // import {Mongo} from 'meteor/mongo' // ---- i have to import this?

    Bookmarks = new Mongo.Collection('bookmarks')

methods.js
    // import {check} from 'meteor/check' // ---- i have to import this?
    import {Bookmarks} from "/imports/schema/bookmarks/index"

    Meteor.methods({
     'bookmark.add'({name, url}){
      check(name,String) // ---------------
      check(url,String)

    const bookmarkId = Bookmarks.insert({name,url})
    Meteor.isServer && console.log(`Id ${bookmarkId} inserted`)
  },
  'bookmark.remove'(_id){
    check(_id,String)

    const bookmark = Bookmarks.findOne({_id})
    if (!bookmark){
      Meteor.isServer && console.log('no such a bookmark!')
    } else {
      const removeBookmarkId = Bookmarks.remove({_id})
      Meteor.isServer && console.log(`remove result ${removeBookmarkId?'success':'error'}`)
    }
  }
})

A: The short answer is yes.  Meteor makes heavy use of the module system for imports and exports.  You can read more about how Meteor modules works, and the reasons motivating the move to Meteor modules here.


text:
Q: I am writing same if statement 5 times, how can I rewrite this with only 1 if statement I have following database columns team_a_set_1, team_a_set_2, team_a_set_3, team_a_set_4, team_a_set_5, team_b_set_1, team_b_set_2, team_b_set_3, team_b_set_4, team_b_set_5. I am using these columns to store tennis game result for 5 sets.
Now I am trying to find out who is winner between team a and team b. Who ever wins the max number of sets is winner. My code looks roughly like this
def find_winner
  team_a_win_count = 0
  team_b_win_count = 0

  if team_a_set_1.present? && team_b_set_1.present?
    if team_a_set_1 > team_b_set_1
      team_a_win_count = team_a_win_count + 1
    elsif team_b_set_1 > team_a_set_1
      team_b_win_count = team_b_win_count +1
    end
  end

  if team_a_set_2.present? && team_b_set_2.present?
    if team_a_set_2 > team_b_set_2
      team_a_win_count = team_a_win_count + 1
    elsif team_b_set_2 > team_a_set_2
      team_b_win_count = team_b_win_count +1
    end
  end

  if team_a_set_3.present? && team_b_set_3.present?
    if team_a_set_3 > team_b_set_3
      team_a_win_count = team_a_win_count + 1
    elsif team_b_set_3 > team_a_set_3
      team_b_win_count = team_b_win_count +1
    end
  end

  if team_a_set_4.present? && team_b_set_4.present?
    if team_a_set_4 > team_b_set_4
      team_a_win_count = team_a_win_count + 1
    elsif team_b_set_4 > team_a_set_4
      team_b_win_count = team_b_win_count +1
    end
  end

  if team_a_set_5.present? && team_b_set_5.present?
    if team_a_set_5 > team_b_set_5
      team_a_win_count = team_a_win_count + 1
    elsif team_b_set_5 > team_a_set_5
      team_b_win_count = team_b_win_count +1
    end
  end

  if team_a_win_count > team_b_win_count
    puts 'Team A won'
  elsif team_b_win_count > team_a_win_count
    puts 'Team B won'
  else
    puts 'Draw'
  end
end

As you can see I am repeating same logic 5 times in if statement. I want to refactor this code so I don't have to repeat same thing 5 times. I tried something like this but it didn't work
1.upto(5) do |n|
  if "team_a_set_#{n}".present? && "team_b_set_#{n}".present?
    if "team_a_set_#{n}" > "team_b_set_#{n}"   # this is not working because it's comparing string
       team_a_win_count = team_a_win_count + 1
     elsif "team_b_set_#{n}" > "team_a_set_#{n}"
       team_b_win_count = team_b_win_count + 1
    end
  end
end

So how can I refactor this code so that I don't have to write if statement 5 times ?
Update: Based on everyone suggestions I end up re designing my database. Now I am storing sets in Hash. And everything looks nice and clean now.

A: The answer here is most likely to model the data better.
class Game < ApplicationRecord
  belongs_to :player_a, class_name: 'Player'
  belongs_to :player_b, class_name: 'Player'
  has_many :game_sets
end

# rails g model game_set game:belongs_to player_a_score:integer player_b_score:integer
class GameSet < ApplicationRecord
  belongs_to :game
end

This sets up a simple one to many instead of having N number of columns. This lets you simply tally up the rows by selecting aggregates:
Game.select(
  'games.*',
  'SUM(
     SELECT 1 FROM gamesets gs WHERE gs.game_id = games.id AND gs.player_a_score > gs.player_b_score
   ) AS player_a_wins',
   'SUM(
     SELECT 1 FROM gamesets gs WHERE gs.game_id = games.id AND gs.player_b_score > gs.player_a_score
   ) AS player_b_wins',
   'SUM(
     SELECT 1 FROM gamesets gs WHERE gs.game_id = games.id AND gs.player_b_score = gs.player_a_score
   ) AS draws'
)

You could also just cache the result on the game_sets table:
class GameSet < ApplicationRecord
  belongs_to :game
  belongs_to :winner,
    class_name: 'Player',
    optional: true # nil for draws
end

There is also a long list of more performant ways to get the aggregates such as using FILTER on Postgres or lateral joins. You should also consider saving the results of the game directly on the games table for better read performance.

A: As I have mentioned before, When you find yourself adding an integer suffix to variable names, think I should have used an array.. Similarly, if you find yourself using string prefixes or suffixes, you should have used a hash.
The way the code is written, it is hard to follow the logic and without knowing any more, it is hard to make a concrete recommendation, but, if you can get the data in the following format:
  games = [
    {
      'a' => [12, 34, 56, 78, 90],
      'b' => [21, 43, 65, 87, 9],
    },
    {
      'a' => [1, 2, 3, 4, 5],
      'b' => [5, 4, 2, 2, 1],
    },
  ]

  games.each_index do |g|
    game = games[g]
    teams = game.keys
    wins = Hash[teams.map {|t| [t, 0]}]

    game[teams[0]].each_index do |i|
      winner = game[teams[0]][i] > game[teams[1]][i] ? 0 : 1
      wins[teams[winner]] += 1
    end

    puts "Winner of game #{g}: #{teams[wins[teams[0]] > wins[teams[1]] ? 0 : 1]}"
  end

You will have the advantage of being able to handle arbitrary numbers of games between arbitrary teams. Also, you won't have to change the code to handle different ways of referring to games/teams.

have following database columns team_a_set_1, team_a_set_2, team_a_set_3, team_a_set_4, team_a_set_5, team_b_set_1, team_b_set_2, team_b_set_3, team_b_set_4, team_b_set_5.

And that really is your problem. The database is not properly designed to actually do this sort of thing. In fact, if the table GAMES had the columns: game, set, team, score, you would not really need to write any Ruby to do this.


text:
Q: Как отправить значения true/false через чекбокс? Написал чекбокс в форме:
<input type="checkbox" name="my_checkbox" value="true">

Но что-то мне подсказывает что value:true передаст строку. Как сделать так, если флажок помечен отправить true, а если не помечен false?

A: Передать булево значение нельзя.
Когда передается форма на сервер( допустим метод POST), то если есть хоть один выбранный чекбокс, то передастся строка $_POST['my_checkbox']=string("true") в вашем случае true при этом передается как string, а если ничего не выбрано, то просто нет $_POST['my_checkbox'], т.е. isset($_POST['my_checkbox'])результат false
Если у вас в форме будет несколько чекбоксов
<input type="checkbox" name="my_checkbox[]" value="true"> <input type="checkbox" name="my_checkbox[]" value="false">
то передаваться будет массив

A: input[type="checkbox"] игнорируется если не имеет состояние checked === true, а если имеет, то отправляет on если value пустое или значение самого value если там что-то указано.
Можно со стороны сервера перепроверять есть ли наличие name данного input'а, и там уже присваивать true\false в зависимости от наличия..
Но думаю это не правильно, т.к. его вообще может не быть.
По этому как вариант предлагаю при отправки формы пересобирать данные для отправки.
Данные записывать в FormData, там проверять наличие input[type="checkbox"] и тут же выдавать записывать его значение как true\false в зависимости от того, какое состояние input.checkbox на данный момент.

document.querySelector('#form').addEventListener('submit', function(form) { // при отправке формы
    form.preventDefault(); // отменяем отправку
    const data = new FormData(); // создаём объект FormData
    const inputs = form.target.querySelectorAll('[name]'); // Собираем все инпуты с атрибутом name
    if(inputs.length > 0) { // Если их больше нуля..
        inputs.forEach(function(input) { // Проходим по ним циклом
            var name = input.name; // получаем значение атрибута name
            var value = input.value; // получаем значение атрибута value

            if(input.type === 'checkbox') { // Если инпут == чекбоксу, то..
                value = input.checked; // в переменную value записываем его состояние checked (true || false)
            }

            data.append(name, value); // добавляем это в FormData
        })
    }
    console.info(data);
  // Вот тут отправляем данные на сервер
    return false;
})
<form id="form">
  Укажите ваше имя
  <input type="text" name="name" value="Василий"/>

  Вы робот?
  <input type="checkbox" name="is-robot" value="true"/>

  <input type="submit"/>
</form>

P.s. в примере данные возвращаются в консоль, её откройте девтулом, в сниппете она криво отображает данные.


text:
Q: Ways to determine $\pi$ I have read that it is possible to determine the value of a single digit, say the 874th of $\pi$. I know that it is a trascentental number, how is that possible?
How many ways are there to determine the value of $\pi$? What is the simplest?


text:
Q: Ajax in for loop without jquery I have a for loop that call a ajax method
function viderTableauConteneur()
{
    var caf =  document.getElementById('CAF').value;
    var tabConteneurAjouter = caf.split("#");
    for (var i = 0; i < tabConteneurAjouter.length; i++) {
        if(!verifierConteneurAppartienClient(tabConteneurAjouter[i]));
            removeConteneur(tabConteneurAjouter[i]);
    };

}

function verifierConteneurAppartienClient(serialNumber)
{
    var e = document.getElementById("id_client");
    var idClient = e.options[e.selectedIndex].value;
    var xhr = getXhr();
    var res = 12;
    xhr.onreadystatechange = function()
    {

        if(xhr.readyState == 4 && xhr.status == 200)
        {
            if(xhr.responseText == "0")
                return false;
            else if(xhr.responseText == "1")
                return true;
        }

    }
    xhr.open("GET","index.php?option=com_tkcontrack&controller=facture&task=verifierConteneurAppartienClient&refConteneur="+serialNumber+"&id_client="+idClient,true);
    xhr.send();

}

Well if I alert the xhr.responseText I got "1", but when I alert the result in the viderTableauConteneur method I always got "Undifined"
Any help please

A: You could modify your code this way :
function viderTableauConteneur()
{
    var caf =  document.getElementById('CAF').value;
    var tabConteneurAjouter = caf.split("#");
    for (var i = 0; i < tabConteneurAjouter.length; i++) {
        verifierConteneurAppartienClient(tabConteneurAjouter[i],
            function()
            {
                alert('true');
            },
            function()
            {
                alert('false');
                removeConteneur(tabConteneurAjouter[i])
            }
         );
     }
}

/* callbcakIfTrue and callbackIfFalse have to be 2 functions
   that will be called respectiveley if the return of the
   ajax call is true or false.
*/
function verifierConteneurAppartienClient(serialNumber, callbackIfTrue, callbackIfFalse)
{
    var e = document.getElementById("id_client");
    var idClient = e.options[e.selectedIndex].value;
    var xhr = getXhr();
    var res = 12;
    xhr.onreadystatechange = function()
    {

        if(xhr.readyState == 4 && xhr.status == 200)
        {

            if(xhr.responseText == "1")
                callbackIfTrue();
            else
                callbackIfFalse();

        }

    }
    xhr.open("GET","index.php?option=com_tkcontrack&controller=facture&task=verifierConteneurAppartienClient&refConteneur="+serialNumber+"&id_client="+idClient,true);
    xhr.send();

}


text:
Q: Is there a reason why the number of channels/filters and batch sizes in many deep learning models are in powers of 2? In many models the number of channels is kept in powers of 2. Also the batch-sizes are described in powers of 2. Is there any reason behind this design choice?

A: There is no significant in keeping channels and batch size as powers of 2.  You can keep any number you want.

A:
In many models the number of channels is kept in powers of 2. Also the batch-sizes are described in powers of 2. Is there any reason behind this design choice?

While both could probably be optimized for speed (cache-alignment? optimal usage of CUDA cores?) to be powers of two, I am 95% certain that 99.9% do it because others used the same numbers / it worked.
For both hyperparameters you could choose any positive integer. So what would you try? Keep in mind, each complete evaluation takes at least several hours. Hence I guess if people play with this parameter, they make something like a binary search: Starting from one number, doubling keep doubling if it improves until an upper bound is found. At some point the differences are minor and then it is irrelevant what you choose. And people will wonder less if you write that you used a batch size of 64 than if you write that you used 50. Or 42.


text:
Q: Using ModelBuilder, how to define directory while using Python script? I have a model (shown below) in which at the very end of it I run a Python script ('SumFieldInsertNew'). One issue I'm having is that I'm creating this model for an end-user that will have little to no knowledge of most things computer-wise. Ergo, I'm trying to make it as hassle-free and flexible as possible. My question is, I want the user to be able to name the file the script will run itself on, but am unsure of how to do something like this. So essentially, I want to make 'Empty FC' a parameter in which the user can decide what they want their file to be named. Then have the Python script directory code (where it's defining the feature class), know that whatever the user named it is conditional to it being able to run its processes.

My model runs as follows:

*

*It establishes a connection to an Oracle dB

*It creates a Query Layer based on the pre-filled 'Query' parameter

*It creates an empty feature class (Empty FC) into a pre-filled GdB parameter

*It then exectures the 'Copy Features' tool on the Query Layer and outputs the copy into the Empty FC

*This newly populated feature class is then given a new field, called 'SUM_Quantity_Solid'

*In which lastly, this new field is populated via the Python script 'SUM_FIELD_INSERT_NEW', which (as seen below), SUMs up a field and then inserts the values.

> import arcpy
>
> # Define the feature class
    fc = r'User_Defined_Path'
>
> # find the unique 'SEGMENT_LENGTH' values
    Slist = list() for row in arcpy.da.SearchCursor(fc, 'SEGMENT_LENGTH'):
>     # if the value isn't in the list then add it to the list
>     if not row[0] in Slist:
>         Slist.append(row[0])
>
> for Value in Slist:
>     # definition query to limit the rows in the cursor
>     DefQ = 'SEGMENT_LENGTH = ' + str(Value)
>
>     # Use a generator expression to populate a list from the 'QUANTITY_SOLID' field
>     b = sum(row[0] for row in arcpy.da.SearchCursor(fc, 'QUANTITY_SOLID'),DefQ)
>
>     with arcpy.da.UpdateCursor(fc, ['QUANTITY_SOLID_SUM'],DefQ) as cursor:
>         for row in cursor:
>             row[0] = b
>             cursor.updateRow(row)

As referenced, I would like to be able to have

fc = r'User_Defined_Path'

be what the user initially defined the 'EMPTY FC' filename parameter as.

A: Instead of calling your python script from the model you would have more control of the code if the tool worked entirely in python.  To do this:

*

*Export your model to python script

*Create a script tool and define input parameters (similar to model parameters)

*Combine the python scripts into one script and re-define the script tool parameters
This will allow you to easily call info (paths) using variables.

A: I use following code to get path of a file.
from Tkinter import Tk
from tkFileDialog import askopenfilename
Tk().withdraw()
filename = askopenfilename()
if filename == '':
     exit(0)
else:
     if filename.split(".")[-1] == "mxd":        #checking file extention
          return filename
     else:
          do smth

This opens a simple window where you can navigate to your file and then use it's path.
Hope this helps)


text:
Q: Does the Enterprise D advance into different galaxies more than once? In the TNG episode "Where No-One Has Gone Before" the Enterprise-D enters another galaxy.

Does she ever go to another galaxy a second time?

Why am I aksing such a absurd question? The spoken opening text of TNG is quite different in the German translation. Translated back to English it goes something like:

Space - infinite vastnesses. We are in a distant future. These are the adventures of the new starship Enterprise, which is many light-years away from earth on its way, to discover new worlds, unknown lifeforms and new civilisations. The Enterprise thereby advances to galaxies, that no man has seen before.

Obviously the guy who did the German translation didn't know much about Star Trek, since travelling to other galaxies is, if at all, only a very minor part of what the series is about. But I grew up with this sentence and it made me wonder: Does the Enterprise D advance into galaxies where no-one (that is: no human) has been before?
I already know of one example, where the Enterprise D entered another galaxy. But that's singular, while the opening text talks about galaxies (plural). Is there another example of the Enterprise D going to another galaxy, or is the German translation of the opening text not only misleading but plainly wrong about that?

For completeness, here is the original opening text:

Space: the final frontier. These are the voyages of the starship
Enterprise. Its continuing mission: to explore strange new worlds, to
seek out new life and new civilizations, to boldly go where no one has
gone before.

And here is the untranslated German opening text:

Der Weltraum, unendliche Weiten. Wir befinden uns in einer fernen
Zukunft. Dies sind die Abenteuer des neuen Raumschiffs Enterprise, das
viele Lichtjahre von der Erde entfernt unterwegs ist, um fremde Welten
zu entdecken, unbekannte Lebensformen und neue Zivilisationen. Die
Enterprise dringt dabei in Galaxien vor, die nie ein Mensch zuvor
gesehen hat.

(emphasis added)

A: Within the context of televised Star Trek, no Federation Starship has successfully traveled to another galaxy, with the sole exception cited of "Where No One Has Gone Before".
There is one occasion upon which the original NCC-1701 Enterprise attempted to leave the galaxy but failed ("Where No Man Has Gone Before") due to the "galactic barrier", and one where they successfully do so, breaking through that barrier ("By Any Other Name"), but they never actually reach Andromeda.
As a result, the closest thing to truly intergalactic relations the Federation could be said to have is that they offered to help the Kelvans ("By Any Other Name") send a robot ship to let their people know that the Federation were willing to help them find a home. The results of that mission are never detailed canonically, although Worf does claim to have fought Kelvans, once, suggesting that at least Rojan's expedition survives into the late 24th Century.


text:
Q: Tic-Tac-Toe program returns java.lang.NullPointerException My assignment is to create a tic-tac-toe game. I thought my code looked good, and it compiles, but it returns:
"Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at TicTacModel.squareClicked(TicTacModel.java:33)
at TicTacGUI$ButtonListener.gridButtonClicked(TicTacGUI.java:79)
at TicTacGUI$ButtonListener.actionPerformed(TicTacGUI.java:53)
at javax.swing.AbstractButton.fireActionPerformed(AbstractButton.java:2018)
at javax.swing.AbstractButton$Handler.actionPerformed(AbstractButton.java:2341)
at javax.swing.DefaultButtonModel.fireActionPerformed(DefaultButtonModel.java:402)
at javax.swing.DefaultButtonModel.setPressed(DefaultButtonModel.java:259)
at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(BasicButtonListener.java:252)
at java.awt.Component.processMouseEvent(Component.java:6505)
at javax.swing.JComponent.processMouseEvent(JComponent.java:3321)
at java.awt.Component.processEvent(Component.java:6270)
at java.awt.Container.processEvent(Container.java:2229)
at java.awt.Component.dispatchEventImpl(Component.java:4861)
at java.awt.Container.dispatchEventImpl(Container.java:2287)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:4832)
at java.awt.LightweightDispatcher.processMouseEvent(Container.java:4492)
at java.awt.LightweightDispatcher.dispatchEvent(Container.java:4422)
at java.awt.Container.dispatchEventImpl(Container.java:2273)
at java.awt.Window.dispatchEventImpl(Window.java:2719)
at java.awt.Component.dispatchEvent(Component.java:4687)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:735)
at java.awt.EventQueue.access$200(EventQueue.java:103)
at java.awt.EventQueue$3.run(EventQueue.java:694)
at java.awt.EventQueue$3.run(EventQueue.java:692)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:87)
at java.awt.EventQueue$4.run(EventQueue.java:708)
at java.awt.EventQueue$4.run(EventQueue.java:706)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:76)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:705)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:242)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:161)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:146)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:138)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:91)

My question: What am I doing that causes this error?
My teacher gave me the GUI class without the source code. Also I am not allowed to replace/modify the main or GUI classes.
Here is my TicTacToe logic class:
public class TicTacModel
{
// Instance Variables.
// You will need to include two 2-D Arrays.
// - one 2-D Array of String objects which remembers the marks on the "game board",
// - another 2-D Array of booleans which will tell the GUI what squares to mark in red. (true = red)
private String[][] marks;
private boolean[][] red;

//Your 2-D Arrays are not full of integer values, so java will not supply reliable defaults.
//Use the constructor to fill them with approprate default values.
public TicTacModel()
{
    boolean[][] red = {{false, false, false},
                       {false, false, false},
                       {false, false, false}};
    String[][] marks = {{" ", " ", " "},
                        {" ", " ", " "},
                        {" ", " ", " "}};
}

//Each time a square is clicked, the GUI will send the location of the click
//and the mark made ("X" or "O"). Record this informaion in your instance 2-D Array of Strings.
public void squareClicked(int row, int col, String mark)
{
    marks[col][row] = mark;
}

//Determine if the 2-D Array of Strings is full of "X"s and "O"s from the GUI.
//Return true if it is full, false otherwise.
public boolean isFull()
{
   int x, y = 0;
   for (x = 0; x <= 2; x++)
   {
       for (y = 0; y <= 2; y++)
       {
           if (marks[x][y] == " ")
           {
               return false;
           }
       }
   }
   return true;
}

//This method will require the most code.
//Check all possible ways there could be a winner.
//Return true if there is a winner, false otherwise.
//Set the corresponding elements of the instance boolean 2-D Array to true.
public boolean isWinner()
{
   if (marks[0][0] == marks[1][0] && marks[0][0] == marks[2][0])
   {
       red[0][0] = true;
       red[1][0] = true;
       red[2][0] = true;
       return true;
   }
   else if (marks[0][0] == marks[0][1] && marks[0][0] == marks[0][2])
   {
       red[0][0] = true;
       red[0][1] = true;
       red[0][2] = true;
       return true;
   }
   else if (marks[0][0] == marks[1][1] && marks[0][0] == marks[2][2])
   {
       red[0][0] = true;
       red[1][1] = true;
       red[2][2] = true;
       return true;
   }
   else if (marks[0][1] == marks[1][1] && marks[0][1] == marks[2][1])
   {
       red[0][1] = true;
       red[1][1] = true;
       red[2][1] = true;
       return true;
   }
   else if (marks[0][2] == marks[1][2] && marks[0][2] == marks[2][2])
   {
       red[0][2] = true;
       red[1][2] = true;
       red[2][2] = true;
       return true;
   }
   else if (marks[1][0] == marks[1][1] && marks[1][0] == marks[1][2])
   {
       red[1][0] = true;
       red[1][1] = true;
       red[1][2] = true;
       return true;
   }
   else if (marks[2][0] == marks[2][1] && marks[2][0] == marks[2][2])
   {
       red[2][0] = true;
       red[2][1] = true;
       red[2][2] = true;
       return true;
   }
   else if (marks[2][0] == marks[1][1] && marks[2][0] == marks[0][2])
   {
       red[2][0] = true;
       red[1][1] = true;
       red[0][2] = true;
       return true;
   }
   else return false;
}

//A getter method which returns the instance 2-D Array of booleans.
//Corresponding elements containing 'true' will be shaded red by the GUI.
public boolean[][] getRedSquares()
{
    return red;
}

}

A: Your problem is that you don't initialize marks. In the constructor you declare a local variable called marks, but so your global one stays null. Change your constructor like this:
public TicTacModel()
{
  red = {{false, false, false},
                   {false, false, false},
                   {false, false, false}};
  marks = {{" ", " ", " "},
                    {" ", " ", " "},
                    {" ", " ", " "}};
}

A: You're shadowing the marks and the red variables by re-declaring them in the constructor. This will initialize the variable that is  local to the constructor, leaving the instance field null. Solution: don't re-declare the variable.


text:
Q: Python struct like Matlab I seem to have found lots of hack answers, without a 'standardized' answer to this questions. I am looking for an implementation of Matlab's struct in Python, specifically with the two following capabilities:

*

*in struct 's', access field value 'a' using dot notation (i.e. s.a)

*create fields on the fly, without initialization of dtype, format (i.e. s.b = np.array([1,2,3,4]) )

Is there no way to do this in Python? To date, the only solution I have found is here, using a dummy class structtype(). This works but feels a little hackish.
I also thought maybe scipy would expose its mat_struct, used in loadmat(), but I couldn't find a public interface to it.
What do other people do? I'm not too worried about performance for this struct, its more of a convenience.

A: If you're on 3.3 and up, there's types.SimpleNamespace. Other than that, an empty class is probably your best option.

A: The simplest and intuitively most similar Python implementation would be to use type to instantiate a temporary class. It is practically similar to making a dummy class, but I think it semantically expresses the intent of a struct--like object more clearly.
>>> s = type('', (), {})()
>>> s.a = 4
>>> s.a
4

Here, type is used to create a nameless class (hence the '') with no bases (or parent classes, indicated by the empty tuple) and no default class attributes (the empty dictionary) and the final () instantiates the class/struct. Bear in mind that values passed to the dictionary do not show up in the instance's __dict__ attribute, but this fact may not be relevant to you. This method also works in older versions (< 3.x) of Python.

A: In Octave I did:
octave:2>      x.a = 1;
octave:3>      x.b = [1, 2; 3, 4];
octave:4>      x.c = "string";
octave:7> save -7 test.mat x

In ipython (2.7):
In [27]: from scipy.io import loadmat
In [28]: A=loadmat('test.mat')

In [29]: A
Out[29]:
{'__globals__': [],
 '__header__': 'MATLAB 5.0 MAT-file, written by Octave 3.8.2, 2015-12-04 02:57:47 UTC',
 '__version__': '1.0',
 'x': array([[([[1.0]], [[1.0, 2.0], [3.0, 4.0]], [u'string'])]],
      dtype=[('a', 'O'), ('b', 'O'), ('c', 'O')])}

In this case A['x'] is a numpy structured array, with 3 dtype=object fields.
In [33]: A['x']['b'][0,0]
Out[33]:
array([[ 1.,  2.],
       [ 3.,  4.]])

In [34]: A['x'][0,0]
Out[34]: ([[1.0]], [[1.0, 2.0], [3.0, 4.0]], [u'string'])

In [35]: A['x'][0,0]['b']
Out[35]:
array([[ 1.,  2.],
       [ 3.,  4.]])

Since x comes from MATLAB I have to index it with [0,0].
octave:9> size(x)
ans =
   1   1

I can load A with a different switch, and access attributes with .b format:
In [62]: A=loadmat('test.mat',struct_as_record=False)

In [63]: A['x'][0,0].b
Out[63]:
array([[ 1.,  2.],
       [ 3.,  4.]])

In this case the elements of A['x'] are of type <scipy.io.matlab.mio5_params.mat_struct at 0x9bed76c>
Some history might help.  MATLAB originally only had 2d matricies.  Then they expanded it to allow higher dimensions.  cells were added, with the same 2d character, but allowing diverse content.  structures were added, allow 'named' attributes.  The original MATLAB class system was built on structures (just link certain functions to a particular class structure). MATLAB is now in its 2nd generation class system.
Python started off with classes, dictionaries, and lists.  Object attributes are accessed with the same . syntax as MATLAB structures. dictionaries with keys (often, but not always strings).  Lists indexed with integers, and have always allowed diverse content (like cells).  And with a mature object class system, it is possible construct much more elaborate data structures in Python, though access is still governed by basic Python syntax.
numpy adds n-dimensional arrays.  A subclass np.matrix is always 2d, modeled on the old style MATLAB matrix.  An array always has the same kind of elements.  But dtype=object arrays contain pointers to Python objects.  In many ways they are just Python lists with an array wrapper.  They are close to MATLAB cells.
numpy also has structured arrays, with a compound dtype, composed of fields.  fields are accessed by name.  np.recarray is a structured array, with added ability to access fields with the . syntax.  That makes them look a lot like MATLAB arrays of structures.


text:
Q: Statement giving unexpected results. is statement written wrong using :not? I have 3 ids id==1  id==2 id==3 . each is a slideshow that has already been turned on on load. Using NOT I wish to turn Off the 2 slide shows not chosen by id.
this is not working. When ID 1 is chosen- both 1 and 2 turn off instead of 2 and 3. When ID 2 is chosen- both 1 and 2 turn off instead of 2 and 3. When ID 3 is chosen - both 1 and 3 turn off instead of 1 and 2.
 Is this a logic error or something to do with the slideshow code?
 if (id == 1){
     alert(id);
     $('div.nivoSlider:not(#c' + id + ')').data('nivoslider').stop(); }

 if (id== 2){
     alert(id);
     $('div.nivoSlider:not(#c' + id + ')').data('nivoslider').stop(); }

     if (id== 3) {
     alert(id);
    $('div.nivoSlider:not(#c' + id + ')').data('nivoslider').stop(); }

Hopefully, I have given enough information.
THank you for your help.

A: Your expected function could be simplified like this:
$(document).ready(function() {
    $('.nivoSlider').click(function() {
      id = $(this).prop('id');
      $('div.nivoSlider:not(#' + id + ')').text('Stop now.');
      $('div#' + id + '').text(id);
    });
});

See demo at JsFiddle.

A: I have done more debugging, It seems that my problem is not the logic.
I believe it to be something with the nivo-slider. I am going to post a question on the nivo-slider and see if anyone has any experience with this.
Thank you all for your answers.
geddeca


text:
Q: What is the difference between C++98 and C++11 SFINAE rules? I have read that SFINAE Rule is more simpler in C++11 than in C++98. In the book of Bjarne Stroustrup "A Tour of C++", it is noted that C++11 has a simpler and more general SFINAE rule. (Section 14.2.1 Item 39)
What is the difference between C++98 and C++11 SFINAE rules?


text:
Q: How to use Dataframe data in python script? Hello everyone I'm trying to figure out how to pull data from a data frame using pandas inside my new script?
So I've got excel data saved and I use pandas to pull the data into python but how do I use that data pulled to reference?
For example :

'start': {
'date': '2022-02-22'

with date 11/17/2022 from the excel sheet.
UPDATE: the event data needs to be JSON string so if I turn the data frame into JSON how would I call this in place?
data = df.to_json(orient='columns')
print(data)

I hope that makes sense? any help would be greatly appreciated!
[![enter image description here][1]][1]
from google_apis import create_service
from pprint import pprint
import pandas as pd
import openpyxl

service = create_service(CLIENT_SECRET_FILE, API_NAME, API_VERSION, SCOPES)

calendar_id_jameson = 'primary'

""""
Create an event
"""
event = {
  'summary': 'Test',
  'description': 'Date 11/17/2022',

A: You have a couple different methods from the Pandas data frame to retrieve the information you want. Here you can find a comprehensive guide, but if we use df.iat[x,y] as an example you can do like this:
...
df = pd.read_excel (r'C:\Users\phlfo\calendar\Case_Files.xlsx')
...
event = {
  'summary': 'Test',
  'description': f'{df.iat[5,2]}',
...

I omitted parts of your code for clarity, but notice that you must give a string to the dictionary under 'description': 'this has to be string'. Here I used an f-string, it will replace the result from what is between curly brackets into your string.


text:
Q: Unable to escape single quotes db2 sql query run via shell script There is probably a very simple solution to this, but I've tried every variation I could think of and still not able get rid of the error:
I'm running this via a shell script:
su - myid -c 'db2 -v "EXPORT TO '/tmp/file.out' OF DEL MODIFIED BY COLDEL| select A, B, C FROM mytable where C = '' and ( F = 1 or F = 2 or F = 3 or F = 4 ) "'

And this is the error I am getting:
SQL0104N  An unexpected token "=   and ( status" was found following "mytable
where C".  Expected tokens may include:  "<space>".  SQLSTATE=42601

Any help would be greatly appreciated

A: You could use an ANSI-quoted string if you are using bash:
su - myid -c $'db2 -v "EXPORT TO \'/tmp/file.out\'...'

in which you can quote a single quote using \'. In POSIX shells, you'll have to use double-quotes, and quote the embedded double-quotes:
su - myid -c "db2 -v \"EXPORT TO '/tmp/file.out' ..."

A: I figured it out. Here's my updated query:
su - myid -c 'db2 -v "EXPORT TO '/tmp/file.out' OF DEL MODIFIED BY COLDEL| select A, B, C FROM mytable where C = '\'''\''  and ( F = 1 or F = 2 or F = 3 or F = 4 ) "'

I had to replace the single '' with '\'''\''  <---those are all single quotes


text:
Q: Understanding of inheritance in Java Please don't be angry if my question is stupid )
I have a piece of code:
public class LinkageTest {

public static class Parent {

    public void test() {
        System.out.println("parent::test");
    }
}

public static class Child extends Parent {

    public void test() {
        System.out.println("child::test");
    }
}

public static class Tester {

    public void test(Parent obj) {
        System.out.println("Testing parent...");
        obj.test();
    }

    public void test(Child obj) {
        System.out.println("Testing child...");
        obj.test();
    }
}

public static void main(String[] args) {
    Parent obj = new Child();
    Tester t = new Tester();
    t.test(obj);
}

}
When I'm running it, the next string is printed:
Testing parent... child::test
I can't understand why test method with Parent is called if we have instance of Child? Can some one help me with it?

A: 1) The class Child redefines (overriding) the test method. (polymorphism)
2) In the Tester class, the test(Parent obj) and test(Child obj) methoda are overloaded. When you call the method, the method with the appropriate type is selected.
3) at the time t.test(obj), the variable obj has an explicitly defined Parent type, so the appropriate method will be selected and "Testing parent ..." printed.
4) at the time obj.test(), the test method of the Child class will be called, since this is a polymorphism

A: You are creating an object of Child via Parent  reference like
Parent obj = new Child(); // obj has Child and Parent both type
System.out.println(obj instanceof Parent); // it returns true

And Child overriding test mathod of Parent,
public static class Child extends Parent{
    public void test(){ //overriding here
        System.out.println("child::test");
    }
}

while you calling t.test(obj) method
    public static void main(String[] args){
    Parent obj = new Child();
    Tester t = new Tester();
    t.test(obj); // obj created by Parent reference
}

So catches by :
public void test(Parent obj){ // catches here
        System.out.println("Testing parent..."); // Here is your first output
        obj.test();
    }

then obj have overridden test method so it calls
public static class Child extends Parent{
    public void test(){ // overridden method first priority
        System.out.println("child::test"); // Here is your second output
    }
}

if you change Child class test method name then it calls Parent class test method,and output will be
Testing parent...
parent::test

A: Because you call
Parent obj = new Child();
t.test(obj); //object created by Parent reference

This obj is from parent, so it will call the "Testing parent" from Tester class.
Then, thanks of polymorphism, it will also call "child::test" from Child class because is overridden.
Try to call:
Child obj = new Child();
t.test(obj);

And you will see:
"Testing child..."
"child::test"

You should also put @Override on the test() method of the Child class.

A: Thats because you're calling tester method with argument type of Parent. But the actual object inside, concrete implementation is Child. These might not be good words to describe it, hope you understand.
If you've called typeof(obj), it would return Parent. If you've debugged the app, you'd see that the method called is the one with Parent argument, because you pass argument which type is Parent.
The more concrete object is Child (actually you can cast the obj Child and it will work fine, because it is child on the inside). And when you do obj.test(), it will call method from child, because it is overriden by child.

A: Decision to call Tester.test(Parent obj) is made at compilation time. During compilation compiler must pick method signature (not implementation, but signature). Compiler sees two methods with same name, but different signatures, it can pick only Parent signature because you've declared Parent obj. This is why in final byte code it will be presented like
find method test(Parent) in object t and execute it

Decision to call Child.test is made at run time. During compilation compiler finds only one signature for method test (despite two different implementations in Parent/Child, signature is the same). So actual implementation in both methods in Tester class will be:
find method test() in object obj and execute it

So, despite the fact that Tester.test(Parent) method is called, it still will try to find method test in passed object, as soon as you passed child - child's version will be actually executed.


text:
Q: Get coordinates of scrollview with respect to view over it In my self.view -subview-> UIScrollview and another self.view -subview-> overlayview
 which seems over UIScollView
After I zoom the scrollview or pan the scrollview, I want the coordinates of scrollview according to the overlayview as shown in image. Where yellow is the overlayview
I tried with this code
CGRect visibleRect = [scrollView convertRect:scrollView.bounds toView:overlayview];

This is not working.
Need to consider zooming and panning also for scrollview
How can I achieve relative coordinate transformation for two different views?
Or Is there any other way to get that much portion of image from scrollview?
Tried this code but also not working
    CGPoint overlayToSelf = [self.view convertPoint:overlayView.frame.origin fromView:overlayView];
   CGPoint selfToScrollview = [scrollView convertPoint:overlayToSelf fromView:self.view];
   visibleRect = CGRectMake(selfToScrollview.x, selfToScrollview.y, Overlaywidth, Overlayheight);


text:
Q: Access range input value to display it on top of slider I want to use a range slider to select a value and render this value on top of the range selector in Angular.
My html code is:

      Raio: {{raio}} metros
      <input type="range" min="100" max="2000" step="100"
      oninput="rangeChange(this.value)"
             class="form-control-range" id="range">

In my component.ts i have the following function:
export class LugaresComponent implements OnInit {
raio = 200;

constructor() {}

ngOnInit() {}

rangeChange(value) {
    this.raio=value;
    console.log(this.raio)
    }
}

When I select a value on the range input I am receiving the following error on the console:
Uncaught ReferenceError: rangeChange is not defined

What is the correct way to do it?

A: I think that you have to use oninput as an event, with () and then pass the event to the function
<input type="range" min="100" max="2000" step="100" (oninput)="rangeChange($event)" />

rangeChange(event) {
   this.raio = event.target.value;
}

But it would be better to use data binding via ngModel, there is no need to handle the event if you only need to bind the value from the input to a component's property
<input type="range" min="100" max="2000" step="100" [(ngModel)]="raio" />


text:
Q: What are the benefits (and drawbacks) of a weakly typed language? I'm a big fan of PHP and it's obviously a very weakly-typed language. I realize some of the benefits include the general independence of changing variable types on the fly and such.
What I'm wondering about are the drawbacks. What can you get out of a strongly-typed language like C that you otherwise can't get from a weakly-typed one like PHP? Also with type setting (like double($variable)), one could argue that even a weakly-typed language can act just like a strongly-typed one.
So. Weak-type. What are some benefits I didn't include? More importantly, what are the drawbacks?

A: I have been using both strong typed (like Java) and weak typed (like JavaScript) languages for some time now.  What I have found is that the convenience of the weak typed languages are great for small applications.  Unfortunately, as the application grows in size, it becomes impossible to manage.  There becomes too much to keep track of in your head and you have to start depending on your IDE and the compiler more and more or your coding grinds to a halt.  That is when strong typed languages start to become more useful - with the application grows very large.
Two examples that constantly drive me nuts in the weak typed JavaScript are using external libraries that are not thoroughly documented and refactoring.
External libraries: When dealing with a strongly typed language, the code from the library itself provides self documentation.  When I create a variable of type Person, the IDE can inspect the code and tell there is a getFirstName(), getLastName() and getFullName().  In weak typed languages, this is not the case as a variable could be anything, have any kind of variable or function and have function arguments that could also be anything (they are not explicitly defined).  As a result, a developer has to lean heavily on documentation, web searches, discussion forums and their memory of past usages.  I find it can take hours of looking things up in JavaScript for external libraries while with Java I just hit the "." key and it pops up all my options with documentation attached.  When you encounter libraries that are not 100% fully documented, it can be really frustrating with weak typed languages.  I recently found myself asking "What is argument 'plot' in function 'draw'?" when using jqplot, a fairly well but not completely documented JavaScript library.  I had to spend an hour or two digging through source code before finally giving up and finding an alternative solution.
Refactoring: With strongly typed languages, I find myself able to refactor quickly by just changing the file I need to change and then going to fix the compiler errors.  Some tools will even refactor for you with a simple click of a button.  With weak typed languages, you have to do a search and then replace with care and then test, test, TEST and then test some more.  You are seldom entirely sure you have found and fixed everything you broke, especially in large applications.
For simple needs and small applications, these two concerns are minimal to non-existent.  But if you are working with an application with 100's of thousands or millions of lines of code, weak typed languages will drive you nuts.
I think many developers get upset about this and turn it into an emotional discussion is because we sometimes get it in our heads that there is one right and one wrong approach.  But each approach has its merits - its own advantages and disadvantages.  Once you recognize that you set the emotion aside and choose the best for you for what you need right now.

A: Many a book has been written about this sort of thing. There's an inherent tradeoff; with a weakly-typed language a lot of annoyances simply cease to be. For instance, in Python you never have to worry about dividing a float by an int; adding an int to a list; typing functions' arguments (did you know, OCaml has special +. operators for adding floats because (+) sends ints to ints!); forgetting that a variable can be null... those sorts of problems simply vanish.
In their place come a whole host of new runtime bugs: Python's [0]*5 gives, wait for it, [0,0,0,0,0]! OCaml, for all the annoyance of strong typing, catches many many bugs with its compiler; and this is precisely why it's good. It's a tradeoff.

A: The cited advantage of static typing is that there are whole classes of errors caught at compile time, that cannot reach runtime. For example, if you have a statically-typed class or interface as a function parameter, then you are darn well not going to accidentally pass in an object of the wrong type (without an explicit and incorrect cast, that is).
Of course, this doesn't stop you passing in the wrong object of the right type, or an implementation of an interface where you've given it the right functions but they do the wrong things. Furthermore, if you have 100% code coverage, say the PHP/Python/etc folks, who cares whether you catch the error at compile time or at run time?
Personally, I've had fun times in languages with static typing, and fun times in languages without. It's rarely the deciding issue, since I've never had to choose between two languages which are identical other than their kind of typing and there are normally more important things to worry about. I do find that when I'm using statically typed languages I deliberately "lean on the compiler", trying to write code in such a way that if it's wrong, it won't compile. For instance there are certain refactors which you can perform by making a change in one place, and then fixing all the compilation errors which result, repeat until clean compile. Doing the same thing by running a full test suite several times might not be very practical. But it's not unheard-of for IDEs to automate the same refactors in other languages, or for tests to complete quickly, so it's a question of what's convenient, not what's possible.
The folks who have a legitimate concern beyond convenience and coding style preference are the ones working on formal proofs of the correctness of code. My ignorant impression is that static type deduction can do most (but not all) of the work that explicit static typing does, and saves considerable wear and tear on the keyboard. So if static typing forces people to write code in a way that makes it easier to prove, then there could well be something to it from that POV. I say "if": I don't know, and it's not as if most people prove their statically-typed code anyway.
changing variable types on the fly and such
I think that's of dubious value. It's always so tempting to do something like (Python/Django):
user = request.GET['username']
# do something with the string variable, "user"
user = get_object_or_404(User,user)
# do something with the User object variable, "user"

But really, should the same name be used for different things within a function? Maybe. Probably not. "Re-using", for example, integer variables for other things in statically typed languages isn't massively encouraged either. The desire not to have to think of concise, descriptive variable names, probably 95% of the time shouldn't override the desire for unambiguous code...
Btw, usually weak typing means that implicit type conversions occur, and strong typing means they don't. By this definition, C is weakly typed as far as the arithmetic types are concerned, so I assume that's not what you mean. I think it's widely considered that full strong typing is more of a nuisance than a help, and "full weak typing" (anything can be converted to anything else) is nonsensical in most languages. So the question there is about how many and what implicit conversions can be tolerated before your code becomes too difficult to figure out. See also, in C++, the ongoing difficulty in deciding whether to implement conversion operators and non-explicit one-arg constructors.

A: Weak and Strong are loaded terms. (Do you want to be a weak language programmer?) Dynamic and Static are better but I would imagine most people would rather be a dynamic programmer than a static one. I would call PHP a promiscuous language (Thats not a loaded term ;) )
PHP:
garbage_out = garbage_in * 3; // garbage_in was not initialized yet
"hello world" + 2; // does this make sense?

Allowing uninitialized variables creates very hard to find errors from misspellings. Allowing operations on unrelated types is also almost always an error that should be reported. Most interpreted dynamic languages do not allow these things for good reason. You can have dynamically typed language without allowing garbage.

A: See this table, showing the results of the PHP == operator applied to pairs of empty or other principal values of various types, such as 0, "0", NULL and "". The operator is non-commutative, and the table is quite unintuitive, to say the least. (Not that it would make much sense to ask if a string is equal to an array, in fairness -- but you can do that in a weakly typed language, which is the pitfall, and may Turing help you if the language tries to "help" you.)

A: Straight from wikipedia:

The advantage claimed of weak typing
  is that it requires less effort on the
  part of the programmer than strong
  typing, because the compiler or
  interpreter  implicitly performs
  certain kinds of conversions. However,
  one claimed disadvantage is that
  weakly typed programming systems catch
  fewer errors at compile time and some
  of these might still remain after
  testing has been completed.

That's about the same thing I would say. However beware of the relative ambiguity of these terms ("strong typing" and "weak typing") since implicit conversions blur the line.
Source: http://en.wikipedia.org/wiki/Weak_typing

A: You have to understand that PHP was created for the context of web applications. Everything in the context of the web is a string. Therefore it is very rare where strong typing would be beneficial.


text:
Q: Make Valid jSON String using character replacements I am writing an iOS app in Swift 4.2
Server is responsing bad quality json with invalid characters. I have to replace some characters to make it a valid json string but I am unable to.
Server response String:

{\"fieldsets\":[{\"properties\":[{\"alias\":\"categories\",\"value\":\"Equity\"},{\"alias\":\"subCategory\",\"value\":\"[\r\n  \\"Banking\\",\r\n  \\"FMCG\\",\r\n  \\"Infrastructure\\",\r\n  \\"International Funds\\",\r\n  \\"Large Cap\\",\r\n  \\"Large & Mid Cap\\",\r\n  \\"Mid Cap\\",\r\n  \\"Balanced Fund\\",\r\n  \\"Multi Cap\\",\r\n  \\"Others\\",\r\n  \\"Pharma\\",\r\n  \\"Tax Planning\\",\r\n  \\"Daily\\",\r\n  \\"Small Cap\\",\r\n  \\"Mid & Small Cap\\",\r\n  \\"Diversified\\"\r\n]\"},{\"alias\":\"icon\",\"value\":\"/media/1138/equity.png\"}],\"alias\":\"categoriesSubCategories\",\"disabled\":false,\"id\":\"170e1ba0-6f05-4a11-a2a6-04e108e7fa1f\",\"releaseDate\":null,\"expireDate\":null,\"allowedMemberGroups\":\"\"},{\"properties\":[{\"alias\":\"categories\",\"value\":\"Balanced\"},{\"alias\":\"subCategory\",\"value\":\"[\r\n  \\"Debt-Oriented Aggressive\\",\r\n  \\"Debt-Oriented Conservative\\",\r\n  \\"credit opportunities\\",\r\n  \\"Equity Oriented\\",\r\n  \\"Asset Allocation\\",\r\n  \\"Others\\",\r\n  \\"Yearly\\",\r\n  \\"Advance\\"\r\n]\"},{\"alias\":\"icon\",\"value\":\"/media/1139/balanced.png\"}],\"alias\":\"categoriesSubCategories\",\"disabled\":false,\"id\":\"aabf640c-1ba4-4136-9dd0-79f3dfd6b79b\",\"releaseDate\":null,\"expireDate\":null,\"allowedMemberGroups\":\"\"},{\"properties\":[{\"alias\":\"categories\",\"value\":\"Tax Saver\"},{\"alias\":\"subCategory\",\"value\":\"[\r\n  \\"Any\\"\r\n]\"},{\"alias\":\"icon\",\"value\":\"/media/1140/tax-saver.png\"}],\"alias\":\"categoriesSubCategories\",\"disabled\":false,\"id\":\"fac9c316-16dc-48ab-bc0d-e8c22c02378f\",\"releaseDate\":null,\"expireDate\":null,\"allowedMemberGroups\":\"\"},{\"properties\":[{\"alias\":\"categories\",\"value\":\"Debt\"},{\"alias\":\"subCategory\",\"value\":\"[\r\n  \\"Liquid\\",\r\n  \\"FMP\\",\r\n  \\"Gilt Medium & Long Term\\",\r\n  \\"Gilt Short Term\\",\r\n  \\"Income\\",\r\n  \\"Others\\",\r\n  \\"Short Term\\",\r\n  \\"Ultra Short Term\\",\r\n  \\"Mid Cap\\",\r\n  \\"Small Cap\\",\r\n  \\"Floaters\\",\r\n  \\"Gilt Fund\\",\r\n  \\"Dynamic Bond\\"\r\n]\"},{\"alias\":\"icon\",\"value\":\"/media/1141/debt.png\"}],\"alias\":\"categoriesSubCategories\",\"disabled\":false,\"id\":\"ef1efeda-3334-4a9b-bda7-afff76474a40\",\"releaseDate\":null,\"expireDate\":null,\"allowedMemberGroups\":\"\"}]}

I am trying to use:
     let convertedStr = jsonStr.replacingOccurrences(of: "\\r\\n", with: "", options: .literal, range: nil)
   let convertedStr2 = convertedStr.replacingOccurrences(of: "\\", with: "", options: .literal, range: nil)
  let convertedStr3 = convertedStr2.replacingOccurrences(of: "\"[", with: "", options: .literal, range: nil)
 let convertedStr4 = convertedStr3.replacingOccurrences(of: "]\"", with: "", options: .literal, range: nil)

It's not working out.

A: Your convertedStr3 and convertedStr4 should look like this:
let convertedStr3 = convertedStr2.replacingOccurrences(of: "\"[", with: "[", options: .literal, range: nil)
let convertedStr4 = convertedStr3.replacingOccurrences(of: "]\"", with: "]", options: .literal, range: nil)

Your code didn't entirely work because you were deleting characters like [ and ] which represent array in json. To fix it, notice I added in both of them with: "[", and with: "]", which makes possible replacing:

*

*"[ with [ in convertedStr3

*]" with ] in convertedStr4

Try to print(convertedStr4) and you should be able to copy the result and check it jsonlint.com to validate the json is in a correct format.

A: The issue is because of \r\n, it should be "\r\n" or nothing because they are inside JSON (JSON Stringified within JSON).
So either of this:
let convertedStr = jsonStr.replacingOccurrences(of: "\r\n", with: "")

or
let convertedStr = jsonStr.replacingOccurrences(of: "\r\n", with: "\\r\\n")

should be enough.
No need for the other modifications. I'd recommend to fix it on the back-end part.
The back-end should send you this (which is valid):
{\"fieldsets\":[{\"alias\":\"categoriesSubCategories\",\"allowedMemberGroups\":\"\",\"id\":\"170e1ba0-6f05-4a11-a2a6-04e108e7fa1f\",\"expireDate\":null,\"properties\":[{\"alias\":\"categories\",\"value\":\"Equity\"},{\"alias\":\"subCategory\",\"value\":\"[\\r\\n \\\"Banking\\\",\\r\\n \\\"FMCG\\\",\\r\\n \\\"Infrastructure\\\",\\r\\n \\\"International Funds\\\",\\r\\n \\\"Large Cap\\\",\\r\\n \\\"Large & Mid Cap\\\",\\r\\n \\\"Mid Cap\\\",\\r\\n \\\"Balanced Fund\\\",\\r\\n \\\"Multi Cap\\\",\\r\\n \\\"Others\\\",\\r\\n \\\"Pharma\\\",\\r\\n \\\"Tax Planning\\\",\\r\\n \\\"Daily\\\",\\r\\n \\\"Small Cap\\\",\\r\\n \\\"Mid & Small Cap\\\",\\r\\n \\\"Diversified\\\"\\r\\n]\"},{\"alias\":\"icon\",\"value\":\"\\/media\\/1138\\/equity.png\"}],\"releaseDate\":null,\"disabled\":false},{\"alias\":\"categoriesSubCategories\",\"allowedMemberGroups\":\"\",\"id\":\"aabf640c-1ba4-4136-9dd0-79f3dfd6b79b\",\"expireDate\":null,\"properties\":[{\"alias\":\"categories\",\"value\":\"Balanced\"},{\"alias\":\"subCategory\",\"value\":\"[\\r\\n \\\"Debt-Oriented Aggressive\\\",\\r\\n \\\"Debt-Oriented Conservative\\\",\\r\\n \\\"credit opportunities\\\",\\r\\n \\\"Equity Oriented\\\",\\r\\n \\\"Asset Allocation\\\",\\r\\n \\\"Others\\\",\\r\\n \\\"Yearly\\\",\\r\\n \\\"Advance\\\"\\r\\n]\"},{\"alias\":\"icon\",\"value\":\"\\/media\\/1139\\/balanced.png\"}],\"releaseDate\":null,\"disabled\":false},{\"alias\":\"categoriesSubCategories\",\"allowedMemberGroups\":\"\",\"id\":\"fac9c316-16dc-48ab-bc0d-e8c22c02378f\",\"expireDate\":null,\"properties\":[{\"alias\":\"categories\",\"value\":\"Tax Saver\"},{\"alias\":\"subCategory\",\"value\":\"[\\r\\n \\\"Any\\\"\\r\\n]\"},{\"alias\":\"icon\",\"value\":\"\\/media\\/1140\\/tax-saver.png\"}],\"releaseDate\":null,\"disabled\":false},{\"alias\":\"categoriesSubCategories\",\"allowedMemberGroups\":\"\",\"id\":\"ef1efeda-3334-4a9b-bda7-afff76474a40\",\"expireDate\":null,\"properties\":[{\"alias\":\"categories\",\"value\":\"Debt\"},{\"alias\":\"subCategory\",\"value\":\"[\\r\\n \\\"Liquid\\\",\\r\\n \\\"FMP\\\",\\r\\n \\\"Gilt Medium & Long Term\\\",\\r\\n \\\"Gilt Short Term\\\",\\r\\n \\\"Income\\\",\\r\\n \\\"Others\\\",\\r\\n \\\"Short Term\\\",\\r\\n \\\"Ultra Short Term\\\",\\r\\n \\\"Mid Cap\\\",\\r\\n \\\"Small Cap\\\",\\r\\n \\\"Floaters\\\",\\r\\n \\\"Gilt Fund\\\",\\r\\n \\\"Dynamic Bond\\\"\\r\\n]\"},{\"alias\":\"icon\",\"value\":\"\\/media\\/1141\\/debt.png\"}],\"releaseDate\":null,\"disabled\":false}]}

or, withouth the antislashes:
{"fieldsets":[{"alias":"categoriesSubCategories","allowedMemberGroups":"","id":"170e1ba0-6f05-4a11-a2a6-04e108e7fa1f","expireDate":null,"properties":[{"alias":"categories","value":"Equity"},{"alias":"subCategory","value":"[\r\n \"Banking\",\r\n \"FMCG\",\r\n \"Infrastructure\",\r\n \"International Funds\",\r\n \"Large Cap\",\r\n \"Large & Mid Cap\",\r\n \"Mid Cap\",\r\n \"Balanced Fund\",\r\n \"Multi Cap\",\r\n \"Others\",\r\n \"Pharma\",\r\n \"Tax Planning\",\r\n \"Daily\",\r\n \"Small Cap\",\r\n \"Mid & Small Cap\",\r\n \"Diversified\"\r\n]"},{"alias":"icon","value":"\/media\/1138\/equity.png"}],"releaseDate":null,"disabled":false},{"alias":"categoriesSubCategories","allowedMemberGroups":"","id":"aabf640c-1ba4-4136-9dd0-79f3dfd6b79b","expireDate":null,"properties":[{"alias":"categories","value":"Balanced"},{"alias":"subCategory","value":"[\r\n \"Debt-Oriented Aggressive\",\r\n \"Debt-Oriented Conservative\",\r\n \"credit opportunities\",\r\n \"Equity Oriented\",\r\n \"Asset Allocation\",\r\n \"Others\",\r\n \"Yearly\",\r\n \"Advance\"\r\n]"},{"alias":"icon","value":"\/media\/1139\/balanced.png"}],"releaseDate":null,"disabled":false},{"alias":"categoriesSubCategories","allowedMemberGroups":"","id":"fac9c316-16dc-48ab-bc0d-e8c22c02378f","expireDate":null,"properties":[{"alias":"categories","value":"Tax Saver"},{"alias":"subCategory","value":"[\r\n \"Any\"\r\n]"},{"alias":"icon","value":"\/media\/1140\/tax-saver.png"}],"releaseDate":null,"disabled":false},{"alias":"categoriesSubCategories","allowedMemberGroups":"","id":"ef1efeda-3334-4a9b-bda7-afff76474a40","expireDate":null,"properties":[{"alias":"categories","value":"Debt"},{"alias":"subCategory","value":"[\r\n \"Liquid\",\r\n \"FMP\",\r\n \"Gilt Medium & Long Term\",\r\n \"Gilt Short Term\",\r\n \"Income\",\r\n \"Others\",\r\n \"Short Term\",\r\n \"Ultra Short Term\",\r\n \"Mid Cap\",\r\n \"Small Cap\",\r\n \"Floaters\",\r\n \"Gilt Fund\",\r\n \"Dynamic Bond\"\r\n]"},{"alias":"icon","value":"\/media\/1141\/debt.png"}],"releaseDate":null,"disabled":false}]}

You can pass the second one into a JSON validator, it's valid. The first one isn't really because "\r\n" arent' correctly escaped.
In another hand, there is no interest in use pretty printed in a json, and I'd say less sense in a JSONStringified one. That just adds tabs, new lines char, that add noises, and memory to the request.


text:
Q: Bluetooth Not Available I have a MacBook Pro (Retina, 15-inch, Mid 2015) running 10.13.6 and I am now getting "Bluetooth: Not Available" in the menu bar. I also cannot access the "Bluetooth" section within System Preferences.

Under "Network" in System Preferences it says "Bluetooth PAN is not connected" and "No PAN devices found".

Under System Report, it says "No Information Found" under Bluetooth.

I have tried the following in an effort to troubleshoot:

*

*Simple restart

*Simple shutdown, turn back on

*No USB devices are connected, so I have none to remove

*Reset the SMC

*Delete .plist files in ~/Library/Preferences/ (there were no com.apple.Bluetooth.plist file in this directory for me, I had to go into ~/Library/Preferences/ByHost to find two com.apple.Bluetooth..plist files

*Reset NVRAM

*I'm unable to reset the Bluetooth module as Shift+Option and clicking on the Bluetooth menu in the menu bar does give me an options.

What other options do I have to troubleshoot this? If this is a hardware issue, do you have a recommendation for a Bluetooth USB adapter that I can use to limp by with?

A: If one reset of the SMC doesn't restore the function, you've done all the triage except for one last ditch option before hardware repair or dropping an USB BTLE adapter on.

*

*Install a clean new 10.14 Mojave installation onto an external drive and let it update the firmware and then test without any user data migration or app installations. A total clean OS install can sometimes restore the drivers or state of the adapter if it's hung up and not a hardware issue.

*Hardware repair is likely going to be costly so I've had very good luck with all manner of BTLE 4.0 dongles that use USB connectors. They cost $9 or so for good quality - try and look for one that says Mac compatible or buy from a company that accepts returns or can offer pre-sales assurance your chosen macOS will work. OWC is a good solid Mac centric vendor but I don't see them stocking, so this Amazon search should get you going: https://www.amazon.com/s/ref=nb_sb_ss_i_1_4?url=search-alias%3Daps&field-keywords=btle+dongle

A: In terminal, also remove the com.apple.driver.AppleBluetoothMultitouch.trackpad.plist and com.apple.driver.AppleBluetoothMultitouch.mouse.plist files from ~/Library/Preferences.
cd ~/Library/Preferences
sudo rm com.apple.driver.AppleBluetoothMultitouch.mouse.plist
sudo rm com.apple.driver.AppleBluetoothMultitouch.trackpad.plist

Then restart.
That fixed it for me.


text:
Q: How much RAM a server needs? I am going to develop a simple system of Perl CGI scripts which do email sending, file storage, and simple HTML user interface. The data should be stored in a MySQL database, HTTP is served with Apache.
As it is a typical server-side software system, I ask the question: How much RAM such a typical system needs?
I ask this because we are considering to order a Linux VPS. For example, on CoolHandle hosting VPS memory starts from 512MB. Is it enough for such simple CGI scripts?

A: There's no such thing as "typical server-side software system", especially if you're developing it yourself. Benchmark it under load and figure it out yourself - that's all you can do for this. For commercial software, the vendor may have sizing/scaling recommendations, but that's not the situation you find yourself in. VPS are cheap - start small with your intended host, benchmark it, and go up if you need to. Benchmarking isn't a one-time thing, either - if your userbase grows, you're going to need to be monitoring to determine when you need to grow anyway.

A: 256MB machine is good enough to host virualmin, with perl, email. To save memory its good to run it like fast-cgi, so can have 1 fast-cgi processor at the time so it makes around 25-50 requests per second, plus one mailbox with antivirus with on-demand spam checking. Fast-cgi runs from a separate context which can be protected with selinux. You can use another account (vhost) to host e.g. your sensitive data, under 64MB Perl process (e.g. without image upload). 256MB ram is more than enough. You might need also some extra RAM for cache, like 32MB.


text:
Q: Jenkins declarative pipeline - push Docker image to private docker hub repo I try to push to a private dockerhub repo from Jenkins but I always get errors due to Authorization I guess.
Here is the relevant Jenkins pipeline:
pipeline {
  agent {
    // run this pipeline inside an docker image with node 8 and git installed
    docker {
      image 'node/8-alpine'
      registryUrl 'https://registry.hub.docker.com'
      registryCredentialsId 'dockerhub' // the id of username/password credentials I have in Jenkins
    }
  }
  environment {
    registry = '<my-org>/<my-project>'
    tag_beta = "${currentBuild.displayName}-${env.BRANCH_NAME}"
  }
  stages {

    stage("Docker") {
      steps {
          script {
            // NPM_TOKEN was set as environment variable inside Jenkins
            def image = docker.build("${env.registry}:${env.tag-beta}",  "-e NPM_TOKEN=${env.NPM_TOKEN}")
            /* Push the container to the custom Registry */
            image.push()
          }

      }
    }
  }
}

Here is the error stack trace
groovy.lang.MissingPropertyException: No such property: beta for class: groovy.lang.Binding
    at groovy.lang.Binding.getVariable(Binding.java:63)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.SandboxInterceptor.onGetProperty(SandboxInterceptor.java:264)
    at org.kohsuke.groovy.sandbox.impl.Checker$6.call(Checker.java:289)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:293)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:269)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:269)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:269)
    at org.kohsuke.groovy.sandbox.impl.Checker.checkedGetProperty(Checker.java:269)
    at com.cloudbees.groovy.cps.sandbox.SandboxInvoker.getProperty(SandboxInvoker.java:29)
    at com.cloudbees.groovy.cps.impl.PropertyAccessBlock.rawGet(PropertyAccessBlock.java:20)
    at WorkflowScript.run(WorkflowScript:57)
    at ___cps.transform___(Native Method)
    at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.get(PropertyishBlock.java:74)
    at com.cloudbees.groovy.cps.LValueBlock$GetAdapter.receive(LValueBlock.java:30)
    at com.cloudbees.groovy.cps.impl.PropertyishBlock$ContinuationImpl.fixName(PropertyishBlock.java:66)
    at sun.reflect.GeneratedMethodAccessor351.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.cloudbees.groovy.cps.impl.ContinuationPtr$ContinuationImpl.receive(ContinuationPtr.java:72)
    at com.cloudbees.groovy.cps.impl.ConstantBlock.eval(ConstantBlock.java:21)
    at com.cloudbees.groovy.cps.Next.step(Next.java:83)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:174)
    at com.cloudbees.groovy.cps.Continuable$1.call(Continuable.java:163)
    at org.codehaus.groovy.runtime.GroovyCategorySupport$ThreadCategoryInfo.use(GroovyCategorySupport.java:129)
    at org.codehaus.groovy.runtime.GroovyCategorySupport.use(GroovyCategorySupport.java:268)
    at com.cloudbees.groovy.cps.Continuable.run0(Continuable.java:163)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.access$101(SandboxContinuable.java:34)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.lambda$run0$0(SandboxContinuable.java:59)
    at org.jenkinsci.plugins.scriptsecurity.sandbox.groovy.GroovySandbox.runInSandbox(GroovySandbox.java:136)
    at org.jenkinsci.plugins.workflow.cps.SandboxContinuable.run0(SandboxContinuable.java:58)
    at org.jenkinsci.plugins.workflow.cps.CpsThread.runNextChunk(CpsThread.java:182)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.run(CpsThreadGroup.java:332)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup.access$200(CpsThreadGroup.java:83)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:244)
    at org.jenkinsci.plugins.workflow.cps.CpsThreadGroup$2.call(CpsThreadGroup.java:232)
    at org.jenkinsci.plugins.workflow.cps.CpsVmExecutorService$2.call(CpsVmExecutorService.java:64)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at hudson.remoting.SingleLaneExecutorService$1.run(SingleLaneExecutorService.java:131)
    at jenkins.util.ContextResettingExecutorService$1.run(ContextResettingExecutorService.java:28)
    at jenkins.security.ImpersonatingExecutorService$1.run(ImpersonatingExecutorService.java:59)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)
Finished: FAILURE

I also tried
docker.withRegistry('', "myJenkinsCredentialsIdForDockerhub") {
  /* Push the container to the custom Registry */
  image.push()
}

Any help on how to authenticate from Jenkins declarative pipeline to private Docker hub registry would be highly appreciated!

A: Here how I create image with two tags, push it to private repository and delete image from local:
stage('Build and Push Docker Images'){
    steps{
        script {
            def imageName = "${containerRegistry}/${serviceName}/${optionalImageName}"
            docker.withRegistry("https://${containerRegistry}/${serviceName}", "1feb1e1e-9999-41bb-a269-89c999999999") {
                def customImage = docker.build(imageName)
                customImage.push("${newVersion}")
                customImage.push("latest")
                sh "docker rmi --force \$(docker images -q ${customImage.id} | uniq)"
            }
        }
    }
}

A: I think you have a typo:
def image = docker.build("${env.registry}:${env.tag-beta}",  "-e NPM_TOKEN=${env.NPM_TOKEN}"
                                                   ^

should be
def image = docker.build("${env.registry}:${env.tag_beta}",  "-e NPM_TOKEN=${env.NPM_TOKEN}"
                                                   ^

Note the _ over - in ${env.tag_beta}

A: In this post there is a good solution, it worked for me: https://issues.jenkins-ci.org/browse/JENKINS-48437?focusedCommentId=338354&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-338354
node {
    withDockerRegistry([credentialsId: 'docker-creds', url: 'https://index.docker.io/v1/']) {
        echo "Hello"
    }
}

A: The withRegistry needs the registry as first parameter and the credentialsID (for jenkins credentials) as second argument. Working example method:
/**
 * Stage **Push to registry**
 * login to Docker registry
 * @param dockerRegistryURL
 * @param dockerRegistryCredentialsId - Jenkins stored credentials for Docker registry
 * @param pushLatest - if true will push again with tag latest
 * @param newImage - Docker image handle with freshly built image to be pushed
 */
void push(String dockerRegistryURL, String dockerRegistryCredentialsId, boolean pushLatest, newImage) {
    stage('Push to registry') {
        echo (
            "pushing to registry url: 'https://${dockerRegistryURL}' " +
            "with credentials: '${dockerRegistryCredentialsId}'"
        )
        docker.withRegistry("https://${dockerRegistryURL}", dockerRegistryCredentialsId) {
            newImage.push()
            if (pushLatest)
                newImage.push("latest")
        }
    }
}


text:
Q: Kernel errors when using FMX BeginDragDrop to another application Update:
Indeed, the issue was fixed since 10.2.
I compared the FMX.Platform.Win from 10.4, the fix is in the  function TWinDropTarget.GetDataObject: TDragObject;

I've implemented the answer for
Drag and drop with TTreeView in Firemonkey to drag&drop TTreeViewItems in a Delphi 10.2 FMX Windows application.
Everything is working perfectly within the same app, however when the user suddenly drops an item to another copy of the same app, it hangs or even shuts down with c0000374 external error.
When trying to debug in the IDE, the source app stops with this system call stack:

I don't actually need the ability to drag between applications (although, it would be perfect). I'm just asking, how to avoid such errors?
According to the comment below, I've added a minimal example. Create a Win32 FMX app and add a TLabel to it:
object Form3: TForm3
  Left = 0
  Top = 0
  Caption = 'Form3'
  ClientHeight = 135
  ClientWidth = 331
  FormFactor.Width = 320
  FormFactor.Height = 480
  FormFactor.Devices = [Desktop]
  DesignerMasterStyle = 0
  object Label1: TLabel
    AutoSize = True
    StyledSettings = [Family, FontColor]
    HitTest = True
    Position.X = 72.000000000000000000
    Position.Y = 32.000000000000000000
    Size.Width = 120.000000000000000000
    Size.Height = 32.000000000000000000
    Size.PlatformDefault = False
    TextSettings.Font.Size = 24.000000000000000000
    TextSettings.Font.StyleExt = {00070000000000000004000000}
    Text = 'DrugMe!'
    TabOrder = 0
    OnMouseDown = Label1MouseDown
  end
end

Use this simple code to activate a drag:
unit Unit1;

interface

uses
  System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
  FMX.Platform,
  FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.Controls.Presentation, FMX.StdCtrls;

type
  TForm3 = class(TForm)
    Label1: TLabel;
    procedure Label1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
  private
    { Private declarations }
  public
    procedure StartDrag;
    { Public declarations }
  end;

var
  Form3: TForm3;

implementation

{$R *.fmx}

procedure TForm3.Label1MouseDown(Sender: TObject; Button: TMouseButton; Shift: TShiftState; X, Y: Single);
begin
  StartDrag;
end;

procedure TForm3.StartDrag;
var
  Svc:         IFMXDragDropService;
  DragData:    TDragObject;
  DragBmp:     TBitmap;
begin
  DragBmp := Label1.MakeScreenshot;

  if TPlatformServices.Current.SupportsPlatformService(IFMXDragDropService, Svc) then begin
    DragData.Source := nil;
    DragData.Files := nil;
    DragData.Data := DragBmp;

    Svc.BeginDragDrop(self, DragData, DragBmp);
  end;
end;

end.

and the DPR file:
program DragBug;

uses
  System.StartUpCopy,
  FMX.Forms,
  Unit1 in 'Unit1.pas' {Form3};

{$R *.res}

begin
  Application.Initialize;
  Application.CreateForm(TForm3, Form3);
  Application.Run;
end.

A: There is a bug in Delphi 10.2 which has been fixed in Delphi 10.4.2. All you have to do is to update to the latest Delphi version.


text:
Q: Debugging: Unable to reveal the value of the TStrings In my debugging, I tried to get Delphi to reveal or expose the value of FTestResult (TStrings). The Delphi's debugger shows in  "FTestResult     ()" in watch window.
private
FTestThread:TTestThread;
FTestState:TState;
FTestResult:TStrings; //represent a list of strings.
........
........
FTestResult.Clear();
FTestResult.Add('EmployeeId=''' + TMainForm(Application.MainForm).UserId.Text + '''');
........

Is this normal if it produces nothing in () after add?
Please advise... Thanks

A:
Is this normal if it produces nothing in () after calling Add?

Yes this is the expected behaviour. Delphi 7 does not have a bespoke debugger visualizer for TStrings. This functionality was added in Delphi 2010. You'll have to find some other way to inspect the contents of this object in Delphi 7.
The () is the output of the standard visualizer for an instance of a class. Inside the parens are the data members, of which TStrings has none.


text:
Q: http //tempuri.org/ in Web services? I am working on webservices. but i dont understand why does http://tempuri.org exist.i have go through some of the articles and came to know that it is used for uniqueness. when i click on that link it is redirecting to bing.
Plese explain how does it works? why it is not used in WCF?

A: From Wikipedia

Each XML Web service needs a unique namespace in order for client applications to distinguish it from other services on the Web.
  tempuri.org is the test default namespace URI used by Microsoft development products, like Visual Studio. It is available for XML Web services that are under development, but published XML Web services should use a more permanent namespace. The term is strictly a placeholder and all instances of it should be replaced with a more meaningful URI in production systems.

Since Microsoft owns tempuri.org, but it's only intended as a placeholder, they figured they would redirect it to a site they actually want you to use.

A: Setting Namespace on WorkflowServiceBehavior should definetly work,unless someother part of code is resetting it to null through servicedescription.Namespace but I will validate it. But to unblock you please try the following.
workflowServiceHost.Description.Namespace = "";; and see it works for you?
Nazim Ali

A: It's the default namespace used for schema and metadata documents when you do not explicitly specify one yourself. For example, when u mark a class with the DataContract attribute bur don't supply a value for the Namespace property. Same goes for an OperationContract, MessageContract, etc.


text:
Q: How do I pass an ArrayList method to a different method in the same class? What I am working on is reading in a file and passing it to an ArrayList which I have already done with this:
public ArrayList readInPhrase() {

    String fileName = "wholephrase.txt";
    ArrayList<String> wholePhrase = new ArrayList<String>();

    try {

        //creates fileReader object
        FileReader inputFile = new FileReader(fileName);

        //create an instance of BufferedReader
        BufferedReader bufferReader = new BufferedReader(inputFile);

        //variable to hold lines in the file
        String line;

        //read file line by line and add to the wholePhrase array
        while ((line = bufferReader.readLine()) != null) {
            wholePhrase.add(line);
        }//end of while

        //close buffer reader
        bufferReader.close();

    }//end of try

    catch(FileNotFoundException ex) {
        JOptionPane.showMessageDialog(null, "Unable to open file '" +
                fileName + " ' ", "Error",
                JOptionPane.INFORMATION_MESSAGE, null);
    }//end of file not found catch

    catch(Exception ex) {
        JOptionPane.showMessageDialog(null, "Error while reading in file '"
                + fileName + " ' ", "Error",
                JOptionPane.INFORMATION_MESSAGE, null);
    }//end of read in error

    return wholePhrase;

}//end of readInPhrase

The problem that I am now having is that I would like to go through this ArrayList and randomly select one phrase from it to eventually append asterisk's
to part of the phrase that is selected. I have tried a variety of different ways to do this.
This is the last attempt that I have tried:
public String getPhrase(ArrayList<String> wholePhrase) {

    Random random = new Random();

    //get random phrase
    int index = random.nextInt(wholePhrase.size());
    String phrase = wholePhrase.get(index);

    return phrase;

    }//end of getPhrase

A: From the comments on the question, you say you're calling getPhrase like this:
HangmanPhrase.getPhrase()

... which results in the error
method getPhrase in class HangmanPhrase cannot be applied to given types;
required: ArrayList<String> found: no arguments reason:
   actual and formal argument lists differ in length

The reason for this is that getPhrase takes an ArrayList<String> as an argument:
public String getPhrase(ArrayList<String> wholePhrase) {

You need to pass an ArrayList to the method getPhrase like so:
ArrayList<String> myListOfStrings = new ArrayList<String>();
// do stuff with myListOfStrings
getPhrase(myListOfStrings);

Also, since getPhrase is an instance method, not a static method, you cannot call it via HangmanPhrase.getPhrase. You need to create an instance of HangmanPhrase and call the method from that instance.

A: two issues as far as I can see.

*

*Return statements in Java follow 'return variable name;' rather than a method type call.

*You should be getting the array list using your random number subtract one, as indexes start at zero.

A: Then just do getPhrase(readInPhrase()). The compiler will call getPhrase(), and then evaulate readInPhrase() with the stack trace return point at getPhrase(...). This will return the ArrayList (which, by the way, needs to be type-parameterized with <String>). Then, getPhrase() is called with the ArrayList as the parameter, and then you get the phrase, and then there was much rejoicing.
Also, readInPhrase() needs to be returning an ArrayList<String> (in Java 1.5+)


text:
Q: Checking the Folner condition only on a set of generators Let $G$ be a countable, discrete group with a set of generators $S$. Let $F_n\subset G$ be a sequence of finite sets that satisfies $$\frac{|sF_n\triangle F_n|}{|F_n|}\to0$$
for all $s\in S$. Is it true then that $F_n$ is a Folner sequence? In other words, is it true that
$$\frac{|gF_n\triangle F_n|}{|F_n|}\to0$$
for all $g\in G$? In particular, does it suffice to check the Folner condition on the generators instead of the entire group? Let's set $\alpha_n(g)=\frac{|gF_n\triangle F_n|}{|F_n|}$.
I believe that this question boils down to showing that (1) if $\alpha_n(g)\to0$ then $\alpha_n(g^{-1})\to0$ and that (2) if $\alpha_n(g)\to0$ and $\alpha_n(h)\to0$ then $\alpha_n(gh)\to0$.
For (2) I observed that $$\alpha_n(gh)=\frac{|ghF_n\triangle F_n|}{|F_n|}=\frac{|(ghF_n\triangle hF_n)\triangle(hF_n\triangle F_n)|}{|F_n|}\leq\frac{|ghF_n\triangle hF_n|}{|F_n|}+\alpha_n(h)=$$
$$=\frac{|g(hF_n)\triangle hF_n|}{|hF_n|}+\alpha_n(h)$$
and I would be done if I could get some estimate of the form $|ghF_n\triangle hF_n|\leq C|gF_n\triangle F_n|$, but this seems impossible to me. Such an estimate would also be enough to show (1).
Any hint or reference is appreciated.

A: Apparently I "interpolated" the wrong thing. The problem is solved if one interpolates the set $gF_n$ instead of $hF_n$. To be more precise:
$$|ghF_n\triangle F_n|\leq|ghF_n\triangle gF_n|+|gF_n\triangle F_n|$$
and $ghF_n\triangle gF_n\subset g(hF_n\triangle F_n)$, because $gA\setminus gB\subset g(A\setminus B)$ for all $A,B$. therefore the above estimate  goes on as
$$\leq |g(hF_n\triangle F_n)|+|gF_n\triangle F_n|=|hF_n\triangle F_n|+|gF_n\triangle F_n|$$
and dividing everything with $|F_n|$ will yield $\alpha_n(gh)\leq\alpha_n(g)+\alpha_n(h)$.
A similar argument works for (1): we have that
$$|g^{-1}F_n\triangle F_n|=|g^{-1}F_n\triangle g^{-1}gF_n|\leq|g^{-1}(gF_n\triangle F_n)|=|gF_n\triangle F_n|$$
for all $g\in G$, thus $\alpha_n(g^{-1})\leq\alpha_n(g)$. Actually by symmetry one concludes that $\alpha_n(g)=\alpha_n(g^{-1})$.
It was very elementary after all. Still, I think it makes a good exercise for beginners!


text:
Q: Resetting click function on next click HI I have created a jcarousel and I want each pager item in the jcarousel to be faded until the user clicks to view the slide this is the current jquery I am using:
$(document).ready(function () {
    $('.overlay').css('display', 'block');
    $('.overlay').css('opacity', 1.0);
    $('.views_slideshow_jcarousel_pager_item').click(function() {
        $('.overlay', this).stop().animate({opacity:0.0},500);
    },
    function()
        $('.overlay').stop().animate({opacity:1.0},500);
    });
});

It's kind of working but it stays in the click state, anybody got any ideas on how to fix this?  The dev site is at dev.shoeboxdesign.co.uk

A: Not sure i get it, but shouldn't it be:
$('.views_slideshow_jcarousel_pager_item').click(function() {
    $('.overlay', this).stop().animate({opacity: 0}, 500, function() {
        $('.overlay').stop().animate({opacity: 1},500);
    });
});

Looks to me like your closing the first animation and then are trying to run a new function or something strange. there's just too many characters there?
Maybe you are trying to do a toggle? Who knows.
Also, you are animating back in all elements with the class .overlay, and not just the one you animated out, for that you could just use $(this) in the second animation, if that is the intended effect that is.


text:
Q: Searching for executable files Is there a way to search and delete all executables files within folder if there is no extension?
e.g  Let's suppose I have 4 files with .ubu extension and the following bash does the job I'm asking for:
rm *.ubu

e.g_2 Now let's suppose I have 4 but there is no extension at all, something like:
test test_2 test_3 (chmod +x on them)
How do I delete those files?

A: If we're talking about files with executable bit set, then find command has -executable test, and a -delete action.
find /DIR/EC/TORY -type f -executable -delete

or
find /DIR/EC/TORY -type f -executable -exec rm -f {} \;

should do the trick.
To specifically delete all executable files in your home directory (not in sub-directories) and ask you whether you want to delete each file you can do something like
find ~ -type f -executable -maxdepth 0 -exec rm -i {} \;

from man find:

   -exec command ;
          Execute  command;  true  if 0 status is returned.  All following
          arguments to find are taken to be arguments to the command until
          an  argument  consisting of `;' is encountered.  The string `{}'
          is replaced by the current file name being processed  everywhere
          it occurs in the arguments to the command, not just in arguments
          where it is alone, as in some versions of find.  Both  of  these
          constructions might need to be escaped (with a `\') or quoted to
          protect them from expansion by the shell.  See the EXAMPLES sec‐
          tion for examples of the use of the -exec option.  The specified
          command is run once for each matched file.  The command is  exe‐
          cuted  in  the starting directory.   There are unavoidable secu‐
          rity problems surrounding use of the -exec  action;  you  should
          use the -execdir option instead.

   -exec command {} +
          This  variant  of the -exec action runs the specified command on
          the selected files, but the command line is built  by  appending
          each  selected file name at the end; the total number of invoca‐
          tions of the command will  be  much  less  than  the  number  of
          matched  files.   The command line is built in much the same way
          that xargs builds its command lines.  Only one instance of  `{}'
          is  allowed  within the command.  The command is executed in the
          starting directory.

A: To find files (or directories!) without a dot, use the extended file matching pattern
!(*.*)

You need shopt -s extglob -- I think that option is on by default in interactive shells.
To delete executable files in bash
shopt -s extglob nullglob
for file in !(*.*); do
    [[ -f $file && -x $file ]] && echo rm "$file"
    # -f -> true if it's a file
    # -x -> true if it's executable
done

A: A binary file will have the executable bit marked.
So you can write a simple bash script which checks if the executable bit is set, and if so delete the file.


text:
Q: Is the functor $\text{Spec}:(\mathsf{CRing})^{\text{op}}\to\mathsf{Set}$ right exact? Let $(\mathsf{CRing})^{\text{op}}$ be the category opposite to the category $\mathsf{CRing}$ of commutative rings with one, and $\mathsf{Set}$ the category of sets. Recall that $\text{Spec}(A)$ is the set of prime ideals of $A$, and that a morphism $f:A\to B$ in $\mathsf{CRing}$ induces, in a functorial way, a map $\text{Spec}(B)\to\text{Spec}(A)$ sending $\mathfrak q$ to $f^{-1}(\mathfrak q)$.

(1a) Is the functor $\text{Spec}:(\mathsf{CRing})^{\text{op}}\to\mathsf{Set}$ right exact?

Here are four other equivalent forms of Question (1a):

(1b) Does the functor $\text{Spec}:(\mathsf{CRing})^{\text{op}}\to\mathsf{Set}$ commute with finite colimits?

Let $(A_i)_{i\in I}$ be a projective system of commutative rings indexed by a finite category $I$.

(1c) Is the natural map $$\operatorname*{colim}_i\text{Spec}(A_i)\to\text{Spec}\left(\lim_i A_i\right)$$ bijective?

The fourth and fifth forms will use the fact that our functor commutes with finite coproducts.  (Recall that coproducts in $(\mathsf{CRing})^{\text{op}}$ correspond to products in $\mathsf{CRing}$.)

(1d) Does the functor $\text{Spec}:(\mathsf{CRing})^{\text{op}}\to\mathsf{Set}$ commute with cokernels?

Let $A\rightrightarrows B$ be two parallel morphisms in $\mathsf{CRing}$.

(1e) Is the natural map $$\operatorname{Coker}\Big(\text{Spec}(B)\rightrightarrows\text{Spec}(A)\Big)\to\text{Spec}\Big(\operatorname{Ker}(A\rightrightarrows B)\Big)$$ bijective?

Here is a second question:

(2) In the above setting, is the natural map $$\text{Spec}(A)\to\text{Spec}\Big(\operatorname{Ker}(A\rightrightarrows B)\Big)$$ surjective?

Of course, if the answer to (2) is "not necessarily", then the answer to (1) will be "no".
Martin Brandenburg asked a somewhat related question.

A: No.  For instance, let $A=B=\mathbb{C}[x]$ and let $f:A\to B$ be the identity map and $g:A\to B$ send $x$ to $x+1$.  Then the equalizer of $f$ and $g$ is the set of polynomials $p$ such that $p(x)=p(x+1)$, which is just the constant polynomials $\mathbb{C}$ (since if such a $p$ were nonconstant, it would need to have infinitely many roots).  But the coequalizer of spectra has more than one point, since it is just the quotient $\mathbb{C}/\mathbb{Z}$ (together with a generic point).
The answer to the second question is also no.  For instance, let $A=\mathbb{C}[x,y,r,s]/(rx+sy-1)$ and $B=\mathbb{C}[x,y,r,s,t,u]/(rx+sy-1,tx+uy-1)$.  There is an obvious inclusion map $f:A\to B$ but there is also a map $g:A\to B$ which sends $r$ and $s$ to $t$ and $u$.  I claim that the equalizer of $f$ and $g$ is just $C=\mathbb{C}[x,y]$.  Given this claim, we see that the prime ideal $P=(x,y)\subset C$ does not extend to any prime ideal of $A$, so the map $\operatorname{Spec} A\to\operatorname{Spec} C$ is not surjective.
To prove the claim, let $a\in A$ be such that $f(a)=g(a)$.  We can write $a$ as a sum of monomials which do not contain $rx$ (since we can replace $rx$ with $1-sy$).  First suppose that no monomial of $a$ contains $r$.  Then $a$ is a polynomial in just $s$, $x$, and $y$; suppose $s$ does appear in $a$.  We can pick values $x_0,y_0\in\mathbb{C}$ with $x_0\neq 0$ such that when we substitute $x_0$ for $x$ and $y_0$ for $y$, $a$ becomes a nonconstant polynomial $p(s)$ in $s$.  For any $\alpha,\beta\in\mathbb{C}$, we can now consider the homomorphism $e_{\alpha,\beta}:B\to\mathbb{C}$ which sends $y$ to $y_0$, $s$ to $\alpha$, $u$ to $\beta$, $x$ to $x_0$, $r$ to $\frac{1-\alpha y_0}{x_0}$, and $t$ to $\frac{1-\beta y_0}{x_0}$.  We then have $e_{\alpha,\beta}(f(a))=p(\alpha)$ and $e_{\alpha,\beta}(g(a))=p(\beta)$.  Since $p$ is nonconstant, we can choose $\alpha$ and $\beta$ such that $p(\alpha)\neq p(\beta)$ and reach a contradiction.
So, we may assume that $r$ does appear in $a$; write $a=\sum_{i=0}^n a_i x^i+\sum_{j=1}^m b_jr^j$ where the $a_i$ and $b_j$ are in $\mathbb{C}[y,s]$.  Replacing every appearance of $r$ by $\frac{1-sy}{x}$, we may consider $a$ as a Laurent polynomial in $x$ with coefficients in $\mathbb{C}[s,y]$ (the division by $x$ is not an issue because we will eventually be substituting a nonzero complex number for $x$).  Since $r$ appears in $a$, some $b_j$ is nonzero.  Thus one of the coefficients of this Laurent polynomial involves $s$, since we replaced $r$ with $\frac{1-sy}{x}$.  So, we can also consider $a$ as a nonconstant polynomial in $s$ with coefficients in $\mathbb{C}[x,1/x,y]$.  We can now choose $x_0,y_0\in\mathbb{C}$ with $x_0\neq 0$ such that when we substitute them for $x$ and $y$, $a$ becomes a nonconstant polynomial in $s$, and reach a contradiction as in the previous case.


text:
Q: How to Calculating ROC and AUC in Caffe? I have trained a binary-classes CNN in Caffe, and now i want to plot the ROC curve and calculate the AUC value. I have two quetions:
1) How to plot the ROC curve in Caffe with python?
2) How to calculate the AUC value of the ROC curve?

A: Python has roc_curve and roc_auc_score functions in sklearn.metrics module, just import and use them.
Assuming you have a binary prediction layer that outputs a two-vector of binary class probabilities (let's call it "prob") then your code should look something like:
import caffe
from sklearn import metrics
# load the net with trained weights
net = caffe.Net('/path/to/deploy.prototxt', '/path/to/weights.caffemodel', caffe.TEST)
y_score = []
y_true = []
for i in xrange(N): # assuming you have N validation samples
    x_i = ... # get i-th validation sample
    y_true.append( y_i )  # y_i is 0 or 1 the TRUE label of x_i
    out = net.forward( data=x_i )  # get prediction for x_i
    y_score.append( out['prob'][1] ) # get score for "1" class
# once you have N y_score and y_true values
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_score, pos_label=1)
auc = metrics.roc_auc_score(y_true, y_scores)