text:
Q: how do I generate multiprocessing jobs inside a list without making duplicates? How do I make a multiprocessor system work, which makes new jobs inside a list?
I keep getting:

assert self._popen is None, 'cannot start a process twice'
  AttributeError: 'Worker' object has no attribute '_popen'

which makes sense, because I'm basically making multiple instances of the same job... so how do i fix that? do I need to set up a multiprocessor pool?
let me know if I need to clarify things more.
here is my multiprocessing class:
class Worker(multiprocessing.Process):

    def __init__(self, output_path, source, file_name):
        self.output_path = output_path
        self.source = source
        self.file_name = file_name

    def run(self):

        t = HTML(self.source)
        output = open(self.output_path+self.file_name+'.html','w')
        word_out = open(self.output_path+self.file_name+'.txt','w')
        try:
            output.write(t.tokenized)

            for w in word_list:
                if w:
                    word_out.write(w+'\n')

            word_out.close()
            output.close()
            word_list = []

        except IndexError:
            output.write(s[1])
            output.close()
            word_out.close()

        except UnboundLocalError:
            output.write(s[1])
            output.close()
            word_out.close()

here is the class that implements this whole thing.
class implement(HTML):

    def __init__(self, input_path, output_path):
        self.input_path = input_path
        self.output_path = output_path

    def ensure_dir(self, directory):
        if not os.path.exists(directory):
            os.makedirs(directory)
        return directory

    def prosses_epubs(self):
        for root, dirs, files in os.walk(self.input_path+"\\"):
            epubs = [root+file for file in files if file.endswith('.epub')]
            output_file = [self.ensure_dir(self.output_path+"\\"+os.path.splitext(os.path.basename(e))[0]+'_output\\') for e in epubs]

        count = 0
        for e in epubs:
            epub = epubLoader(e)

            jobs = []

            # this is what's breaking everything right here. I'm not sure how to fix it.
            for output_epub in epub.get_html_from_epub():
                worker = Worker(output_file[count], output_epub[1], output_epub[0])
                jobs.append(worker)
                worker.start()

            for j in jobs:
                j.join()

            count += 1
        print "done!"

if __name__ == '__main__':
    test = implement('some local directory', 'some local directory')
    test.prosses_epubs()

any help on this would be greatly appreciated. also let me know if something I'm doing in my code can be done better... I'm always trying to learn how to do things the best way.

A: *

*Don't use classes when functions suffice. In this case, your classes
each have essentially one meaty method, and the __init__ method is
simply holding arguments used in the meaty method. You can make your
code sleeker by just making the meaty method a function and passing
the arguments directly to it.

*Separate the idea of "jobs" (i.e. tasks) from the idea of "workers"
(i.e. processes). Your machine has a limited number of processors,
but the number of jobs could be far greater. You don't want to open a
new process for each job since that might swamp your CPUs --
essentially fork-bombing yourself.

*Use the with statement to guarantee that your file handles get
closed. I see output.close() and word_out.close() getting called
in three different places each. You can eliminate all those lines by
using the with-statement, which will automatically close those file
handles once Python leaves the with-suite.

*I think a multiprocessing Pool would work well with your code. The jobs can be sent to the workers in the pool
using pool.apply_async. Each call queues a job which will wait
until a worker in the pool is available to handle it. pool.join()
causes the main process to wait until all the jobs are done.

*Use os.path.join instead of joining directories with '\\'. This
will make your code compatible with non-Windows machines.

*Use enumerate instead of manually implementing/incrementing
counters. It's less typing and will make your code a bit more readable.

The following code will not run since epubLoader, HTML, and word_list are not defined, but it may give you a clearer idea of what I am suggesting above:
import multiprocessing as mp

def worker(output_path, source, filename):
    t = HTML(source)
    output_path = output_path+filename
    output = open(output_path+'.html', 'w')
    word_out = open(output_path+'.txt','w')
    with output, word_out:
        try:
            output.write(t.tokenized)

            for w in word_list:
                if w:
                    word_out.write(w+'\n')

            word_list = []

        except IndexError:
            output.write(s[1])

        except UnboundLocalError:
            output.write(s[1])

def ensure_dir(directory):
    if not os.path.exists(directory):
        os.makedirs(directory)
    return directory

def process_epubs(input_path, output_path):
    pool = mp.Pool()

    for root, dirs, files in os.walk(input_path):
        epubs = [os.path.join(root, file) for file in files
                 if file.endswith('.epub')]
        output_file = [
            ensure_dir(
                os.path.join(
                    output_path,
                    os.path.splitext(os.path.basename(e))[0] + '_output')
                for e in epubs)]

    for count, e in enumerate(epubs):
        epub = epubLoader(e)
        for filename, source in epub.get_html_from_epub():
            pool.apply_async(
                worker,
                args=(output_file[count], source, filename))
    pool.close()
    pool.join()

    print "done!"

if __name__ == '__main__':
    process_epubs('some local directory', 'some local directory')


text:
Q: Can't add a new view in a storyboard without getting an not key value compliant message I'm getting the "not key-value coding compliant message".
I've had this several times in the past and know what it means and have always been able to resolve it, but I don't know why I'm getting it in this instance. All I've done is:
1) drag n drop a UILabel onto the main view:

2) Drag from the UILabel to view controller and get IB to insert and connect an outlet:

But when I run I get "this class is not key value coding-compliant for the key currentStatus.'"
Here's the connections:

Why is it not working, what is missing?

A: What you have shown is ok, check if you removed some outlet properties from your code file (.h) and forgot to remove their links from IB.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to trigger only my requests using Xdebug on remote server I'm trying to debug code that is on remote server.
I'm using

*

*Ubuntu 16 server, LEMP, PHP 7.0 as remote server

*OSX, PhpStorm, Chrome Xdebug helper as local environment

So, when

*

*Xdebug connection is established by
ssh -R 9000:localhost:9000 {username}@{serverhost}

*Xdebug helper in debug mode

*PhpStorm start listening is enabled

Xdebug triggers to each requests not only from my browser or PhpStorm, but from all other users from the internet.
Is it normal?
Is it possible to watch only requests initiated from my PhpStorm or from my Chrome requests? If yes, so how to setup?

A:
Xdebug triggers to each requests not only from my browser or PhpStorm, but from all other users from the internet.
Is it normal?

That depends on your Xdebug configuration. Right now it looks like it's configured to automatically attempt to debug every single request (not a good idea in many situations).

Is it possible to watch only requests initiated from my PhpStorm or from my Chrome requests? If yes, so how to setup?

Yes, make sure that xdebug.remote_autostart is turned off (set to 0/no).
Then just follow the official guide: https://www.jetbrains.com/help/phpstorm/debugging-with-phpstorm-ultimate-guide.html
Xdebug will see your Xdebug cookie set by Chrome Xdebug Helper (or GET/POST parameter if you pass it manually in URL/request) and will try to debug only those requests.
P.S. There is another scenarios where the aforementioned option will not help.. but so far it does not look like you are having that case (would need to see much more details for that).


text:
Q: Launch4J creates exe file leading to false positives with VirusTotal? I have an executable jar exported with ecplise (for example my.jar) that I transform to an Windows exe with using lauch4j (for example my.exe).
The my.exe is works correct, but if I load it on virus total, it founds this:

*

*Jiangmin - TrojanSpy.Java.c

*McAfee-GW-Edition - BehavesLike.Win32.Suspicious-JAR.wc

I have try to use sign4j to sign my.exe created by launch4j.
I have try this command:
sign4j.exe --verbose signtool.exe sign /fd SHA256 /f mycertificates.pfx /p mypassword /t http://timestamp.verisign.com/scripts/timstamp.dll my_signed.exe

The tools tell me "Successfully signed" and my_signed.exe result have a different size from my.exe
But if scan my_signed.exe to virus total I obtain same virus:

*

*Jiangmin - TrojanSpy.Java.c

*McAfee-GW-Edition - BehavesLike.Win32.Suspicious-JAR.wc

Is there a way to use sign4j differently, to avoid such problems? Or is there other way to prevent antivirus false positives?

A: It seems that this is a common problem, see this entry from their bugtracker:

I sometimes receive reports that some protection software complains about my L4J wrapped JAR containing a virus or trojan. At the moment, I receive the following reports:
McAfee-GW-Edition: BehavesLike Win32 Suspicious-JARE.wc
Microsoft: Trojan:Win32/Vigorf.A

The solution suggested there is to use the comodo tool for signing.


text:
Q: Script to upload to Internet Archive (archive.org) Is there a script somewhere that will allow me to upload files to an archive.org project? I'd like to be able to simply run a script on a folder and have it upload and then spit out a list of URLs, for free, permanent, file hosting.

A: Actually, I should have spent about 30 more seconds on Google ...
http://www.archive.org/help/abouts3.txt says I can use the s3cmd tool:
sudo apt-get install s3cmd
And then edit the configuration file, so ~/.s3cfg looks like:
[default]
host_base = s3.us.archive.org
host_bucket = %(bucket)s.s3.us.archive.org
access_key = key
secret_key = key
use_https = False
verbosity = WARNING

Then use the following script to upload everything to archive.org:
#!/bin/sh
BASE_URL=http://archive.org/details/
BASE_HEADER=something-$(date -u +%s) #something that should be unique
echo Converts to PDF and uploads the contents of a directory given as the command-line argument.
echo Now converting PDF to JPG
for file in `ls $1/*.pdf`
do
   convert $file `echo $file | sed 's/\.pdf$/\.jpg/'`
done
echo Listing JPGs: #make sure the conversion worked
ls $1/*.jpg
echo Making the bucket...
s3cmd mb s3://$BASE_HEADER
echo Sleeping...#sometimes it takes a moment to be processed on their end
sleep 20
echo Uploading files...
for file in `ls $1`
do
        s3cmd put $1/$file s3://$BASE_HEADER/$file
done
echo $BASE_URL$BASE_HEADER

It's run like upload.sh ~/stuff/


text:
Q: CKEDITOR has incorrect basepath when using NPM & Laravel Mix When I attempt to include CKEDITOR into my new Laravel 5.5 project using NPM, I get the following error in Chrome Console (using laravel Valet for the local.dev):
app.js:16991 GET https://local.dev/chart/config.js?t=H7HG
app.js:16991 GET https://local.dev/chart/skins/moono-lisa/editor.css?t=H7HG
app.js:16991 GET https://local.dev/chart/lang/en.js?t=H7HG

My Laravel Mix setup looks like this:
mix.js('resources/assets/js/app.js', 'public/js')
  .babel(['resources/assets/js/libraries/*.js'], 'public/js/vendor.js')
  .version();

My CKEDITOR installation is located in:
/vendor/ckeditor/ckeditor

I am able to access the CKEDITOR instance when the site has loaded. However, as displayed above, when I navigate to https://local.dev/chart, CKEDITOR now looks for the config, skin, and lang files with /chart appended to it's basepath.
I did some research, and found some related issues and was able to change the base_path using asset() successfully. The related stackOverflow questions can be found here and here.
What I would like to do is pull CKEDITOR in through NPM, use Laravel Mix to combine, version, and minify my scripts (one for vendor libraries, one for my app-specific JS), and then output those two.js files to these directories in the laravel app:
 /public/js/vendor.js
 /public/js/app.js

Laravel mix produces these two files, builds successfully, and all other libraries play nicely. However, CKEDITOR loses it's base path and throws errors looking for skins / langs / config.js -- any idea how I can adjust CKEDITOR's basePath to point to the vendor files so that it'll stop squaking these errors and work correctly?
Thanks you in advance for any assistance you can provide!

A: For those of you having the same issue as me, I found a work around that didn't involve modifying CKEDITOR at all:
Used Webpack to copy the needed CKEDITOR files:
.copy('node_modules/ckeditor/config.js', 'public/js/ckeditor/config.js')
.copy('node_modules/ckeditor/styles.js', 'public/js/ckeditor/styles.js')
.copy('node_modules/ckeditor/contents.css', 'public/js/ckeditor/contents.css')
.copyDirectory('node_modules/ckeditor/skins', 'public/js/ckeditor/skins')
.copyDirectory('node_modules/ckeditor/lang', 'public/js/ckeditor/lang')
.copyDirectory('node_modules/ckeditor/plugins', 'public/js/ckeditor/plugins')

Then, in the body of your page, add:
<script> var CKEDITOR_BASEPATH = '/js/ckeditor/'; </script>

This will allow CKEDITOR to find the desired files. This felt a little ugly to me, so maybe there is a better way to do this - if so, please let me know and downvote this answer.

A: Since I can't add a comment, just wanted to provide an alternative way to
<script> var CKEDITOR_BASEPATH = '/js/ckeditor/'; </script>

In your app.js you could do the following instead of the  above:
 window.CKEDITOR_BASEPATH = '/js/ckeditor/';

A: That error had for me but i changed the code and problem is solving.
After than write codes the webpack.mix.js,
Just:
In your app.js or bootstrap.js after than require or import,
write this code:
CKEDITOR.basePath = '/admin/ckeditor/'

I hope problem is solved.
Thank.


text:
Q: How to recieve & store an image file from another server, being passed programatically with paramaters? I am using the API of an image editing website (pixlr.com) for use by members of my site. I open Pixlr.com in an iframe where they can create an image and upon SAVE, pixlr sends the image file by use of parameters.
I want to save these image files (unique for each member) in a folder on my server (or on Amazon's S3 image server), using PHP. How do I receive their parameters ("image") of the image file and store them on my/Amazon's image server?

A: If the image is sent to your PHP script via POST, then you should be able to do something like this:
$handle = fopen($imageName, "wb");
fwrite($handle, $_POST["image"]);
fclose($handle);

Where $imageName is the absolute path and filename of the image where you want to save it (make sure you Apache user has write permissions to that directory). Depending on the picture's encoding you may need to figure out which extension to save it with (ie .jpg, .bmp, .png, etc).

EDIT:
Looks like they are sending the image via $_FILES. Try this:
move_uploaded_file($_FILES["image"]["tmp_name"], "/home/path/domain.com/upload/". time() .".png");


text:
Q: SVNKit , show list of files to commit I almost use SVNKit API.
I make my client and I can not find a way to show files that can commit.
In some of the clients such as Tortoise, we have change dialog with a list of files that have been modified. And we can choose files for "commit".
How can I extract the names/path of these files?
Does API allow you to do?
Thank you in advance

A: You may have a look at:
SVNCommitClient.doCommit(File[], boolean, String, SVNProperties, String[], boolean, boolean, SVNDepth).
It first collects committable files and directories with doCollectCommitItems(), returns the result in an SVNCommitPacket and then commits this packet by doCommit(). You may copy that code and customize SVNCommitPacket, especially use SVNCommitPacket.setCommitItemSkipped() to skip files.


text:
Q: Data Scraping from Website - receiving error on different player pages I'm trying to data scrape game logs from basketball reference.com. It worked perfectly on two players I choose (demar derozan and lamarcus aldridge). But then I started going through other players and it just wouldn't scrape the data for many of the other players (Kevin Durant).
I have NO Idea why it wouldn't work. For example, I tried Stephen Curry and it worked fine, but players like Draymond Green and Kevin Durant, the code would just not scrape the data at all. For some reason after the column Date, everything stopped working.
Sub Data()
    Dim ieObj As InternetExplorer
    Dim htmlEle As IHTMLElement
    Dim i As Integer

    i = 1

    Set ieObj = New InternetExplorer
    ieObj.Visible = True
    ieObj.navigate "https://www.basketball-reference.com/players/d/duranke01/gamelog/2019"

    Application.ScreenUpdating = False
    Application.DisplayStatusBar = True
    Application.Wait Now + TimeValue("00:00:05")

    For Each htmlEle In ieObj.document.getElementsByClassName("stats_table")(0).getElementsByTagName("tr")

        With ActiveSheet
            .Range("A" & i).Value = htmlEle.Children(0).textContent
            .Range("B" & i).Value = htmlEle.Children(1).textContent
            .Range("C" & i).Value = htmlEle.Children(2).textContent
            .Range("D" & i).Value = htmlEle.Children(3).textContent

        End With

    i = i + 1
    On Error Resume Next

    Next htmlEle

End Sub

The error always happens on this line:
.Range("D" & i).Value = htmlEle.Children(3).textContent
I tried skipping columns to but it still wouldn't work.

A: I found no problem with using id for table, as seen in .responseText and using xmlhttp over browser.
I only tested with 3 urls - in sheet 1 A1:A3

*

*https://www.basketball-reference.com/players/d/duranke01/gamelog/2019

*https://www.basketball-reference.com/players/c/curryst01/gamelog/2019

*https://www.basketball-reference.com/players/g/greendr01/gamelog/2019
With this site sometimes you can encounter tables inside comments so I stripped out the comment tags before processing. This was not necessary for the links I tried.
I use clipboard to copy paste but you could just use
Set hTable = html.getElementById("pgl_basic")

Then loop the tr and td as you wish using getElementsByTagName.

References (VBE>Tools>References):

*

*Microsoft HTML Object Library

Option Explicit
Public Sub GetPlayerInfo()
    Dim urls(), i As Long, html As HTMLDocument, hTable As Object
    Dim ws As Worksheet, wsCurrent As Object, clipboard As Object
    Dim lastRow As Long, playerIdentifier As String, arr() As String

    Set clipboard = GetObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    lastRow = ws.Cells(ws.rows.Count, "A").End(xlUp).Row
    urls = Application.Transpose(ws.Range("A1:A" & lastRow).Value)
    Set html = New HTMLDocument

    With CreateObject("MSXML2.XMLHTTP")
        For i = LBound(urls) To UBound(urls)
            .Open "GET", urls(i), False
            .send
            html.body.innerHTML = Replace$(Replace$(.responseText, "-->", vbNullString), "<!--", vbNullString) 'remove comments
            arr = Split(urls(i), "/")
            playerIdentifier = arr(5)
            If SheetExists(playerIdentifier) Then
                With ThisWorkbook.Worksheets(playerIdentifier).Cells
                    .ClearContents
                    .ClearFormats
                    Set wsCurrent = ThisWorkbook.Worksheets(playerIdentifier)
                End With
            Else
                 Set wsCurrent = ThisWorkbook.Worksheets.Add
                 wsCurrent.name = playerIdentifier
            End If
            Set hTable = html.querySelector("#pgl_basic")
            clipboard.SetText hTable.outerHTML
            clipboard.PutInClipboard
            wsCurrent.Range("A1").PasteSpecial
            Set wsCurrent = Nothing: Set hTable = Nothing: Erase arr: playerIdentifier = vbNullString
            Application.CutCopyMode = False
        Next
    End With
End Sub

Public Function SheetExists(ByVal sheetName As String) As Boolean '<==  function by @Rory
    SheetExists = Evaluate("ISREF('" & sheetName & "'!A1)")
End Function

IE
Note proper page load wait used.
Option Explicit

Public Sub GetPlayerInfo()
    Dim ieObj As InternetExplorer, htmlEle As IHTMLElement
    Dim urls(), i As Long, j As Long, hTable As Object
    Dim ws As Worksheet, wsCurrent As Object
    Dim lastRow As Long, playerIdentifier As String, arr() As String
    Application.ScreenUpdating = False
    On Error GoTo errHand
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
    urls = Application.Transpose(ws.Range("A1:A" & lastRow).Value)

    Set ieObj = New InternetExplorer
    With ieObj
        .Visible = True
        For j = LBound(urls) To UBound(urls)
            .navigate urls(j)
            While .Busy Or .readyState <> 4: DoEvents: Wend
            arr = Split(urls(j), "/")
            playerIdentifier = arr(5)
            If SheetExists(playerIdentifier) Then
                With ThisWorkbook.Worksheets(playerIdentifier).Cells
                    .ClearContents
                    .ClearFormats
                    Set wsCurrent = ThisWorkbook.Worksheets(playerIdentifier)
                End With
            Else
                Set wsCurrent = ThisWorkbook.Worksheets.Add
                wsCurrent.Name = playerIdentifier
            End If
            i = 1
            Set hTable = .document.getElementById("pgl_basic")
            If Not hTable Is Nothing Then
                For Each htmlEle In hTable.getElementsByTagName("tr")
                    With wsCurrent
                        .Range("A" & i).Value = htmlEle.Children(0).textContent
                        .Range("B" & i).Value = htmlEle.Children(1).textContent
                        .Range("C" & i).Value = htmlEle.Children(2).textContent
                        .Range("D" & i).Value = htmlEle.Children(3).textContent
                    End With
                    i = i + 1
                Next htmlEle
            End If
            Set wsCurrent = Nothing: Set hTable = Nothing: Erase arr: playerIdentifier = vbNullString
        Next
    End With
errHand:
    Application.ScreenUpdating = True
    If Err.Number <> 0 Then Debug.Print Err.Number, Err.Description
    ie.Quit
End Sub


text:
Q: Parsing - Top down / First & Follow I have this Grammer where i am trying to find First and Follow sets. I am not sure if i am doing it right since my follow sets never include the first of R
Grammar
E --> TP
P --> +TP | ε
T --> FQ
Q --> FQ | ε
F --> (E)R | iR
R --> *R | ε

First Sets -
First(E) = First(T) = First(F) = { (, i }
First(P) = { +, ε }
First(Q) = First(F) = { (, i }   // not needed i dont think
First(R) = { *, ε }

Follow Sets -
Follow(E) = { $, ) }
Follow(P) = Follow(E) = { $, ) }
Follow(T) = First(P) -{ε} + Follow(E) = {+, $, ) }
Follow(Q) = Follow(T) = { +, $, ) }
Follow(F) = First(Q)-{ε} + Follow(T) + First(F) = { +, (, ) , $, i }
Follow(R) = Follow(F) = { +, (, ) , $, i }

I never get to first(R) in the follow set so im not sure what to think. However, i dont think its possible either. Am i correct with my first and follow sets or is my understanding somewhat wrong?

A: Since R doesn't start any production, First(R) wouldn't come into play (except if/when you start from R).  So you SHOULDN'T reach it from anything else.


text:
Q: Multi-Channel Back Projection Assertion (j < nimages) Attempting to do histogram back-projection on a three-channel image results in the following error:

OpenCV Error: Assertion failed (j < nimages) in histPrepareImages, file ../modules/imgproc/src/histogram.cpp, line 148

The code which fails:
cv::Mat _refImage; //contains reference image of type CV_8UC3
cv::Mat output;    //contains image data of type CV_8UC3
int histSize[] = {16, 16, 16};
int channels[] = {0, 1, 2};
const float hRange[] = {0.f, 256.f};
const float* ranges[] = {hRange, hRange, hRange};
int nChannels = 3;

cv::Mat hist;
cv::calcHist(&_refImage, 1, channels, cv::noArray(), hist, nChannels, histSize, ranges);

cv::calcBackProject(&output, 1, channels, hist, output, ranges);    //This line causes assertion failure

Running nearly identical code on a single-channeled image works. According to the documentation, multi-channel images are also supported. Why won't this code work?

A: The short answer is that cv::calcBackProject() does not support in-place operation, although this is not mentioned in the documentation.
Explanation
Digging into the OpenCV source yields the following snippet:
void calcBackProject( const Mat* images, int nimages, const int* channels,
                         InputArray _hist, OutputArray _backProject,
                         const float** ranges, double scale, bool uniform )
{
    //Some code...

    _backProject.create( images[0].size(), images[0].depth() );
    Mat backProject = _backProject.getMat();
    assert(backProject.type() == CV_8UC1);
    histPrepareImages( images, nimages, channels, backProject, dims, hist.size, ranges,
                      uniform, ptrs, deltas, imsize, uniranges );
    //More code...
}

The line which causes the problem is:
_backProject.create( images[0].size(), images[0].depth() );

which, if the source and destination are the same, reallocates the input image data. images[0].depth() evaluates to CV_8U, which is numerically equivalent to the type specifier CV_8UC1. Thus, the data is created as a single-channel image.
This is a problem because histPrepareImages still expects the input image to have 3 channels, and the assertion is thrown.
Solution
Fortunately, the workaround is simple. The output parameter must be different from the input, like so:
cv::Mat result;
cv::calcBackProject(&output, 1, channels, hist, result, ranges);


text:
Q: How to see previously committed version of file in Git I have created a folder name A and have ran git init ( which initialized ).
Under it I created 2 files a.txt and b.txt and than ran git add . and then git commit.
Now those files were committed.
Now if I do modification to a.txt and save it, but want to checkout the original file ( saved during commit in local repository ) how can I do it ?
PS: I am doing it in CentOS server where GIT is installed, so it itself is a local repository and I want to fetch data from it.

A: If you want to get the version of the file that was just commited:
git checkout -- <path-to-file>

Be aware that if  is a folder it will be applied recursively
If you just want to see the old file version:
git show COMMIT:<path-to-file>


text:
Q: Javascript tab navigation issue I was wondering if anybody could help me with a fix for an error in the following script.
Everything works fine until I add a second line with the same links, then the behavior is not as expected.
This is a simple script to hide and show tabs.
At some point, when clicking on both top and bottom row of links, 2 tabs are displayed at the same time.
There's a live example on: http://jsfiddle.net/8cwqH/1/

Tab1

Tab2

Tab3

 tab1
tab1

 tab1
tab1

 tab2
tab2

 tab2
tab2

 tab3
tab3

 tab3
tab3

 Tab1
 Tab2
 Tab3

tab 2 link

This is the script:
// Wait until the DOM has loaded before querying the document
$(document).ready(function(){
    $('ul.tabs, div.othertabs').each(function(){
        // For each set of tabs, we want to keep track of
        // which tab is active and it's associated content
        var $active, $content, $links = $(this).find('a');

        // If the location.hash matches one of the links, use that as the active tab.
        // If no match is found, use the first link as the initial active tab.
        $active = $($links.filter('[href="'+location.hash+'"]')[0] || $links[0]);
        $active.addClass('active');
        $content = $($active.attr('href'));

        // Hide the remaining content
        $links.not($active).each(function () {
            $($(this).attr('href')).hide();
        });

        // Bind the click event handler
        $(this).on('click', 'a', function(e){
            // Make the old tab inactive.
            $active.removeClass('active');
            $content.hide();

            // Update the variables with the new link and content
            $active = $(this);
            $content = $($(this).attr('href'));

            // Make the tab active.
            $active.addClass('active');
            $content.fadeIn();

            // Prevent the anchor's default click action
            e.preventDefault();
        });
    });
});

A: You're redeclaring the $active and $content variables in each iteration of the loop. This means that clicking Tab3 in one set of tabs, then Tab2 in the other will cause both tabs to appear at the same time.
You need to refactor your code to move those two variable outside of the loop, and will probably want to set the active variable to a string (e.g. #tab1) so that it doesn't matter which tab set you click on (at the moment, your $active variable points to a specific tab in one of the tab sets).
Here is a working example with the modifications I've mentioned; http://jsfiddle.net/8cwqH/2/


text:
Q: When to assert a 'Same Individual As' property to an individual in Protege? I am new to Ontologies, so I apologize if seems like a very naive question.
For example, I have a class named 'PersonalInformation' and a subClass within it called 'Name'. PersonalInformation as an individual named 'Name' and Name (class) has individuals: 'FirstName', 'MiddleName', and 'LastName'. Do I set the 'Same Indidividual As' property as for Name (individual) as FirstName, MiddleName, and LastName, since they are all in essence names?
How do I set this up, and when is it appropriate to use the 'Same Individual As' property?

A: It is appropriate to assign the 'Same Individual As' axiom, when two individuals are named differently, but refer to one and the same instance. You could for example have one individual named after your real name and one named after your nickname. Both individuals describe the same person (and they would probably be an instance of a class called 'Person').
Now concerning your question, I wouldn't even use individuals, but model everything as classes, because they all describe a set of potential individuals. For example FirstName is a class that could contain individuals like 'Peter', 'George', 'Anna', etc.


text:
Q: How to get a kendo grid on a kendo template Firstly I have made a Kendo grid. Each row of the grid has a button on it, which on-click opens a Kendo template (pop-up). still here it's fine.
Is it possible to add another grid in the popup and add editable child items(like grid hierarchy) to each grid row?
This is my main grid:

var grid= $("#Grid").kendoGrid({
        columns: [
          { field: "Name", title: "Name" },
          { field: "Description", title:"Description"},
          { field: "Remarks", title:"Remarks" },
          { command: { name: "details", text: "....", click: showDetails }, title: "Button", attributes: {
              style: "text-align: center;"
          }
          },
          {field:"Status",title:"Status"},
          ],

{......... data source and irrelevant code }

});

Code for window pop-up and button on-click function:

wnd = $("#details")
                        .kendoWindow({
                            title: "Details",
                            modal: true,
                            visible: false,
                            resizable: false,
                            width: 400,
                            height:600
                        }).data("kendoWindow");

    detailsTemplate = kendo.template($("#template").html());
    });

    function showDetails(e) {
        e.preventDefault();

        var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
        wnd.content(detailsTemplate(dataItem));
        wnd.center().open();
    }

Code for template look like:

The div tag including window grid is not displaying the grid but displaying remaining other things.
can you suggest what mistake I have done in the code
Secondly, Can you help me with the code to get a child row for each grid row.
Thank you
EDIT This is the dojo link of whole code: http://dojo.telerik.com/igOroG

A: You are trying to initialise an element before it has been rendered in the x-kendo-template, so just move your grid instantiation to after the open of the kendoWindow.
function showDetails(e) {
    e.preventDefault();

    var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
    wnd.content(detailsTemplate(dataItem));
    wnd.center().open();
    // grid definition here
    var grid = $("#windowgrid").kendoGrid({
        .....
    }).data("kendoGrid");
}

"Code to get a child row for each grid row"
You can use detailInit with detailTemplate on the grids in order to achieve this. With your detailInit function, you will be able to access the data at that specific row using [e.data].
// gets elements on detailRow
var detailRow = e.detailRow;
// get the data at the expanded row
var dataList = [e.data];

I have updated your Dojo example to display the changes required to firstly initialise the grid and extended the code to provide detail rows for the first grid.
EDIT
In order to apply a filtered dataSource to the pop-up grid based on the value selected, you can use the filter function on the data before applying to the Kendo DataSource:
var filteredDataArr = dataArr.filter(function(el) {
    return el.NId == e.NId
});

el being the element in the data array and e.NId being the selected NId in the parent grid.
Updated Dojo example to demonstrate the above in action.


text:
Q: How to get the value of div tag How can I get MY_TROUBLE_TWO from it and click?
I have tried below mentioned code, but it didn't get work for me.
Tried code 1)
WebElement element = driver.findElement(By.xpath(".//div[7]/div/div/div/div/div/div/div[2]/div[@class='dx-item-content dx-list-item-content']"));
element.click();

Tried code 2)
wait.until(ExpectedConditions.presenceOfElementLocated(By.xpath(".//div[7]/div/div/div/div/div/div/div[2]/div[@class='dx-item-content dx-list-item-content']"))).click();

Tried code 3)
Select select = new Select(driver.findElement(By.xpath(".//xpath_to_item")));
select.selectByVisibleText("MY_TROUBLE_TWO");

My html code as below:

MY_TROUBLE_ONE

MY_TROUBLE_TWO

A: Try this below code to get the value of MY_TROUBLE_TWO
Note: Instead of using an absolute xpath, Use relative xpath.
Explanation: Put some wait before going to the element, For wait I have used explicit wait method. After wait find element using text method with div tag to get the element.
WebDriverWait wait = new WebDriverWait(driver, 15);
wait.until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("//div[contains(text(), 'MY_TROUBLE_TWO')]")))).click();


text:
Q: Sublime Text's Terminus is not displaying Oh My Zsh icons I get a generic ? where the icons should be.
A similar issue but for Visual Studio Code is documented here:
https://dev.to/avantar/how-to-fix-zsh-icons-in-visual-studio-code-terminal-38bb
Needless to say, I haven't been able to find an equivalent fix.

A: I fixed it by setting "font_face": "MesloLGS NF", the preferred font of the powerlevel10k theme.

A: Thank you @ctrebbau. That worked.
I added this to Terminus Sublime Settings, and then restarted Sublime. That fixed it.
{
    "view_settings": {
        "font_face": "MesloLGS NF"
    }
}


text:
Q: Is an implied proper noun *really* a proper noun? With reference to the following sentence:

I am returning to University in a few weeks.

Given that the person stating this is referring to a specific university through implication (for example, because they are returning for their second year of study at the university they studied at during their first year), is this still considered  a proper noun, or should it be treated as a common noun?
In other words, should the spelling of University be capitalised in this context?

A: Many years ago I attended classes (sporadically) at a tiny college in Maryland whose staff and students consistently referred to it in internal correspondence as "The College." The college's quarterly magazine was even named The College. Then I attended classes in graduate school (even more sporadically) at a gigantic state university that so dominated its in-state peers (in the minds of its staff and students) that many people would buy stick-on decals for their car that read "The University of Texas" and then snip off the "of Texas," confident that everyone would know what school "The University" referred to.
In both instances, however, the definite article was always included with "College" or "University." Without "The" (or at the very least "the"), the designation would have become too amorphous to sustain its sense, I think. In any case, I would spell university with a lowercase u in the example sentence you give, since I don't see any improvement in meaning to be got from the capital U.


text:
Q: Service crash, even with startForeground when the activity gets shut down and the alarmManager sets off I have mainActivity that starts service with START_STICKY onStartCommand, in that service I also use startForeground and alarmManager repeater. When I close the main activity by swiping the app away, service is still running, and the notification icon from the startForeground remains, however, when the alarm from the alarmManager sets off inside service, the service get crashed and restart itself within 5000 ms. Why does the service crash soon as it gets to setting of an alarm?
MainActivity.java:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Messenger;
import android.util.Log;
public class MainActivity extends Activity {
    Messenger mService = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CheckIfServiceIsRunning();
    }
    private void CheckIfServiceIsRunning() {
        if (MyService.isRunning()) {
        } else {
            startService(new Intent(MainActivity.this, MyService.class));
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        //stopService(new Intent(MainActivity.this, MyService.class)); //disabled line so that killing UI-app doesn't kill service aswell
    }
}

MyService.java:
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.util.Log;
public class MyService extends Service {
    public AlarmManager alarmManager;
    public PendingIntent pendingIntent;
    private Timer timer = new Timer();
    private int counter = 0, incrementby = 1;
    private static boolean isRunning = false;
    final public static int NOTIFICATION_FOREGROUND = 34444;
    ArrayList<Messenger> mClients = new ArrayList<Messenger>();
    final Messenger mMessenger = new Messenger(new IncomingHandler());
    @Override
    public IBinder onBind(Intent intent) {
        return mMessenger.getBinder();
    }
    @SuppressLint("HandlerLeak")
    class IncomingHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
        }
    }
    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("MyService", "---- Service Started. ----");
        timer.scheduleAtFixedRate(new TimerTask(){ public void run() {onTimerTick();}}, 0, 1000L);
        isRunning = true;
        StartForegroundNotification();
        alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        Intent broadcast_intent = new Intent(this, MyAlarmReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(this, 0,  broadcast_intent, 0);
        Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 10*1000, pendingIntent);
    }
    @SuppressWarnings("deprecation")
    public void StartForegroundNotification(){
        String title = "Service Title";
        String message = "Service Message";
        Notification notify = new Notification(R.drawable.ic_launcher, null, 0);
        Intent notifIntent = new Intent(this, MainActivity.class);
        PendingIntent i = PendingIntent.getActivity(this, 0, notifIntent, 0);
        notify.setLatestEventInfo(this, title, message, i);
        notify.flags |= Notification.FLAG_NO_CLEAR;
        startForeground(NOTIFICATION_FOREGROUND, notify);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("MyService", "Received start id " + startId + ": " + intent);
        return START_STICKY;
    }
    public static boolean isRunning()
    {
        return isRunning;
    }
    private void onTimerTick() {
        Log.i("TimerTick", "Timer doing work." + counter);
        try {
            counter += incrementby;
        } catch (Throwable t) {
            Log.e("TimerTick", "Timer Tick Failed.", t);
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        alarmManager.cancel(pendingIntent);
        if (timer != null) {timer.cancel();}
        stopForeground(true);
        counter=0;
        Log.i("MyService", "---- Service Stopped. ----");
        isRunning = false;
    }
}

MyAlarmReceiver.java:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class MyAlarmReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.i("alarmer", "I got it");
    }
}

and in manifest I used:
<service android:name=".MyService" />
<receiver android:name=".MyAlarmReceiver" />

and the logcat (soon as it hit alarm time - after timer ticks 3 in this case - it crashed if the app is closed, however, after it restarts itself, it will not be crashed again, I guess because it's being started from different context, and not from MainActivity.this, it gets "null" intent in onStartCommand):
12-16 19:08:50.614: I/TimerTick(27069): Timer doing work.1
12-16 19:08:53.614: I/TimerTick(27069): Timer doing work.2
12-16 19:08:56.614: I/TimerTick(27069): Timer doing work.3
12-16 19:08:57.622: I/ActivityManager(395): Killing 27069:com.example.serviceexample/u0a10097: remove task
12-16 19:08:57.629: W/ActivityManager(395): Scheduling restart of crashed service com.example.serviceexample/.MyService in 5000ms
12-16 19:09:02.661: I/ActivityManager(395): Start proc com.example.serviceexample for service com.example.serviceexample/.MyService: pid=27100 uid=10097 gids={50097, 1028}
12-16 19:09:02.715: I/MyService(27100): ---- Service Started. ----
12-16 19:09:02.715: I/TimerTick(27100): Timer doing work.0
12-16 19:09:02.723: I/MyService(27100): Received start id 3: null


text:
Q: How to configurate Ehcache for peer-to-peer replication I read a few times that ehcache can be used in replication mode. So I can set up a cluster without a terracotta-server (like a peer-to-peer network). But I only find information about the replication in old ehcache docs (version 2.x). In the new documentation the point "Replicated Cache" is missing and the ehcache-config is incompatible with the new ehcache version. Is this feature in v3.x gone ? If not: how to config ehcache ?
Regards

A: This feature has not been ported in Ehcache 3.x indeed.
It suffers from a total lack of consistency since it can only offer last write wins on a per node basis which is rarely an acceptable guarantee.
If you need to share a single cache across multiple nodes, the Terracotta clustering is the recommended way.


text:
Q: How to change Android EditText keyboard color? In iOS TextField has a property called Appeareance can have a Dark value. It will change the KEYBOARD color, (not the textfield itsels) But in Android I do not find the appropriate one for EditText, to change keyboard color to dark, or black.

A: There is no single "the keyboard" in Android. Android supports replaceable input method editors (a.k.a., soft keyboards). These are published by apps, including both pre-installed apps and apps installed by users. Anyone can write one of these.
AFAIK, there is nothing in the input method editor protocol that allows the editor to know anything about the color scheme of the app that happened to cause that editor to appear. But, even if the protocol included this information, the developer of the input method editor could choose to ignore it.
And, even if the developer of the input method editor knew about the general theme (light vs. dark) and chose to implement something for it, you still might not like what the developer chooses. After all, there is no universal definition of what a "light" or "dark" theme should look like. The input method editor developer might choose a deep purple color for "dark", and you went with dark brown.

A: Simple answer: you can't.
In Android the keyboard is not (only) a native feature. You can chose wether showing it or not and which keyboard to show.
But since it's another application, you can't access it directly, the only tasks you can do are opening the app with intent.
here you can find the official doc about it

A: Not sure what you are trying to achieve but note the following

*

*The keyboard is a different application

*The text appearance properties can be easily modified from the xml file

look at the example code below
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:id="@+id/simple_list_item"
    android:gravity="center_vertical"
    android:padding="5dp"
    android:paddingLeft="10dp"
    android:paddingStart="10dp"
    android:textSize="15dp"
    android:typeface="serif"
    android:textStyle="bold"
    android:background="@color/white"
    android:allowUndo="false"
    android:text="Sample Still Testing"
    android:textColor="#003325" />


text:
Q: How can I use a Python defaultdict to divide one value by another? I have a defaultdict built with keys and values, but I need to be able to divide the first value by the second value if there are two values in the pair.
defaultdict(<type 'list'>, {3: [7567, 6525], 4: [0], 65542: [609, 5245], 13:
[73585, 84764], 14: [159, 19385], 65552: [1834], 22: [47333], 25: [0, 5320],
65562: [0], 98332: [0], 30: [0, 704249], 32: [5612], 33: [76050]}

So, for 3:, I would need to get 7567/6525, and put that into a new dictionary with the same key. But, for 32, I can't do any division, so I'd need to remove it from the set.
How would I go about doing this, knowing I don't always have 2 values to divide with?

A: Use a dictionary comprehension and the ternary operator.
Python 3
from operator import truediv

{key: (truediv(*val) if len(val) == 2 else val[0]) for key, val in dic.items()}

Python 2
from operator import truediv

{key: (truediv(*val) if len(val) == 2 else val[0]) for key, val in dic.iteritems()}

I'll continue with Python 3. If you want to remove those entries with less than 2 items
{key: div(*val) for key, val in dic.items() if len(val) == 2}

Update per your comment under the question
Wrapping the results back into lists and getting a list of the "outliers".
new_dic = {key: [div(*val)] for key, val in dic.items() if len(val) == 2}
outliers = [key for key, val in dic.items() if len(val) != 2]

A: I guess since everyone else is interpreting the question this way I'll post my version as an answer:
{k: reduce(operator.div, map(float, v)) for k, v in original.items()}

Alternatively:
{k: reduce(operator.truediv, v) for k, v in original.items()}

Where original is your dict and you import operator. If you're on Python 3 you'll need to from functools import reduce as well (global in Python 2).
Also, if you're using Python 3, you can drop map(float, v) in favor of just v. That's so you don't get burned by integer division (Floor division) on Python 2. You can use truediv instead of map to avoid this -- I was thinking, incorrectly, this was not portable between versions of Python. I stand corrected.
Note: This will not work if your dict values are not always iterable. You're using a defaultdict with a list default so you'll be fine.

A: You could do something like this:
for k in mydict.keys():
  if len(mydict[k]) != 2:
    mydict.pop(k)
  else:
    v1, v2 = mydict[k]
    mydict[k] = v1 / v2


text:
Q: image not showing inside webpage, but works outside Please take a look at this URL
http://www.viewpromocode.com/product/redmi-3s-prime-silver-32-gb-4/
It has a broken image in it, but if you open the image in another tab, it work !!
why ?
I am using the following image compression script.
It is even generating correct thumbnails, but the it is loading inside the webpage.
https://github.com/whizzzkid/phpimageresize

A: Your script http://www.viewpromocode.com/content/img/example.php returns html:

instead image content


text:
Q: Run WebTest in vNext build via PS-Remoting on Windows 10 server got "System.Data.Entity.Core.ProviderIncompatibleException" In TFS vNext build I deploy serveral webtests via PS-Remoting to one Windows 10 test agent and run all webtests. It does not not stable because sometimes I get an error with "System.Data.Entity.Core.ProviderIncompatibleException" (s.below)
Visual Studio 2015 has be installed on the server. The same tests under the sam condition run very well on Windows 7 test agent.
What is the reason and how could I fix this? Many thanks!
<Timestamp> [5] ERROR <MyService>.GlobalExceptionHandler:29 - Internal Server Error!
System.Data.Entity.Core.ProviderIncompatibleException: The provider did not return a ProviderManifest instance. ---> System.Runtime.InteropServices.COMException: Catastrophic failure (Exception from HRESULT: 0x8000FFFF (E_UNEXPECTED))
at System.Security.Policy.PEFileEvidenceFactory.GetLocationEvidence(SafePEFileHandle peFile, SecurityZone& zone, StringHandleOnStack retUrl)
at System.Security.Policy.PEFileEvidenceFactory.GenerateLocationEvidence()
at System.Security.Policy.PEFileEvidenceFactory.GenerateEvidence(Type evidenceType)
at System.Security.Policy.AssemblyEvidenceFactory.GenerateEvidence(Type evidenceType)
at System.Security.Policy.Evidence.GenerateHostEvidence(Type type, Boolean hostCanGenerate)
at System.Security.Policy.Evidence.GetHostEvidenceNoLock(Type type)
at System.Security.Policy.Evidence.GetHostEvidence(Type type, Boolean markDelayEvaluatedEvidenceUsed)
at System.Security.Policy.AppDomainEvidenceFactory.GenerateEvidence(Type evidenceType)
at System.Security.Policy.Evidence.GenerateHostEvidence(Type type, Boolean hostCanGenerate)
at System.Security.Policy.Evidence.GetHostEvidenceNoLock(Type type)
at System.Security.Policy.Evidence.RawEvidenceEnumerator.MoveNext()
at System.Security.Policy.Evidence.EvidenceEnumerator.MoveNext()
at System.Configuration.ClientConfigPaths.GetEvidenceInfo(AppDomain appDomain, String exePath, String& typeName)
at System.Configuration.ClientConfigPaths.GetTypeAndHashSuffix(AppDomain appDomain, String exePath)
at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Xml.XmlConfiguration.XmlReaderSection.get_ProhibitDefaultUrlResolver()
at System.Xml.Schema.Parser..ctor(SchemaType schemaType, XmlNameTable nameTable, SchemaNames schemaNames, ValidationEventHandler eventHandler)
at System.Xml.Schema.XmlSchema.Read(XmlReader reader, ValidationEventHandler validationEventHandler)
at System.Data.Entity.Core.SchemaObjectModel.Schema.SomSchemaSetHelper.AddXmlSchemaToSet(XmlSchemaSet schemaSet, XmlSchemaResource schemaResource, HashSet`1 schemasAlreadyAdded)
at System.Data.Entity.Core.SchemaObjectModel.Schema.SomSchemaSetHelper.ComputeSchemaSet(SchemaDataModelOption dataModel)
at System.Data.Entity.Core.Common.Utils.Memoizer`2.<>c__DisplayClass2.<Evaluate>b__0()
at System.Data.Entity.Core.Common.Utils.Memoizer`2.Result.GetValue()
at System.Data.Entity.Core.Common.Utils.Memoizer`2.Evaluate(TArg arg)
at System.Data.Entity.Core.SchemaObjectModel.Schema.CreateXmlReaderSettings()
at System.Data.Entity.Core.SchemaObjectModel.Schema.Parse(XmlReader sourceReader, String sourceLocation)
at System.Data.Entity.Core.SchemaObjectModel.SchemaManager.ParseAndValidate(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModel, AttributeValueNotification providerNotification, AttributeValueNotification providerManifestTokenNotification, ProviderManifestNeeded providerManifestNeeded, IList`1& schemaCollection)
at System.Data.Entity.Core.SchemaObjectModel.SchemaManager.ParseAndValidate(IEnumerable`1 xmlReaders, IEnumerable`1 sourceFilePaths, SchemaDataModelOption dataModel, DbProviderManifest providerManifest, IList`1& schemaCollection)
at System.Data.Entity.Core.SchemaObjectModel.SchemaManager.LoadProviderManifest(XmlReader xmlReader, String location, Boolean checkForSystemNamespace, Schema& schema)
at System.Data.Entity.Core.Common.DbXmlEnabledProviderManifest.Load(XmlReader reader)
at System.Data.Entity.Core.Common.DbXmlEnabledProviderManifest..ctor(XmlReader reader)
at System.Data.SQLite.EF6.SQLiteProviderManifest..ctor(String manifestToken)
at System.Data.SQLite.EF6.SQLiteProviderServices.GetDbProviderManifest(String versionHint)
at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifest(String manifestToken)
--- End of inner exception stack trace ---
at System.Data.Entity.Core.Common.DbProviderServices.GetProviderManifest(String manifestToken)
at System.Data.Entity.Utilities.DbConnectionExtensions.GetProviderInfo(DbConnection connection, DbProviderManifest& providerManifest)
at System.Data.Entity.DbModelBuilder.Build(DbConnection providerConnection)
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext internalContext)
at System.Data.Entity.Internal.RetryLazy`2.GetValue(TInput input)
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.Create()
at System.Data.Entity.DbSet`1.Create()
at <MyService>.Persistence.EF.DeploymentRepository.CreateDeployment(String name, DeploymentStatus status)
at <MyService>.Persistence.EF.DeploymentRepository.CreateDeployment(String name)
at <MyService>.Controllers.DeploymentController.<CreateDeploymentAsync>d__7.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Threading.Tasks.TaskHelpersExtensions.<CastToObject>d__3`1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ApiControllerActionInvoker.<InvokeActionAsyncCore>d__0.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Controllers.ActionFilterResult.<ExecuteAsync>d__2.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Web.Http.HttpServer.<SendAsync>d__0.MoveNext()

A: Are you installed the same version of VS on Windows 7 test agent? If not, you can try to remove VS from WIN10 and install that version same as WIN7, then try it again.
If the issue still exist, please check the Entity Framework version. Seems related to Entity Framework, see this article for more info, you can try using EFPowerTools to update Nuget EF accordingly.
Please reference below threads:

*

*EntityFramework error: The provider did not return a ProviderManifest instance

*How to use Entity Framework Power Tools in Visual Studio 2015?


text:
Q: How (or can) I backup a Google Artifact Registry instance? I'm looking at moving to using Artifact Registry as a replacement for Artifactory and I wondering how, or if, I would backup the stored files to guard against a server failure?
Maybe that's not a thing I need to worry about with GCP?

A: Artifact Registry is a managed Service. you don't have access to the underlying Infrastructure powering the service so you have to worry about backup.
You can read more about this here https://cloud.google.com/artifact-registry/docs/repositories/repo-locations


text:
Q: Remembering a checkbox status in localstorage onload? I'm building a Chrome Extension in which a user defaultly sees one div on load but can check checkboxes revealing (or hiding) other divs which I want to persist even after the page is closed.
My HTML is:
  <input id="click" type="checkbox"></input>

<input id="clicktwo" type="checkbox"></input>

and my JS is (currently only for 'clicktwo' checkbox):
function save(){
var checkbox = document.getElementById('clicktwo');
localStorage.setItem('clicktwo', checkbox.checked);
}

function load(){
var checked = JSON.parse(localStorage.getItem('clicktwo'));
document.getElementById("clicktwo").checked = checked;
}

function wis(){
location.reload();
localStorage.clear()

}

My question is, why isn't this working? I've cross referenced a few sources but still find myself lost. Any and all help will be appreciated!
Thanks in advance.

A: *

*Add event listeners to checkbox onclick event
function checkBoxClick(event) { ... };

*callback function will be called with atribute - event. Ithrough it you can get the HTML of the clicked node and it's attributes.

*feed these attributes to persist function:
function persist(elementId, checkBoxState) {
    /*set to localStorage["elementId"] = checkBoxState; */
};
Now you have you data changes persisted.

*During page load get the values from localStorage and make correspondent changes to UI.

N.B. It's a good idea to have an array of objects {id: "id_of_checkbox", state: "is_checked?"} and save to localStorage whole array at once ( under one name ).


text:
Q: ES Index with python - combine normal Mapping Setting incl. index.mapping.ignore_malformed I need help while trying to add ignore_malformed to my index settings.
I have:
from elasticsearch import Elasticsearch
es = Elasticsearch(
  [{'host': 'localhost', 'port': 9200}])

index_name = 'product'

settings = {
"settings": {
    "index.refresh_interval" : "1s",
    "index.mapping.total_fields.limit": 10000,
    "number_of_shards": 1,
    "number_of_replicas": 0
  },
"mappings": {
  "properties": {
        "location": {
          "type": "geo_point"
        }
      },
    "dynamic_templates": [
      {
        "strings_as_keywords": {
          "match_mapping_type": "string",
          "mapping": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
        }
      }
    ]
  }
}

es.indices.create(index=index_name, body=settings)

If I try to add "index.mapping.ignore_malformed": true,
I get:
NameError: name 'true' is not defined
With following I can perform this setting but I need both at once while indexing:
from elasticsearch import Elasticsearch
# conntect es
es = Elasticsearch(
  [{'host': 'localhost', 'port': 9200}])
from elasticsearch_dsl import Index
index_name = 'product'
index = Index(index_name, es)
index.settings(
        index={'mapping':{'ignore_malformed':True}}
    )
index.create()

Under Edit Settings in Kibana my current index specs are:
{
  "index.blocks.read_only_allow_delete": "false",
  "index.priority": "1",
  "index.query.default_field": [
    "*"
  ],
  "index.write.wait_for_active_shards": "1",
  "index.mapping.total_fields.limit": "10000",
  "index.refresh_interval": "1s",
  "index.number_of_replicas": "0"
}

How can I combine above mentioned while creating my index to get:
{
  "index.blocks.read_only_allow_delete": "false",
  "index.priority": "1",
  "index.query.default_field": [
    "*"
  ],
  "index.write.wait_for_active_shards": "1",
  "index.mapping.total_fields.limit": "10000",
  "index.refresh_interval": "1s",
  "index.mapping.ignore_malformed": "true",
  "index.number_of_replicas": "0"
}

Beside:
It is also not possible to add this string by editing in Kibana
Result = Bad Request (wtf why!?)
Reference:
Empty string in Elasticsearch date field?
How set ignore_malformed in index level when creating an index through ElasticSearch DSL python wrapper?
Thanks for any help
Regards

A: oh yes, typo error...
I reworked the settings, now it works, even on field level :)
settings = {
"settings": {
    "index.refresh_interval" : "1s",
    "index.mapping.total_fields.limit": 10000,
    "number_of_shards": 1,
    "number_of_replicas": 0,
    "index.mapping.ignore_malformed": "true"
  },
"mappings": {
  "properties": {
        "location": {
          "type": "geo_point"
        },
        "Date":{
          "type": "date",
          #"ignore_malformed": "true"
        }
      },
    "dynamic_templates": [
      {
        "strings_as_keywords": {
          "match_mapping_type": "string",
          "mapping": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword",
                "ignore_above": 256
              }
            }
          }
        }
      }
    ]
  }
}


text:
Q: c# Xamarin Forms implement ASMX Service I have online azure service and managed to use it in my UWP application.
I added service reference, and use it as instance:
var service = new ServiceReference1.MyWebService1SoapClient();
var books = await service.GetAllBooks();

And in books I get the response.
Now I need to make this to work on my android phone. I have created Xamarin Forms project, and it is working on my phone. But, I am unable to use this service. I have added service as web reference. It is now located in folder WebServices, and named "net.azurewebsites.nameOfMyService".
How to use this service as instance/object? Or is there any better way via HttpClient?
Thanx.


text:
Q: Is there a way to retrieve the weights from a GPflow GPR model? Is there a way to retrieve the weights from a GPflow GPR model?
I do not necessarily need the explicit weights. However, I have two issues that may be solved using the weights:

*

*I would like to compile and send a trained model to a third party. I
would like to do this without sending the training data and without
the third party having access to the training data.

*I would like to be able to predict new mean values without
calculating new variances. Currently predict_f calculates both the
mean and the variance, but I only use the mean. I believe I could
speed up my prediction significantly if I didn't calculate the
variance.

I could resolve both of these issues if I could retrieve the weights from the GPR model after training. However, if it is possible to resolve these tasks without ever dealing with explicit weights, that would be even better.

A: It's not entirely clear what you mean by "explicit weights", but if you mean alpha = Kxx^{-1} y where Kxx is the evaluation of k(x,x') and y is the vector of observation targets, then you can get that by using the Posterior object (see https://github.com/GPflow/GPflow/blob/develop/gpflow/posteriors.py), which you get by calling posterior = model.posterior(). You can then access posterior.alpha.
Re 1.: However, for predictions you still need to be able to compute Kzx the covariance between new test points and the training points, so you will also need to provide the training locations and kernel hyperparameters.
This also means that you cannot rely on this to keep your training data secret, as the third party could simply compute Kxx instead of Kzx and then get back y = Kxx @ alpha. You can avoid sharing exact (x,y) training set pairs by using a sparse approximation (this would remove "individual identifiability" at least). But I still wouldn't rely on it for privacy.
Re 2.: The Posterior object already provides much faster predictions; if you only ask for full_cov=False (marginal variances, the default), then you're at worst about a factor ~3 or so slower than predicting just the mean (in practice, I would guesstimate less than 1.5x as slow). As of GPflow 2.3.0, there is no implementation within GPflow of predicting the mean only.


text:
Q: Outlook - Is it possible to apply custom views to folders in different pst files? I have a IMAP account and would like to copy custom views across to other folders in different pst files.
The idea is to use VBA to do that.
At the moment I can use VBA to apply a specific view to the IMAP folder because I already created these views. But, looking in other pst files, these same views don't exist there.
Based on the tip of using the Outlook.View I created a form with 2 buttons and with 2 events that call 2 different subs with a store/apply functions:
Private Sub CommandButtonApplyView_Click()
    Call ApplyStoredView
End Sub

Private Sub CommandButtonStoreView_Click()
    Call StoreView
End Sub

And on a module I have:
Public StoredView As Outlook.View

Public Sub StoreView()
    Set StoredView = Application.ActiveExplorer().CurrentView
End Sub

Public Sub ApplyStoredView()
    StoredView.Apply
End Sub

The idea is to store the view on the global var StoredView and store it on click using CommandButtonApplyView and on any other folder using the other button CommandButtonStoreView
The folder where my view is to be applied (e.g. in another pst file) does not re-format according with the view that was stored.
It seems that we only keep the standard 4 views existing in the pst "Table view", "Compact", "Single" and "Preview". The new view (stored) isn't considered.

A: You can readMAPIFolder.CurrentView.XML and apply it to another folder.


text:
Q: Handling an exception where more or less than 4 characters is entered I'm writing a Mastermind program where it takes input for the guess, but I need to make sure that it only takes 4 characters of input. So if someone entered anything other than 4 characters, it would prompt for reentry. I know this isn't hard at all, I'm just drawing a blank and haven't been able to find an answer on here anywhere.

A: Lets try to do it, one step at a time.

*

*Get user input in your program. If it's standard input, one way to pull it is with System.in, which is an InputStream.

*Store the input in an intermediate variable. The type of this variable can be String.

*If needed, cast the value to a type which is the most relevant to your application's requirement. Before that check input for bad values like null.

*Perform the logic on the input, which in your case is finding out whether the length of the input is 4.

*Prompt again for input if the current one doesn't meet the requirement. One way to do it is to put your relevant code in a loop which terminates only when you get the right input.

And if that doesn't work, you're most welcome to ask again including code that shows your effort.


text:
Q: Convert Epoch time to local time log_input.log
1949,1603441909,984159,0.002608,19.8829994202,0.0,640.0
950,1603441910,  416274
21,160340, 24666082,0.002608,19.81913,0.0,638.0

Check the column consistency, disregard the row if the column number are not consistent. Read the second column and convert the second column into local time format.
log_output.log
1949, 10-31-49,984159,0.002608,19.8829994202,0.0,640.0
21, 9-32-20, 24666082,0.002608,19.81913,0.0,638.0

Code:
with open('log_input.txt', 'r') as f:
    csv_data = csv.reader(f)
    csv_lines = list(csv_data)

for line in csv_lines:
  line[1] = convert(line[1].split(':')[1].strip())

A: You can convert epoch to a date using datetime with:
time.strftime('%Y-%m-%d', time.localtime(<your epoch>))

In case it is less than a day, just check if it is less than 86400, and if yes, write as-is.


text:
Q: Issue with select tag in IE with Protractor I have protractor tests running with Selenium using the IEDriverServer (32 bit). I am having a few issues with <select> tags not being clicked and revealing their options.
Here is my conf.js:
exports.config = {
// The address of a running selenium server.
seleniumAddress: 'http://localhost:4444/wd/hub',

// Capabilities to be passed to the webdriver instance.
multiCapabilities: [
    {
        browserName: 'internet explorer',
        ignoreProtectedModeSettings: true,
        ignoreZoomSetting: true,
        nativeEvents: false
    }
    //,
    //{
    //    browserName: 'chrome'
    //}
],
baseUrl: String(process.env.COMPUTERNAME.toLowerCase()) === String('build') ? 'http://dev/' : 'http://' + process.env.COMPUTERNAME + '/',

// can use 'suites' instead of 'specs' - check api documentation
suites: {
    dashboard: 'dashboard/myCallbacksWidget_spec.js',
    employees: 'employees/employees_spec.js',
    lead: 'lead/lead_spec.js',
},

// Options to be passed to Jasmine-node.
jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 80000
},

allScriptsTimeout: 80000,

onPrepare: function () {

    browser.driver.manage().window().maximize();

    if (process.env.TEAMCITY_VERSION) {
        require('jasmine-reporters');
        jasmine.getEnv().addReporter(new jasmine.TeamcityReporter());
    };
    //var ScreenShotReporter = require('protractor-screenshot-reporter');
    var ScreenShotReporter = require('protractor-html-screenshot-reporter');
    var path = require('path');
    jasmine.getEnv().addReporter(new ScreenShotReporter({
        baseDirectory: 'tmp/report',
        pathBuilder: function pathBuilder(spec, descriptions, results, capabilities) {
            return descriptions.join('-');
        }
        //takeScreenShotsOnlyForFailedSpecs: true
    }));
   }
};

Here is my test:
describe('Lead Details Test', function () {
var arrowDown = '\uE015';

it('should open the first lead', function () {
    browser.get('Slate.Iva/#/search-leads');

    var firstItem = element(by.repeater('row in renderedRows').row(0));
    firstItem.evaluate('onDblClickRow(row)');

    expect(element(by.id('leadName')).isPresent()).toBe(true);
});

it('should select reason for difficulty', function () {
    var reasonForDifficulty = element(by.id('reasonForDifficultySelect'));
    expect(reasonForDifficulty.isPresent()).toBe(true);
    reasonForDifficulty.click().sendKeys(arrowDown).sendKeys(protractor.Key.ENTER);

    var saveButton = element(by.id('saveLead'));
    saveButton.click();

    browser.refresh();

    var firstOption = element.all(by.options('item.id as item.name for item in leadData.reasonForDifficultyTypes')).first();
    expect(firstOption.getText()).toEqual('Cosmetic Surgery');
  });
});

When I do reasonForDifficulty.click(), it highlights the <select> but the sendKeys don't seem to work.
This code works if the <select> is a chosen dropdown.
I am using Protractor 2.0.0, Selenium 2.45.0 and IEDriverServer 2.45.0.0. I am also running on Windows 8.1 and have IE11.
Is there a workaround for this or have I missed something in my code?

A: As per my comment the following should work;
var value = 'It was too difficult';
reasonForDifficulty.element(by.cssContainingText('option', value)).click();

This will select the drop down option "It was too difficult", this is good if you are testing a specific options effect on your application.
Alternatively if you wanted to do it by number you can use
 var optionNum = 5
 var options = reasonForDifficulty.all(by.tagName('option'))
    .then(function(options){
      options[optionNum].click();
    });

The second one will select the 6th option (0 being the first of course) in the drop down list, this is a good option if you don't really care what option is selected, and is better if you are testing an application where data is changing constantly and it makes your tests that much more robust (in my opinion).


text:
Q: Storing and accessing dataframe objects I'm trying to read some excel files as pandas dataframes. The problem is they are quite large (about 2500 rows, columns up to 'CYK' label in the excel sheet, and there are 14 of them).
Every time that I run my program, it has to import again the files from excel. This causes the runtime to grow a lot, currently it's a bit more than 15 minutes and as of now the program doesn't even do anything significant except importing the files.
I would like to be able to import the files just once, then save the dataframe objects somewhere and make my program work only on those dataframes.
Any suggestions?
This is the code I developed until now:
import pandas as pd
import os

path = r'C:/Users/damia/Dropbox/Tesi/WIOD'
dirs = os.listdir(path)

complete_dirs = []
for f in dirs:
    complete_dirs.append(path + r"/" + f)

data = []
for el in complete_dirs:
    wiod = pd.read_excel(el, engine='pyxlsb')
    data.append(wiod)

If anyone is interested, you can find the files I'm trying to read at this link:
http://www.wiod.org/database/wiots16

A: You could use the to_pickle and read_pickle methods provided by pandas to serialize the dataframes and store them in files.
docs
Example pickling:
data = []
pickle_paths = []
for el in complete_dirs:
    wiod = pd.read_excel(el, engine='pyxlsb')
    # here's where you store it
    pickle_loc = 'your_unique_path_to_save_this_frame'
    wiod.to_pickle(pickle_loc)
    pickle_paths.append(pickle_loc)
    data.append(wiod)

Depickling
data = []
for el in pickle_paths:
    data.append(pd.read_pickle(el))

A: Another solution using to_pickle and read_pickle.
As an aside, you can read Excel files directly from URLs if you don't want to save to your drive first.
#read each file from the URL and save to disk
for year in range(2000, 2015):
    pd.read_excel(f"http://www.wiod.org/protected3/data16/wiot_ROW/WIOT{year}_Nov16_ROW.xlsb").to_pickle(f"{year}.pkl")

#read pickle files from disk to a dataframe
data = list()
for year in range(2000, 2015):
    data.append(pd.read_pickle(f"{year}.pkl"))
data = pd.concat(data)


text:
Q: Are non-template friends of template classes instantiated? Consider the following code :
//Allows to automatically define post in/de-crement operators from their pre- version
template<typename T>
struct Arithmetic
{
    //Not a template?
    friend constexpr auto operator++(T& l, int)
    { auto old = l; ++l; return old; }

    friend constexpr auto operator--(T& l, int)
    { auto old = l; --l; return old; }
};

//Only defines increment
struct Foo : Arithmetic<Foo>
{
    int val;
    Foo& operator++() { ++val; return *this; }
};

int main(int argc, char* argv[])
{
    Foo f;
    f.val = 12;
    ++f;
    f++;

    return 0;
}

If I tried to define the post-decrement operator "manually" (outside of Arithmetic), I would get an error on --l; because the pre-decrement operator is not defined. As non-template friends of template classes are apparently not considered template functions, I would expect the same behaviour.
But as it is, the code compiles just fine for C++17 (at least on msvc and gcc). Why is that so? Is this kind of function a specific case of non-template function that still gets instanciated?
What parts of the standard allow or prevent me from doing such things?

A: A non-template friend function defined in a template class is a templated entity.
From the C++ 20 Standard (13.1 Preamble)

8 A templated entity is
(8.1) — a template,
(8.2) — an entity defined (6.2) or created (6.7.7) in a templated
  entity,
(8.3) — a member of a templated entity,
(8.4) — an enumerator for an enumeration that is a templated entity,
  or
(8.5) — the closure type of a lambda-expression (7.5.5.1) appearing in
  the declaration of a templated entity
[Note: A local class, a local variable, or a friend function defined
  in a templated entity is a templated entity. —end note]

It is instantiated when it is required. So in this class definition
//Only defines increment
struct Foo : Arithmetic<Foo>
{
    int val;
    Foo& operator++() { ++val; return *this; }
};

the templated entity
friend constexpr auto operator--(T& l, int)
{ auto old = l; --l; return old; }

is not instantiated.
In the case when the friend function only declared in the template class struct Arithmetic and is defined outside the class for its specialization then the compiler will issue an error because the operator --l is not declared in the class Foo.

A:
If I tried to define the post-decrement operator "manually" (outside of Arithmetic), I would get an error on --l;

Those are indeed not template functions, so you have to provide manually the function for each T, here version for Foo:
constexpr auto operator--(Foo& l, int)
{
    auto old = l; --l; return old;
}


text:
Q: All Gradient values calculated as "None" if using BCE loss manually I am working on a multi-output model where I need to weigh all output losses before calculating the overall loss. I have a customized model. fit() training loop to achieve this.
As I need to calculate the sample-wise loss for all four outputs and fuse these sample-wise losses after applying weight, I have customized the standard code. Now, the loss is calculating sample-wise but while calculating the gradient, all gradient values are calculated as "None". I tried to put tape.watch(loss) also, but it is not working. Kindly, help me to fix this issue.
class CustomModel(keras.Model):
    def train_step(self, data):
        print(tf.executing_eagerly())
        # Unpack the data. Its structure depends on your model and
        # on what you pass to `fit()`.
        x, y = data
        alpha = 0.1
        loss = 0
        y_pred_all = []

        with tf.GradientTape() as tape:
            bce = tf.keras.losses.BinaryCrossentropy(reduction=tf.keras.losses.Reduction.NONE)
            for spl in range(1 if np.shape(x)[0] == None else np.shape(x)[0]):
                tape.watch(loss)
                tape.watch(loss_mean)
                tape.watch(loss_element)
                x_spl = np.reshape(x[spl], (1, np.shape(x)[1], np.shape(x)[2], np.shape(x)[3]))
                y_pred = self(x_spl, training=True)  # Forward pass
                y_pred_all.append(y_pred)
                loss_element = bce(y[spl], y_pred)
                loss_mean = [np.mean(loss_element[0]), np.mean(loss_element[1]), np.mean(loss_element[2]), np.mean(loss_element[3])]
                id = np.argmin(loss_mean)
                for i, ele in enumerate(loss_mean):
                    if i == id:
                        loss_mean[i] *= 1
                    else:
                        loss_mean[i] *= alpha

                loss = loss + np.sum(loss_mean)

        # Compute gradients
        trainable_vars = self.trainable_variables

        gradients = tape.gradient(loss, trainable_vars)

        # Update weights
        self.optimizer.apply_gradients(zip(gradients, trainable_vars))

        # Update metrics (includes the metric that tracks the loss)
        self.compiled_metrics.update_state(y, y_pred_all)
        # Return a dict mapping metric names to current value
        return {m.name: m.result() for m in self.metrics}

UPDATE
I did few changes as suggested by @rvinas
Now it is calculating the gradient without any error but I am not sure if the changes I did are correct or not:
class CustomModel(keras.Model):
    def train_step(self, data):
        # print(tf.executing_eagerly())
        # Unpack the data. Its structure depends on your model and
        # on what you pass to `fit()`.
        x, y = data
        alpha = 0.1
        loss = tf.Variable(0, dtype='float32')
        y_pred_all = []

        with tf.GradientTape() as tape:
            bce = tf.keras.losses.BinaryCrossentropy(reduction=tf.keras.losses.Reduction.NONE)
            for spl in tf.range(1 if tf.shape(x)[0] == None else tf.shape(x)[0]):
                loss_mean=tf.convert_to_tensor([])
                x_spl =  tf.reshape(x[spl], (1, tf.shape(x)[1], tf.shape(x)[2], tf.shape(x)[3]))
                y_pred = self(x_spl, training=True)  # Forward pass
                y_pred_all.append(y_pred)
                loss_element = bce(y[spl], y_pred)
                loss_mean = [tf.reduce_mean(loss_element[0]), tf.reduce_mean(loss_element[1]), tf.reduce_mean(loss_element[2]), tf.reduce_mean(loss_element[3])]

                id = tf.argmin(loss_mean)
                for i, ele in enumerate(loss_mean):
                    if i == id:
                        loss_mean[i] = tf.multiply(loss_mean[i], 1)
                    else:
                        loss_mean[i] = tf.multiply(loss_mean[i], alpha)

                loss = tf.add(loss, tf.add(tf.add(tf.add(loss_mean[0],loss_mean[1]), loss_mean[2]), loss_mean[3]))

        # Compute gradients
        trainable_vars = self.trainable_variables

        gradients = tape.gradient(loss, trainable_vars)

        # Update weights
        self.optimizer.apply_gradients(zip(gradients, trainable_vars))

        # Update metrics (includes the metric that tracks the loss)
        self.compiled_metrics.update_state(y, y_pred_all)
        # Return a dict mapping metric names to current value
        return {m.name: m.result() for m in self.metrics}

A: The NaN gradients occur because you are using NumPy operations (e.g. np.sum, np.reshape, ...), which results in a disconnected graph. Instead one needs to implement the logic using tensorflow operations only.

For example, one could implement the weightings described in the comments section as follows:
bce = tf.keras.losses.BinaryCrossentropy(reduction=tf.keras.losses.Reduction.NONE)
with tf.GradientTape() as tape:
    # Compute element-wise losses
    y_pred = self(x, training=True)
    losses = bce(y, y_pred)  # Shape=(bs, 4)

    # Find maximum loss for each sample
    idx_max = tf.argmax(losses, axis=-1)  # Shape=(bs,)
    idx_max_onehot = tf.one_hot(idx_max, depth=y.shape[-1])  # Shape=(bs, 4)

    # Create weights tensor
    weight_max = 1
    weight_others = 0.1
    weights = idx_max_onehot * weight_max + (1 - idx_max_onehot) * weight_others

    # Aggregate losses
    losses = tf.reduce_sum(weights * losses, axis=-1)
    loss = tf.reduce_mean(losses)


text:
Q: Coding numerous instances of jQuery underlines I'm using a custom jQuery plugin that creates easily customisable text underlines with script. The plugin only creates these underlines on mouseover events. So far I have managed to customise it so that underlines are permanent and load with the web page but I am struggling to create numerous instances of the underline on one web page, for some reason despite the use of classes, only one underline can exist at any time.
Here is the jQuery;
(function($){
$.fn.underline = function(options) {
    var defaults = {
                    width:       1,
                    distance:    0,
                    color:       '#000',
                    durationOn:  250,
                    durationOff: 250,
                    extend:      2,
                   };

    var options = $.extend(defaults, options);

        $('body').append('

');

          $('.underlineLine')

            var position  = $(this).offset();
            var top       = position.top;
            var left      = position.left;

            var objWidth  = $(this).width();
            var objHeight = $(this).height();

            $('.underlineLine').css({'position'        :'absolute',
                                     'display'         :'none',
                                     'height'          : options.width+'px',
                                     'background-color': options.color,});

            $('.underlineLine').css({'left' : left-options.extend,
                                     'top'  : top+objHeight+options.distance,
                                     'width': objWidth+options.extend*2 })
                               .fadeIn();

};
})(jQuery);

The calling of the script on my php web-page:

And the simple HTML summon:

LINK

LINK

LINK

If anyone could spare a couple of minutes to help me with this I would really appreciate it.
Thanks,
Matt

A: You needed to loop all the objects in this
(function($){
$.fn.underline = function(options) {
    var defaults = {
                    width:       1,
                    distance:    0,
                    color:       '#000',
                    durationOn:  250,
                    durationOff: 250,
                    extend:      2,
                   };

    var options = $.extend(defaults, options);

    for(i = 0; i < this.length; i++)
    {
        var row = this[i];
        var line = $("

");

        var position  = $(row).offset();
        var top       = position.top;
        var left      = position.left;

        var objWidth  = $(row).width();
        var objHeight = $(row).height();

        $(line).css({'position' :'absolute',
                     'display'         :'none',
                     'height'          : options.width+'px',
                     'background-color': options.color,});

        $(line).css({'left' : left-options.extend,
                     'top'  : top+objHeight+options.distance,
                     'width': objWidth+options.extend*2 }).fadeIn();

        $('body').append(line);
    }
};
})(jQuery);


text:
Q: How do I get a smaller size of an avatar image I have a function that creates a bio-line at the top of every post. One part gets the avatar of that user, that he uploaded in WordPress (I use a plugin so people don't need to use Gravatar for this).
function mm_author_byline()
{
    if (is_single() AND (get_post_type() == 'post' OR get_post_type() == 'theme_product_review')) {
        ?>

        <div class="mm-byline-image">
            <?= get_avatar(get_the_author_meta('ID')) ?>
        </div>

        <?php
    }
}

The problem now is, that this image is neither cropped, nor is it sized down. It takes the original image, that can be huge. How can I get a sized down version of the avatar image?

A: get_avatar takes a second parameter according to the documentation for avatar size. If you're using a plugin that doesn't respect that, you'll need to reach out or check their documentation for a way to change the size.


text:
Q: Using Google Cloud Vision API I'm trying to use Google Cloud Vision API, but facing some issues. Let me explain the steps I took and then the issue I'm facing. I'm running this code in Windows 10.

*

*Download and install "GoogleCloudSDKInstaller".

*gcloud auth application-default login to activate my login
credential

*Used this code to run the face detector, for the image
in my local system.

*cd into the folder where image exists

*Then run the following code:
python detect_face.py "image.jpg"
But I'm getting this error:

raise EnvironmentError('Project was not passed and could not be '
  OSError: Project was not passed and could not be determined from the
  environment.

Can anyone please tell me why I'm getting this issue?

A: I'm using the Google Vision API but in C# with Visual Studios 2017, and I needed to set the environment variable to GOOGLE_DEFAULT_CREDENTIALS.
You might have this problem, try to look on the net how to set it.


text:
Q: A question about stereographic projection of a plane onto a sphere I am reading a paper by Christine Bernardi, available here http://epubs.siam.org/doi/pdf/10.1137/0726068, my question relates to page 1237, which I shall elaborate on:
In this part we have the unit sphere (in $\Bbb R^3$), and a regular tetrahedron $T$ inscribed in the sphere. The paper states that if we let $\omega_j$ be the faces of $T$, then the six planes containing
an edge of $T$ and the origin divide the unit sphere F into four equal parts, $\Gamma_j$.
The paper then reads that each $\Gamma_j$ is the stereographic projection of $\omega_j$, but my question is how one defines the stereographic projection of a face (i.e. a plane) onto a sphere, since to my knowledge, one would project a sphere onto a plane.
Thanks in advance for any help!
As an addendum I believe I have figured out what is meant by this type of projection though I welcome any comments or criticisms, I believe you consider the face $\omega_j$, and at each point $x\in\omega_j$ you consider the inscribed sphere with its (relative) north pole at $x$ and south pole lying on the unit sphere, you then project the point onto the plane tangent to the south pole of this sphere (which lies on the original unit sphere), taking all projections of all points $x\in\omega_j$  we get $\Gamma_j$.

A: For what it's worth at this late date (and not having read the paper): I'd guess the author means "radial projection from the origin", which sends each point $x$ on the tetrahedron to its normalization $x/\|x\|$:


text:
Q: Mimic radiobuttons in datagridview using DataGridViewCheckBoxColumns PLEASE NOTE: this question is about DataGridViewCheckBoxColumns inside a DataGridView control - not the normal CheckBox control.
I have a winforms app that contains a DataGridView with three checkbox (DataGridViewCheckBoxColumn) columns. I'd like to mimic radiobuttons ie. one, and only one, checkbox is checked at a time. I am able to turn off the other checkboxes in the grid when one is clicked as follows:
Private Sub dgvNormalReports_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvNormalReports.CellClick
  If mblnSuppressUI Then Exit Sub
  mblnSuppressUI = True
  If e.ColumnIndex >= 0 And e.ColumnIndex <= dgvNormalReports.ColumnCount - 1 And e.RowIndex >= 0 And e.RowIndex <= dgvNormalReports.Rows.Count - 1 Then
    Select Case dgvNormalReports.Columns(e.ColumnIndex).Name
      Case "dclLeaveOnThisList", "dclPrintLetter", "dclNoLetterNeeded" 'mimic radiobutton - turn off other checkboxes
        dgvNormalReports.Rows(e.RowIndex).Cells("dclLeaveOnThisList").Value = False
        dgvNormalReports.Rows(e.RowIndex).Cells("dclPrintLetter").Value = False
        dgvNormalReports.Rows(e.RowIndex).Cells("dclNoLetterNeeded").Value = False
        'N.B. current cell's checked status is changed AFTER this event
      Case Else
        'ignore
    End Select
  End If
  mblnSuppressUI = False
End Sub

The problem I am having is that if the user clicks on a checkbox that is already checked, it becomes unchecked, and then none of the three checkboxes are checked. I always want one (and only one) checkbox ticked at all times.

A: Use CurrentCellDirtyStateChanged event handler.
Private Sub dgvNormalReports_CurrentCellDirtyStateChanged(sender As Object, e As EventArgs) Handles dgvNormalReports.CurrentCellDirtyStateChanged
    If Me.dgvNormalReports.IsCurrentCellDirty = True Then
        If Me.dgvNormalReports.CurrentCell.OwningColumn.GetType() = GetType(DataGridViewCheckBoxColumn) Then
            If Me.dgvNormalReports.CurrentCell.Value = False Then
                'Update only if changed from false to true
                If Me.dgvNormalReports.CurrentCell.OwningColumn.Name.Equals("dclLeaveOnThisList") = false Then Me.dgvNormalReports.CurrentRow.Cells("dclLeaveOnThisList").Value = False
                If Me.dgvNormalReports.CurrentCell.OwningColumn.Name.Equals("dclPrintLetter") = false Then Me.dgvNormalReports.CurrentRow.Cells("dclPrintLetter").Value = False
                If Me.dgvNormalReports.CurrentCell.OwningColumn.Name.Equals("dclNoLetterNeeded") = false Then Me.dgvNormalReports.CurrentRow.Cells("dclNoLetterNeeded").Value = False

                Me.dgvNormalReports.CommitEdit(DataGridViewDataErrorContexts.Commit)
            Else
                'Prevent changes
                Me.dgvNormalReports.CancelEdit()
            End If
        End If
    End If
End Sub

If you have predefined columns in datagridview, then may be better will be used a generated by VisualStudio column objects:
Me.dclLeaveOnThisList.Name
Me.dclPrintLetter.Name
Me.dclNoLetterNeeded.Name

A: First step, edit your three DataGridView columns and set each columns property ReadOnly to true (this will prevent user from changing the values)

*

*dclLeaveOnThisList

*dclPrintLetter

*dclNoLetterNeeded

and second, use the following code below
Private Sub dgvNormalReports_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvNormalReports.CellClick
  If mblnSuppressUI Then Exit Sub
  mblnSuppressUI = True
  If e.ColumnIndex >= 0 And e.ColumnIndex <= dgvNormalReports.ColumnCount - 1 And e.RowIndex >= 0 And e.RowIndex <= dgvNormalReports.Rows.Count - 1 Then

    Dim tmpColName As String = dgvNormalReports.Columns(e.ColumnIndex).Name
    With dgvNormalReports.Rows(e.RowIndex)
        Select Case tmpColName
        Case "dclLeaveOnThisList", "dclPrintLetter", "dclNoLetterNeeded" 'mimic radiobutton - turn off other checkboxes
                'Unchecked all checkboxes besides the selected one
                If tmpColName <> "dclLeaveOnThisList" Then .Cells("dclLeaveOnThisList").Value = False
                If tmpColName <> "dclPrintLetter" Then .Cells("dclPrintLetter").Value = False
                If tmpColName <> "dclNoLetterNeeded" Then .Cells("dclNoLetterNeeded").Value = False

             'Ensures that the selected cell is checked
             .Cells(e.ColumnIndex).Value = True

        End Select

    End With

  End If
  mblnSuppressUI = False
End Sub

A: You can use a combination of these DataGridView events:

*

*CellValueChanged

*CurrentCellDirtyStateChanged

*CellBeginEdit
You can use CellValueChanged instead of CellClick because CellClick event occurs when any part of a cell is clicked, including borders and padding (MSDN).
CurrentCellDirtyStateChanged event commit the change when the CheckBox is clicked.
The code in CellBeginEdit prevents user from modify a checked CheckBox.
This is an example:
    Private Sub DataGridView1_CellValueChanged(sender As Object, e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.CellValueChanged

        With Me.DataGridView1

            .CurrentCell.Value = True

            If .Columns(e.ColumnIndex).Name = "dgvchkOptionA" Then
                .Rows(e.RowIndex).Cells("dgvchkOptionB").Value = False
                .Rows(e.RowIndex).Cells("dgvchkOptionC").Value = False
            ElseIf .Columns(e.ColumnIndex).Name = "dgvchkOptionB" Then
                .Rows(e.RowIndex).Cells("dgvchkOptionA").Value = False
                .Rows(e.RowIndex).Cells("dgvchkOptionC").Value = False
            ElseIf .Columns(e.ColumnIndex).Name = "dgvchkOptionC" Then
                .Rows(e.RowIndex).Cells("dgvchkOptionA").Value = False
                .Rows(e.RowIndex).Cells("dgvchkOptionB").Value = False
            End If

        End With

    End Sub

    Private Sub DataGridView1_CurrentCellDirtyStateChanged(sender As Object, e As System.EventArgs) Handles DataGridView1.CurrentCellDirtyStateChanged

        If Me.DataGridView1.IsCurrentCellDirty Then
            DataGridView1.CommitEdit(DataGridViewDataErrorContexts.Commit)
        End If

    End Sub

    Private Sub DataGridView1_CellBeginEdit(sender As Object, e As System.Windows.Forms.DataGridViewCellCancelEventArgs) Handles DataGridView1.CellBeginEdit

        With Me.DataGridView1
            If .CurrentCell Is .Rows(e.RowIndex).Cells(e.ColumnIndex) And _
                .CurrentCell.Value Then e.Cancel = True
        End With

    End Sub


text:
Q: MySQL 8.0: Error when inserting date data I have a tab separated file as follows:

When i try to import the file as follows in MySql:
LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/customer.csv'
INTO TABLE customers
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS;

I get the following error:

Incorrect date value: '02/15/2008' for column 'BI_signup_date' at row 1

How do I fix this?

A: The format of dates in your file do not match the format expected by MySQL. Also you have some non-date values in that column ('not BI'). A solution is to preprocess your input to transform it to the relevant format.
LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/customer.csv'
INTO TABLE customers
FIELDS TERMINATED BY '\t'
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(customer_id, @BI_signup_date, email_address)
SET BI_signup_date = CASE
    WHEN @BI_signup_date = 'not BI' THEN NULL
    ELSE STR_TO_DATE(@BI_signup_date, '%m/%d/%Y')
END;

This will turn value 'not BI' to NULL(since obviously this cannot be converted to a date), and convert other values to MySQL date format. Other strategies are possible, like checking the format of the value against a regex. You can modify the logic as needed.
Reference: Input preprocessing in MySQL LOAD DATA syntax:

Each col_name_or_user_var value is either a column name or a user variable. With user variables, the SET clause enables you to perform preprocessing transformations on their values before assigning the result to columns.

A: Edit your csv file and convert the date format to Y-m-d.
This is will resolve all of your issue regarding date format.