text:
Q: Rolify and Rails 4 role management I am trying to implement a role based access system in my rails 4 app, and I want the end user (super_admin) to have the ability to edit role assignments via the UI.
I have achieved some success but can't help feeling that there has to be a better way (Since I'm new to rails). Here is my code:
users_roles_controller.rb

# GET /user_roles/new/:id
def new
  @roles = Role.all
end

# POST /user_roles/new/:id
def create
  populated = params[:roles][:name].reject(&:empty?)
  populated.each do |key|
    @user.add_role  Role.find(key).name
  end

  redirect_to users_path
end

And in my Form (HAML and simple_form):
= simple_form_for :roles, :url => create_user_roles_path(@user.id), :method => "post" do |f|

= f.input :name, :collection => @roles,   as: :check_boxes

= f.button :submit

I'm struggling with the following:

*

*How do I validate form entries, since there is no model?

*Should I be using strong parameters and if so how do I implement on a form without a model

*How do I create something similar, but with Current roles already checked? (True role management)

UPDATE
I have looked at using the reform Gem as suggested by the comments. This seems like a great solution. I am however having issues with the implementation on this case.
Let me map it out:
I have 3 tables in the database:

*

*users

*users_roles (Mapping Table with 2 Attributes : user_id & role_id {Join Table -> HABTM})

*roles

I want to construct a form with all the values in the Roles model as checkboxes.The checkboxes should dictate what values are fed into the users_roles table (With relation to a specific user). What I want reform to do is validate the input of this form. This form will always display all of the values in Roles, but some/all of the boxes might be unchecked.
I have created a form folder in my app and started with the following code:
class UserRoleForm < Reform::Form

property :user__id, on: :user
property :role_id, on: :role

validates :user__id, presence: true
validates :role__id, presence: true
end

Am I going in the right direction?
Thanks for the help.

A: You need two things to build your form: a user's roles and the possible roles.
If I recall correctly, rolify gives your model associations ad should just let you do something like some_user.roles to return all the roles applied to some_user.
To get possible roles, try Role.all.
To combine both, try
user_roles = some_user.roles.pluck(:name) # suppose this returns ["admin"]
Role.pluck(:name).map { |r| [r, user_roles.include?(r)] }

You now have an array like this that you can use to build your form checkboxes with an each loop.
 [["customer", false], ["admin", true], ["editor", false]]

Define your reform object's sync or save method to handle what to do with the submitted input, however you are handling it. You can (SHOULD) make a custom validation to verify if the submitted roles are valid roles.


text:
Q: Reset PHP cache via command line When I try to reset cache from command line with:
php -r "opcache_reset();"

I get the following error message:

Call to undefined function opcache_reset() in Command line code on
  line 1

Is there a way to add the opcache_reset function to PHP via php.ini or something like this?
Thanks for help.

A: You need to check your php.ini config files.
Option 1)
Enable the following flag in your opcache config, likely under mods-available
opcache.enable_cli

Option 2)
If you have different config for CLI and apache2/fpm then check the CLI version has enabled opcache

redpajama_set_name: RedPajamaStackExchange


text:
Q: App crashes when nothing is entered in the TextBoxes I'm trying to parse I'm developing an app for windows phone in Visual Studio and it's my first time using C# language in general because I'm an Android developer and I can't figure out why my app crashes on button press if nothing is entered.
If someone could help that would be awesome. Thanks alot!!
private void sum_Click(object sender, RoutedEventArgs e)
{
    decimal n1 = decimal.Parse(num1.Text);
    decimal n2 = decimal.Parse(num2.Text);
    decimal n3 = decimal.Parse(num3.Text);

    if (n1.Equals(null) || n2.Equals(null) || n3.Equals(null))
    {
        sum1.Text = "Enter something!";
    }
    else
    {
        decimal sum = n1 + n2 + n3;
        String m = Convert.ToString(sum);
        sum1.Text = m;
    }
}

A: Attempting to parse empty text fields (or fields with invalid data) is the most likely candidate for throwing an exception and causing a crash. Also, the result of decimal.Parse is not going to be null, so the if portion of your if/else block won't execute.
I'd recommend using decimal.TryParse instead, which allows you to do something (like display your message) when parsing fails.
private void sum_Click(object sender, RoutedEventArgs e)
{
    decimal n1;
    decimal n2;
    decimal n3;

    if (decimal.TryParse(num1.Text, out n1)
        && decimal.TryParse(num2.Text, out n2)
        && decimal.TryParse(num3.Text, out n3))
    {
        decimal sum = n1 + n2 + n3;
        String m = Convert.ToString(sum);
        sum1.Text = m;
    }
    else
    {
        sum1.Text = "One or more fields has a missing/invalid value.";
    }
}


text:
Q: Код вроде верный, но не проходит скрытые тесты в обучающей программе Доброй ночи.
Поставлена следующая задача:
Дан список стран и городов каждой страны. Затем даны названия городов. Для каждого города укажите, в какой стране он находится.
Программа получает на вход количество стран N. Далее идет N строк, каждая строка начинается с названия страны, затем идут названия городов этой страны. В следующей строке записано число M, далее идут M запросов — названия каких-то M городов, перечисленных выше.
Для каждого из запроса выведите название страны, в котором находится данный город.

Написала код, приведенный ниже. Вроде на всех данных, которые я ввожу, программа работает. При загрузке в тестирующую систему не засчитывает результат, говорит, что не пройдены скрытые тесты. Причем в качестве примера выгружает тот массив данных, на которых тест как раз пройден. Как понять, что им не нравится?
Мои догадки, что название страны может писаться не одним словом, а через пробел, напр. The United States of America или The United Kingdom. Помогите, пожалуйста, разобраться.
n = int(input())
CountryCity = {}
CityList = []
for i in range(n):
    a = input().split()
    CountryCity[a[0]] = list(a[1:])
m = int(input())
for j in range(m):
    CityList.append(input())
for x in range(0, len(CityList)):
    for key in CountryCity:
        if CityList[x] in CountryCity[key]:
            print(key)

A: Я бы сделал наоборот:
словарь городов - где каждому городу в соответствие поставлена страна
n = int(input())

cities = dict()

for i in range(n):
    info = input().split()
    for city in info[1:]:
        cities[city] = info[0]

m = int(input())

res = []

for i in range(m):
    city = input()
    res.append(cities[city])

print(*res, sep='\n')

вывод такой хитрый сделал, потому что иногда в тестах вывод требуется только после ввода всей информации
P.S.
касательно почему алгоритм даёт сбой на некоторых тестах, то думаю

*

*вряд ли страны состоят из нескольких слов иначе это было бы в условии, да и как определить такую страну и отделить ее от города

*возможно, что город с одним и тем же названием есть в нескольких странах и требуется вывести только 1 страну - в вашем коде вывод всех стран с городом будет

*возможно вводятся города, которых не было в списках и надо добавлять проверку на это - чтобы программа не падала
P.P.S.
кстати ваш код, если выкинуть лишние вызовы, трамбуется в такой:
n = int(input())

CountryCity = {}
CityList = []

for i in range(n):
    a = input().split()
    CountryCity[a[0]] = a[1:]

m = int(input())

for j in range(m):
    CityList.append(input())

for city in CityList:
    for key in CountryCity:
        if city in CountryCity[key]:
            print(key)


text:
Q: TransactionScope throws TransactionAbortedException when Disposed I have the following scenario:

*

*Parent process start TransactionScope, a token identifying the  transaction is created using TransactionInterop.GetTransmitterPropagationToken, inserts data to database. TransactionScope completes.

*Another process is started, using the above mentioned token it creates Transaction which is then used to create TransactionScope. This process also inserts data to database. TransactionScope completes and is disposed.

*Parent process tries to dispose its TransactionScope at this point, and TransactionAbortedException is thrown. The exception doesn't give any reasons for not being able to commit.

Stack Trace:
at System.Transactions.TransactionStatePromotedAborted.BeginCommit(InternalTransaction tx, Boolean asyncCommit, AsyncCallback asyncCallback, Object asyncState)
at System.Transactions.CommittableTransaction.Commit()
at System.Transactions.TransactionScope.InternalDispose()
at System.Transactions.TransactionScope.Dispose()
at DistributedTransactions.Program.Main() in c:\Users\agolan.ALLSHARE\Documents\Visual Studio 2013\Projects\DistributedTransactions\DistributedTransactions\Program.cs:line 44
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()

Here is the code of the application:
internal class Program {
    private static void Main() {
        string connString = "data source=.;initial catalog=Test;integrated security=True;persist security info=True";
        string tokenFile = @"c:\Temp\token.txt";

        Transaction transaction = null;
        bool isChild = false;
        if (File.Exists(tokenFile)) {
            isChild = true;
            string tokenString = File.ReadAllText(tokenFile);
            byte[] token = Convert.FromBase64String(tokenString);
            transaction = TransactionInterop.GetTransactionFromTransmitterPropagationToken(token);
        }
        using (var transactionScope = transaction != null ? new TransactionScope(transaction) : new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 15, 0))) {
            var curr = Transaction.Current;
            if (!isChild) {
                byte[] transactionBytes = TransactionInterop.GetTransmitterPropagationToken(curr);

                string tokenString = Convert.ToBase64String(transactionBytes);
                File.WriteAllText(tokenFile, tokenString);
            }
            using (var conn = new SqlConnection(connString)) {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand()) {
                    Console.WriteLine("Enter id and value");
                    cmd.CommandText = "INSERT INTO KeyValue(Id, Value) VALUES (@1, @2)";
                    cmd.Parameters.Add(new SqlParameter("@1", Console.ReadLine()));
                    cmd.Parameters.Add(new SqlParameter("@2", Console.ReadLine()));
                    cmd.ExecuteNonQuery();
                }
            }
            transactionScope.Complete();

            Console.WriteLine("Dispose");
            Console.ReadLine();
        }
    }
}

The questions:

*

*Why is it not able to commit?

*Is it possible to use TransactionScope in this scenario (I read answer Using transactions across processes but I would like to use TransactionScope)? How?

A: I was able to replicate this locally and it happens because the other application has exited before the parent process has committed the transaction. The other applications must continue running until the parent commits or rolls back the transaction. One way of doing this is preventing the applications from exiting until the TransactionCompleted event is fired.
I revised your code to use a ManualResetEventSlim to make the child process wait for the parent transaction process to complete before exiting.
internal class Program
{
    private static void Main()
    {
        string connString = "data source=.;initial catalog=Test;integrated security=True;persist security info=True";
        string tokenFile = @"c:\Temp\token.txt";

    Transaction transaction = null;
    bool isChild = false;
    if (File.Exists(tokenFile))
    {
        isChild = true;
        string tokenString = File.ReadAllText(tokenFile);
        byte[] token = Convert.FromBase64String(tokenString);
        transaction = TransactionInterop.GetTransactionFromTransmitterPropagationToken(token);
    }
    using (var parentTxCompleteEvent = new ManualResetEventSlim(!isChild))
    {
        using (var transactionScope = transaction != null ? new TransactionScope(transaction) : new TransactionScope(TransactionScopeOption.Required, new TimeSpan(0, 15, 0)))
        {
            var curr = Transaction.Current;
            if (!isChild)
            {
                byte[] transactionBytes = TransactionInterop.GetTransmitterPropagationToken(curr);

                string tokenString = Convert.ToBase64String(transactionBytes);
                File.WriteAllText(tokenFile, tokenString);
            }
            else
            {
                transaction.TransactionCompleted += (sender, e) => parentTxCompleteEvent.Set();
            }
            using (var conn = new SqlConnection(connString))
            {
                conn.Open();
                using (SqlCommand cmd = conn.CreateCommand())
                {
                    Console.WriteLine("Enter id and value");
                    cmd.CommandText = "INSERT INTO KeyValue(Id, Value) VALUES (@1, @2)";
                    cmd.Parameters.Add(new SqlParameter("@1", Console.ReadLine()));
                    cmd.Parameters.Add(new SqlParameter("@2", Console.ReadLine()));
                    cmd.ExecuteNonQuery();
                }
            }
            transactionScope.Complete();

            Console.WriteLine("Dispose");
            Console.ReadLine();
        }
        parentTxCompleteEvent.Wait();
    }
}

}


text:
Q: Fetch API call for each item in a Jinja2 for loop I'm currently stuck on a personal project where Im making Fetch API calls to get the audio src for a list of html audio tags.
The fetch call is triggered by an onclick event on the track. Though regardless of what track i click on, fetch calls /play_track/1/ and appends the audio player to only the first track. Any way to remedy this?
As you can see my index.html is basically just jinja2:
{% extends 'base.html' %}

{% block content %}

    {% for track in tracks %}
        {% include '_post.html' %}
    {% endfor %}

{% endblock content %}

Heres _post.html with the Fetch call: (Currently using an onclick event to call but will switch to onpageload)

{{ track.title }}

{{ track.artist }}

Uploaded on {{ track.created_at.strftime('%b %m, %Y') }}

{{ track.id }}

And here is the backend code: (Which im pretty sure if i tweak I can avoid Fetch all-together but thats another issue)
@bp.route('/play_track/<track_id>/')
def play_track(track_id):

    track = Track.query.filter_by(id=track_id).first()

    res = requests.get(track.audio)
    if not res.status_code == 200:
        return f'Status code: {res.status_code}'

    json_res = json.loads(res.text)
    mpeg_audio_url = json_res['url']

    msg_dict = {
        'url': mpeg_audio_url
    }

    res = make_response(jsonify({'message': msg_dict}))
    return res

To summarize: Fetch call not understanding Jinja2 for loop. Whether i click on track 1, 10, or 46, etc, It calls /play_track/1/ and appends the audio tag to the first track.
Thanks!

A:         function fetchURL(event) {
            tid = event.target;
            track_id = tid.innerHTML;

            fetch(`${window.origin}/play_track/${track_id}`)
                .then((response) => {
                    console.log(response.status);
                    return response.json();
                })
                .then(function(data) {
                    console.log(data.message.url);
                    createAudioPlayer(data, event);
                });
        }

The problem was the first line. you weren't getting the current event target.
Ids are must be unique thus every time you loop through the track you create an element with the same id. Change track-id from id to class.

{{ track.id }}

Also since you were using document.getElementById() it would return the first occurrence of that id. That is the reason, it was returning track 1 constantly. Another thing, there is no point in having it loop the javascript over and over since the new ones would just override the old ones.
Fixed createAudioPlayer(), make sure to pass the event object into it. I already did it for you, so just copy the new fetchURL function.
        function createAudioPlayer(data, event) {

            let cardBody = event.target.parentElement;

            let audio = document.createElement('audio');
            audio.controls = true;

            let source = document.createElement('source');
            source.type = "audio/mpeg";
            source.src = data.message.url

            cardBody.append(audio);
            audio.prepend(source);
        };


text:
Q: How do you do block comments in YAML? How do I comment a block of lines in YAML?

A: In Vim you can do one of the following:

*

*Comment all lines: :%s/^/#

*Comment lines 10 - 15: :10,15s/^/#

*Comment line 10 to current line: :10,.s/^/#

*Comment line 10 to end: :10,$s/^/#
or using visual block:

*

*Select a multiple-line column after entering visual block via Ctrl+v.

*Press r followed by # to comment out the multiple-line block replacing the selection, or Shift+i#Esc to insert comment characters before the selection.

A: An alternative approach:
If

*

*your YAML structure has well defined fields to be used by your app

*AND you may freely add additional fields that won't mess up with your app

then

*

*at any level you may add a new block text field named like "Description" or "Comment" or "Notes" or whatever

Example:
Instead of
# This comment
# is too long

use
Description: >
  This comment
  is too long

or
Comment: >
    This comment is also too long
    and newlines survive from parsing!

More advantages:

*

*If the comments become large and complex and have a repeating pattern, you may promote them from plain text blocks to objects

*Your app may -in the future- read or update those comments

A: The specification only describes one way of marking comments:

An explicit comment is marked by a "#" indicator.

That's all. There aren't any block comments.

A: One way to block commenting in YAML is by using a text editor like Notepad++ to add a # (comment) tag to multiple lines at once.
In Notepad++ you can do that using the "Block Comment" right-click option for selected text.

A: YAML supports inline comments, but does not support block comments.
From Wikipedia:

Comments begin with the number sign ( # ), can start anywhere on a line, and continue until the end of the line

A comparison with JSON, also from Wikipedia:

The syntax differences are subtle and seldom arise in practice: JSON allows extended charactersets like UTF-32, YAML requires a space after separators like comma, equals, and colon while JSON does not, and some non-standard implementations of JSON extend the grammar to include Javascript's /* ... */ comments. Handling such edge cases may require light pre-processing of the JSON before parsing as in-line YAML.

# If you want to write
# a block-commented Haiku
# you'll need three pound signs

A: I am not trying to be smart about it, but if you use Sublime Text for your editor, the steps are:

*

*Select the block

*Cmd + / on Mac or Ctrl + / on Linux and Windows

*Profit

I'd imagine that other editors have similar functionality too. Which one are you using? I'd be happy to do some digging.

A: Emacs has comment-dwim (Do What I Mean) - just select the block and do a:

M-;

It's a toggle - use it to comment AND uncomment blocks.
If you don't have yaml-mode installed you will need to tell Emacs to use the hash character (#).

A: In the Azure DevOps browser (pipeline YAML editor),
Ctrl + K + C Comment Block
Ctrl + K + U Uncomment Block
There also a 'Toggle Block Comment' option, but this did not work for me.

There are other 'weird' ways too: Right-click to see 'Command Palette' or F1

Then choose a cursor option.

Now it is just a matter of #.
Or even smarter [Ctrl + K] + [Ctrl + C]

A: For RubyMine users on Windows:

*

*Open the file in the editor.

*Select the block and press:
Ctrl + /,

*And you will have the selected block starting with #.
Now if you want to uncomment the commented block, press the same key combination Ctrl + forward slash again.

A: In a .gitlab-ci.yml file, the following works:

To comment out a block (multiline): Select the whole block section >
Ctrl K C
To uncomment already commented out block (multiline): Select the
whole block section >  Ctrl K U

A: If you are using Eclipse with the YEdit plugin (an editor for .yaml files), you can comment-out multiple lines by:

*

*selecting lines to be commented, and then

*Ctrl + Shift + C
And to uncomment, follow the same steps.


text:
Q: ADF - Edit multiple rows of detail table simultaneously from master table My query surrounds the Master-Detail relationship in Oracle ADF Development.
What i am trying to do is make a "batch" change to all rows of a particular detail table without having to change each row individually.
For example, i have a master table of countries and corresponding detail tables of all the cities within those countries. The cities table has a column for "dialing code". If i select "UK" from the countries table i want to be able to populate the "dialing code" column of all the cities in UK with the value "+44" without having to go through them one by one.
Is this possible? I'm assuming a Master-Detail relationship is perfect for this but if not, what else is out there?
Thanks in advance for your help.

A: You can write a service method on your master VO that iterates through all the details of a row and updates an attribute in them.
You can then expose that service method to the client and drag it to add it to a page you are building.
Some links:
http://download.oracle.com/otn_hosted_doc/jdeveloper/11gdemos/ADF_Insider_Essentials/IterateRows/IterateRows.html
https://blogs.oracle.com/shay/entry/am_service_method_-_simple_dem


text:
Q: Как обновить базу данных в VS? Есть функция, удаляющая выделенную пользователем строку из таблицы базы данных, а так же все строки из дочерней таблицы, содержащие тот же ID родительской таблицы. Но после перезапуска программы изменения не сохраняются, в чем может быть проблема?
private void buttonDelete_Click(object sender, EventArgs e) {
int numRow = bindingSourse.Position;
string parentID = null;

DataRow selectRow = dataSetDP_DB.Tables[DataSpr.NameTable].Rows[numRow];
foreach (DataColumn prCol in dataSetDP_DB.Tables[DataSpr.NameTable].Columns) {
    if (prCol.Unique == true) {
        int numCol = prCol.Ordinal;
        parentID = selectRow[prCol.Ordinal].ToString();
        break;
    }
}

DataRow[] delrow = null;

foreach (DataRelation relation in dataSetDP_DB.Tables[DataSpr.NameTable].ChildRelations) {
    int k = 0;
    foreach (DataColumn chCol in relation.ChildColumns) {
        foreach (DataRow row in relation.ChildTable.Rows) {
            if (row[chCol.Ordinal].Equals(parentID)) {
                row.Delete();
            }

        }
    }
}
dataSetDP_DB.Tables[DataSpr.NameTable].Rows.RemoveAt(numRow);
tableAdapterManagerSPR.UpdateAll(dataSetDP_DB);
}

A: Если вы используете локальную базу данных, там есть один нюанс: нужно изменить в настройках базы свойство Copy to output directory на Copy if newer (ну или попробуйте другие варианты).


text:
Q: Run a specific version of Julia in Jupyter notebook I recently installed Julia version 0.7.0 (I need this older version). Prior to that, I had installed Julia 1.6.2, and I can use it in Jupyter notebook. Now, through Julia command line in version 0.7.0, I installed IJulia, and after launching the jupyter notebook through the same command line, I am not able to open notebooks in version 0.7.0. I only see options for 1.6.2.
How can I launch a notebook with version 0.7.0 of Julia?
UPDATE
Now I am able to see Julia 0.7.0 as an option when I open Jupyter notebook, but now the kernel does not connect when I want to use it for this specific version. It works fine for version 1.6.2.
I have tried opening a notebook in two different ways:

*

*From anaconda command line: The notebook launches, but the kernel does not connect. The following error keeps repeating:

ERROR: LoadError: MethodError: no method matching setindex!(::Ptr{Nothing}, ::Ptr{Nothing})
Stacktrace:
 [1] start_heartbeat(::ZMQ.Socket) at C:\Users\josh\.julia\packages\IJulia\AQu2H\src\heartbeat.jl:20
 [2] init(::Array{String,1}) at C:\Users\josh\.julia\packages\IJulia\AQu2H\src\init.jl:100
 [3] top-level scope at none:0
 [4] include at .\boot.jl:317 [inlined]
 [5] include_relative(::Module, ::String) at .\loading.jl:1038
 [6] include(::Module, ::String) at .\sysimg.jl:29
 [7] exec_options(::Base.JLOptions) at .\client.jl:239
 [8] _start() at .\client.jl:432
in expression starting at C:\Users\josh\.julia\packages\IJulia\AQu2H\src\kernel.jl:24

*From Julia command line: I get a message that says Process Exited(1) at the end without opening any notebook.

A: Try
julia> using Pkg; Pkg.build("IJulia")

within the 0.7 REPL. This should install the Jupyter kernel for Julia 0.7 and make it available as an option.
In case that doesn't work for some reason, you can also try explicitly calling the installkernel function:
julia> installkernel("Julia 0.7")


text:
Q: Alter table on a running database I am using Postgres 8.4
I need to execute an ALTER statement on a running database with ~4M data on the relevant table. My sql is like:
ALTER TABLE some_table ALTER a_row bigint;

Now, relevant row type is int
But what i wonder is data consistency, Nearly 3-4 records are written to that table and some more are being read per second.
What i need to do for avoiding data consistency and such other problems.

A: When you execute and ALTER TABLE sql, table will be locked and you shouldn't have any problems except some possible performance issues in INSERT sqls in your case. But if you are going to do this once, there is no reason to hesitate.


text:
Q: How to make form upload multiple files? I have a question about uploading multiple files? I have set the HTML to multiple="multiple" and then you can upload multiple but what I received in the email is only one file. Is there a way to make it upload multiple files not just one? Im thanking you in advance. Here is the php:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
/*
Tested working with PHP5.4 and above (including PHP 7 )

 */
require_once './vendor/autoload.php';

use FormGuide\Handlx\FormHandler;

$pp = new FormHandler();

$validator = $pp->getValidator();
$validator->fields(['name','email'])->areRequired()->maxLength(50);
$validator->field('email')->isEmail();
$validator->field('message')->maxLength(6000);

$pp->attachFiles(['image']);

$pp->sendEmailTo('ragnaruus3@gmail.com'); // ← Your email here

echo $pp->process($_POST);

$(function() {
  function after_form_submitted(data) {
    if (data.result == 'success') {
      $('form#reused_form').hide();
      $('#success_message').show();
      $('#error_message').hide();
    } else {
      $('#error_message').append('

');

      jQuery.each(data.errors, function(key, val) {
        $('#error_message ul').append('
' + key + ':' + val + '
');
      });
      $('#success_message').hide();
      $('#error_message').show();

      //reverse the response on the button
      $('button[type="button"]', $form).each(function() {
        $btn = $(this);
        label = $btn.prop('orig_label');
        if (label) {
          $btn.prop('type', 'submit');
          $btn.text(label);
          $btn.prop('orig_label', '');
        }
      });

    } //else
  }

  $('#reused_form').submit(function(e) {
    e.preventDefault();

    $form = $(this);
    //show some response on the button
    $('button[type="submit"]', $form).each(function() {
      $btn = $(this);
      $btn.prop('type', 'button');
      $btn.prop('orig_label', $btn.text());
      $btn.text('Saadab ...');
    });

    var formdata = new FormData(this);
    $.ajax({
      type: "POST",
      url: 'handler.php',
      data: formdata,
      success: after_form_submitted,
      dataType: 'json',
      processData: false,
      contentType: false,
      cache: false
    });

  });
});

          <form role="form" method="post" id="reused_form" enctype="multipart/form-data">

               Nimi:
              <input type="text" class="form-control" id="name" name="name" required maxlength="50">

               Email:
              <input type="email" class="form-control" id="email" name="email" required maxlength="50">

               Sõnum:
              <textarea class="form-control" type="textarea" name="message" id="message" placeholder="Sinu sõnum siia" maxlength="6000" rows="7"></textarea>

               Lisa manusesse fail (Max 25mb):
              <input type="file" class="form-control" id="image" name="image" multiple="multiple" required>

            <button type="submit" class="btn btn-lg btn-success pull-right" id="btnContactUs">Saada! →</button>
          </form>

Sinu sõnum saadeti edukalt!

VIGA
 Vabandame sinu sõnumi saatmisega tekkis viga. Palun vaadake sõnum üle.

A: Here is how to deal with multiple uploads:
    // the form field of type FILE in the HTML is named "upload" - yours may have other name, e.g. "image"

    // Count # of uploaded files in array
    $total = count($_FILES['upload']['name']);

    // Loop through each file
    for( $i=0 ; $i < $total ; $i++ )
    {
      //Get the temp file path
      $tmpFilePath = $_FILES['upload']['tmp_name'][$i];

      //Make sure we have a file path
      if ($tmpFilePath != "")
      {
        //Setup our new file path
        $filename = $_FILES['upload']['name'][$i];
        $size = $_FILES['upload']['size'][$i]; // might not be needed in your usecase

        $newDir = '/var/www/files/knowledge';
        if(!file_exists($newDir)) mkdir($newDir, 0777, TRUE);

        if(move_uploaded_file($tmpFilePath, $newDir.'/'.$filename))
        {
          // do whatever you need - e.g. store some info into a database
        }
      }
    }


text:
Q: How I center html "ul" element in bootstrap 4 (horizontal + vertical) inside  How to center html "ul" element in bootstrap4 (horizontal + vertical) with horizontal aligned "li"

A

B

C

A: If you use this code the list will be displayed in the center of the yellow box. I don't know why it won't work on the code preview on stackoverflow, but here you can see that it works.

A

B

C


text:
Q: Aggregate 3 table retreiveing full data of one I've already resolved, thanks to @RolandoMySQLDBA, a great part of this aggregation of 3 tables as shown on the link
old state of question with sqlfiddle
But I want to display whole rows of tblb even if it's not within the range of date. As  in the link, cacao is not displayed but it's in data of tblb.
Is it possible ? Using another method such Union etc.. ?
sqlfiddle

A: Just use LEFT join when joining tableb and tablec - in that case all records from tableb will be included.
sqlfiddle


text:
Q: CSS contain + position partially off-screen I want to fit a background image, using the css background-size: contain; properties, but position it partially off-screen. I have an image with a transparrent part and I would like to be able to manipulate the "fill", so I thought moving a background image into view would be a good way to achieve this:
.bottle {
    background-image: res://bottle_fill;
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: contain;
    background-position: 50% 30%;
}

But it seems that with the contain parameter, the image can't "overspill" from the div? I tried adding overflow: hidden but it didn't help. How can I achieve this? A JavaScript solution is fine if there isn't a css way.
Update:
https://jsfiddle.net/ghhxddnj/ here is a JSFiddle - try to get the smiley face half on, half off the screen, whilst it is sized contain. As noted by some of the comments, I know this is a slightly strange thing to want to do, but the background image must be the same size as the contents of the div (and <image> sized with the contain parameter) the raw files are the same size, hence if they both use contain, they will come out the same size and I can set x align to be center and then use y align to control how much of the bottle is full.

A: Try this:
var image_url = $('#logo').css('background-image'),
    image;

// Remove url() or in case of Chrome url("")
image_url = image_url.match(/^url\("?(.+?)"?\)$/);

if (image_url[1]) {
    image_url = image_url[1];
    image = new Image();

    // just in case it is not already loaded
    image.src = image_url;
    var imgoffset = image.height;
    $('#logo').css('background-position',-imgoffset)
}

Source: How do I get background image size in jQuery?
EDIT: https://jsfiddle.net/ckf55axs/


text:
Q: Complement of the union of countably many , mutually disjoint , non-empty open balls in $\mathbb R^n , (n >1) $ is path connected? Let $n \ge 2$ and $\{B_m\}_{m=1}^\infty$ be countably infinitely many , mutually disjoint , non-empty  open balls in $\mathbb R^n$ , then is $\mathbb R^n \setminus \cup_{m=1}^\infty B_m$ path-connected ?

A: Yes.
Let $B_m$ be the open ball of radius $r_m$ around $(x_m,y_m)$.
It suffices to consider the case $n=2$ and here to show that there exists a path from $(0,0)$ to $(1,0)$ (assuming wlog. that these points are in the set).
The obvious attempt is the curve $\gamma\colon [0,1]\to\mathbb R^2$, $t\mapsto (t,0)$, but for each disk it intersects we need to take a detour along the boundary of the disk. So try this $t\mapsto (t,f(t))$ instead, where
$$f(t)=\begin{cases}y_m+\sqrt{r_m^2-(t-x_m)^2}&\text{if $(t,0)\in B_m$ and $y_m\le 0$}\\
y_m-\sqrt{r_m^2-(t-x_m)^2}&\text{if $(t,0)\in B_m$ and $y_m> 0$}\\0&\text{otherwise}\end{cases} $$
This is well-defined (because $(t,0)$ can be inside at most one $B_m$), clearly continuous, and avoids all $B_m$ (again per their open disjointness).
Additionally, it turns out that this path is rectifyable and of length at most $\pi$ (or in the general case: $\pi$ times the straight distance).


text:
Q: Different form of equation of a straight line I have been told that any straight line in $\mathbb{R}^2$ can be represented by two parameters $(p,\theta)$ and the equation:
$$x\cos(\theta)+y\sin(\theta)-p=0$$
But am struggling to see intuitively why this equation gives a straight line. Can anyone explain to me in terms of geometry what the parameters $p$ and $\theta$ represent in terms of the line (i.e. like when we represent a line as $y=mx+c$, $m$ is the gradient and $c$ is the intercept, what is $\theta$ and $p$ in this setting?)?

A: You may rewrite the equation in the familiar form $y=mx+c$,
$$y=-\cot\theta\> x+p\csc\theta$$
to identify
$$m = -\cot\theta,\>\>\>\>\>p= c\sin\theta$$
Knowing that $m$ is the gradient, measured by $m=\tan\alpha$, with $\alpha$ being the angle between the line and the $x$-axis, you can rewrite $m=\tan(\frac\pi2 + \theta)$ and deduce that $\theta$ is the angle between the given line and the $y$-axis. (See the graph below.)
Similarly, knowing that $c$ is the $y$-intercept, then $p=c\cos\theta$ represents the distance of the line from the origin.

A: This is sometimes called a "normal" equation. Here, $(\cos\theta,\sin\theta)$ is a normal vector to the line, and therefore $\theta$ is the angle between the normal and the $OX$-axis. $p$ is the distance from the line to the origin.


text:
Q: Request an explain for a limit $$\lim_{x\to 0+}\exp\left(\frac{\ln \left( \frac{\ln(1+\tan 4x)}{4x} \right)}{\tan x}\right)=\lim_{x\to 0+}\exp\left(\frac{ \frac{\ln(1+\tan 4x)}{4x} -1}{x}\right)$$
Can anybody explain above equation? I can't understand right hand side of the equation. Where is $\tan x$ and how pop up $-1$? Thank you.
Sorry, infact I solved a question linked my question using Taylor expansion and I'm looking for a solution that not using Taylor and I saw the solution I have mentioned but I can't get it.

A: The notion of asymptotic equivalence is convenient here.
As $x\to0,$

*

*$\tan x\sim x$, and

*$\ln(1+\tan 4x)\sim\tan4x\sim4x$ i.e.
$$u:=\frac{\ln(1+\tan4x)}{4x}\to1,\text{ hence }\ln u\sim u-1.$$
Let us now look at the limit of the exponent in your RHS (which will also be the limit of the exponent in your LHS, by the previous observations).
$$\frac{u-1}x=\frac{\ln(1+\tan 4x)-4x}{4x^2}=\frac{\tan 4x-\frac{\tan^2(4x)}2+o(x^2)-4x}{4x^2}\sim\frac{-\frac{(4x)^2}2}{4x^2}=-2.$$
So, each of your two limits is equal to $e^{-2}$


text:
Q: Custom loss function on Keras gives a weird error: __call__() missing 1 required positional argument: 'y_true' I have an error that has been baffling me for hours. So basically, I implemented this loss function drawn from an article. With y_true = [0,0,...,1,...,0] and y_pred being my network's output of same size with probabilities to belong to each class. The idea is to add log(y_j) before 1 and add log(1-y_j) after 1. This penalization is useful in one problem I am trying to solve.
Yet I have this annoying error that I don't understand:
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-39-0a4261d1fc84> in <module>
     24 ])
     25
---> 26 model.compile(loss=custom_loss, optimizer='adam', metrics=['mse'])
     27
     28 model.fit(CT_scan_train[:250], dummy_y[:250], epochs=5)

~\AppData\Local\Continuum\anaconda3\lib\site-packages\keras\engine\training.py in compile(self, optimizer, loss, metrics, loss_weights, sample_weight_mode, weighted_metrics, target_tensors, **kwargs)
    227         #                   loss_weight_2 * output_2_loss_fn(...) +
    228         #                   layer losses.
--> 229         self.total_loss = self._prepare_total_loss(masks)
    230
    231         # Functions for train, test and predict will

~\AppData\Local\Continuum\anaconda3\lib\site-packages\keras\engine\training.py in _prepare_total_loss(self, masks)
    690
    691                     output_loss = loss_fn(
--> 692                         y_true, y_pred, sample_weight=sample_weight)
    693
    694                 if len(self.outputs) > 1:

TypeError: __call__() missing 1 required positional argument: 'y_true'

Thanks for your help !
import keras.backend as K
from sklearn.metrics import make_scorer

def loss(y_true, y_pred):
    d = K.argmax(y_true)
    loss = K.sum(K.log(y_pred[:d]))+K.sum(K.log(1-y_pred[d:]))
    return loss

custom_loss = make_scorer(loss)

model = Sequential([
    Conv3D(2,(5,5,5), strides=(1, 1, 1), input_shape=(92, 92, 92, 1)),
    Activation('relu'),
    MaxPooling3D(pool_size=(2, 2, 2), strides=None, padding='valid', data_format=None),
    Conv3D(2, (3,3,3), strides=(1, 1, 1)),
    Activation('relu'),
    MaxPooling3D(pool_size=(2, 2, 2), strides=None, padding='valid', data_format=None),
    Conv3D(2, (3,3,3), strides=(1, 1, 1)),
    Activation('relu'),
    #Reshape(target_shape)
    Flatten(),
    Dense(64),
    Activation('relu'),
    Dense(32),
    Activation('relu'),
    Dense(5),
    Activation('relu'),
])

model.compile(loss=custom_loss, optimizer='adam')

model.fit(X, y, epochs=5)

For more information about make_scorer, see: https://scikit-learn.org/stable/modules/generated/sklearn.metrics.make_scorer.html

A: check the answer here.
You don't need to use make_scorer for this, you can directly give your loss  function to model.compile
Hope it helps


text:
Q: Python:Errno 22 Invalid argument I am saving an attachment in a folder with python(2.7.5) and django(1.6.1).It is perfectly working on linux machine.But i am executing this project on windows  i am getting following error.
[Errno 22] Invalid argument
Request Method: POST
Request URL:    http://127.0.0.1:8000/save_partner
Django Version: 1.6.1
Exception Type: OSError
Exception Value:
[Errno 22] Invalid argument
Exception Location: C:\Python27\lib\site-packages\django\core\files\storage.py in    _save, line 199
Python Executable:  C:\Python27\python.exe
Python Version: 2.7.6
Python Path:
['C:\\Projects\\customer',
'C:\\Python27\\lib\\site-packages\\distribute-0.6.49-py2.7.egg',
'C:\\Python27\\lib\\site-packages\\pymongo-2.6.3-py2.7-win-amd64.egg',
'C:\\Windows\\system32\\python27.zip',
'C:\\Python27\\DLLs',
'C:\\Python27\\lib',
'C:\\Python27\\lib\\plat-win',
'C:\\Python27\\lib\\lib-tk',
'C:\\Python27',
'C:\\Python27\\lib\\site-packages',
'C:\\Python27\\lib\\site-packages\\setuptools-0.6c11-py2.7.egg-info']
Server time:    Sat, 29 Mar 2014 12:53:35 +0530

The error is showing in default_storage(last line) line
for i in request.FILES.getlist('avtar'):
    avatarName = i.name
    filepath='avatars/'+date+'_'+avatarName
    address = settings.MEDIA_ROOT+filepath
    path = refine(address)
    avtar_path=path
    default_storage.save("%s"%(filepath), ContentFile(i.read()))

default_storage.save("%s"%(filepath), ContentFile(i.read()))

the    default _storage    is imported from django
from django.core.files.storage import default_storage

Why it is not working in windows7..?

A: How are you populating filepath? Most likely you are constructing it using Linux file path convention, Linux uses front-slash (/) as path separator whereas Windows uses back-slash (\). Use Python's os.path module to formulate file paths in a platform independent manner.
#prints spam\egg on Windows and spam/egg on Linux
print os.path.join('spam', 'egg')


text:
Q: Slick.js don't work when v-for is updated Hi I used VueJS and slickjs.
The slick runs fine till v-for is updated.
I update v-for when click on event and send ajax.
The new data is store on same object that uses v-for.
V-for updates and all slides is visible, and slick doesn't work.
enter code here

               {{place.location}}

                 {{place.country}}

A: My assumption is that the code you have in the updated hook is what you are wanting to run when the data being rendered by the v-for directive changes. If that is the case, you should try using a watcher like so:
{
    data() {
        return {
            id: undefined,
            image: undefined,
            locattion: undefined,
            country: undefined,
            tags: "Experiences",
            destinations: undefined
        }
    },
    created() {
        this.getData();
    },

    watch: {
        destinations: {
            deep: true, // this will make it observe deep changes
            // in objects this means it also fires when changes to its properties happen, not just when the object changes.
            // not 100% positive, but I'm pretty sure you get a similar effect with arrays and their contents
            handler: () => {
                $('.slickItem').not('.slick-initialized').slick({
                    infinite: true,
                    slidesToShow: 3,
                    arrows: false
                });
            }
        }
    },
    methods: {
        getData() {
            this.destinations = false;
            this.axios.get('/api/destinations/tags/' + this.tags).then((response) => {
                this.destinations = response.data;
                console.log(this.destinations);
            })
        },
        //Update ajax
        changeTag(tag) {
            $(".slickItem").slick("unslick");
            $('.slickItem').html('')
            this.tags = tag;
            this.getData();
        }
    }
}


text:
Q: WordPress: Remove name & Public name registration fields Is there any possibility to remove unnecessary fields in the wordpress standard registration process like the name, last name and public name fields? There are just more stepts for users that nobody needs. Normally these fields are required in the registration.
Just the username and the email field are sufficient.

A: Yes you can do this in wordpress...
You just need to edit the templates...
OR
change the hooks.-

A: Absolutely YES, you can achieve this.
Rule 1: WordPress requires a username. We must provide a username.
Rule 2: Don't edit WordPress core code.
We can achieve this by hiding username field, get email and store it as username.
Step-1: Remove Username textfield
add_action('login_head', function(){
?>
    <style>
        #registerform > p:first-child{
            display:none;
        }
    </style>

    <script type="text/javascript" src="<?php echo site_url('/wp-includes/js/jquery/jquery.js'); ?>"></script>
    <script type="text/javascript">
        jQuery(document).ready(function($){
            $('#registerform > p:first-child').css('display', 'none');
        });
    </script>
<?php
});

Step-2: Remove Username error
//Remove error for username, only show error for email only.
add_filter('registration_errors', function($wp_error, $sanitized_user_login, $user_email){
    if(isset($wp_error->errors['empty_username'])){
        unset($wp_error->errors['empty_username']);
    }

    if(isset($wp_error->errors['username_exists'])){
        unset($wp_error->errors['username_exists']);
    }
    return $wp_error;
}, 10, 3);

Step-3: Manipulate Background Registration Functionality.
add_action('login_form_register', function(){
    if(isset($_POST['user_login']) && isset($_POST['user_email']) && !empty($_POST['user_email'])){
        $_POST['user_login'] = $_POST['user_email'];
    }
});


text:
Q: How to submit a form with ajax if two parameters are set I have a simple rails form and want to submit the form when the two parameters are set without the click of a submit button. How can i write a simple jquery ajax request to do this.
my form below is

    <%= form_tag search_by_group_admin_codes_path, :method => :get, class: "well form-inline" do %>

Black List Codes

          <%= text_field_tag 'q', @q, placeholder: "between", id: "q"  %>
          <%= text_field_tag 's', @s, placeholder: "to", id: "s"  %>

    <% end %>

Any help thanks? i am Not too good at ajax in rails without the click of a button

A: $(function(){
  $('input').on("input", checkInput)
  //$('input').on("keyup", checkInput)
})

function checkInput(ev){
    if($('#q').val != '' && $('#q').val().length == 8 &&  $('#s').val != '' && $('#s').val().length == 8 )
    {
        $(this).closest('form').submit()
    }
}


text:
Q: Possible circular import in flask? I have this structure:
├── app
│   ├── __init__.py
│   └── views.py
├── requirements.txt
├── sources
│   └── passport
│       ├── field_mapping.
│       ├── listener.py
│       ├── main.py

this is my init file:
from flask import Flask

app = Flask(__name__)

from app import views

my views file. Is this the best way to send plain text?
from app import app
from flask import Response
from sources.app_metrics import meters

# from sources.passport.main import subscription_types

@app.route('/metrics')
def metrics():
    def generateMetrics():
        metrics = ""
        for subscription in ["something", "some other thing"]:
            metrics += "thing_{}_count {}\n".format(subscription, meters[subscription].get()['count'])
        return metrics
    print(generateMetrics())
    return Response(generateMetrics(), mimetype='text/plain')

My sources/passport/main file looks like this:
subscription_types = ["opportunity", "account", "lead"]

if __name__ == "__main__":
    loop = asyncio.get_event_loop()
    ...

    for subscription in subscription_types():

I also ran export FLASK_ENV=app/__init__.py before running flask app
When I visit /metrics I get an error that looks like some kind of circular dependency error.
When I uncomment that import comment in my views, file, the error occurs.
Pulling out subscription_types into a variable and importing it seems to be causing the problem.
My stack trace:
 File "/usr/local/lib/python3.7/site-packages/flask/cli.py", line 235, in locate_app
    __import__(module_name)
  File "/Users/jwan/extract/app/__init__.py", line 5, in <module>
    from app import views
  File "/Users/jwan//extract/app/views.py", line 5, in <module>
    from sources.passport.main import subscription_types
  File "/Users/jwan/extract/sources/passport/main.py", line 3, in <module>
    from sources.passport.listener import subscribe, close_subscriptions
  File "/Users/jwan/extract/sources/passport/listener.py", line 18, in <module>
    QUEUE = boto3.resource("sqs").get_queue_by_name(QueueName=CONFIG["assertions_queue"][ENV])

botocore.errorfactory.QueueDoesNotExist: An error occurred (AWS.SimpleQueueService.NonExistentQueue) when calling the GetQueueUrl operation: The specified queue does not exist for this wsdl versio

My sources/passport/listener file has this on line 18:
import gzip
import log
from os import getenv
from sources.passport.normalizer import normalize_message
from sources.app_metrics import meters

QUEUE = boto3.resource("sqs").get_queue_by_name(QueueName=CONFIG["assertions_queue"][ENV])


text:
Q: Ubuntu defaults to IPv6, should default to IPv4 Ubuntu 16.04.5 with kernel 4.4 used to work as intended: IPv4 is default. Since changing to kernel (hwe) 4.15, it uses IPv6 as default.
It has IPv6 available via Tunnelbroker, broadcasted by the router.
It is now defaulting to IPv6: curl ifconfig.co returns the machine's IPv6. Only curl -4 ifconfig.co returns the desired IPv4 address. (curl -6 ifconfig.co as expected returns IPv6)
$ ip rule list
0:      from all lookup local
32766:  from all lookup main
32767:  from all lookup default

$ ip -6 rule list
0:      from all lookup local
32766:  from all lookup main

$ ip route list
default via 192.168.1.1 dev eth0
192.168.1.0/24 dev eth0  proto kernel  scope link  src 192.168.1.x

$ ip -6 route list
2001:470:x:999::9999:f6a dev eth0  proto kernel  metric 256  pref medium
2001:470:x:999::/64 dev eth0  proto kernel  metric 256  expires 42905sec pref medium
fe80::/64 dev eth0  proto kernel  metric 256  pref medium
default via fe80::2ac6:8eff:fe65:d117 dev eth0  proto ra  metric 1024  expires 1505sec hoplimit 64 pref medium

PS: Some providers still report IPv4, for example curl ipinfo.io/ip. I've used ifconfig.co for a long time, so I am not sure if they changed their setup (less likely) or the kernel upgrade makes Ubuntu prefer IPv6.
How do I find out what is causing IPv6 to be preferred?

A: Set name resolving to prefer v4. For users of glibc's getaddrinfo, uncomment the precedence line after the "prefer IPv4" comment  in /etc/gai.conf. The one with the IPv4 /96.

A: To prefer IPv4 over v6, you can just uncomment or add the following line in /etc/gai.conf file:
precedence ::ffff:0:0/96  100


text:
Q: How to request notification permission in Android Studio before API 33 (TIRAMISU) In my project i need to post notification but in case of phone with old API the notification prompt doesn't show up so notifications are disbaled by default. The only way to enable notifications i found is by enabling them from system settings
tried everything suggested online but if anything comes up its about Android 13


text:
Q: sprintf : fixed point, big numbers and precision loss I need to read some numbers in a database and write them into a text file using Perl.
In the table where are the numbers, the data format is defined as numeric (25,5) (it reads 25 digits, including 5 decimals).
I format the numbers in my file with a sprintf "%.5f", $myvalue to force 5 decimals and I just noticed that for greats values, there is a precision loss for numbers with more than 17 digits :
db   = 123.12345
file = 123.12345 (OK)

db   = 12345678901234891.12345
file = 12345678901234892.00000 (seems to be rounded to upper integer)

db   = 12345678901234567890.12345
file = 12345678901234567000.00000 (truncation ?)

What is Perl's greatest precision for fixed decimal numbers?
I am aware of the concepts and limitations of floating point arithmetic in general, but I am not a Perl monk and I do not know the internals of Perl so I don't know if it is normal (or if it is related at all to floating point). I am not sure either if it is a internal limitation of Perl, or a problem related to the sprintf processing.
Is there a workaround or a dedicated module that could help with that problem?
Some notable points :

*

*this is an additional feature of a system that already uses Perl, so using another tool is not an option

*the data being crunched is financial so I need to keep every cent and I cannot cope with a +/- 10 000 units precision :^S

A: Once again, I am finding a solution right after asking SO. I am putting my solution here, to help a future visitor :
replace
$myout = sprintf "%.5f", $myvalue;

by
use Math::BigFloat;
$myout = Math::BigFloat->new($myvalue)->ffround( -5 )->bstr;

A: Without modules like Math::BigFloat, everything above 16 digits is pure magic... e.g.
perl -e 'printf "*10^%02d: %-.50g\n", $_, log(42)*(10**$_) for (0..20)'

produces
*10^00: 3.7376696182833684112267746968427672982215881347656
*10^01: 37.376696182833683224089327268302440643310546875
*10^02: 373.76696182833683224089327268302440643310546875
*10^03: 3737.6696182833684360957704484462738037109375
*10^04: 37376.6961828336861799471080303192138671875
*10^05: 373766.96182833681814372539520263671875
*10^06: 3737669.6182833681814372539520263671875
*10^07: 37376696.18283368647098541259765625
*10^08: 373766961.82833683490753173828125
*10^09: 3737669618.283368587493896484375
*10^10: 37376696182.83368682861328125
*10^11: 373766961828.33685302734375
*10^12: 3737669618283.36865234375
*10^13: 37376696182833.6875
*10^14: 373766961828336.8125
*10^15: 3737669618283368.5
*10^16: 37376696182833688
*10^17: 373766961828336832
*10^18: 3737669618283368448
*10^19: 37376696182833684480
*10^20: 373766961828336828416

A:
What is Perl's greatest precision for fixed decimal numbers?

Perl doesn't have fixed point decimal numbers. Very few languages do, actually. You could use a module like Math::FixedPoint, though

A: Perl is storing your values as floating-point numbers internally.1 The precision is dependent on how your version of Perl is compiled, but it's probably a 64-bit double.
C:\>perl -MConfig -E "say $Config::Config{doublesize}"
8

A 64-bit double-precision float2 has a 53-bit significand (a.k.a. fraction or mantissa) which gives it approximately 16 decimal characters of precision. Your database is defined as storing 25 characters of precision. You'll be fine if you treat the data as a string but if you treat it as a number you'll lose precision.
Perl's bignum pragma provides transparent support for arbitrarily large numbers. It can slow things down considerably so limit its use to the smallest possible scope. If you want big floats only (without making other numeric types "big") use Math::BigFloat instead.

1. Internally, perl uses a datatype called an SV that can hold floats, ints, and/or strings simultaneously.
2. Assuming IEEE 754 format.

A: Alternatively, if you're just transferring the values from the database to a text file and not operating on them as numbers, then have the DB format them as strings. Then read and print them as strings (perhaps using "printf '%s'"). For example:
select Big_fixed_point_col(format '-Z(24)9.9(5)')(CHAR(32))


text:
Q: @keyframes not working in expected way CSS
I'm recoding this website for practice purposes. I've changed the background image to black in my codepen because images don't work in codepen. Here's a link to my code. I've also placed the code here in case you can't view the codepen:
INDEX.HTML
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <link rel="stylesheet" type="text/css" href="styles.css">
  <link rel="stylesheet" type="text/css" href="reset.css">
  <link href="https://fonts.googleapis.com/css?family=Raleway" rel="stylesheet">
  <title>Coming Soon</title>

Logo

Coming Soon

35 days left

STYLES.CSS
  body {
  background-color: white;
  font-size: 10px;
}

.background {
  animation-name: fadeout;
  animation-duration: .8s;
  background-image: url(Images/forestbridge.jpg);
  background-size: cover;
  background-position: top;
  animation-fill-mode: backwards;
  height: 100vh;
  font-family: "Raleway", sans-serif;
}

.logo {
  color: white;
  font-weight: 100;
  font-size: 1.5rem;
  padding: 1rem 0 0 1rem;
}

.bigtext {
  color: white;
  text-transform: uppercase;
  font-size: 4rem;
  text-align: center;
  padding-bottom: 1rem;
}

.dropdownwrapper {
  animation-name: dropdown;
  animation-duration: .8s;
  animation-fill-mode: forwards;
}

.divider {
  border: none;
  width: 20%;
  height: 1px;
  background-color: lightgrey;
  margin-bottom: 1.5rem;
}

.smalltext {
  color: white;
  font-size: 1.25rem;
  text-align: center;
}

@keyframes fadeout {
  0% {
    opacity: 0;
  }

  100% {
    opacity: 1;
  }
}

@keyframes dropdown {
  0% {
    margin-top: 10vh;
  }

  100% {
    margin-top: 40vh;
  }
}

I also have a reset.css, but it's just a standard Eric Meyer 2.0 reset (I've placed it in the codepen, though). My problem is that when you reload the W3Schools version I'm attempting to recode, the text "COMING SOON" comes down, and the line and "35 days left" text stay in place. However, in my code, the entire block of text comes down. Why is the "COMING SOON" text on my site not coming down by itself when I've only selected it's parent div that the other elements are in? How can I make it so that only the "COMING SOON" text comes down?
Thanks,
Lyfe

A: This is happening because you are animating the margin-top of the COMING SOON text. Since the element is in the normal document flow, animating the margin gives the impression that the elements after the COMING SOON are also being animated, even though they are not. To resolve this, you should be animating using transform, which manipulates an element's position in place. Check out the forked codepen.
Additionally, if you wish to centre the entire block of text in the centre of the page, you should wrap all of it an div and position it absolutely. I've forked another codepen to demonstrate this.
The slide down effect appears more profound in the second codepen.


text:
Q: Tkinter GUI window not recognised in other functions I am making a simple program that saves someone's name and their email address in a file. I am coding in python idle. My code is:
import random
from tkinter import *

num = (random.randint(1,3))
NOSa = open("CN.txt", "r")
NOS = (NOSa.read())
NOSa.close()
NOSa = open("CN.txt", "w")
if num == ("1"):
    NOS = NOS + "a"
elif num == ("2"):
    NOS = NOS + "v"
else:
    NOS = NOS + "x"
NOSa.write(NOS)
NOSa.close()

def efg():
        window2.destroy()
        window2.mainloop()
        exit()

def abc():
    name = entry.get()
    email = entry2.get()
    window.destroy()
    window2 = Tk()
    window2.title("OP")
    OT = Text(window2, width=30, height=10, wrap=WORD, background="yellow")
    OT.grid(row=0, column=0, sticky=W)
    OT.delete(0.0, END)
    MT = "We have logged your details " + name
    MT2 = ". We have a file saved called " + NOS
    MT3 = ". Go check it out!"
    OT.insert(END, MT)
    OT.insert(END, MT2)
    OT.insert(END, MT3)
    new_file = open(NOS, "a")
    new_file.write("This is ")
    new_file.write(name)
    new_file.write(" email address.")
    new_file.write(" ")
    new_file.write(email)
    button2 = Button(window2, text="OK", width=5, command=efg)
    button2.grid(row=1, column=0, sticky=W)
    window.mainloop()
    window2.mainloop()

window = Tk()
window.title("EN")
label = Label(window, text="Enter your name: ")
label.grid(row=0, column=0, sticky=W)
entry = Entry(window, width=20, bg="light green")
entry.grid(row=1, column=0, sticky=W)
label2 = Label(window, text="Enter your email address: ")
label2.grid(row=2, column=0, sticky=W)
entry2 = Entry(window, width=25, bg="light green")
entry2.grid(row=3, column=0, sticky=W)
button = Button(window, text="SUBMIT", width=5, command=abc)
button.grid(row=4, column=0, sticky=W)
window.mainloop()

When I run the code my first 2 boxes appear and run their code perfectly. However, when I click the button 'OK' I get this error:
NameError: name 'window2' is not defined
I use python-idle.

A: You may make windows2 global
window2 = None

def efg():
        global window2

and later
def abc():
    global window2


text:
Q: Synthesize-able delay in Verilog I want to synthesize a SystemVerilog code that has delay written as ##1 but the synthesizer gives syntax errors as delay is not synthesize-able. I want to know is there any way I can give delay that will be synthesized?
For instance, this is a SystemVerilog assertion in the code with delays
assert property ( ( req1 == 0 ) ##1( req1 == 1 ) ##1 !( req2 == 1 ) || ( gnt1 == 0 ) );
how can I synthesize this without losing its behavior?

A: Properties are not part of Verilog, but a part of SystemVerilog. More to the point, properties themselves are not synthesizable either. Properties are used in cover or assert statements in a simulation environment.
As for delays, your only option is to use a flip-flop to delay the signal. In your property ##1 means "on the next edge" assuming that your property has some clocking related to it (either in the cover/assert statement or that it is within a clocking-block).
To create synthesizable cycle-delays in otherwise synthesizable code:
always@(posedge ck or posedge arst) begin
  if(arst)
    data_delayed <= '0;
  else
    data_delayed <= data;
end

A: The property you wrote does not make any sense. You cannot add delays in the middle of a Boolean expression. Did you mean to write a sequence of expressions instead? Then the correct syntax would be
sequence s1;
 ( ( req1 == 0 ) ##1( req1 == 1 ) ##1 !( req2 == 1 ) || ( gnt1 == 0 ) );
endsequence


text:
Q: Unable to login as root in mysql I've been trying out all solutions mentioned in google for this problem to no avail. This website is built using bitnami wordpress stack in AWS. All I want to do is to log slow query. I only have wp-config user credentials to login in to mysql. But with this access I cannot run SET GLOBAL slow_query_log = 'ON';
as it requires super user privilege.
To my understanding, unless I login as root user and assign the privilege to this user or run the command as root user itself no other workaround to get this sorted.
Problem is, no password for root. Maybe it's configured without password when it was first installed (mysql).
I checked this file for password but found none.
/opt/bitnami/mysql/my.cnf

I can't view the mysql log too (permission denied)
/opt/bitnami/mysql/data/mysqld.log
I dont find the password in aws->instance settings -> get system log
I tried resetting password as mentioned here. https://community.bitnami.com/t/unable-to-reset-mysql-root-password/44360/3
mysql stops but stuck at starting in safe mode forever usin below commands:
$ sudo /opt/bitnami/ctlscript.sh stop mysql
$ sudo /opt/bitnami/mysql/bin/mysqld_safe --skip-grant-tables

How do I enable the slow query log now or get root password or reset it?

A: Hi Bitnami Engineer here,
The root's password of the database is the same one the instance configures for WordPress during the boot process. That means that if you have not changed the WordPress' admin password, both passwords are the same now.
You can open the bitnami_credentials file in the home folder of the bitnami user to obtain the password the instance used during the configuration process.
cat /home/bitnami/bitnami_credentials

After that, just run the mysql command to access the database
mysql -u root -p


text:
Q: Can someone explain what is active and debounce for? I dont know what is active and debounce for i mean what are they doing why they are there ? Can someone explain please ?
Ok so here is the code:

local debounce = false
local active = false

UIS.InputBegan:Connect(function(input,isTyping)
    if isTyping then
        return
    elseif input.KeyCode == Enum.KeyCode.E then
        if debounce == false and active == false then
            debounce = true

            blabla:FireServer(active)
        end
    end
end)

A: local debounce variable its an a bool value, that used(in that script) to mark is the server event is already fired/firing(you can see that by "if debounce == false" field), if player pressing E key the event fires and the debounce's value setting to false, so event won't be fired again by that script, until you/code set it to true.
By the way, you can view all information about roblox's lua type at roblox's web site, here you can find post about bool values & variables
https://developer.roblox.com/en-us/articles/Boolean
And the active its value used for remote event that created by server(server gets active variable by remote event for on-server function)


text:
Q: What is the best approach of creating a talking bot? When creating a AI talking bot what kind of methods of design should I use? Should it be one function, multiple modules, should it have classes?

A: Understanding language is complicated, so the goal you need to determine first is what aspect of language you want to understand.
An AI must be able to understand what the person says to it, then relate it to what it already knows, and then generate a legitimate response.
These three steps can all be thought of as nearly independent, so you need to address each on its own.
The brain, the world's best language processor, uses a Neural Network, but that's not likely to work well for you.
A logic-based proof solving system, where facts that follow from facts are derived would probably work best, and I know of at least one system that uses it fairly effectively.

A: I'd start with an existing AI program (like the famous Eliza) and run its output through a speech synthesizer.
Some source for Eliza is available here.  One open source speech synthisizer is FreeTTS.
If you're using a language other than Java, there are similar candidates AI bots and text-to-speech code out there.

A: I've started to do some work in this space using this open source project called Talkify:
https://github.com/manthanhd/talkify
It is a bot framework intended to help orchestrate flow of information between bot providers like Microsoft (Skype), Facebook (Messenger) etc and your backend services. The framework doesn't really provide implementation for the bot providers yet but does provide hooks into its natural language recognition engine.
The built in natural language recognition library can be used to classify sentences to topics which you can then map to skill functions.
Give it a try! I'd really like people's input to see if how it can be improved.


text:
Q: How can I tell which app is coming from which source in GNOME? I use some programs where there are 2 or 3 versions on my PC, perhaps an apt installed, version, and a snap, and an appimage, usually because the developers release bug fixes. For example, LMMS and Kdenlive work differently via appimage versus apt install.
When I open up the dash using the windows key and search for an app, for example typing lm or kd, I see multiple icons, one for each app version. What I can't see is how to tell which is which. Ideally, I should be able to right click and see where that app is located. Right clicking only reveals 'New window' or 'Add to favourites'.
How can I tell which is which? I suspect they also move around in the dash, so just remembering where they are won't help.
Example: Here's a screenshot illustrating the problem with Kdenlive. There is an apt package and 2 appimage files. Each is a different version of the program, with different bugfixes and features. It's the same with LMMS, some features only work in the appimage, but the apt is more stable.
As you can see, there is no 'show details' option.

A: GNOME Shell looks for a .desktop launcher associated to an applications in some standard directories:

*

*/usr/share/applications/ (standard location for applications installed system-wide)

*~/.local/share/applications/ (for applications installed locally, i.e. only for the current user)

*/var/lib/snapd/desktop/applications/ (for snap applications)

If you open a .desktop launcher file with a text editor, you would find a Name= key which provides the name of the application (e.g. "Kdenlive") shown in your Activities or applications overview. There is also an Exec= key which contains the command to be used to run the application, thus it would also tell you what the source of the application is.
You can then simply rename the application as you wish by changing the Name= key to distinguish it from another one with the same name, for example change Name=Kdenlive to Name=Kdenlive (AppImage) for the one installed using AppImage. Then it would appear as 'Kdenlive (AppImage)' instead.
You can use GUI tools to achieve this perhaps more easily, for example:

*

*Main Menu aka alacarte
Install by  running
sudo apt install alacarte

*MenuLibre
Install by  running
sudo apt install menulibre

A: On my computer the apt package is the first item in the Dash and the snap package is the second item in the Dash. This is a quick way to select either the apt package or the snap package even if their icons are identical. In Ubuntu 20.04 and later many apt and snap versions of the same application have small differences in their icons.

Otherwise you can do it the long way. In Ubuntu 20.04 some snap application icons don't show their details in the software app when you right-click them and select Show Details, so try the method in the first paragraph of this answer first.

*

*Search for an application in the Dash.

*Right-click the application and select Show Details.

*The application will open in the Software app. If there are two applications listed in the Software app try right-clicking the other application. If that application is a snap application it will show only one application in the list instead of two applications. In the above screenshot the System Monitor apt package icon has a black screen with a green line and the snap package icon has a black screen with a yellow line. Clicking the first System Monitor icon shows a list of apps in the Software app. Clicking the second System Monitor icon shows only one System Monitor app in the Software app.
It works the same way with apt and snap packages that both have the same icon, for example Leafpad. It also works the same way if you select the Add to Favorites option in the above screenshot and right-click the app's icon in the Dock and select Show Details.

*Click the application in the Software app. This will bring up a new screen that shows information about that app including whether it is an apt application or a snap application.


text:
Q: Getting "prefix 'soap' is not defined" in xslt file I am trying to transform a string with xml data (response from a web service). I tried to start simple by just getting the name:
<?xml version="1.0" encoding="utf-8"?>
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    xmlns:msxsl="urn:schemas-microsoft-com:xslt" exclude-result-prefixes="msxsl">
    <xsl:output method="html" indent="yes"/>

    <xsl:template match="/">

          Name

        <xsl:for-each select="soap:Envelope/soap:Body/ABRSearchByABNResponse/ABRPayloadSearchResults/response/legalName/">

              <xsl:value-of select="givenName"/>

      </xsl:for-each>

    </xsl:template>
</xsl:stylesheet>

However, I get "prefix 'soap' is not defined", how do I fix this?
Thanks.

A: In XSLT any namespace prefix used in an XPath expression must be defined in a corresponding namespace declaration.
This is not the case with your code and hence the error.
Solution:
Declare the soap namespace:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:msxsl="urn:schemas-microsoft-com:xslt"
 xmlns:soap="http://soap/envelope/"
>

A: The namespace prefix, soap in your case, is just shorthand for the real namespace URI. To avoid you have http://soap/envelope/ everywhere, you can define once that soap stands for http://soap/envelope/, and use soap in the rest of your document.
This means that if you use a namespace prefix, it has to be defined so that the real namespace can be found.
You could also declare that pizza corresponds to http://soap/envelope/ and use that instead. The soap namespace prefix is not special.


text:
Q: Clover and Jacoco give different code coverage results I just ran a code coverage analysis on my project with Clover and the result is about 60%. I ran the analysis on the same project with Jacoco and the result is about 52%. Is the 8% difference normal? I've been running code coverage analysis with these tools in the past too and the difference is never this huge.

A: Please note that Clover and JaCoCo are using different code coverage metrics:

*

*Clover has method, statement and branch coverage (plus the total coverage metric which is a sum of all three)

*JaCoCo has method, code block, line, branch and instruction coverage

So you cannot simply put the equality sign between results produced by these two tools. I suggest checking reports side-by-side to find where is the highest difference and next to have a look at code constructs used there, resulting in such difference.
Oh. By the way. Keep in mind that JaCoCo uses byte code instrumentation, which means that it will also instrument synthetic methods created by javac compiler and which are not visible in the source code.


text:
Q: WSO2 4.1.0 JWTGenerator I'm doing a wso2 migration from version 2.6.0 to 4.1.0.
In version 2.6.0, we have our own com.carus.api.gateway.JwtTokenGenerator class that extends JWTGenerator, in our version certain claims are added there. I don't see a drastic difference in the generator except to update the versions of the dependencies to the latest ones, so I think the current generator should work in the same way on version 4.1.0
I do everything as it says in the documentation here: https://apim.docs.wso2.com/en/latest/deploy-and-publish/deploy-on-gateway/api-gateway/passing-enduser-attributes-to-the-backend-via-api-gateway/#expiry-time-of-the-jwt
I copy the same jar that works on 2.6.0 and extends JWTGenerator to wso2am-4.1.0/repository/components/lib
I start wso2 and make a request on devportal. In the logs, on another machine to which the request and this token are sent, I receive a token and there it appears that the request did not go through my generator. It looks like this:
   {
      "sub": "APIUSER",
      "https://carus.com/claims/enduserTenantId": "-1234",
      "https://carus.com/claims/subscriber": "CARCYAYU/apiuser",
      "iss": "wso2.org/products/am",
      "https://carus.com/claims/apiname": "Bookings Read API",
      "https://carus.com/claims/tier": "Unlimited",
      "https://carus.com/claims/applicationtier": "Unlimited",
      "https://carus.com/claims/version": "v1",
      "https://carus.com/claims/enduser": "CARCYAYU/apiuser@carbon.super",
      "azp": "sQbDNZgidubfCGlb33IcGiQMJE8a",
      "scope": "default",
      "https://carus.com/claims/applicationUUId": "ce6354a5-0227-4ca2-b649-e959323dc9bc",
      "https://carus.com/claims/apicontext": "/bookings-read/carcyayu/v1",
      "https://carus.com/claims/applicationid": "3",
      "exp": 1663422523,
      "https://carus.com/claims/applicationname": "Yaroslav",
      "https://carus.com/claims/keytype": "PRODUCTION",
      "iat": 1663421623,
      "jti": "42d5a74d-bb07-4608-9a7a-e3723ec834dd",
      "https://carus.com/claims/usertype": "Application_User"
   }

My config in deployment.toml:
[apim.jwt]

enable = true
encoding = "base64" # base64,base64url
generator_impl ="com.carus.api.gateway.JwtTokenGenerator"
claim_dialect ="https://carus.com/claims"
convert_dialect = true
header ="X-JWT-Assertion"
signing_algorithm = "NONE"
enable_user_claims = true
claims_extractor_impl = "org.wso2.carbon.apimgt.impl.token.DefaultClaimsRetriever"

Can someone explain to me how to make my generator work in this 4.1.0 version as well and how to include logs, where and what config to set so that my generator logs and in which file to look for them?
Also, the question is what is the difference between JWTGenerator and APIMgtGatewayJWTGeneratorImpl in version 2.6.0 was only JWTGenerator, this can be seen in the api-manager.xml file by versions.
The latest update is when I copy my custom generator (jar) to /components/lib.
When I make a request, I receive the same token as above, but in the log file wso2carbon.log I get the following errors:
TID: [-1234] [oauth2] [2022-09-17 22:08:59,608] ERROR {org.wso2.is.notification.EventSender} - Error while sending Revocation Event to https://api-yayu-carc.internal.carus.com:9443/internal/data/v1/notify javax.net.ssl.SSLPeerUnverifiedException: Certificate for <api-yayu-carc.internal.carus.com> doesn't match any of the subject alternative names: [localhost]
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.verifyHostname(SSLConnectionSocketFactory.java:507)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:437)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:384)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
    at org.wso2.is.notification.EventSender$EventRunner.run(EventSender.java:116)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)

TID: [-1234] [oauth2] [2022-09-17 22:09:10,256] ERROR {org.wso2.is.notification.EventSender} - Error while sending Revocation Event to https://api-yayu-carc.internal.carus.com:9443/internal/data/v1/notify javax.net.ssl.SSLPeerUnverifiedException: Certificate for <api-yayu-carc.internal.carus.com> doesn't match any of the subject alternative names: [localhost]
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.verifyHostname(SSLConnectionSocketFactory.java:507)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:437)
    at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:384)
    at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:142)
    at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:376)
    at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:393)
    at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236)
    at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:186)
    at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:89)
    at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110)
    at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:185)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
    at org.wso2.is.notification.EventSender$EventRunner.run(EventSender.java:116)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)

TID: [-1234] [] [2022-09-17 22:09:16,160] ERROR {org.wso2.carbon.apimgt.impl.jwt.JWTValidatorImpl} - Error while parsing JWT org.apache.http.client.ClientProtocolException: URI does not specify a valid host name: https:9443/oauth2/jwks
    at org.apache.http.impl.client.CloseableHttpClient.determineTarget(CloseableHttpClient.java:95)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:83)
    at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:108)
    at org.wso2.carbon.apimgt.impl.utils.JWTUtil.retrieveJWKSConfiguration_aroundBody0(JWTUtil.java:58)
    at org.wso2.carbon.apimgt.impl.utils.JWTUtil.retrieveJWKSConfiguration(JWTUtil.java:52)
    at org.wso2.carbon.apimgt.impl.jwt.JWTValidatorImpl.retrieveJWKSet_aroundBody22(JWTValidatorImpl.java:227)
    at org.wso2.carbon.apimgt.impl.jwt.JWTValidatorImpl.retrieveJWKSet(JWTValidatorImpl.java:224)
    at org.wso2.carbon.apimgt.impl.jwt.JWTValidatorImpl.validateSignature_aroundBody8(JWTValidatorImpl.java:145)
    at org.wso2.carbon.apimgt.impl.jwt.JWTValidatorImpl.validateSignature(JWTValidatorImpl.java:135)
    at org.wso2.carbon.apimgt.impl.jwt.JWTValidatorImpl.validateToken_aroundBody0(JWTValidatorImpl.java:62)
    at org.wso2.carbon.apimgt.impl.jwt.JWTValidatorImpl.validateToken(JWTValidatorImpl.java:57)
    at org.wso2.carbon.apimgt.impl.jwt.JWTValidationServiceImpl.validateJWTToken_aroundBody0(JWTValidationServiceImpl.java:44)
    at org.wso2.carbon.apimgt.impl.jwt.JWTValidationServiceImpl.validateJWTToken(JWTValidationServiceImpl.java:36)
    at org.wso2.carbon.apimgt.gateway.handlers.security.jwt.JWTValidator.getJwtValidationInfo_aroundBody32(JWTValidator.java:691)
    at org.wso2.carbon.apimgt.gateway.handlers.security.jwt.JWTValidator.getJwtValidationInfo(JWTValidator.java:659)
    at org.wso2.carbon.apimgt.gateway.handlers.security.jwt.JWTValidator.authenticate_aroundBody0(JWTValidator.java:174)
    at org.wso2.carbon.apimgt.gateway.handlers.security.jwt.JWTValidator.authenticate(JWTValidator.java:142)
    at org.wso2.carbon.apimgt.gateway.handlers.security.oauth.OAuthAuthenticator.authenticate_aroundBody4(OAuthAuthenticator.java:301)
    at org.wso2.carbon.apimgt.gateway.handlers.security.oauth.OAuthAuthenticator.authenticate(OAuthAuthenticator.java:111)
    at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.isAuthenticate_aroundBody56(APIAuthenticationHandler.java:522)
    at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.isAuthenticate(APIAuthenticationHandler.java:516)
    at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.handleRequest_aroundBody46(APIAuthenticationHandler.java:402)
    at org.wso2.carbon.apimgt.gateway.handlers.security.APIAuthenticationHandler.handleRequest(APIAuthenticationHandler.java:353)
    at org.apache.synapse.api.API.process(API.java:403)
    at org.apache.synapse.api.AbstractApiHandler.apiProcessNonDefaultStrategy(AbstractApiHandler.java:107)
    at org.apache.synapse.api.AbstractApiHandler.identifyAPI(AbstractApiHandler.java:127)
    at org.apache.synapse.api.AbstractApiHandler.dispatchToAPI(AbstractApiHandler.java:59)
    at org.apache.synapse.api.rest.RestRequestHandler.dispatchToAPI(RestRequestHandler.java:90)
    at org.apache.synapse.api.rest.RestRequestHandler.process(RestRequestHandler.java:76)
    at org.apache.synapse.rest.RESTRequestHandler.process(RESTRequestHandler.java:54)
    at org.apache.synapse.core.axis2.Axis2SynapseEnvironment.injectMessage(Axis2SynapseEnvironment.java:344)
    at org.apache.synapse.core.axis2.SynapseMessageReceiver.receive(SynapseMessageReceiver.java:101)
    at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:180)
    at org.apache.synapse.transport.passthru.ServerWorker.processNonEntityEnclosingRESTHandler(ServerWorker.java:376)
    at org.apache.synapse.transport.passthru.ServerWorker.run(ServerWorker.java:190)
    at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
    at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
    at java.base/java.lang.Thread.run(Thread.java:829)


text:
Q: Python: keep objects selected throughout script I'm quite new to programming. I got an assignment for school.
What it has to do is:
By selecting 2 random objects clone the 2nd selected objects around the first selected object along it's rotation plane.
This has to be done through a window with 2 options. 1 option to adjust the size of the radius of the cloned objects. The 2nd option is the number of clones you want to have. Pressing a button creates the cloned objects.
import maya.cmds as cmds

def setRadius(circleRadius):
    selected = cmds.ls( sl=True)
    #selected = cmds.ls ('pCube1') + cmds.ls ('pCube2') #used for testing
    pivotcube = cmds.xform(selected[0], ws=True, q=True, t=True)
    satellite = cmds.xform(selected[1], ws=True, q=True, t=True)

def circularDuplicate(nrOfObjects):
    selected = cmds.ls( sl=True)
    #selected = cmds.ls ('pCube1') + cmds.ls ('pCube2') #used for testing

Currently I'm actually having several problems. First I hard selected 2 objects in the scene for test convenience. Changing the code to manually selected objects and storing them in a list, introduced a problem. After the first Function has been called the Script gives an error that the list index is out of range. Apparently after the first function (which adjust the position of the 2nd selected object to fix the radius) the objects are deselected. Now i could just put
selected = cmds.ls( sl=True)

outside of the functions but I want to be able to select 2 different objects and clone objects without having to close the window and to run the script again.
The second problem is the cloned objects all have the same translation values....
So i can't use any of the cloned objects and run the script again because the measuring will return an error. How can I clones in a decent way where all the clones have their own correct translate and rotation values?

A: There are three things going wrong for you here.
Selections
As long as you do not delete or rename objects within a single block of script code, you can 'restore' the selection by re-selecting your original list. In your example:
def setRadius(circleRadius):
    selected = cmds.ls( sl=True)
    pivotcube = cmds.xform(selected[0], ws=True, q=True, t=True)
    satellite = cmds.xform(selected[1], ws=True, q=True, t=True)
    cmds.select(selected)  # reselect the original objects

will restore your selection.
As you get better you'll find there are still lots of ways this can go wrong - renaming, deleting and sometimes even creating objects can invalidate a selection that has been stored just as a list of names. For more complex examples you can create sets (using cmds.set) which will survive name changes.
If you switch to PyMel, the return values from commands like ls will be handles to the actual maya scene nodes (and not just string names, which is what you get from the cmds versions).  Pymel objects retain their collection to the original scene nodes so they survive name changes, etc.
Getting/setting values
Your setRadius function doesn't do anything.  You are asking for the world space pivot and target locations -- but you're not doing anything with them.   Do you want to return them? Or are you trying to set them as the name of the def suggests? If you're getting them, add
return pivotcube, satellite

to the end of the def.  If you're setting them, you need to call xform without the q flag, and supply the values you want, something like
pivotpos = (0,0,0)
cmds.xform(selected[0], t=pivotpos, ws=True)

Doing the duplication
THere's nothing in the supplied code that actually does the radial duplication. You want something like this:

*

*select the target object

*move it to (0, 0, radius) of the pivot object.  You could do this by getting the transform matrix of the pivot and multipling (0,0,radius) against it. However  it's simpler to temporarily parent the duplicate object to the pivot object and  set it's local position to  (0,0, radius). For this example I'm assuming you want to rotate around the local Y of the pivot object - you could exchange coordinates as needed.

*zero out the local rotations of the target object

*set the world space pivot of the target to the world space pivot of the pivot

*As many times as needed: duplicate the object, rotated it by (0, 360/number-of-copies,0)

*(if desired) reset the pivot of the duplicate(s)

If you walk through this in the GUI and pay attention to the command output you should be able to see the way your actual script should go.


text:
Q: JIRA: How to search using "Key" Or "Issuekey" I am making following REST API call to my JIRA instance.
Am getting the total result as 1, but am not getting any values inside the issues : [ ]
JQL:
http://myjira:8080/rest/api/2/search?startAt=1&maxResults=50&fields=project,status&jql=fields project status jql project=C00195 and key=C00195-2210

But I'm getting an error response:
{"startAt":1,"maxResults":50,"total":1,"issues":[]}

Above JQL is not working in browser as well.
If we remove the key filter then it was working as expected.
Working JQL:
http://myjira:8080/rest/api/2/search?startAt=1&maxResults=50&jql=project=C00095

Response:
{"expand":"schema,names","startAt":1,"maxResults":50,"total":2175,"issues":[{"expand":"operations,versionedRepresentations,editmeta,changelog,renderedFields","id":"12560","self":"http://myjira:8080/rest/api/2/issue/12560","key":"C00095-2215","fields":{"parent":{"id":"12559","key":"C00095-2214","self":"http://myjira:8080/rest/api/2/issue/12559","fields":{"summary":"Task for tagging testing","status":

A: You need to change startAt from 1 to 0. This resource is counting from zero so by setting it to one you actually skip the single issue that was found.


text:
Q: Access Next.js client state on the server I'm trying to fetch dynamic data in my Next.js app using the getServerSideProps function. The request must contain a token, which is stored client-side, to authenticate the user on the backend.
I've tried the following:
export async function getServerSideProps(context) {
  const token = window.localStorage.getItem('token')
  const data = await axios.get("/data", { headers: { Authorization: `Bearer ${token}` }});
  return { props: { data } };
}

But I get ReferenceError : window is not defined, which makes sense because the request is being made on the server and the window object doesn't exist there (it only exists on the client).
Can I access client state in getServerSideProps or store next state on the server? If not, looks like the only way to do this would be to make the request client-side.

A: use cookies instead. Because getServersideProps happen in server-side rendering, so window or localStorage cannot access. Use cookies and js-cookie library to set and get token.


text:
Q: power point font changing on closing and reopening I have created a ppt by copying the slides from another power point.
When both the power points are opened together then the fonts look okay, but if open the one i created alone then fonts get messed up.

A: I found the solution.
The font in the first ppt was not available in the power-point.
so when both were open simultaneously the font was getting loaded in the system, however when it was opened alone the font was not getting recognized and getting changed.
Changed the fonts manually in my ppt to resolve the issue.


text:
Q: Comparing Gridview Columns I have two gridviews, and I need to compare the results by column. Sometimes one of the gridviews might have columns which are not in the other one, thus I need to compare only those columns which exist in both grids.
The code i have written actually goes through every cell of each row, it starts at row 0 cell 0 and continue row 0 cell 1 and then goes to the next row. However, I would like to cell have it in a way that if the column in say Grid 2 exists in Grid 1 i would go through it's cells and then pass to the next column. Below is the code i have:
List<String> columnsGrid43 = new List<String>();

foreach (TableCell cell in gridReport43.Rows[0].Cells)
{
    BoundField fieldGrid43 = (BoundField)((DataControlFieldCell)cell).ContainingField;
    columnsGrid43.Add(fieldGrid43.DataField);
}

foreach (TableCell cell in gridReport44.Rows[0].Cells)
{
    BoundField fieldReportGrid44 = (BoundField)((DataControlFieldCell)cell).ContainingField;
    if (columnsGrid43.Contains(fieldReportGrid44.DataField))
    {
        for (int countRow = 0; countRow < gridReport44.Rows.Count; countRow++)
        {
            for (int countCell = 0; countCell < gridReport44.Rows[countRow].Cells.Count; countCell++)
            {
                string grid1Value = gridReport43.Rows[countRow].Cells[countCell].Text;
                string grid2Value = gridReport44.Rows[countRow].Cells[countCell].Text;
                if (grid2Value.Contains(grid1Value))
                {
                    gridReport43.Rows[countRow].Cells[countCell].BackColor = Color.FromArgb(101, 226, 75);
                    gridReport44.Rows[countRow].Cells[countCell].BackColor = Color.FromArgb(101, 226, 75);
                }
                else
                {
                    gridReport43.Rows[countRow].Cells[countCell].BackColor = Color.FromArgb(255, 102, 102);
                    gridReport44.Rows[countRow].Cells[countCell].BackColor = Color.FromArgb(255, 102, 102);
                }
            }
        }
    }
}

A: I suggest you to compare two DataTables of you two GridViews, il very easy.
Yous can use differents method on DataTable.Rows such as : Contains, Find or CopyTo
link : http://msdn.microsoft.com/fr-fr/library/system.data.datarowcollection.aspx
Here sample of code :
    public static void CompareRows(DataTable table1, DataTable table2)
    {
    foreach (DataRow row1 in table1.Rows)
    {
        foreach (DataRow row2 in table2.Rows)
        {
        var array1 = row1.ItemArray;
        var array2 = row2.ItemArray;

        if (array1.SequenceEqual(array2))
        {
            Console.WriteLine("Equal: {0} {1}", row1["ColumnName"], row2["ColumnName"]);
        }
        else
        {
            Console.WriteLine("Not equal: {0} {1}", row1["ColumnName"], row2["ColumnName"]);
        }
        }
    }
    }


text:
Q: Move UITextView to bottom of ViewController programmatically? I created the textView and Button(reply) programmatically and I want to move it down to the bottom of my ViewController. It's now being placed under the label(Joshyjosh) and it shouldn't do that. Is there something I need to add to my code or change so it can move to the bottom?

import UIKit
    class DetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate, UITextViewDelegate {
var commentView: UITextView?
var footerView: UIView?
var contentHeight: CGFloat = 0
let FOOTERHEIGHT : CGFloat = 50;
override func viewDidLoad() {
        super.viewDidLoad()
}

    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
    if self.footerView != nil {
        return self.footerView!.bounds.height
    }
    return FOOTERHEIGHT
}

func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
    footerView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.bounds.width, height: FOOTERHEIGHT))
    footerView?.backgroundColor = UIColor(red: 243.0/255, green: 243.0/255, blue: 243.0/255, alpha: 1)
    commentView = UITextView(frame: CGRect(x: 10, y: 5, width: tableView.bounds.width - 80 , height: 40))
    commentView?.backgroundColor = UIColor.whiteColor()
    commentView?.textContainerInset = UIEdgeInsetsMake(5, 5, 5, 5)
    commentView?.layer.cornerRadius = 2
    commentView?.scrollsToTop = true

    footerView?.addSubview(commentView!)
    let button = UIButton(frame: CGRect(x: tableView.bounds.width - 65, y: 10, width: 60 , height: 30))
    button.setTitle("Reply", forState: UIControlState.Normal)
    button.backgroundColor = UIColor(red: 155.0/255, green: 189.0/255, blue: 113.0/255, alpha: 1)
    button.layer.cornerRadius = 5
    button.addTarget(self, action: "reply", forControlEvents: UIControlEvents.TouchUpInside)
    footerView?.addSubview(button)
    commentView?.delegate = self
    return footerView
}

func textViewDidChange(textView: UITextView) {

    if (contentHeight == 0) {
        contentHeight = commentView!.contentSize.height
    }

    if(commentView!.contentSize.height != contentHeight && commentView!.contentSize.height > footerView!.bounds.height) {
        UIView.animateWithDuration(0.2, animations: { () -> Void in
            let myview = self.footerView
            print(self.commentView!.contentSize.height)
            print(self.commentView?.font!.lineHeight)
            let newHeight : CGFloat = self.commentView!.font!.lineHeight
            let myFrame = CGRect(x: myview!.frame.minX, y: myview!.frame.minY - newHeight , width: myview!.bounds.width, height: newHeight + myview!.bounds.height)
            myview?.frame = myFrame

            let mycommview = self.commentView
            let newCommHeight : CGFloat = self.commentView!.contentSize.height
            let myCommFrame = CGRect(x: mycommview!.frame.minX, y: mycommview!.frame.minY, width: mycommview!.bounds.width, height: newCommHeight)
            mycommview?.frame = myCommFrame

            self.commentView = mycommview
            self.footerView  = myview

            for item in self.footerView!.subviews {
                if(item.isKindOfClass(UIButton.self)){
                    let button = item as! UIButton
                    let newY = self.footerView!.bounds.height / 2 - button.bounds.height / 2
                    let buttonFrame = CGRect(x: button.frame.minX, y: newY , width: button.bounds.width, height : button.bounds.height)
                    button.frame = buttonFrame

                }
            }
        })

        print(self.footerView?.frame)
        print(self.commentView?.frame)
        contentHeight = commentView!.contentSize.height
    }

}