text:
Q: Connecting to a remote db through a jump server in Django I'm trying to tunnel my db connection in a django application through a jump server but can't seem to get it working because django manage.py handles & process the connections.
here's that I have in the settings.py
#process ssh_key first
ssh_key= os.getenv('SSH_KEY', '').encode('utf8').decode('unicode_escape')
server ={}
with sshtunnel.open_tunnel(
   (os.environ.get('SSH_HOST'),int(os.getenv('SSH_PORT'))),
    ssh_pkey=paramiko.RSAKey.from_private_key(io.StringIO(ssh_key)),
    ssh_username= os.environ.get('SSH_USERNAME'),
    remote_bind_address=(os.environ.get('DB_HOST'),  int(os.getenv('DB_PORT'))),
) as ssh_proxy_host:
    server={
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'HOST':  'localhost',
        'PORT':  ssh_proxy_host.local_bind_port,
        'NAME':  os.environ.get('DB_NAME'),
        'USER':  os.environ.get('DB_USER'),
        'PASSWORD':  os.environ.get('DB_PASS'),
    }
   # here's where I should have the connection function to db, but don't know if django has that option available

A: The true remote host is specified upon tunnel creation.  The HOST used for the db connection should be localhost because you need it to find your end of the tunnel, not the other end of it.


text:
Q: Separating HTML tags from a javascript string into individual strings I have Javascript string which is
 "
" +
 "
What color does the blackcurrant berry actually have?
" +
 "" +
 "<audio><source src="horse.ogg" type="audio/ogg"></audio>" +
 "
"

and the expected result is three separate strings. like
expected output:

console.log(title) // "
What color does the blackcurrant berry actually have?
"
console.log(image) // ""

Please help with how to do this. Thanks in advance.

A: I would render the JS string into HTML, then access it's children.

document.getElementsByTagName("body")[0].innerHTML = "
" +
 "
What color does the blackcurrant berry actually have?
" +
 "<img src=`img_girl.jpg` alt='Girl in a jacket' width=`500` height=`600`>" +
 "<audio><source src=`horse.ogg` type='audio/ogg'></audio>" +
 "
"

let title = document.getElementsByTagName("body")[0].children[0].children[0]

let image = document.getElementsByTagName("body")[0].children[0].children[1]

console.log(title)
console.log(image)

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to compile .java files in terminal? I have already installed JDK in my 12.04, but i don't know how to compile .java files in Terminal.
I used javac FILENAME.java then java FILENAME in terminalbut this shows error like this
javac: file not found: sum.java
Usage: javac
use -help for a list of possible options

A: Your current working directory in the terminal needs to be the same directory that has the sum.java file in it. The cd command is used to change directories in the terminal. Then the usage is the same as you wrote in your question, and it's also in: How to run a Java program in Ubuntu if you want to see another example.


text:
Q: Multiple receipt count for restoreCompletedTransaction inapp purchasing I have an autorenewable subscription.  When the app is installed on a new device, Apple returns ALL previous purchase receipts, in this case since it is sandbox I get 6 receipts every time I install.  The observer then sends the queue for restoredCompleted transactions.   I have a method to send the transaction to my server for Apple verification, but it runs 6 times because of the 6 receipts.  I really only want to deal with the LAST receipt sent.
So I am trying to count the transactions in the queue and ONLY verify the receipt when the count reaches 1.
Here is what I have so far:
    - (void)paymentQueue: (SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
if (myQueue == nil) {
    myQueue = [SKPaymentQueue defaultQueue];
}

NSLog(@"Transactions in Array  in My Store %@", [queue transactions]);
tCount =myQueue.transactions.count;
NSString *transCount =  [NSString stringWithFormat:@"%d",tCount];

for (SKPaymentTransaction *transaction in transactions)

{ switch (transaction.transactionState)

    { case SKPaymentTransactionStatePurchased:
            [self completeTransaction: transaction];
            break;

        case SKPaymentTransactionStateFailed:
            [self failedTransaction: transaction];
            break;

        case SKPaymentTransactionStateRestored:

            if  ([transCount isEqualToString:@"1"]) {
                [self restoreTransaction: transaction];
            }

            else {
               tCount--;

                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void) {
                    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
                });
            }

        default:
            break;

          }
      }
    return;
   }

The restore cycles through, but the count does not decrement.  This is probably something simple and dumb.  Can someone show me how to decrement this count?
Thanks!

A: I wait until restoreCompletedTransactionsFinished before sending a receipt to my server to verify with Apple.  This eliminates sending every receipt, which after a few months could get onerous. So, no need to decrement to transaction cout.


text:
Q: Late-binding public object variable in one sub and losing contents when execution moves to next sub I have a form which calls a number of subs from Module1. In Module1 I have a publicly declared object variable. The idea with that variable is to create a late-binded scripting.dictionary to avoid having to add too many references to my current vba project. The dictionary is successfully created and populated in Sub1. But, once Sub1 completes and Sub2 is called I notice the dictionary variable has reverted back to its original type of Object.
Login Form:
Public progresslbl As Object, subprogresslbl As Object, progressbar As Object, webBr As Object

Private Sub GetExports_Click()
...
...
...
progresslbl.Caption = "Requesting Exports"
RequestExports

'Wait for all emails to be received (reset currentsupplier and count emails, wait for currentsupplier = suppliercount)
WaitforEmails 'Still needs to be created

'Download Exports & Save them to destination user specifies
DownloadFiles

'Restore Outlook: remove temp folder and rule
progresslbl.Caption = "Restoring Outlook Settings"
RestoreOutlook

Module1:
Public IE As Object, downloadTo As String, Outlook As Object, Items As Object, err As Integer, itemdic As Object
'itemdic shows as type Object in Watch window

Sub RequestExports()

    Set itemdic = CreateObject("Scripting.Dictionary"): itemdic.comparemode = vbTextCompare
    'itemdic now shows at type scripting.dictionary in Watch window
    For x = 1 To suppliercount
        With IE.Document
            esplogin.subprogresslbl.Caption = "Searching for Supplier " & x & " of " & suppliercount
            currentsupplier = ActiveSheet.Range("A" & x).Value

            delay 3 'Wait 3 seconds to allow screen to load fully

            .getElementById("supplierSearchTextBox").Focus 'Select Search Box
            .getElementById("supplierSearchTextBox").Value = currentsupplier 'Fill in Search Box

            'Invoke keypress event so the contents are detected
            Set evt = .CreateEvent("keyboardevent"): evt.initEvent "change", True, False
            .getElementById("supplierSearchTextBox").dispatchEvent evt

            Dim searchButton As Object: Set searchButton = .getElementsByTagName("a")(5)
            searchButton.Click

            delay 3

            Dim supplierLink As Object: Set supplierLink = .getElementsByTagName("a")(6)
            'Cycle through list of suppliers in excel until we find another active one
            Do While supplierLink Is Nothing
                err = err + 1
                esplogin.subprogresslbl.Caption = "Supplier Not Found"
                delay 1
                ActiveSheet.Range("A" & x).Interior.Color = vbYellow
                If x = suppliercount Then Exit For
                esplogin.progressbar.Width = 150 / suppliercount * x
                x = x + 1
                esplogin.subprogresslbl.Caption = "Searching for Supplier " & x & " of " & suppliercount
                currentsupplier = ActiveSheet.Range("A" & x).Value
                'Select & Fill in Search Box
                .getElementById("supplierSearchTextBox").Focus
                .getElementById("supplierSearchTextBox").Value = currentsupplier

                'Invoke keypress event so the contents are detected
                Set evt = .CreateEvent("keyboardevent"): evt.initEvent "change", True, False
                .getElementById("supplierSearchTextBox").dispatchEvent evt

                Set searchButton = .getElementsByTagName("a")(5)
                searchButton.Click

                delay 2

                Set supplierLink = .getElementsByTagName("a")(6)
            Loop
            'Login to supplier
            supplierLink.Click

            While IE.Busy
                DoEvents
            Wend

            esplogin.subprogresslbl.Caption = "Exporting Supplier " & x & " of " & suppliercount
            delay 4

            Dim exportButton As Object: Set exportButton = .getElementsByTagName("button")(3)
            exportButton.Click

            delay 1
            .getElementsByTagName("select")(0).Value = "all"
            .getElementsByTagName("select")(1).Value = "5"
            delay 1
            .getElementById("btnExport").Click 'Click Export button
            delay 2

            'Click Ok button to close "Export sent to email" window
            Dim exportResultOK As Object: Set exportResultOK = .getElementById("exportProductModalResul").getElementsByTagName("button")(1)
            exportResultOK.Click

            esplogin.subprogresslbl.Caption = "Awaiting Export Confirm. Email for Supplier " & x & " of " & suppliercount
            delay 1

            Set eitDashboardButton = .getElementsByTagName("a")(11)
            eitDashboardButton.Click
        End With

        'Check to see if latestExport confirmation has arrived yet
        Set latestExport = Items.Find("[Subject] = ""Product Updates Product Export confirmation""")
        'If we haven't already found the latestExport wait and keep checking until we do
        Do While latestExport Is Nothing
            Set latestExport = Items.Find("[Subject] = ""Product Updates Product Export confirmation""")
        Loop

        esplogin.subprogresslbl.Caption = "Received Confirm. Email for Supplier " & x & " of " & suppliercount

        With latestExport
            BatchID = Mid(.Body, InStr(1, .Body, "Batch ID of ", vbTextCompare) + 12, InStrRev(.Body, ".", Len(.Body) - 1, vbTextCompare) - (InStr(1, .Body, "Batch ID of ", vbTextCompare) + 12))
            itemdic.Add currentsupplier, BatchID
            latestExport.Subject = "Product Updates Product Export confirmation - " & currentsupplier
            latestExport.Save 'Save the updated subject
        End With

        esplogin.progressbar.Width = 150 / suppliercount * x
    Next x

    esplogin.progresslbl.Caption = "Export Requests Complete"

    IE.Quit
    Set IE = Nothing
    Exit Sub
Restore:
    RestoreOutlook
    MsgBox ("Issue with Export code")
End Sub

Sub WaitforEmails(Optional currentcount As Integer = 0)

////As soon as the code reaches this point the item dic variable is now a type Object again and has no values

    Dim item As Object, BatchID As String, k As Object

    For Each item In Items
        With item
            If .Subject = "Product Updates: Product Export" Then
                'Instr check for batch id (ie dic key) then whatever dic value it matches replace batch id in dic with download link
                For Each k In itemdic.keys
                    If InStr(1, .HTMLBody, k, vbTextCompare) > 0 Then
                        'Store the download link in place of the batch id
                        itemdic(k) = Mid(.HTMLBody, InStr(1, .HTMLBody, "a href=") + 8, (InStrRev(.HTMLBody, ">here") - 2) - (InStr(1, .HTMLBody, "a href=") + 8))
                        Exit For
                    End If
                Next
                currentcount = currentcount + 1
                If currentcount = (suppliercount - errs) Then Exit For 'we have all of the emails
            End If
        End With
    Next
    If Not currentcount = (suppliercount - errs) Then Application.OnTime Now + TimeValue("00:01:00"), "WaitforEmails(currentcount)"
    While Not currentcount = (suppliercount - errs)
        DoEvents
    Wend
    Exit Sub
Restore:
    RestoreOutlook
    MsgBox ("Issue with WaitforEmail code")
End Sub

'When moving to sub 2 itemdic now reverts back to showing as type Object in Watch window

Sub 2()
    'Work with items in dictionary
    'Application or Object-defined Error I believe?
    'Some error
End Sub

My Question:
Is there a way to have the late-binded dictionary variable keep its type (and its contents/values) across subs (in Module1) without having to add the reference?

A: Something in Sub1 must be resetting your project.
The following works fine:
Public D As Object

Sub sub1()
    Set D = CreateObject("Scripting.Dictionary")
    D.Add "hello", "world"
End Sub

Sub sub2()
    Debug.Print D("hello")
End Sub

Sub test()
    sub1
    sub2 'prints "world" in the immediate window
End Sub

But -- the following works differently:
Public D As Object

Sub sub1()
    Set D = CreateObject("Scripting.Dictionary")
    D.Add "hello", "world"
    End
End Sub

Sub sub2()
    Debug.Print D("hello")
End Sub

Sub test()
    sub1
    sub2 'call doesn't print anything
End Sub

Make sure that you don't have any stray End in your code. If it isn't End it is something else. In any event, there is definitely no restriction in VBA about late-binding a public object variable in one sub and using that bound object in another.

A: Wow, so I feel like a real moron. The issue has been looking me in the face the entire time, well partly at least. I believe the issue was two-pronged:

*

*The project needed to be "cleaned" (exported the Module and Form and imported them into a new project)

*

*This took care of the itemdic not having it's values when arriving to the WaitforEmails sub. However, I did notice that when I reach the end of the first sub itemdic has the correct type and has values. What I realized is when it goes back to the code of the Userform it shows (temporarily) in the Watch window as having no values and being a type Object again, which is weird, but I imagine it's because the Each window is looking within the scope of whichever current module is actively executing code which makes sense. Once the WaitforEmails sub is called from the Userform and the code is going through the lines in that sub itemdic shows correctly with values and as type Dictionary.

*The key variable that I use to loop through the items in the dictionary is declared wrong, it should be declared as a Variant not an Object (doh!)


text:
Q: How can I show a status when building a document for download in ASP.Net? I am iterating through multiple recordsets to create multiple Excel worksheets that can take up to 30 seconds for the results, so I want to provide the user with feedback. A Processing.gif would be fine, but I would rather list the name of each Excel tab as it is being worked on.
Either way, no status shows up, just a blank page while the Excel file is being built.
Here is very sparse default.aspx
<form id="form1" runat="server">
    <div>
        <!-- never shows -->
        <asp:Image AlternateText="Processing for download" ImageUrl="/Images/Wait_Loader.gif"
    </div>
</form>

The code uses NPOI to build the spreadsheet file.
//*** New worksheet
Sheet sheet;
sheet = workbook.CreateSheet(sWorksheetName);

// Save the Excel spreadsheet to a MemoryStream and return it to the client
using (var exportData = new MemoryStream())
{
    workbook.Write(exportData);

    string saveAsFileName = sFileName + ".xls";

    Response.ContentType = "application/vnd.ms-excel";
    Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}", saveAsFileName));
    Response.Clear();
    Response.BinaryWrite(exportData.GetBuffer());
    Response.End();
}

All of this code works just fine, but when try to set the text of a label control or view a processing.gif, it is still just a blank screen. When I tried a Response.Write, I got statuses followed by the error Server cannot set status after HTTP headers have been sent
It seems like there is a collision between my Response.Writes and the NPOI using the Response object to write to the file.
How do I get something besides a blank window?


text:
Q: Is there any way to continue the Nutch Crawl task which has been killed unexpected? I have a Nutch crawl task which has been running a whole day long until i killed the process by a mistake.
I don't want to re-crawl the seeds (cost to much time), so i wonder whether there is a way or some Nutch Crawler parameters there, can make the crawler ignore those urls which has already been crawled.
Many thanks !

A: After you started crawling, there might be some segments created in the output directory. Use bin/nutch command and point -dir option to the output directory of previous run. For urlDir argument, create a dummy one with a single url (just for getting away from error if the urldir doesnt have any url in it.)


text:
Q: Java code in different build environments As I specified in title how can I write Java code, what is portable in multiple environments. I currently work at large application what was very library dependent, now after some work I come with a solution to refactor that code using MVC in mind. For each method that calls another method from that specific java library, I want somehow to add (C\C++) macros. I understand that it is not possible in java because it is compiled at runtime.
For example:
#if(LIB=TMERR)
    // Activate this code region
    // Some java code here
#else if(LIB=ZPAR)
    // Activate this code region
    // Some java code here

My question is, if exist a solutions to exclude regions of code from java code without having syntax errors. Or the case would be to exclude these files from build, and using reflection methods for each function that call another methods from specific library TMERR or ZPAR.
Thanks


text:
Q: VMware: How to directly access the GPU I have VMware Workstation running on Ubuntu host with a Ubuntu Guest.
Is it possible to directly access the GPU from the VM?
I want to run CUDA on the VM

A: It isn't unless nVidia provides a VMware-compatible paravirtualized driver for that purpose.
This discussion on the nVidia forums explains why.
Now, newer CPUs and chipsets support "IOMMU", which could serve the similar function as "PCI-E passthrough" that they discuss on that forum.  However, this still requires support and cooperation from both VMware's paravirtualized drivers and nVidia's drivers, which does not exist yet.

A: If you are ready to use Xen instead of VMware Workstation, you can try out Xen VGA Passthrough and see if your hardware configuration is supported. This would give you full control over the graphic card in the VM.
Here is an example of what you can accomplish: http://www.youtube.com/watch?v=Gtmwnx-k2qg


text:
Q: Laravel :: Routes Vs. Controller As I am new to the laravel 4 after spending some few months in Codeigniter, I went through the lots of tutorials about laravel and one thing I want to be clear is what is the actual difference between Routes and Controller in laravel, because we can create and generate view in both controller and routes too. Will anyone explain me in brief when to use routes and Controller in laravel? Because in other Framework we need routes to specify some particular URL's within the apps and Controller were used to do some real tasks but in laravel I didnt get the main concept of Routes except the routing mechanism?

A: In Laravel, you can totally skip controllers and do the task of performing business logic and generating the view in the routes.
E.g I have a link  b2.com/getUsers   so in routes.php I can write:
Route::get('/getUsers',function()
{
    $users=User::all();   //select * from users
    return View::make('allUsers')->with('users',$users);
}

So, here to serve the request b2.com/getUsers, we didn't use controller at all and you can very well do this for handling all requests in your application, both get and post.
But then, if your application is large and have 500+ url's with complex business logic then imagine putting everything in one routes.php. It will totally make it criminally messy and whole purpose of architecture will be defeated. Hence what we usually do is, reserve routes.php for routing only and write all business logic (along with generation of views inside controllers)
So the same example can be solved as:
To handle link:  b2.com/getUsers, in routes.php
Route::get('/getUsers', array('before' => 'auth', 'uses' => 'MyController@getUsers'));

MyController has the method getUsers defined like this:
public function getUsers()
{
    $users=User::all();   //select * from users
    return View::make('allUsers')->with('users',$users);
}

I usually create a controller for related activities e.g for login/signup/logout. I create AuthController and all the links related to those activities are routed to AuthController through routes.php.

A: The fact that you can get views or do a lot of things in Routes::any() is against MVC and separation of logic.
In Route::get("admin", function(){}), you indeed have a fast access to your route callback, which otherwise in a standard fashion must just be bound to controller. But Laravel allows you to do your job there in a closure (function(){}), instead of binding it to a controller. Anyway, it lets you, but you'd better avoid it. In Route::get() you only should go with your 'routing' and nothing more.
There is no reason for you to use callbacks in Route unless for testing or some trivial requests. So, better to avoid this:
Route::get("admin", function(){
    return View::make("admin_index");
});

And rather go with this:
Route::controller("admin", "AdminController");

And in your AdminController.php :
// I mean create a file named AdminController.php in controllers directory under app.
class AdminController extends Controller
{
   function getIndex()
   {
      return View::make("admin_index");
   }
}

Read more about Route::controller and restful controllers.
Some Notes:

*

*Having the ability to add closures in your Routes allows you to make
complex decisions on Routes and have a powerful routing system.

*These callbacks let you add conditions to your route.

*Having Controller separated from you Routes makes you application
more extensible, less confusing and makes other coders more
comfortable in future.

*It allows you to focus better on your problem and finding solution,
this physical separation is very important. Having View::make()
inside your Route stirs all problems into each other and makes up a
confusion for the coder.

A: Let's see what we have in both cases:
In CodeIgniter, a route is just pointing your request to a specific method of your controller:
$route['blog/joe'] = "blogs/users/34";

Here when you visit application.com/blog/joe, you will invoke the controller BlogsController, call the method users() and pass 34 as the first parameter. Nothing else. As they put it, a route in CI is just a one-to-one relationship between a URL string and its corresponding controller class/method.
Now, in Laravel, you have a lot of possibilities:

*

*You can directly return a simple response

*You can return a view

*You can point the request to a specific controller and a method

*You can write some logic in a closure and then decide what you want to do

You can add some additional functionality to them, like attaching filters, checking parameters upon a regex, give them separate names, etc., but this is the main functionality.
What's the reason for being able to do so much stuff? It gives you the power to use them in any way you need. Examples:

*

*Need a small website, rendering static HTML? Use them like this:

Route::get('/', function()
{
    return View::make('greeting');
});

*

*Need a bigger application using the traditional MVC pattern? Use like this:

Route::get('user/{id}', 'UserController@showProfile');

*

*Need a RESTful approach? No problem. This will generate routes for all the CRUD methods:

Route::resource('photo', 'PhotoController');

*

*Need something quick and dirty to handle a specific Ajax request? Keep it simple:

Route::post('foo/bar', function()
{
    return 'Hello World';
});

TL;DR: For very simple things without or with very little logic, use them instead of controllers. Otherwise, always stick to the MVC principles and route to your controllers, so that they're the ones who do the actual work.


text:
Q: Clean install of 12.10 - reused 12.04 /home. Cannot start unity/login for legacy/imported user I have separate disks for / and /home.  I did have 12.04 installed but decided to do a clean install (format and install) of 12.10. I created my user at install.  I should be able to login, right? Well, I can't.  LightDM comes up with my username and I enter my password, but it just goes back to the login screen.  Is there something I should delete from my old profile or ~?
I can login to the terminal. My files and directories are there in /home.


text:
Q: Prepayment management or Credit Management? I am a software programmer developing a system for a theme park, which take orders from multiple travel agents.
Before the travel agent can make any order, the agents have to pay certain amount of money to the theme park first. When the theme park process the order, the amount is deducted from the balance.
My questions:

*

*Should I call this system "Prepayment Management System"? one of my colleague suggested "Credit Management System" and "Account Balance Management System"

*Should I call the balance "Prepaid Balance" or "Credit Balance"?

Why I ask this question is because I feel weird to call it "Credit Management", it sounds like the theme park is taking order "on credit", like the park take the orders first and then send an invoice to the agent, so the agent owes the park some money.

A: I would rely on the more common usage of "debit" and "credit".
Given further examination, we can separate this into two different actions.
1.  The company pays upfront
This is a debit transaction.
OED link

1.1 A payment made or owed.
'a further debit of £21 had been received from the Locomotive Department'

2. The company then receives a balance on our platform.
That balance is a form of credit that they can spend towards things on your platform.
Notice that this is not "credit" in the sense that you provide services and the company only pays afterwards, like how it is used in "credit card".
It is more closely related to "store credit", i.e. a debt which is owed to you (not by you).
OED link

2.2 Entitlement to a set amount of a particular company's goods or services, typically paid for in advance of use.
'she had £15 credit on her account'

Conclusion
You need to distinguish between the money (legal tender) that is transferred, and the balance (fictional representation of the money that was paid to you) that is shown on the account.
If you were building a free-to-play game, and a player would send you money in exchange for gems/gold/...; then you would have already made that distinction quite clear. But because you are expressing the fictional credit of the company's account in real world currency, you are wrongly assuming that they are the same thing.
Even if they are always of equal value, it is still important to be able to distinguish between the two, as they represent different things.
Just because these two concepts are related, and may be of equal value, that does not prove that they express the same thing. My house number is currently the same as my age, but that doesn't mean that they express the same value. Funnily enough, this is the third time in my life where my age equals my house number, yet there is no direct correlation between the two.
Therefore, it would be correct to say that the debit sent to you by your customer (company), extends credit to the account of that customer (company).

But that doesn't help me with finding a name for the combined system.
Good point. Let me answer your two questions more directly:

*

*Should I call this system "Prepayment Management System"? one of my colleague suggested "Credit Management System" and "Account Balance Management System"

Externally, towards the customer (company), I would refrain from giving this system a name. It is a feature of your framework, not a standalone product or concept.
I would simply refer to the user as having an "account balance", and provide the option to "add credit" (to their account).
Internally, for your personal work situation, I would be okay with using either "Credit Management System" or "Account Balance Management System". Both are adequately descriptive, it is clear what the intention of the system is.

*Should I call the balance "Prepaid Balance" or "Credit Balance"?

I would opt for "Account balance". It's more correct in the user's context. It seems the most correct to say that the user will add credit to their balance (which is logically bound to their account).


text:
Q: How can I pick up the conversation_id of a message just sent or received? This answer says:

There is a conversation_id, which is the same at both endpoints.
And there is conversation_handle, which must be different at each
  endpoint.

So I thought it would be useful for troubleshooting to write the conversation_id to an audit table at each endpoint of a conversation.  That way I could easily track down the audit information at each endpoint for a given conversation.
The problem is where to pick up the conversation_id from.  I had originally thought I could look it up from sys.conversation_endpoints against the conversation_handle of the message just sent or received.  However, the database users that send and receive messages do not have permissions to see the metadata in sys.conversation_endpoints.
I could get around that by making the users sending and receiving messages database owners but I would prefer not to for security reasons.  What are the minimum permissions they would need to see the records in sys.conversation_endpoints?  Alternatively, how else could I read the conversation_id of a message that had just been sent or received (from the code doing the sending or receiving, which would not have dbo or sysadmin permissions)?
Edit: I read the Books Online article about Metadata Visibility Configuration which states

the visibility of metadata is limited to securables that a user either owns or on which the user has been granted some permission

For catalog views such as sys.tables or sys.procedures it's fairly obvious what the securables are that the user needs to be granted permission to.  But what are the securables listed in sys.conversation_endpoints: conversations, conversation endpoints?  And how do you grant permissions to them?  The user already has permission to begin a dialog or end a conversation so I would have thought it would already have adequate permission on a conversation.

A: The best place to get it is from sys.conversation_endpoints.
Whenever you are faced with the issue that your application requires privileges not held by the current user the best option is to leverage code signing. SQL Server allows an administrator to inspect and sign stored procedures, using certificates, and grant permissions to the signature. This allows an user to invoke the procedure and the procedure can access information not directly accessible to the user.
See signing Activated Procedures for an example.
As to why you can't see your own conversations: imho it's a bug. Running sp_helptext 'sys.conversation_endpoints' shows the permissions filter applied:
 CREATE VIEW sys.conversation_endpoints AS
SELECT ce.conversation_handle,
    ...
    FROM sys.conversation_endpoints$ ce
LEFT JOIN sys.syssingleobjrefs f
      ON f.depid = ce.service_id
      AND f.class = 21
      AND f.depsubid = 0 -- SRC_SVCTOQUEUE
WHERE has_access('CO', f.indepid) = 1

The view shows conversations for which the user has CONTROL access over the queue of the service to which the dialog belongs (it takes some know-how about syssingleobjrefs to understand what the view condition is, but that what it translates to). The permission check should be for RECEIVE permission, because that is the permission required to BEGIN DIALOG/SEND/END messages on this service:

To begin a dialog, the current user must have RECEIVE permission on the queue for the service specified in the FROM clause of the command and REFERENCES permission for the contract specified
  To send a message, the current user must have RECEIVE permission on the queue of every service that sends the message.

The MSND is actually wrong on the topic of END CONVERSATION permissions when it says 'To end an active conversation, the current user must be the owner of the conversation, a member of the sysadmin fixed server role or a member of the db_owner fixed database role'. The required permission is the same as one for SEND (this can be easily tested).
It can be easily argued that if you can manipulate a securable (and SEND, END are clearly manipulating conversations) then one should be able to see the metadata of the securable being manipulated.


text:
Q: CSS added to PHP file doesn't show up at all? I'm trying to add a CSS file to my PHP file, but for some reason it's not working... Can someone help me out?
    <!DOCTYPE html>
  <head>
    <title>Lab Test</title>
    <link rel="stylesheet" type="text/css" href="CSS/style.css" />
  </head>
  <body>

<?php
// define variables and set to empty values
$nameErr = $emailErr = $genderErr = $incomeErr = $websiteErr = "";
$name = $email = $gender = $comment = $income = $website = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   if (empty($_POST["name"])) {
     $nameErr = "Name is required";
   } else {
     $name = test_input($_POST["name"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
       $nameErr = "Only letters and white space allowed";
     }
   }

There's more code but I haven't added it.

A: Have you tried <link rel="stylesheet" type="text/css" href="../CSS/style.css" /> to align your css file with your php file?


text:
Q: VS2019 - Attempting to Publish an SQLCLR Class Library - System.Drawing' is not trusted When I attempt to Publish my SQLCLR program, I get the following error:
(47,1): SQL72014: .Net SqlClient Data Provider: Msg 10327, Level 14, State 1, Line 1 CREATE ASSEMBLY for assembly 'SqlClassLibrary' failed because assembly 'System.Drawing' is not trusted. The assembly is trusted when either of the following is true: the assembly is signed with a certificate or an asymmetric key that has a corresponding login with UNSAFE ASSEMBLY permission, or the assembly is trusted using sp_add_trusted_assembly.
System.Drawing IS in sys.trusted_assemblies. It was added using sp_add_trusted_assembly.
However, VS2019 still seems to think it is not.
permission-set-desc: UNSAFE_ACCESS

A: I resolved this by creating an Asymmetric key using System.Drawing and a login for it with Unsafe Assembly permissions:
USE master; GO CREATE ASYMMETRIC KEY SQLCLRTestKey FROM EXECUTABLE FILE = 'C:\Windows\Microsoft.NET\Framework64\v4.0.30319\System.Drawing.dll'; CREATE LOGIN
SQLCLRTestLogin FROM ASYMMETRIC KEY SQLCLRTestKey ; GRANT UNSAFE ASSEMBLY TO
SQLCLRTestLogin ; GO


text:
Q: change objects inside a set I dont really know why this is so hard to find.. but basically I have a set in an object and I need to change the set's values.
The object may or may not be pre-populated with data but the user can make selections to populate this set.  Regardless of wether or not the set had data in it already, if the user does this I need to clear all the objects inside the set and replace it with what the user has chosen.
However, the setByAddingOjbectsFromArray method of NSSet does not recreate a new set if there is data already there.
What exactly am I missing?

A: Does NSMutableSet do what you need?

A: If you don't want to keep what was in the set, what don't you use :
mySet = [NSSet setWithArray:myUserChoices];


text:
Q: Why is the data from firebase not getting displayed in my text views? I had posted questions on firebase realtime database as a json array of questions and tried to retrieve it from the firebase to my app but i am getting to see same text in my text views as I had set as default in my xml file so please help
My database is a json array containing a class Questions , in that there are five categories and each category has 9 question fields which has six sections ; the question,four options and correct answer (all strings)
public class Questions extends AppCompatActivity {
DatabaseReference dref;
DatabaseReference ref,ques;
TextView question,option1,option2,option3,option4;
ImageButton imageButton;

int val,correct,wrong,score;

public Questions() {
    this.val = 0;
    this.correct=0;
    this.wrong=0;
    this.score=0;
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_questions);
    question=findViewById(R.id.question);
    imageButton=findViewById(R.id.next);
    option1=findViewById(R.id.opt1);
    option2=findViewById(R.id.opt2);
    option3=findViewById(R.id.opt3);
    option4=findViewById(R.id.opt4);
    dref= FirebaseDatabase.getInstance().getReference();
    Intent intent=getIntent();
    Integer value=intent.getIntExtra("type",0);
   switch (value)
   {
       case 1:
           ref=dref.child("Questions").child("Bollywood");

            break;
       case 2:
           ref=dref.child("Questions").child("Sports");
           break;
       case 3:
           ref=dref.child("Questions").child("Technology");
           break;
       case 4:
           ref=dref.child("Questions").child("Entertainment");
           break;
       case 5:
           ref=dref.child("Questions").child("Miscellaneous");
           break;
           default:
               break;
   }
    ques = ref.child(String.valueOf(val));
    ques.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            QAnswer qAnswer=dataSnapshot.getValue(QAnswer.class);
            question.setText(qAnswer.getQuestion());
            option1.setText(qAnswer.getOption1());
            option2.setText(qAnswer.getOption2());
            option3.setText(qAnswer.getOption3());
            option4.setText(qAnswer.getOption4());
        }

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

        }
    });
   imageButton.setOnClickListener(new View.OnClickListener() {
       @Override
       public void onClick(View v) {
           if(val>15)
           {

           }
           else {
               ques = ref.child(String.valueOf(++val));
               ques.addValueEventListener(new ValueEventListener() {
                   @Override
                   public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                       final QAnswer qAnswer=dataSnapshot.getValue(QAnswer.class);
                       Log.d("value",qAnswer.getQuestion()+qAnswer.getAnswer());
                       question.setText(qAnswer.getQuestion());
                       option1.setText(qAnswer.getOption1());
                       option2.setText(qAnswer.getOption2());
                       option3.setText(qAnswer.getOption3());
                       option4.setText(qAnswer.getOption4());
                       option1.setOnClickListener(new View.OnClickListener() {
                           @Override
                           public void onClick(View v) {
                               if(qAnswer.getOption1()==qAnswer.getAnswer())
                               {
                                   option1.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
                                   correct++;
                               }
                               else {
                                   option1.setBackgroundColor(getResources().getColor(R.color.colorAccent));
                                   wrong++;

                               }
                           }
                       });
                       option2.setOnClickListener(new View.OnClickListener() {
                           @Override
                           public void onClick(View v) {

                           }
                       });
                       option3.setOnClickListener(new View.OnClickListener() {
                           @Override
                           public void onClick(View v) {

                           }
                       });
                       option4.setOnClickListener(new View.OnClickListener() {
                           @Override
                           public void onClick(View v) {

                           }
                       });
                   }

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

                   }
               });

           }
       }
   });

}
}

This is my questions model class:
public class QAnswer {
String question;
String option1;
String option2;
String option3;
String option4;
String answer;

public QAnswer(String question, String option1, String option2, String option3, String option4, String answer) {
    this.question = question;
    this.option1 = option1;
    this.option2 = option2;
    this.option3 = option3;
    this.option4 = option4;
    this.answer = answer;
}

public String getQuestion() {
    return question;
}

public void setQuestion(String question) {
    this.question = question;
}

public String getOption1() {
    return option1;
}

public void setOption1(String option1) {
    this.option1 = option1;
}

public String getOption2() {
    return option2;
}

public void setOption2(String option2) {
    this.option2 = option2;
}

public String getOption3() {
    return option3;
}

public void setOption3(String option3) {
    this.option3 = option3;
}

public String getOption4() {
    return option4;
}

public void setOption4(String option4) {
    this.option4 = option4;
}

public String getAnswer() {
    return answer;
}

public void setAnswer(String answer) {
    this.answer = answer;
}
 }

A: Add this to your questions model class
public QAnswer(){
}

before this
public QAnswer(String question, String option1, String option2, String option3, String option4, String answer) {
    this.question = question;
    this.option1 = option1;
    this.option2 = option2;
    this.option3 = option3;
    this.option4 = option4;
    this.answer = answer;
}


text:
Q: ng-repeat and ng-if not working I want to do following:

*

*Show all the html elements on the page based on some conditions,
my understanding was i can use ng-if.

*If employeeList is empty then do i need to create another copy of the inner elements to make sure it shows on the page

*ng-if prints both divs and spans which only one should be printed my html is this

html:

{{p.company}}

{{p.department}}

               {{ p.Value | date: "hh:mm:ss" }}

               0

my json is following
profileData: [
                  {
                   ID: "1",
                   metricStatList: [{"Value":0.003,"Stat":{"parameter":0,"Name":"test0","Tag":"Devo100"}},
                                 {"Value":0.004,"Stat":{"parameter":0,"Name":"test1","Tag":"Devo101"}},
                                 {"Value":0.005,"Stat":{"parameter":0,"Name":"test2","Tag":"Devo102"}}],
                   comapny: "MSDFT",
                   department: "Sales"
                  },
                  {
                   ID: "2",
                   metricStatList: null,
                   comapny: "MSDFT",
                   department: "HR"
                  },
                  {
                   ID: "3",
                   metricStatList: [{"Value":0.003,"Stat":{"parameter":0,"Name":"test0","Tag":"Devo100"}},
                                 {"Value":0.004,"Stat":{"parameter":0,"Name":"test1","Tag":"Devo101"}}],
                   comapny: "MSDFT",
                   department: "Development"
                  },
                  {
                   ID: "4",
                   metricStatList: [{"Value":0.1,"Stat":{"parameter":0,"Name":"test2","Tag":"Devo102"}},
                                 {"Value":0.25,"Stat":{"parameter":0,"Name":"test1","Tag":"Devo101"}}],
                   comapny: "MSDFT",
                   department: "Finance"
                  },
                  {
                   ID: "5",
                   metricStatList: [{"Value":0.233,"Stat":{"parameter":0,"Name":"test0","Tag":"Devo100"}}],
                   comapny: "MSDFT",
                   department: "Accounts"
                  }
                ]


text:
Q: Starting babel takes 80% of startup time when running simple unit tests I have a pretty big project with lots of modules. When I try to run a simple test like:
it('foo', () => {
    console.log('Running test');
});

the command yarn run jest --runTestsByPath src/simple-test.js takes 10 seconds. Babel will use the transformed JavaScript from the cache.
After doing some profiling, I found that roughly 8 seconds of that are spent loading 32'000 files from node_modules/@babel*.
Is there a way to compile all of this into a single (big) JavaScript file once with webpack and then reuse it for all my tests?
Other than that, is it possible to see why each module is loaded (= which module imports the others) so we can maybe trim this?


text:
Q: jQuery document ready - function calls: sequential or asynch? I recognise this question probably goes to how Javascript functions operate in general (and not just my particular case), but...
I want to know how my document ready function... umm... functions. In stylised form, it's like the following:
$(function () {
    object1.init();
    object2.init();
    object3.init(); etc...

Will object2.init() only fire when object1.init() returns? Or will they all fire in an asynchronous kind of way?
UPDATE: If they fire sequentially, is there any way I can get them to go simultaneously (which I possibly don't need to do)?
Thanks.

A:
Will object2.init() only fire when object1.init() returns? Or will they all fire in an asynchronous kind of way?

object2.init() only fire when object1.init() returns.
All the functions are stored in a queue, and get fired one after the other.
There is no way to make them fire simultaneously.
Not just jQuery, but javascript doesn't support parallel programming.

You can see the jQuery source code:
( Update: I removed the actuall code, because the answer became a mini jQuery source code...)
// Handle when the DOM is ready
ready: function(wait) {
    ...

// Call all callbacks with the given context and arguments
fireWith: function(context, args) {
    ...

jQuery.Callbacks = function( flags ) {
    ...

// The deferred used on DOM ready
readyList,

Check those functions and variables in the jQuery source code

A: It wil run sequencially.
If one of the init()'s does an async call, that will obviously be async, but each function (or any line actually) will run in turn.


text:
Q: Adding a widget to a layout created from .ui file I am creating a GUI in Python using PySide2, this is my .ui file:
<?xml version="1.0" encoding="UTF-8"?>
<ui version="4.0">
 <class>main_window</class>
 <widget class="QWidget" name="main_window">
  <property name="windowModality">
   <enum>Qt::NonModal</enum>
  </property>
  <property name="enabled">
   <bool>true</bool>
  </property>
  <property name="geometry">
   <rect>
    <x>0</x>
    <y>0</y>
    <width>1000</width>
    <height>640</height>
   </rect>
  </property>
  <property name="windowTitle">
   <string>Testing App</string>
  </property>
  <layout class="QVBoxLayout" name="layout">
   <item>
    <layout class="QVBoxLayout" name="other_layout">
     <item>
      <widget class="QWidget" name="panel" native="true">
       <layout class="QHBoxLayout" name="layout3">
        <item>
         <layout class="QVBoxLayout" name="layout4">
          <item>
           <layout class="QHBoxLayout" name="layout5">
            <item>
             <widget class="QLabel" name="lo">
              <property name="text">
               <string>X</string>
              </property>
              <property name="alignment">
               <set>Qt::AlignCenter</set>
              </property>
             </widget>
            </item>
            <item>
             <widget class="QLineEdit" name="resolution_x">
              <property name="sizePolicy">
               <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
                <horstretch>0</horstretch>
                <verstretch>0</verstretch>
               </sizepolicy>
              </property>
              <property name="inputMethodHints">
               <set>Qt::ImhDigitsOnly</set>
              </property>
              <property name="text">
               <string>175</string>
              </property>
             </widget>
            </item>
           </layout>
          </item>
          <item>
           <layout class="QHBoxLayout" name="layout6">
            <item>
             <widget class="QLabel" name="lo2">
              <property name="text">
               <string>Y</string>
              </property>
              <property name="alignment">
               <set>Qt::AlignCenter</set>
              </property>
             </widget>
            </item>
            <item>
             <widget class="QLineEdit" name="res2">
              <property name="sizePolicy">
               <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
                <horstretch>0</horstretch>
                <verstretch>0</verstretch>
               </sizepolicy>
              </property>
              <property name="inputMethodHints">
               <set>Qt::ImhDigitsOnly</set>
              </property>
              <property name="text">
               <string>150</string>
              </property>
             </widget>
            </item>
           </layout>
          </item>
         </layout>
        </item>
        <item>
         <layout class="QVBoxLayout" name="layout7">
          <item>
           <layout class="QHBoxLayout" name="iterations_layout">
            <item>
             <widget class="QLabel" name="iterLab">
              <property name="text">
               <string>Num Passes</string>
              </property>
              <property name="alignment">
               <set>Qt::AlignCenter</set>
              </property>
             </widget>
            </item>
            <item>
             <widget class="QLineEdit" name="itr">
              <property name="sizePolicy">
               <sizepolicy hsizetype="Preferred" vsizetype="Fixed">
                <horstretch>0</horstretch>
                <verstretch>0</verstretch>
               </sizepolicy>
              </property>
              <property name="inputMethodHints">
               <set>Qt::ImhDigitsOnly</set>
              </property>
              <property name="text">
               <string>20</string>
              </property>
             </widget>
            </item>
           </layout>
          </item>
          <item>
           <layout class="QHBoxLayout" name="layout8">
            <item>
             <widget class="QPushButton" name="reset_button">
              <property name="sizePolicy">
               <sizepolicy hsizetype="Maximum" vsizetype="Fixed">
                <horstretch>0</horstretch>
                <verstretch>0</verstretch>
               </sizepolicy>
              </property>
              <property name="minimumSize">
               <size>
                <width>50</width>
                <height>0</height>
               </size>
              </property>
              <property name="layoutDirection">
               <enum>Qt::LeftToRight</enum>
              </property>
              <property name="text">
               <string>Zoom</string>
              </property>
             </widget>
            </item>
           </layout>
          </item>
         </layout>
        </item>
       </layout>
      </widget>
     </item>
     <item>
      <layout class="QHBoxLayout" name="process_layout">
       <item alignment="Qt::AlignLeft">
        <widget class="QLabel" name="status">
         <property name="sizePolicy">
          <sizepolicy hsizetype="Fixed" vsizetype="Fixed">
           <horstretch>0</horstretch>
           <verstretch>0</verstretch>
          </sizepolicy>
         </property>
         <property name="minimumSize">
          <size>
           <width>120</width>
           <height>20</height>
          </size>
         </property>
         <property name="maximumSize">
          <size>
           <width>120</width>
           <height>20</height>
          </size>
         </property>
         <property name="text">
          <string/>
         </property>
         <property name="alignment">
          <set>Qt::AlignCenter</set>
         </property>
        </widget>
       </item>
       <item alignment="Qt::AlignRight">
        <widget class="QLabel" name="procLab">
         <property name="minimumSize">
          <size>
           <width>77</width>
           <height>20</height>
          </size>
         </property>
         <property name="maximumSize">
          <size>
           <width>77</width>
           <height>20</height>
          </size>
         </property>
         <property name="text">
          <string>#</string>
         </property>
        </widget>
       </item>
       <item alignment="Qt::AlignRight">
        <widget class="QLineEdit" name="processes">
         <property name="sizePolicy">
          <sizepolicy hsizetype="Maximum" vsizetype="Fixed">
           <horstretch>0</horstretch>
           <verstretch>0</verstretch>
          </sizepolicy>
         </property>
         <property name="minimumSize">
          <size>
           <width>50</width>
           <height>0</height>
          </size>
         </property>
         <property name="maximumSize">
          <size>
           <width>50</width>
           <height>2000</height>
          </size>
         </property>
         <property name="inputMethodHints">
          <set>Qt::ImhDigitsOnly</set>
         </property>
         <property name="text">
          <string>8</string>
         </property>
        </widget>
       </item>
      </layout>
     </item>
    </layout>
   </item>
  </layout>
 </widget>
 <resources/>
 <connections/>
</ui>

I want to add a widget dynamically from my Python script to the main layout ('layout'):
app = QApplication(sys.argv)
f = MyWindow()
sys.exit(app.exec_())

class MyWindow(QWidget):
    def __init__(self):
        super(MyWindow, self).__init__(None)
        ui_file = QtCore.QFile("./myui.ui")
        ui_file.open(QtCore.QFile.ReadOnly)
        loader = QtUiTools.QUiLoader()
        self.window = loader.load(ui_file)
        ui_file.close()

        self.layout.addWidget(QLabel('Stuff'))

        self.window.show()

However, I get the following error
    self.layout.addWidget(QLabel('Stuff'))
AttributeError: 'builtin_function_or_method' object has no attribute 'addWidget'

I don't understand why self.layout doesn't have the property addWidget. I thought self.layout would have a reference to a QVBoxLayout object?

A: You have several errors:

*

*The widget loaded from the .ui is not the MyWindow, on the other hand in PySide2 it is not possible to load a .ui to a widget class implemented by python (in PyQt5 if possible via uic.loadUi()) so the class should handle the widget.

*On the other hand, do not use variable names that may conflict with the names of the methods, for example the QWidget class has a layout method so it is not recommended that you have an attribute with that name, a possible solution is to use findChild to get the layout:
import sys

from PySide2.QtCore import QObject, QFile
from PySide2.QtWidgets import QApplication, QLabel, QVBoxLayout, QWidget
from PySide2.QtUiTools import QUiLoader

class Manager(QObject):
    def __init__(self):
        super(Manager, self).__init__(None)
        ui_file = QFile("./myui.ui")
        ui_file.open(QFile.ReadOnly)
        loader = QUiLoader()
        self.window = loader.load(ui_file)
        ui_file.close()
        lay = self.window.findChild(QVBoxLayout, "layout")
        lay.addWidget(QLabel("Stuff"))

        self.window.show()

if __name__ == "__main__":

    app = QApplication(sys.argv)
    f = Manager()
    sys.exit(app.exec_())

*

*Another possible solution is to change the name of the layout to for example vlayout: <layout class="QVBoxLayout" name="vlayout">
import sys

from PySide2.QtCore import QObject, QFile
from PySide2.QtWidgets import QApplication, QLabel, QWidget
from PySide2.QtUiTools import QUiLoader

class Manager(QObject):
    def __init__(self):
        super(Manager, self).__init__(None)
        ui_file = QFile("./myui.ui")
        ui_file.open(QFile.ReadOnly)
        loader = QUiLoader()
        self.window = loader.load(ui_file)
        ui_file.close()
        self.window.vlayout.addWidget(QLabel("Stuff"))

        self.window.show()

if __name__ == "__main__":

    app = QApplication(sys.argv)
    f = Manager()
    sys.exit(app.exec_())


text:
Q: How to make child not inherit animation property I'm experimenting with css animation property and making a spinner, but it turns out i can't make the childs (text) not rotate along with its direct parent,  i gave a thorough look to w3schools specs regarding to animation for details and searched for posts on this.. but so far got nothing.. Do you know if this can be done?? or after all...there needs to be a different approach in order to solve it??... Thank you in advance.

body{
  padding: 0;
  margin: 0;
}

#spinnerLayer{
 position: absolute;
 padding: 0;
 margin: 0;
 z-index: 2;
 width: 100vw;
 height: 100vh;
 background-color: rgba(0, 0, 0, 0.603);
}

#spinner span{
  position: absolute;
  animation: reverse;
  font-size: .3em;
  letter-spacing: 0.010em;
  color: white;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}

#spinner{
  padding: 2px;
  border-radius: 50%;
  border: 2px solid transparent;
  display: inline-block;
  border-left-color: cyan;
  border-right-color: cyan;
  animation: gira 2s infinite  forwards;
  animation-direction: normal;
  animation-timing-function: linear;
}

#spinner div{
  width: 15px;
  margin: 0;
  height: 15px;
  border-radius: inherit;
  border: 2.3px solid transparent;
  border-bottom: cyan solid 2px;
  border-top: cyan solid 2px;
  animation: gira 7s infinite  forwards;
  animation-direction: normal;
  animation-timing-function: linear;
}

@keyframes gira{
  0%{
    transform: rotate(0);
  }
  100%{
    transform: rotate(360deg);
  }
}
<!DOCTYPE html>

  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>

      99%

A: I came with an answer to this issue, and sadly.. in the end i got to wrap the #spinner with another div, move the span to it, and set both to position: absolute, thereby since the wrapper adjusts its size automatically only according to its content text gets positioned to center avoiding this way being under animation property. So, this is a workaround.
Resultant code:

   body{
          padding: 0;
          margin: 0;
        }
        #spinnerLayer{
         position: absolute;
         padding: 0;
         margin: 0;
         z-index: 2;
         width: 100vw;
         height: 100vh;
         background-color: rgba(0, 0, 0, 0.603);
        }
        #spinnerLayer > div {
          position: absolute;

        }
        span{

          position: absolute;
          font-size: .3em;
          letter-spacing: 0.010em;
          color: white;
          left: 50%;
          top: 50%;
          transform: translate(-50%, -50%);

        }
        #spinner{
          padding: 2px;
          border-radius: 50%;
          border: 2px solid transparent;
          display: inline-block;
          border-left-color: cyan;
          border-right-color: cyan;
          animation: gira 2s infinite  forwards;
          animation-direction: normal;
          animation-timing-function: linear;

        }
        #spinner div{
          width: 15px;
          margin: 0;
          height: 15px;
          border-radius: inherit;
          border: 2.3px solid transparent;
          border-bottom: cyan solid 2px;
          border-top: cyan solid 2px;
          animation: gira 7s infinite  forwards;
          animation-direction: normal;
          animation-timing-function: linear;
        }

        @keyframes gira{
          0%{
            transform: rotate(0);
          }
          100%{
            transform: rotate(360deg);
          }

        }

   <!DOCTYPE html>

      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Document</title>

           99%


text:
Q: One-to-one coloring correspondence between dual graphs and rectangles Here in the example I have a dual graph of intersections of various rectangles. $x$ simply denotes the point corresponding to the unbounded face of the graph. I am trying to determine a coloring for the edges of the dual graph in the following manner: we have two colors in total, say black and white, and we color each rectangle either black or white. The goal is to find a set of colorings of the edges of the dual graph that is in one-to-one correspondence with the set of all possible colorings of the rectangles.
Initially, my idea was to color each edge of the dual graph based on the color of the rectangle which it crosses. However, I am not sure how I would mathematically or algorithmically express this (this is the main issue). Moreover, I simply cannot take the set of all possible colorings of the dual graph, since this is not clearly in one-to-one correspondence with the colorings of the rectangles.
For the set of $N$ rectangles, there are $2^N$ possible different colorings, so there should also be $2^N$ different colorings of the edges that are in one-to-one correspondence with the colorings of the rectangles. Problem is, by only looking at the dual graph, how would one be able to determine the arrangement of rectangles it corresponds to? If there would be a one-to-one correspondence between dual graphs and arrangements of rectangles, this problem would be a lot easier (I am not sure if this is the case, is there a way to prove or disprove this?). However, I am not sure whether even if this is the case, how would coloring the edges of the dual graph black and white apply here?


text:
Q: Maximum sum rectangle in a 2D matrix using divide and conquer I need to implement a maximum sum algorithm that uses the divide and conquer strategy on a 2D matrix.  I'm familiar with the brute force approach which runs in O(n^6) time and Kadane's algorithm which runs in O(n^3) but how would one go about implementing a divide and conquer approach?  I've been thinking about it all day and nothing comes to mind.  In order to provide context, the brute force solution is this:
void maxSumBruteForce() {
    vector<vector<int>> matrix = genRandomMatrix();
    int maxSum = INT_MIN;
    printMatrix(matrix);

    for (int startRow = 0; startRow < matrix.size(); ++startRow) {
        for (int startCol = 0; startCol < matrix.size(); ++startCol) {
            for (int endRow = startRow; endRow < matrix.size(); ++endRow) {
                for (int endCol = startCol; endCol < matrix.size(); ++endCol) {
                    int curSum = 0;
                    for (int row = startRow; row <= endRow; ++row) {
                        for (int col = startCol; col <= endCol; ++col) {
                            curSum += matrix[row][col];
                        }
                    }

                    if (curSum > maxSum)
                        maxSum = curSum;
                }
            }
        }
    }

    cout << "MAX SUM: " << maxSum << endl;
}

Kadane's algorithm can be found here: https://www.geeksforgeeks.org/maximum-sum-rectangle-in-a-2d-matrix-dp-27/
I figure the solution would check the four quadrants of the matrix, then various combinations of the middles.

A: One way to adapt the article1 David Eisenstat shared in the comments could be the following:
If we divide the rectangle in two,
 -------------------
|         |         |
|         |         |
|   A     |    B    |
|         |         |
|         |         |
 -------------------

either the max sum is in A or it's in B or it's in a rectangle that has a part in A and a part in B. To calculate the latter, we use from each side total_sum, max_sum, max_prefix, max_suffix, for each O(num_rows^2) row bounds.
        A
 ---------------
|               |
|-----row_i-----|
|               |
|<--total_sum-->|
|               |
|max_pfx--|     |
|     |--max_sfx|
|               |
|-----row_j-----|
|               |
|               |
 ---------------

Then for each window of rows row_i to row_j, from A and B we have:
total_sum_AB = total_sum_A + total_sum_B
max_prefix_AB = max(max_prefix_A, total_sum_A + max_prefix_B)
max_suffix_AB = max(max_suffix_B, max_suffix_A + total_sum_B)
max_sum_AB = max(max_sum_A, max_sum_B, max_suffix_A + max_prefix_B)

Python code:
def g(M, num_rows, l, r):
  dp = [[None] * num_rows for _ in range(num_rows)]

  if l == r:
    for i in range(num_rows):
      dp[i][i] = [M[i][l], M[i][l], M[i][l], M[i][l]]

      for j in range(i+1, num_rows):
        dp[i][j] = [M[j][l] + dp[i][j-1][0], M[j][l] + dp[i][j-1][1], M[j][l] + dp[i][j-1][2], M[j][l] + dp[i][j-1][3]]

    return dp

  mid = l + (r - l) // 2

  dp_l = g(M, num_rows, l, mid)
  dp_r = g(M, num_rows, mid + 1, r)

  for i in range(num_rows):
    for j in range(i, num_rows):
      [total_sum_l, max_sum_l, max_pfx_l, max_sfx_l] = dp_l[i][j]
      [total_sum_r, max_sum_r, max_pfx_r, max_sfx_r] = dp_r[i][j]

      total_sum = total_sum_l + total_sum_r
      max_pfx = max(max_pfx_l, total_sum_l + max_pfx_r)
      max_sfx = max(max_sfx_r, total_sum_r + max_sfx_l)
      max_sum = max(max_sum_l, max_sum_r, max_sfx_l + max_pfx_r)

      dp[i][j] = [total_sum, max_sum, max_pfx, max_sfx]

  return dp

def f(M):
  num_rows = len(M)

  dp = g(M, num_rows, 0, len(M[0]) - 1)

  best = -float('inf')

  for i in range(num_rows):
    for j in range(i, num_rows):
      [total_sum, max_sum, max_pfx, max_sfx] = dp[i][j]
      best = max(best, max_sum, max_pfx, max_sfx)

  return best

Output:
M = [
  [ 1,  2, -1, -4,-20],
  [-8, -3,  4,  2,  1],
  [ 3,  8, 10,  1,  3],
  [-4, -1,  1,  7, -6]
]

print(f(M)) # 29

"""
  [ 1,  2, -1, -4,-20],
       -----------
  [-8,| -3,  4,  2,|  1],
  [ 3,|  8, 10,  1,|  3],
  [-4,| -1,  1,  7,| -6]
       -----------
"""

1 Divide & Conquer strikes back: maximum-subarray in linear time (Ovidiu Daescu and Shane St. Luce, Department of Computer Science, University of Texas at Dallas)


text:
Q: Why would removing gnash also remove gnome-desktop-enviroment? I've been having flash troubles with my firefox.  someone from some place suggested trying gnash.  It worked for a while but while it re-enabled flash player on youtube, it is still incompatible with other flash apps out there.
when i tried to remove it, it says it will also remove gnome-desktop-environment.  why?  why should removing gnash, a mere flash plugin, remove my desktop environment?

A: gnome-desktop-environment depends on swfdec-gnome, which in turn depends on gnash.
Fortunately gnome-desktop-environment is a metapackage (e.g. it doesn't install any files); removing it shouldn't cause problems.


text:
Q: AdjustTokenPrivileges Failed with Error 1300 ERROR_NOT_ALL_ASSIGNED I have developed SNMP extension DLL to perform some operations like Shutdown,Restart,etc Remotely.It is working fine with XP.Now I am migrating the DLL for Windows 7.I have read the document "impact of session-0 isolation" from MSDN and followed the instructions for DLL migration.For example, I have followed the instructions in the link How To ShutDown the System - msdn and coded the same for the shutdown operation. But "AdjustTokenPrivileges" always returning Error:1300 Not all privileges or groups referenced are assigned to the caller.
Is there any way to solve this error? How do I enable the shutdown privilege for Windows 7 Using VC++?

A: Yes, there is one: assign the privileges to the caller (requires logoff before it takes effect). This requires the admin of the computer or the domain/AD to act. You can also do it programatically with LsaAddAccountRights() and LsaRemoveAccountRights().
Consider this: every user has a set of assigned privileges. Any assigned ones can be enabled or disabled for a token representing this user. What you are trying to do is to enable a privilege that was never assigned to the user in the first place. Therefore it cannot be enabled/activated.
However, I suggest you post your code, because it is very unusual that a local user cannot shut down the system. This privilege is usually granted to everyone logging on locally by default.


text:
Q: Error in Google Maps android "android Failed to load map. Could not contact Google servers." i am trying to implement google maps in my android application but i am stuck on an error
"android Failed to load map. Could not contact Google servers."
i have included google play library, got the key using SHA1 certificate fingerprint.
i got the SHA1 certificate fingerprint as :
 sudo keytool -v -list -alias androiddebugkey \-keystore /home/.android/debug.keystore

i managed my manifest file according to This
now i am unable to find the cause of this error.. any suggestion is greatly appreciated...

*

*i have seen questions on stackoverflow but didnt got any solution!

EDIT:
my manifest file permissions are as:
<permission
    android:name="PAKG_NAME.permission.MAPS_RECEIVE"
    android:protectionLevel="signature" />

<uses-permission android:name="PAKG_NAME.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.com.google.android.providers.gsf.permission.READ_GSERVICES" />

<uses-feature
    android:glEsVersion="0x00020000"
    android:required="true" />

.....................

      <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="MY_KEY" />

and my layout xml have fragment as:
  <fragment
            android:id="@+id/map"
            android:layout_width="match_parent"
            android:layout_height="100dp"
            android:layout_marginLeft="10dp"
            android:layout_marginRight="10dp"
            class="com.google.android.gms.maps.SupportMapFragment" />

Logcat output:
 E/Google Maps Android API(31478): Failed to load map.  Could not contact Google servers.

A: Are you sure you have enabled "Google Maps Android API v2" and not "Google Maps API v2"?
After changing that, delete and recreate the API key. This worked for me...

A: Try right click on your project and select Properties > Android > and in "Project Build target" select Google APIs. That worked for me :)

A: If you are sure about your API key, you should uninstall program from your phone and install again. It worked for me :)

A: Have u enable Google android map API v2 in console check
 It properly .
I think u enable Google map v2 that why request failed...

A: You should check if you have duplicate API_KEY for the same project. As you know, we will use sha1 key and android project name for getting an API key. If you try to use same sha1;android_project_name pair to get API key, Google will give you another API key. So its duplicated. If you delete the newer one and use the older one in your project, it will solve your problem.
At least I hope :)

A: I had this problem when refactoring and changing my project bundle identifier. If is this your case, you will have to create a new project on Google Developer Console and link again to your project. For some reason Google blocks requests from the same app if it changes its ID.


text:
Q: Is it possible to catch errors within an iframe with Javascript? I'm using the lightwidget to include instagram posts to my website with an iframe.
Some people have Firefox settings / plugins to block posts from instagram, so they'll get the error: GET https://scontent-frx5-1.cdninstagram.com/v/somepost net::ERR_NAME_NOT_RESOLVED
because the images wont load. Can I somehow catch that error?
I want to show some message instead and display: none; the iframe, so the user doesn't see an endless spinning wheel.
I tried to catch the error like this, but it didn't work:
window.addEventListener('error', function(event) {
    alert('error')
})

Thanks for any help


text:
Q: How to loop an array using the value of an xml child node using PHP? I'm new to PHP and in particularly XML.
I'm trying to pull data from an XML file using the particular values of one of the child nodes. All the online resources I seem to find lead me to how to get all the values from a child node but I want to pull only the ones that contain a certain value in a child node. I'm struggling to get the format of the if statement right.
Any help, much appreciated, thank you!
My code so far:
if( !($xml = simplexml_load_file('images/database.xml')) )
{
  echo "Unable to load XML file";
}
else
{
  foreach($xml->children() as $document)
  {
    if ($xml->$document->city == $xml->$document->city['London'])
    {
      echo $document->name . ", ";
      echo $document->description . ", ";
      echo $document->image . ", <br>";
    }
  }
}


text:
Q: Why is my for loop an illegal declaration I created two subs one to do Fibonacci and the other to test even numbers. When I call it though it is saying my for loop in line 7 the sub Fibonacci is illegal why?
#!/usr/bin/perl
use strict;
use warnings;

my ($x,$y);
my $num = 0;

sub Fibs($start,$stop){
    for ($start..$stop){
        ($x, $y) = ($y, $x+$y);
            my $total += $y;
        }
    print "$total \n"
}

sub even($num){
    if ($num % 2 == 0){
        return $num;}
}

my $big_total = Fibs(even($num), 3999999)

Edited from suggestions below.
Clearly I am missing something. From feedback updated to new version.
#!/usr/bin/perl
use strict;
use warnings;

my ($x,$y);
my $num = 0;

sub Fibs{
    my ($start, $stop) = @_ ;
    for ($start..$stop){
        my ($x, $y) = (0,2);
            if ($x % 2 == 0){
                ($x, $y) = ($y, $x+$y);
                    my $total += $y;
        }
}

my $big_total = Fibs(0, 3999999)

A: In addition to the missing opening braces, Perl doesn't support that kind of declaration for subroutine parameters.
Rather than
sub Fibs($start, $stop) {
    ...
}

you need to write something like:
sub Fibs {
    my($start, $stop) = @_;
    ...
}

(Perl does have prototypes, but they're not really intended for declaring the types of parameters, and they don't provide names.  See this article for a discussion.)
Other problems:
You should add
use strict;
use warnings;

You never use the $x and $y that you declare in the outer scope.
Your even function appears to be incomplete.  It doesn't (explicitly) return a value if its argument is an odd number.  What exactly is it intended to do?


text:
Q: Get the total size of the TCheckbox, including box and text, in Delphi I want to get the total size of the TCheckbox, including the box and the text in Delphi. I check the article at Delphi FMX TCheckbox/TRadiobutton Autosize, but it seems that TCheckbox does not have a Canvas property so the code does not fit for it.
Update
Let me explain the reason why I need to know that. In some of my checkboxes, I need to put a spinedit related to the checkbox. For example, in checkbox "Split the file when it size larger than" ### "Bytes", where ### is the spin edit.
Since checkbox does not support auto-size, one way is to enlarge the checkbox so that it accomondate all the texts. Then put the spin edit after the last visible character.
This is fine for single language, however, to support multi-langauge, some language will be very longer than the others.
In such a case, I can choose:

*

*Calculate the size of the checkbxo visible part.

or

*Keep some spaces between the last visible character and the spin edit.

method 2 is not very good as there will be huge distance between the checkbox and the spin edit for some languages.
Update 2
One more issue, I try to do the same thing for a button, as below:
var
  bmp: TBitmap;
  size: TSize;
  width: Integer;
begin
  Checkbox1.Caption := Edit3.Text;
  Button3.Caption := Edit3.Text;

  bmp := TBitmap.Create;
  try
    bmp.SetSize(CheckBox1.Width, CheckBox1.Height);
    bmp.Canvas.Font := CheckBox1.Font;
    size := bmp.Canvas.TextExtent(CheckBox1.Caption);
    Width := bmp.Canvas.TextWidth(Checkbox1.Caption);
    CheckBox1.Width := size.cx + 20;
    button3.Width := size.cx;
    SpinEdit1.Left := Checkbox1.Left + Checkbox1.Width + 5;
  finally
    bmp.Free;
  end;
end;

As the button does not have any box, so I use the size.cx instead of adding some value. However, in my test, actually the text width is not correct, which makes the button cannot accomondate the whole text, see below:

A: Here's my two cents.
To get the size of the actual checkbox, I believe you should ask the Win32 theme API (uses UxTheme):
var
  h: HTHEME;
  S: TSize;
begin

  h := OpenThemeData(Handle, 'BUTTON');
  try

    if Succeeded(GetThemePartSize(h, Canvas.Handle, BP_CHECKBOX,
      CBS_UNCHECKEDNORMAL, nil, TS_DRAW, S))
    then
      ShowMessage('Check box width: ' + S.cx.ToString);

  finally
    CloseThemeData(h);
  end;

Similarly, this retrieves the width of the text (caption):
var
  h: HTHEME;
  R: TRect;
begin

  h := OpenThemeData(Handle, 'BUTTON');
  try

    if Succeeded(GetThemeTextExtent(h, Canvas.Handle, BP_CHECKBOX,
      CBS_UNCHECKEDNORMAL, PChar(CheckBox1.Caption),
      Length(CheckBox1.Caption), 0, nil, R))
    then
      ShowMessage('Caption width: ' + R.Width.ToString);

  finally
    CloseThemeData(h);
  end;

What remains unknown is the padding between the check box and the caption. I don't know the right way to obtain this, but it seems like it is most often the same as the width of a space:
var
  h: HTHEME;
  S: TSize;
  R: TRect;
begin

  h := OpenThemeData(Handle, 'BUTTON');
  try

    if Succeeded(GetThemePartSize(h, Canvas.Handle, BP_CHECKBOX,
      CBS_UNCHECKEDNORMAL, nil, TS_DRAW, S))
    then
      ShowMessage('Check box width: ' + S.cx.ToString);

    if Succeeded(GetThemeTextExtent(h, Canvas.Handle, BP_CHECKBOX,
      CBS_UNCHECKEDNORMAL, PChar(#32+CheckBox1.Caption),
      1+Length(CheckBox1.Caption), 0, nil, R))
    then
      ShowMessage('Caption width including padding: ' + R.Width.ToString);

  finally
    CloseThemeData(h);
  end;


text:
Q: Error 1193 when following 'employees database' install tutorial with MySQL 5.7.11 I downloaded and installed a vanilla instance of MySQL 5.7.11 (that's the version it reports when I run > mysql -v).  The instance is up and running.
Then I tried to follow the seemingly simple tutorial here:
https://dev.mysql.com/doc/employee/en/employees-installation.html
When I get to the step to run: mysql -t < employees.sql it fails, giving the error:
ERROR 1193 (HY000) at line 38: Unknown system variable 'storage_engine'

The employees.sql file is configured as instructed in the tutorial with the default setting.  How do I fix this error?
Note: I'm performing all steps as root in MySQL, and the system is Win10 if that has any bearing.

A: If anyone cares to know the fix without finding the updated archive it's relatively simple:

*

*Open the employees.sql file in your editor of choice

*Edit lines 38 and 44
// change line 38 from:
set storage_engine = InnoDB;
// to:
set default_storage_engine = InnoDB;

// change line 44 from:
select CONCAT('storage engine: ', @@storage_engine) as INFO;
// to:
select CONCAT('default storage engine: ', @@default_storage_engine) as INFO;

*Save employees.sql, then open a console window and navigate to the employees_db folder. Execute the following command from the prompt and your all set.
c:\employees_db>c:\Path\to\MySql\bin\mysql.exe -u username -p < employees.sql

A: The tutorial hasn't been updated to reflect changes in recent MySQL versions. From the documentation

This variable is deprecated and was removed in MySQL 5.7.5. Use default_storage_engine instead.

A: [root@001 employees_db]# vim employees.sql

set **default_storage_engine** = InnoDB;

-- set storage_engine = MyISAM;

-- set storage_engine = Falcon;

-- set storage_engine = PBXT;

-- set storage_engine = Maria;

select CONCAT('storage engine: ', @@**default_storage_engine**) as INFO;

Two changes needed : default_storage_engine

A: Updated db is available in https://github.com/datacharmer/test_db
It has the fix for MySQL 5.7.x

A: no its not fix in a new version... I got the same error:
ERROR 1193 (HY000) at line 38: Unknown system variable 'storage_engine'


text:
Q: UIImagePickerController.cameraViewTransform ignores translation My app stopped working correctly with iOS 4.3. It uses a custom camera view overlay for the UIImagePickerController. Because of the aspect ratio differences between camera and screen live view by default has a black bar at the bottom. To get rid of it I used to apply two transforms which shift the view down and scales it to full screen:
self.cameraFeed = [[UIImagePickerController alloc] init];
CGAffineTransform translate = CGAffineTransformMakeTranslation(0.0, 25.0);
self.cameraFeed.cameraViewTransform = CGAffineTransformScale(translate, 480.0/430.0, 480.0/430.0);

With the current iOS version it seems that the translation transform doesn't do anything - I have a 25px black bar at the bottom and changing the values doesn't have any effect. However scale and rotate transforms work as expected.
Anyone has any similar problems?

A: You should use the video preview layer (available since 4.2 if memory serves) instead of UIImagePicker. With it you can fully customize your UI as you see fit.


text:
Q: Prevent django widthratio calculating more than 100 % Im trying to put together a bootstrap 3 progress bar with multiple percentage values (see docs example).
The combined value of all the values can not be more than 100%, but django is rounding up, and I'm getting a value of 101%
#max_width = 100
#total.count = 17

#a.count = 11 (65%)
#b.count = 2 (12%)
#c.count = 4 (24%)

    {{ a.count }} ({% widthratio a.count total.count max_width %}%)

    {{ b.count }} ({% widthratio b.count total.count max_width %}%)

    {{ c.count }} ({% widthratio c.count total.count max_width %}%)

Output

        11 (65%)

        2 (12%)

        4 (24%)

As you can see, all the percentage is added up to 101%, and therefore the last value is not displaying in the progress bar. Is there any way to fix this?

A: I found this, which doesn't really help. I am looking at the same issue.
https://code.djangoproject.com/ticket/12026
Not sure if this is the best approach but:
@register.simple_tag
def percentage(value, total):
    return float(value)/float(total) * 100

and then in the template:
style="width: {% percentage group.count total.count %}%;"


text:
Q: JavaScript count the number of times a specific value is mentioned in an array of objects I am looking for a solution to an issue I am currently experiencing with looping over an array containing objects. Within the child objects I would like to access the second element [2], take its value in my example beneath;
windows, windows_11, linux_sys
Check whether they current exist within an array (array starts empty therefore it'll append the values into it if they don't already exist, and count the number of times a specific "Software Name" occurs in all child objects.
Here is an example input of my JSON array and what I currently have:
json_output = [
  {
    "id": "1",
    "Device Name": "device3",
    "Software Name": "windows"
  },
  {
    "id": "2",
    "Device Name": "device6",
    "Software Name": "windows"
  },
  {
    "id": "3",
    "Device Name": "device11",
    "Software Name": "windows"
  },
  {
    "id": "4",
    "Device Name": "device11",
    "Software Name": "windows_11"
  },
  {
    "id": "5",
    "Device Name": "device11",
    "Software Name": "linux_sys"
      }
   ]

new_arr = [];

for (var i = 0; i < json_output.length; i++) {
    new_arr.push(Object.values(json_output[i])[2]);
}

This is returning a list containing:
["windows","windows","windows", "windows_11", "linux_sys"]

If anyone could help me create the beneath I would greatly appreciate it. Instead of a array as I currently have, I'd quite like to recreate the beneath;
   software_name_count [
      {
        "windows": "3"
      },
      {
        "windows_11": "1"
      },
      {
        "linux_sys": "1"
      }
    ]

Thank you to anyone that assists me with conquering this problem. I'm relatively noobish with JS. If there's any more information that's required please let me know.
p.s. I cannot hard code any section of this code, such as the software names windows, windows_11 and linux_sys.
Thanks
George

A: Using an object is more useful than an array here to save the data. But you can convert if need be.

json_output = [
  {
    "id": "1",
    "Device Name": "device3",
    "Software Name": "windows"
  },
  {
    "id": "2",
    "Device Name": "device6",
    "Software Name": "windows"
  },
  {
    "id": "3",
    "Device Name": "device11",
    "Software Name": "windows"
  },
  {
    "id": "4",
    "Device Name": "device11",
    "Software Name": "windows_11"
  },
  {
    "id": "5",
    "Device Name": "device11",
    "Software Name": "linux_sys"
  }
];

new_obj = {};

for (obj of json_output) {
  let key = obj["Software Name"];
  new_obj[key] = json_output.filter(a => a["Software Name"] == key).length;
}

console.log( new_obj );

// do you need to format this as an array? if so, do this

const new_arr = [];
for (const [softwareName, count] of Object.entries(new_obj)) {
  let row = {[softwareName]: count};
  new_arr.push(row);
}

console.log( new_arr );


text:
Q: Celery chain stops in the middle without any reason (AWS Redis db, RabbitMQ broker) Found strange behavior implementing tasks pipeline on Celery. Most of the time tasks chain executed, but sometimes it just silently stops in the middle after successful run of the previous task.
Example pipeline
    pipelines = []
    for task in Factory.gen_tasks(request):
        pipelines.append(
            chain(
                first_process_step.si(task),
                second_process_step.si(task),
                group(
                    chain(
                        post_process_first_step.s(task.id),
                        post_process_second_step.s(task.id),
                    ),
                    notify_user.s(task.id),
                ),
            )
        )

    async_task = group(pipelines).apply_async()

Some config options:
    celery_app.conf.update(task_acks_late=True)
    celery_app.conf.update(task_reject_on_worker_lost=True)
    celery_app.conf.update(worker_proc_alive_timeout=20)
    celery_app.conf.update(worker_lost_wait=10)

So most of the time (99%, probably) everything is fine and task executed after another task. But sometimes execution stopped after first_process_step or sometimes after second_process_step
In both cases, I see in logs that the previous task completed, but the next step task is not received by a worker. Also, the queue is empty. So I started to think that a message was not sent to the broker.
App deployed to Kube and works with AWS Redis and RabbitMQ.
UPDATE:
So, if anyone will have similar behavior when the pipeline looks pretty regular, you use RabbitMQ and sometimes messages lost silently then you need to consider adding this not documented option:
    celery_app.conf.update(
        broker_transport_options={"confirm_publish": True},
    )

Which enabled ConfirmPublish and ensures that a message will be processed at least once.
Defect about documentation update:
https://github.com/celery/celery/issues/5410


text:
Q: Do data conversion after Django model object is fetched I want to save the python dictionary inside the Django model as JSON and I want to convert that JSON back into a python dictionary when that data is fetched.
I know I can do it inside view but I want to implement it in the model so it can return dictionary object when queried.
is there any signal or any post_fetch method that I can use to achieve it, I couldn't find anything googling it...

A: You might want to look into simply using the Python JSON package, unless you are using Postgres as your database - in which case JSONField is the way to go. The json package is explained here and you could use it in a model like so if I understand what you are saying:
import json

class MyModel(models.Model):
    json_field = models.TextField() # or you can use JSONField if using Postgres

    @property
    def get_json_field_as_dictionary(self):
       return json.loads(self.json_field)

   def set_json_field(self, mydict):
       self.json_field = json.dumps(mydict)

    @classmethod
    def get_json_from_dictionary(cls, mydict):
        return json.dumps(mydict)

When you are saving to the database, you can use json.dumps(myDictionary) or convert the dictionary to JSON by calling MyModelObject.set_json_field(myDictionary) to convert a Python dictionary to JSON and then store it in the json_field of the model. To retrieve the JSON data as a dictionary, you simply call MyModel.objects.last().get_json_field_as_dictionary (or whatever you prefer to call it, json_dictionary perhaps so it would be MyModel.objects.last().json_dictionary) and it will return the value of that property as if it were an element in the model without having to do the conversion each time.
Or, if you are using Postgres as your backend, this is a lot easier with JSONField:
class MyModel(models.Model):
    json_field = models.JSONField(null=True)

And to save:
    myObject = myModel.objects.create(json_field=myDictionary)

If you clarify I can update my answer to explain better.

A: You may want to use JSONField. It allows storing data encoded as JSON and retrieve them as the corresponding Python data type, including dictionary.
JSONField only works on PostgreSQL with Django < 3.1, but works on any database with Django >= 3.1.


text:
Q: Registration of the app failed I'm very new so ...
I was watching a "how-to" video, followed the instructions (create a "Visual C#", "Store Apps", "Blank App".  Changed the background color to orange, then pressed Ctrl + f5 and below is the error.
1>Error : DEP0700 : Registration of the app failed.
Windows cannot deploy to path G:\C#_Stuff\Projects\WindowStoreAppOrange\WindowStoreAppOrange\WindowStoreAppOrange\bin\Debug of file system type FAT32.
The path must be located on an NTFS volume. (0x80073

Any helpful thoughts?

A: The error message clearly states that your project cannot be deployed to a drive with a FAT32 filesystem. Move your deploy directory to a NTFS drive.


text:
Q: How to implement recaptcha in odoo We are using odoo 12 online for enterprises.
We would like to protect our forms using google recaptcha.
How can we implement google recaptcha? If possible a full example how to implement it.
We would prefer recaptcha v3 but if not possible a v2 implementation is fine.
When I try to search online for implementation of google recaptcha there's almost every time a .php file included. Our pages are loaded with QWeb view types and php isn't supported.
Is it possible to implement without php? We could definitely use html and javascript and probably python, is it possible to do with only these? If it's possible we would like to do it with only javascript and html but I'm assuming that's not the case.
Is there any other form protection we could implement using only html and javascript?

A: Google reCAPTCHA v3 in Python
You need to install reCAPTCHA on the frontend and implement the verification on the backend. At the bottom of the post, I linked the official Google reCAPTCHA documentation.
Frontend Integration
<script src="https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"></script>
<script>
grecaptcha.ready(function() {
    grecaptcha.execute('reCAPTCHA_site_key', {action: 'homepage'}).then(function(token) {
       ...
    });
});
</script>

The frontend just needs to:

*

*Load the JavaScript api with your sitekey

*Call grecaptcha.execute on an action or when the page loads

*Send the token to your backend with the request to verify

Backend Integration
The verification of the token is the same as in reCAPTCHA v2. When the user submits the form on your site, you get the POST parameter g-recaptcha-response. You need to make a POST request to the Google reCAPTCHA service with following parameters. You can take your HTTP request framework of your choice.

*

*URL: https://www.google.com/recaptcha/api/siteverify
POST Parameter  Description
secret          Required. The shared key between your site and reCAPTCHA.
response        Required. The user response token provided by the reCAPTCHA client-side integration on your site.
remoteip        Optional. The user's IP address.

Then you get a JSON response from the service and if the request failed, you can handle further actions on the backend.
{
  "success": true|false,
  "challenge_ts": timestamp,  // timestamp of the challenge load (ISO format yyyy-MM-dd'T'HH:mm:ssZZ)
  "hostname": string,         // the hostname of the site where the reCAPTCHA was solved
  "error-codes": [...]        // optional
}

Sources

*

*Google | reCAPTCHA Installation

*Google | reCAPTCHA Verification

A: Hope this will helps, you can get an idea from odoo forum.


text:
Q: Symfony 2.6 - How to validate non-entity form using validation.yml? I have a form which does not represent any Entity object, however, I would like to validate this form, but for some reasons (for example clean code etc), it must be done by using validation.yml file.
I store my form object in \\src\ZaquPL\MyCustomBundle\Form\Type\MyCustomFormType.php. Moreover, I created validation.yml file:
ZaquPL\MyCustomBundle\Form\Type\MyCustomFormType:
    properties:
        myField:
            - NotBlank: ~

But my form is not validated. $form->isValid() always return true.

A: I think is link contain the perfect example as you want. http://symfony.com/doc/current/cookbook/doctrine/registration_form.html
You see there is a model named as Registration which is not an entity. Here it is
http://symfony.com/doc/current/cookbook/doctrine/registration_form.html#embedding-the-user-form-into-a-registration-form
The directory of the of this class is src/Acme/AccountBundle/Form/Model/Registration.php, This can be validated perfectly as you want.

A: In my opinion it's not possible. Validators placed in annotations or yml file, should be connected with entity object, not with form type.
But there is small workaround.
You can create your own FormBuilder service. His method should get as argument your FormType, then he will rewrite your FormType to get form created by method 'createFormBuilder': Symfony form documentation. Then in this service you can read validation file and add validators in this way:
Symfony documentation - adding validation
It's really time-consuming and I think that's better to attach validators to your entity.

A: Simply create an plain php object as model class and use this as data object in your createForm(). Then you can create the validation.yml on this simple model object.


text:
Q: I'm trying to create a formula for subtracting one value from existing column using trigger using MYSQL create table product
(PROD_CODE varchar(100),
PROD_QOH int);

insert into product
values("ABC", 1250);

create table part
(PART_CODE varchar(100),
PROD_QOH int);

insert into part
values("A", 567),
("B", 98),
('C', 549);