text:
Q: Same view for both create and edit in SwiftUI since a couple of days I try to find a solution for using the same view for both create and edit an CoreData object in SwiftUI.
Assume that we have a CoreData entity called Entry. And it only has one property name: String
Now we have a Main/Master view with a List of all Entry objects. To navigate to the DetailView I use the following code:
List {
    ForEach(entires) { entry in
        NavigationLink(destination: DetailView(entry: entry)) {
            Text(item.name ?? "empty")
        }
    }
}

In this DetailView I can then edit the existing object:
struct DetailView: View {
    @Environment(\.presentationMode) var presentationMode
    @Environment(\.managedObjectContext) private var viewContext

    @State var name: String = ""

    @ObservedObject var entry: Entry

    init(entry: Entry) {
        self.entry = entry
        self._name = State(initialValue: entry.name ?? "")
    }

    var body: some View {
        NavigationView {
            Form {
                Section {
                    TextField("Name", text: $name)
                    Button("Save") {

                        guard name != "" else {return}
                        entry.name = name

                        do {
                            try viewContext.save()
                            print("saved")
                        } catch {
                            print(error.localizedDescription)
                        }

                        presentationMode.wrappedValue.dismiss()
                    }
                }
                Button("Cancel") {
                    presentationMode.wrappedValue.dismiss()
                }.accentColor(.red)
            }
            .navigationTitle("Entry Name")
        }
    }
}

But then I need a different view which looks quite the same just for the new entry, since this view does not require a @ObservedObject. This view I access via a simple add button from the Main/Master view and it looks like this:
struct AddView: View {
    @Environment(\.presentationMode) var presentationMode
    @Environment(\.managedObjectContext) private var viewContext

    @State var name: String = ""

    var body: some View {
        NavigationView {
            Form {
                TextField("Name", text: $name)
                Button("Save") {

                    guard name != "" else {return}

                    let entry = Entry(context: viewContext)
                    entry.name = name

                    do {
                        try viewContext.save()
                        print("saved")
                    } catch {
                        print(error.localizedDescription)
                    }

                    presentationMode.wrappedValue.dismiss()
                }

                Button("Cancel") {
                    presentationMode.wrappedValue.dismiss()
                }.accentColor(.red)
            }
            .navigationTitle("Add new Entry")
        }
    }
}

What I don't like here is that I have two views which are 99% equal except that one has the @ObservedObject and the other does not. How can I combine those two views into one? What I would need is something like a @ObservedObject var entry: Entry? where I can keep the Entry optional.


text:
Q: Access other website API How to access other website api from salesforce?
I wanna access the career builder api(http://developer.careerbuilder.com/endpoints/index#collapse4)
For that What I've to do?

A: To do this you will be required to make an web service callout using Apex in your controller (for example, assuming you want the data displayed on a VF page). To call out to the application service for example (see docs here):
public void getApplication(String applicationId) {
  HttpRequest req = new HttpRequest();
  req.setMethod('GET');
  req.setEndpoint('https://api.careerbuilder.com/cbapi/application/' + applicationId);
  req.setHeader('DeveloperKey', 'Your career builder developer key');
  req.setHeader('HostSite', URL.getSalesforceBaseUrl().toExternalForm());
  Http http = new Http();
  HTTPResponse res = http.send(req);
  System.debug(res.getBody());
}

That is an example call and should be enough to get you moving. The documentation from CareerBuilder you linked to seems clear about parameters and URLs for use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bad rendering for borders of circles on a game in Canvas I made a little game. Here you can see a zoom of black and white circles which represent the points of 2 players. Blue circles are the potential hits to play :

My issue is that borders of blue circles are badly rendered : the white border is not well drawn and I can't understand why whereas for white and black circles, borders are thin and well displayed.
Here is the code that I have used in JavaScript:
function showPlayableHits(HitCurrent, isShowing) {
 for (var i = 0; i < 8; i++)
  for (var j = 0; j < 8; j++) {
   if (HitCurrent.arrayPlayable[i][j] == 'playable') {
    if (isShowing)
     drawPiece(i, j, HitCurrent.playableColor, HitCurrent.playableBorderColor);
    else
     deleteHit(i, j);
   }
  }
}

with :
function drawPiece(ix, iy, colorIn, colorBorder) {
 // Coordinates on canvas :
 // x horizontal increasing from left to right
 // y vertical increasing from top to bottom
 var k = ix*width/8 + width/16;
 var l = iy*height/8 + height/16;
 // Draw piece
 context.beginPath();
 context.arc(k, l, radius, 0, 2*Math.PI, false);
 context.fillStyle = colorIn;
 context.fill();
 context.lineWidth = 1;
 context.strokeStyle = colorBorder;
 context.stroke();
}

I don't know where this bad rendering could come from. Maybe this a stuff with 0.5 pixels shifting like we often see concerning the drawing with Canvas but I am not sure of that.
UPDATE 1: I realized there is another issue : all circles on image seem to be shifted slightly on the left towards the boxes (1 pixel or 0.5 pixel ?) in which there are : maybe this will merit another post on SO.
UPDATE 2: so let's get in details : the main board is contained into main div :

                 <canvas id="othello-canvas" width="480" height="480"></canvas>

                       White Score

                          <svg height="48" width="48">
                             <circle cx="24" cy="24" r="23" stroke="black" stroke-width="1" fill="white" />
                          </svg>

                       Black Score

                          <svg height="48" width="48">
                             <circle cx="24" cy="24" r="23" stroke="white" stroke-width="1" fill="black" />
                          </svg>

with following CSS for othello-wrapper id :
#othello-wrapper {
    border: 5px solid black;
    cursor: crosshair;
    margin: 0;
    float: left;
    width: 481px;
    height: 481px;
    overflow: hidden;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px 10px 10px 10px;
}

and for drawing dimensions (see function drawPiece(ix, iy, colorIn, colorBorder above) :
// Size of canvas
var width = canvas.width,
    height = canvas.height;
// Radius of each piece
var radius = 0.9 * width/16;

Does issue come from the (481,481) size for div and (480,480) size for canvas ?

A: The issue is with stacked elements that have anti-aliasing, in this case the border of the blue circle. When multiple anti-aliased edges are drawn on top of each other the opacities are added and will cause the edge to appear aliased.
In the function to determine whether to render the playable hits or not:
function showPlayableHits(HitCurrent, isShowing) {
  for (var i = 0; i < 8; i++)
    for (var j = 0; j < 8; j++) {
      if (HitCurrent.arrayPlayable[i][j] == 'playable') {
        if (isShowing)
          drawPiece(i, j, HitCurrent.playableColor, HitCurrent.playableBorderColor);
        else
          deleteHit(i, j);
      }
    }
}

you are only deleting the "hits" if the isShowing flag is false. You need to call this function on every iteration of the draw call, otherwise drawPiece is called and multiple circles are drawn on top of each other.


text:
Q: Selenium Java - Writing the hashmap values to excel I am trying to use the hashmap values for writing the testcase status in excel file, but it is not writing the data to the excel. Here is my code -
    public void readData() throws Exception {
    String filePath = System.getProperty("user.dir") + "\\Test Data";
    String fileName = "editSubscriptions.xls";
    String sheetName = "datapool";

    File file = new File(filePath + "\\" + fileName);
    FileInputStream fis = new FileInputStream(file);
    Workbook workbook = null;

    String fileExtName = fileName.substring(fileName.indexOf("."));

    if (fileExtName.equals(".xlsx")) {
        workbook = new XSSFWorkbook(fis);
    } else if (fileExtName.equals(".xls")) {
        workbook = new HSSFWorkbook(fis);
    }
    Sheet sheet = workbook.getSheet(sheetName);
    int rowCount = sheet.getLastRowNum() - sheet.getFirstRowNum();
    HashMap<String, String> hm = new HashMap<String, String>();
    for (int i = 1; i < rowCount + 1; i++) {
        Row row = sheet.getRow(i);
        for (int j = 1; j < row.getLastCellNum(); j++) {
            System.out.println(row.getCell(j).getStringCellValue());
            driver.findElement(By.linkText("Login")).click();
            WebDriverWait wait = new WebDriverWait(driver, 10);
            wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("username")));
            driver.findElement(By.id("username")).sendKeys(row.getCell(0).toString());
            driver.findElement(By.id("password")).sendKeys(row.getCell(1).toString());
            driver.findElement(By.name("submit")).click();
            Thread.sleep(10000);
            try {
                driver.findElement(By.linkText("Logout")).click();
                WebDriverWait wait1 = new WebDriverWait(driver, 10);
                wait1.until(ExpectedConditions.visibilityOfElementLocated(By.linkText("Login")));
                hm.put(row.getCell(0).toString(), "Pass");
            } catch (Exception ex) {
                hm.put(row.getCell(0).toString(), "Fail");
                driver.get("http://www.openclinica.com");
            }
        }
    }
    Set<String> keys = hm.keySet();
    for (String key: keys){
        System.out.println("Value of "+key+" is: "+hm.get(key));

        String filePath1 = System.getProperty("user.dir") + "\\Test Data";
        String fileName1 = "editSubscriptions1.xls";
        String sheetName1 = "datapool";

        File file1 = new File(filePath1 + "\\" + fileName1);
        FileInputStream fis1 = new FileInputStream(file1);
        Workbook workbook1 = null;

        String fileExtName1 = fileName1.substring(fileName1.indexOf("."));

        if (fileExtName1.equals(".xlsx")) {
            workbook1 = new XSSFWorkbook(fis1);
        } else if (fileExtName1.equals(".xls")) {
            workbook1 = new HSSFWorkbook(fis1);
        }
        Sheet sheet1 = workbook1.getSheet(sheetName1);
        int rowCount1 = sheet1.getLastRowNum() - sheet1.getFirstRowNum();

        for (int i=1; i < rowCount1; i++){
            Cell cell = sheet1.getRow(i).createCell(2);
            cell.setCellType(Cell.CELL_TYPE_STRING);
            cell.setCellValue(hm.put(key, hm.get(key)));
        }
    }
}

I would like to add the status as Pass or Fail to the excel sheet by using hashmap key. I am able to print the status in the console, but that is not transforming to the excel sheet.
Value of HemaSai is: Fail
Value of MoulikaNimmala is: Pass
Value of Keshav is: Fail
Please help me in resolving the problem..
Thank you in advance.

A: int rowCount1 = sheet1.getLastRowNum() - sheet1.getFirstRowNum();

    for (int i=1; i < rowCount1; i++){
        Cell cell = sheet1.getRow(i).createCell(2);
        cell.setCellType(Cell.CELL_TYPE_STRING);
        cell.setCellValue(hm.put(key, hm.get(key)));
    }

your loop should start at index 0 according to the doc.
it looks like you never get into a loop, as you start at index 1 but your rowcount is initial 0 if you start with an empty sheet.
edit: after the comments, i would go for a solution like this (untested!)
 Set<String> keys = hm.keySet();
String filePath1 = System.getProperty("user.dir") + "\\Test Data";
    String fileName1 = "editSubscriptions1.xls";
    String sheetName1 = "datapool";

    File file1 = new File(filePath1 + "\\" + fileName1);
    FileInputStream fis1 = new FileInputStream(file1);
    Workbook workbook1 = null;

    String fileExtName1 = fileName1.substring(fileName1.indexOf("."));

    if (fileExtName1.equals(".xlsx")) {
        workbook1 = new XSSFWorkbook(fis1);
    } else if (fileExtName1.equals(".xls")) {
        workbook1 = new HSSFWorkbook(fis1);
    }
    Sheet sheet1 = workbook1.getSheet(sheetName1);
    int rowCount1 = sheet1.getLastRowNum() - sheet1.getFirstRowNum(); //set rowNumber to the last already set one
for (String key: keys){ //for every key write the name in column 1 and the result in column 2
    rowcount1++; //start at the next free row

    Cell cell1 = sheet1.createRow(rowCount1).createCell(1);
        Cell cell2 = sheet1.getRow(rowCount1).createCell(2);
        cell1.setCellType(Cell.CELL_TYPE_STRING);
        cell2.setCellType(Cell.CELL_TYPE_STRING);
        cell1.setCellValue(key));
        cell2.setCellValue(hm.get(key)));
    }
}


text:
Q: Formatting type declarations that include many [Attributes] for readability Lately I found myself relying on custom [Attributes] allot. I'm on a quest for creating RTTI and Generics based variants of the VCL controls I most often use; My intention is to reduce the amount of boilerplate code to a minimum, and I find RTTI, Anonymous methods and Attributes to be awesome.
I've got an unusual problem. Since I end up using lots of [Attributes], I need a readable way to format this code. Might sound like an insignificant problem but I'm very obsessive with my formatting and indenting. The problem with attributes is that they're not formatted in a special way by the IDE. In a block of multiple field declarations, inter-wind with [Attribute] declarations, you'd have a hard time guessing what's a type, what's an attribute, what attribute applies to what field. Here's a minimal example:
type
  [OneAttribute('SomeParam', 7), AnOtherAttribute]
  TSomething = class
  public
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    FieldName: string;
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    OtherField: Integer;
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    function Sum(a,b:Integer):Currency;
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    property Name:string read FieldName write FieldName;
  end;

The way I formated those [Attributes] in the example above is the way most often seen in C# code; Unfortunately I have seen no example of Delphi code using attributes, except my own. This works slightly better for C# because you're less likely to apply attributes to actual fields and more likely to apply them to properties or functions; Since in C# the function implementation immediately follows it's declaration (the same for properties) you don't get the same kind of block as with Delphi; functions and property declarations are naturally separated so glancing over the code is not hindered by the use of attributes.
I tried the obvious source for delphi-related "style" information. The code formater in Delphi 2010 doesn't understand property declarations at all! In the above example, if I remove the public keyword and run the built-in code formater then the first line of Attributes declarations is moved one line up behind the class keyword as if it's declaring an ancestor class.
I grepped around the Delphi 2010 source code. Either my grep-fu is failing me badly or there's absolutely no use of attributes in the whole of the Delphi 2010 sources. Just to be clear, after trying to grep for the actual uses of attributes (difficult because square brackets are used allot and they rarely mean it's an attribute declaration) I started grepping for TCustomAttribute: there's no descendant of TCustomAttribute anywhere, so obviously there's no use of attributes.
Finaly to the question:
How do you format [Attributes] for readability?
My latest solution looks like this:
type
 [OneAttribute('SomeParam', 7), AnOtherAttribute]
  TSomething = class
  public
   [OneAttribute('SomeParam', 7), AnOtherAttribute]
    FieldName: string;
   [OneAttribute('SomeParam', 7), AnOtherAttribute]
    OtherField: Integer;
   [OneAttribute('SomeParam', 7), AnOtherAttribute]
    function Sum(a,b:Integer):Currency;
   [OneAttribute('SomeParam', 7), AnOtherAttribute]
    property Name:string read FieldName write FieldName;
  end;

I'm normally using two-column indent; For attributes I'm thinking of moving the attribute declaration one-to-the-left; There's always space for that since my types, fields, methods and properties always have a minimum of 2 columns right-indent (for types) or 4 for class members. Left-indenting like seems to blend nicely with existing declarations that do not use attributes, and I want the attributes to "stand out", so left indent is better then right indent.
What do you think? Have you got better ideas?

A: An answer as per request.
I use the first version and just add blank lines after each. And optionally two blank lines after a group of those attribute/method-property pairs for "functional separation". I have also been known to repeat the visibility specifier to separate functional groups of methods/properties.
It needs more screen real estate, but it helps..
type
  [OneAttribute('SomeParam', 7), AnOtherAttribute]
  TSomething = class
  public
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    FieldName: string;

    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    OtherField: Integer;

    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    function Sum(a,b:Integer):Currency;

    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    property Name:string read FieldName write FieldName;

  public
    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    TableName: string;

    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    OtherTable: Integer;

    [OneAttribute('SomeParam', 7), AnOtherAttribute]
    function TableSum(a,b:Integer):Currency;
  end;


text:
Q: 'module' object not callable when trying to log into webpage using requests().post() I am trying to script a log-in into this website: https://www.trademap.org/Index.aspx
You will require log-in details but just indicate that you are from a developing country and you will have free access.
You will find the log-in button around the top right-hand corner of the webpage. It seems like that is no dedicated URL for the log-in.
The code that I wrote is as such:
import requests
from bs4 import BeautifulSoup as soup

trademap_mainpage_url = "https://www.trademap.org/Index.aspx"

login_data = {"PageContent_Login1_UserName": " ---------------", "PageContent_Login1_Password":" -------------"}
requests().post(trademap_mainpage_url, login_data)

My login detail have been hyphened out.
Error message:
TypeError                                 Traceback (most recent call last)
<ipython-input-18-a9a30e4eb11b> in <module>
      1 login_data = {"PageContent_Login1_UserName": "-----------", "PageContent_Login1_Password":"----------"}
----> 2 requests().post(trademap_mainpage_url, login_data)
TypeError: 'module' object is not callable

Again, login details have been hyphened out.
On a side note, I am completely new to web scraping, just started reading about it today so I apologize for my incompetence.

A: It's not:
requests().post(url, data)

but instead:
requests.post(url, data)


text:
Q: What "*#" means after executint a command in PostgreSql 10 on Windows 7? I'm using PostgreSQL on Windows 7 through the command line.  I want to import the content of different CSV files into a newly created table.
After executing the command the database name appeared like:
database=#

Now appears like
database*# after executing:
type directory/*.csv | psql -c 'COPY sch.trips(value1, value2) from stdin CSV HEADER';

What does *# mean?
Thanks

A: This answer is for Linux and as such doesn't answer OP's question for Windows. I'll leave it up anyway for anyone that comes across this in the future.

You accidentally started a block comment with your type directory/*.csv. type doesn't do what you think it does. From the bash built-ins:

With no options, indicate how each name would be interpreted if used as a command  name.

Try doing cat instead:
cat directory/*.csv | psql -c 'COPY sch.trips(value1, value2) from stdin CSV HEADER';

If this gives you issues because each CSV has its own header, you can also do:
for file in directory/*.csv; do cat "$file" | psql -c 'COPY sch.trips(value1, value2) from stdin CSV HEADER'; done

Type Command
The type built-in command in Bash is a way of viewing command interpreter results. For example, using it with ssh:
$ type ssh
ssh is /usr/bin/ssh

This indicates how ssh would be interpreted when you run ssh as a command in the current Bash environment. This is useful for things like aliases. As an example for this, ll is usually an alias to ls -l. Here's what my Bash environment had for ll:
$ type ll
ll is aliased to `ls -l --color=auto'

For you, when you pipe the result of this command to psql, it encounters the /* in the input and assumes it's a block comment, which is what the database*# prompt means (the * indicates it's waiting for the comment close pattern, */).
Cat Command
cat is for concatenating multiple files together. By default, it writes to standard out, so cat directory/*.csv will write each CSV file to standard out one after another. However, piping this means that each CSV's header will also be piped mid-stream of the copy. This may not be desirable, so:
For Loop
We can use for to loop over each file and individually import it. The version I have above, for file in directory/*.csv, will properly handle files with spaces. Properly formatted:
for file in directory/*; do
    cat "$file" | psql -c 'COPY sch.trips(value1, value2) from stdin CSV HEADER'
done

References

*

*PostgreSQL 10 Comments Documentation (postgresql.org)

*type built-in Manual page (mankier.com)

*cat Manual page  (mankier.com)

*Bash looping tutorial (tldp.org)


text:
Q: deequ - How one can "train" deequ for a number trend? let's say we have a column with a number that increases a bit on a daily basis, but cannot predict the increase with good precision.
For example (the value on day_x is):
day_1 = 10,
day_2 = 20,
day_3 = 35,
day_4 = 22, (a sudden decrease here)
day_5 = 41
...etc

So we know in general that there is an upward trend with different percentage every time.
How can we get the current ratio, or even better "predict" the next increase?
Can deequ train itself with some accuracy?
Thank you!

A: use the anomaly detection feature in deequ.
Multiple "anomaly detection algorithm" can be used.  Most likely the "RelativeRateOfChangeStrategy", where min/max percentage change can be applied.
Below is an example of such detector: https://github.com/awslabs/deequ/blob/master/src/main/scala/com/amazon/deequ/examples/anomaly_detection_example.md
If you're looking for unexpected low value, decrease by more than 20%
maxRateDecrease=0.8


text:
Q: Angular JS - Error: ng:areq Bad Argument Argument 'GameContoller' is not a function, got undefined I'm just trying to link up my "GameController" in Angular and it keeps spitting out this error above. Haven't put anything in the scope yet but I'm not sure what's wrong with my controller. Any suggestions? It's for a basic Tic Tac Toe game.
JS:
// module
var xoxoApp = angular.module('xoxoApp', []);

// defines controller
xoxoApp.controller('GameController', function ($scope) {
    $scope.boxes = []
});

HTML:
<!DOCTYPE html>

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

<title>Tic Tac Toe</title>

A: Could it be that you misspelled GameController?


text:
Q: HTTP error on ystockquote I would like to fix an old script that I have made with Python 2.7. I've already adjusted the syntax for Python 3 but I'm not able to download stock quotes by using the module ystockquote (HTTPError: HTTP Error 502: notresolvable):
import ystockquote
#Function for taking the sample of Close prices:
def close_prices(symbol, start_date, close_date):
    data = ystockquote.get_historical_prices(symbol,start_date, close_date)
    sample = []

for date in data:
    # print data[date]['Close']
    sample.append(float(data[date]['Close']))

return sample

Thank you in advance


text:
Q: How do I obtain the data to train my ML model? I am building a machine learning model that would suggest attractions in a specific location.
I have most of the details worked out. However, I still need to collect the data of the attractions to train my model.
Is there somewhere I could find a dataset for this (I already checked Kaggle)? If not which websites should I scrape?

A: If you want to scrape data, twitter probably is the easiest to start. You can use twitter API to get any tweet that contain a specific keyword or hashtag, input your desired location as the keyword and scrape it using tweepy, i would suggest you to scrape from a specific account like Influencer or travel blog to get data about attraction.
Applying to get twitter API might take several days, and you can only scrape tweet within a time range of a weeks. older than that you need to sign up to their premium subscription.


text:
Q: Loading correct details of a listing on a new page I am fairly new to Laravel, hence I don't know that many "Laravel-terms" and stuff, so it is a bit hard to search for what I mean, however I hope it is understandable what my issue is.
But I got a website which displays different listings of Jobs, like so:
https://i.stack.imgur.com/Cz7ql.jpg
As you can see on the right side there are 2 buttons, the upper one is for "apply now" and the lower one for "details" (details about the job), when the user clicks for instance on the "details" button a new view loads with the details about the job
Now my question is, is it possible to display the correct details automatically when a user clicks on the details button?
How can I implement that laravel shows the details that match the listing?
Here is my blade code that outputs the listings:
@extends('layouts.app')

@section('content')

 Übersicht der Stellenanzeigen

            @if ($posts->count())
                @foreach($posts as $post)

 {{ $post->Titel }}

                                <button type="submit" class="text-white px-4 py-3 rounded text-base font-medium
                                bg-gradient-to-r from-green-400 to-blue-500 float-right shadow transition
                                duration-500 ease-in-out transform hover:-translate-y-1 hover:scale-100" onclick="window.location=' {{ url('bewerben') }}'">Direkt bewerben!</button>

 Standort: {{ $post->Standort }}

 Kontakt: {{ $post->Kontakt }}

                                <button type="submit" class="text-white px-4 py-3 rounded text-base font-medium
                                bg-gradient-to-r from-green-400 to-blue-500 float-right shadow transition duration-500 ease-in-out transform hover:-translate-y-1 hover:scale-100">Details!</button>

 Startdatum: {{ $post->startdate }}

 Enddatum: {{ $post->enddate }}

                        @endforeach

                        @endif

@endsection

I thought about ways to implement it theoretically, and came up with two that at least sound kind of logic to me that MAY work:

*

*I have to somehow "save" the ID of the listing so that when a user clicks on the button of the third listing the details are displayed on the next view that are from the listing in the database with the same ID as the third listing.

*I could use the title of the listing to search the details of a DB entry with the same title, however I think that's a bit stupid to say the least because then every title has to be unique.
Any food for though appreciated!
Edit: I got a question ban because my questions are not upvoted, but answered and some good discussion happens in the comments. But the stack exchange team told me to edit my questions to making them more clear, but they received answers so I think they were clear. I am not a native speaker so my English is not the best and I cant express myself that good. But they told me to edit them so they appear as new and can be upvoted. I don't see why that makes sense, but maybe it lifts my question ban if I get some upvotes, so maybe upvote if you don't mind.

A: you can use AJAX to get the detail.instead of this button you can use  tag as a button.
<button type="" class="text-white px-4 py-3 rounded text-base font-medium bg-gradient-to-r from-green-400 to-blue-500 float-right shadow transition duration-500 ease-in-out transform hover:-translate-y-1 hover:scale-100">Details!</button>

id}}'">

pass the id of your specific job inside the "get_detail" function.
then you can easily use this id to get data through AJAX


text:
Q: Creating several graphs using 'for' loop I have a dataset that looks like
Node  Target Group
A       B      1
A       C      1
B       D      2
F       E      3
F       A      3
G       M      3

I would like to create a graph for each distinct value in Group. There are 5 groups in total.
file_num = 1
for item <=5: # this is wrong
    item.plot(title='Iteration n.'+item)
    plt.savefig(f'{file}_{file_num}.png')
    file_num += 1

    G = nx.from_pandas_edgelist(df, source='Node', target='Target')

    cytoscapeobj = ipycytoscape.CytoscapeWidget()
    cytoscapeobj.graph.add_graph_from_networkx(G)
    cytoscapeobj

This code, however, does not generate individual graphs (G and the objet from Cytoscape), meaning that something does not work within the loop (at least).
Any help would be extremely useful.

A: Let's call the DataFrame df. Then you iterate over the unique values in the Group column, subset df by this Group value, and save a new figure each iteration of the loop.
file_num = 1
for group_val in df.Group.unique():
    df_group = item[item['group'] == group_val]
    df_group.plot(title='Iteration n.'+item)
    plt.savefig(f'{file}_{file_num}.png')
    file_num += 1

    G = nx.from_pandas_edgelist(df_group, source='Node', target='Target')

    cytoscapeobj = ipycytoscape.CytoscapeWidget()
    cytoscapeobj.graph.add_graph_from_networkx(G)
    cytoscapeobj

A: You should use display() function on cytoscapeobj:
for group_val in df.Group.unique():
<...>
    display(cytoscapeobj)


text:
Q: impliment array.map() on an array which itself is an element of another array Here i have an array called "array" which has 4 arrays as element.As individual elements of "array" are also arrays itself,so i can use any array methods on them,right?So if choose the first element say array[0].map(callback) ,but unfortunately an error is occurring .How can i fix this problem ??
var array=[['apple','jackfruit'],['orange'],['pineapple'],['banana']];
(function(){
   console.log(array[0]);
     var arr=array[0].map(function(row){
         return row.reduce(function(first,second){
             return Math.max(first,second.length);
         },0);
      });
      console.log(arr);

})();

A: I can only guess - do you search for the string in your array with the largest length?
With http://lodash.com/ you can do this:
var array=[['apple','jacklongfurit'],['orange'],['pineapple'],['banana']];

// Sort by string.length (reverse) and use "flatten" to make a 1-imension-array.
array = _.sortBy(_.flatten(array), function(element){
   return -element.length;
});

console.log(array[0]);


text:
Q: Analyzing image complexity Are there any algorithms available for analyzing the complexity of an image? Basically I'm writing a Perl script that will use the system() function to launch MPlayer in the background to generate 10 to 20 screenshots for the input video file and I'd like it to be able to discard any simple images such as a shot of the sky, or a black background, and other simple images and keep just 3 of those images with the highest complexity or most number of colors. Is there a module or a separate program I can use to accomplish this? I'm guessing maybe Image::Magick can take care of this.

A: Great paper here on the subject.  It considers the more narrow problem of matching images in a military application, but surveys the research and contains plenty of different metrics of image complexity that have been considered by various authors.  It's possible you might need only one or two of the methods in your particular task.  Check it out.

A: See how small a JPEG-compressed copy is.   JPEG works hard to remove redundancies in image information and "complex" images simply don't have as much redundancy to remove.

A: My first answer would be the JPEG method but somebody already suggested it, so my next answer would be to compute a histogram ($image->Histogram()). Just look at the number of different colors in the image. For photos (things like the sky), the more colors in an image, the more complex it is.

A: You might consider doing an FFT and looking for high-frequency information in the images... That would give you a rough idea of complexity.

A: I don't know of a ready-made library method, but there are some algorithms to measure this ...
You could try to add up the absolute values of the differences of one pixel to the next, separately per color channel. The sample image with the highest result would win, then. Still, it would be a very rough measurement...
Bit of pseudo-code, since I don't know perl:
complexity = 0
// image coordinates start at [0,0]
for x = 1 to image.max_x:
   for y = 1 to image.max_y:
       complexity += abs(image[x,y].red - image[x,y-1].red)
       complexity += abs(image[x,y].red - image[x-1,y].red)
       complexity += abs(image[x,y].blue - image[x,y-1].blue)
       complexity += abs(image[x,y].blue - image[x-1,y].blue)
       complexity += abs(image[x,y].green - image[x,y-1].green)
       complexity += abs(image[x,y].green - image[x-1,y].green)


text:
Q: python simpler way to find missing items in a list in relation to another list I was struggling to properly title this question but I will try and explain this situation.
I have two lists
l1=['beststreet', 'borocd', 'am_linkid3', 'bestfrom', 'resurf19', 'rmmweekly']
l2=['beststreet', 'borocd', 'bestfrom', 'rmmweekly','weird','noises']

l1 will always remain the same.
l2 can either contain the exact items as l1 or have only some of the items as l1 and in any scenario there can be extra items in the list.
GOAL: find only the missing items in l2 that are in l1 (disregard the extra items in l2)
here is my full code for this, it works totally fine I just feel like I am overthinking this and what I want can have a simpler more pythonic workflow
l1=['beststreet', 'borocd', 'am_linkid3', 'bestfrom', 'resurf19', 'rmmweekly']
l2=['beststreet', 'borocd', 'bestfrom', 'rmmweekly','weird','noises']

result = [[n if n in l1 else None, n if n in l2 else None] for n in set(l1 + l2)]

missing_columns=[]
for r in result:
    if None in r:
        exists= [z for z in l1 if z in r]
        if exists:
            missing_columns.append(exists[0])
print missing_columns

A: print([item for item in l1 if item not in l2])

A: Use set difference
>>> set(l1).difference(l2)
{'noises', 'weird'}

A: To get only the difference you could use sets:
l1 = ['beststreet', 'borocd', 'am_linkid3', 'bestfrom', 'resurf19',
      'rmmweekly']
l2 = ['beststreet', 'borocd', 'bestfrom', 'rmmweekly', 'weird', 'noises']

s1 = set(l1)
s2 = set(l2)

# find missing items from s1 in s2
print(s1.difference(s2))


text:
Q: 301 Redirect to Nginx & keep the URL I have a domain hosted at an ISP. Let's say - hello.mysite.com.
I have set up an nginx http server to serve static html at home. Let's say public ip address of nginx http server is 37.252.120.91. I have configured a 301 forward from hello.mysite.com to http->>//37.252.120.91. This forwards works well but I lose the original url in my browser. I would like to see the contents from http://37.252.120.91 but I still want to see http://hello.mysite.com on my browser address bar. I have tried the following setting in my nginx.conf file but it has no effect.
server {
listen 80;
server_name  hello.mysite.com;

location / {
    proxy_set_header X-Forwarded-Host $host;
    proxy_set_header X-Forwarded-Server $host;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_pass http://37.252.120.91/;
    }
}

Can you help fix this problem?

A: A redirect is just that, a redirect. You are directed elsewhere, away from the original site. You can't do what you're asking at a web server level alone.
You'll need to use something like an iframe: http://www.w3.org/wiki/HTML/Elements/iframe
That way, you can set up hosting on hello.mysite.com which iframes http://37.252.120.91 and appears to be the same content.


text:
Q: How can I rotate an Object around the camera (angle)? What I want to do is spawn an object in front of the camera and the side I am looking at. When I change the rotation of the camera (looking at a different side), the object is still spawned at the same position. How can I change this (that the Object also changes his angle)?
public void Create(Object myPrefab)
{
    Vector3 instantGO = Camera.main.transform.position + new Vector3(0, 0, 7);
    Instantiate(myPrefab, instantGO, Quaternion.identity);
}

A: Use this Instantiate variant:
Instantiate(Object original, Vector3 position, Quaternion rotation, Transform parent);

And pass the Camera transform as the parent parameter. This will make the new object a child of the camera and thus always moves/rotates with the camera.

A: Use transform.forward - this gives a position relative to the transform e.g. Camera.main.transform.position + (Camera.main.transform.forward * 5) for 5m in front of the cam.
The forward and left properties return a vector of magnitude one, pointing in the direction the transform is facing, or to it's left. You can use -forward and -left to align backwards or to the right. Add this to the position of the object and multiply it to give a position a number of units away. In recent versions of Unity you also have transform... up, down, right etc.


text:
Q: Linear programming: constraints that depend on sign Edit: following a comment, more detail and context, and removed lengthy confusing remains of previous edits
I basically want to check whether there is a sequence $y_1,\dots, y_n \in (-\infty,0]$ that satisfies the following, where $p_1,\dots,p_n$ are known and correspond to a probability distribution: $p_i\in[0,1]$, $\sum_i p_i = 1$; and $\alpha$ is a (fixed) small constant.
$$\begin{align}
& y_i \leq 0 \\
& y_{i+1} \geq y_{i} \\
&\sum_{i=1}^n \lvert e^{\sum_{j=1}^{i-1} y_j} - e^{\sum_{j=1}^{i} y_j} - p_i \rvert \leq \alpha
\end{align}
$$
The goal find $y_i$'s that can be used to get a structured probability distribution whose $\ell_1$ distance to $p$ is no more than $C\cdot\alpha$ for some constant $C$, if we are promised there exists one at distance $\leq \alpha$ (I have some slack regarding $C$, even something like 10 or 1000 would be fine).
That is, this linear program is trying to enforce that the probability distribution obtained (after renormalization) by setting $q_i \stackrel{\rm def}{=} (1-e^{y_i})e^{\sum_{j=1}^{i-1} y_j}$ have some particular structure (be a "monotone hazard rate" distribution (MHR)). (The fact that the $q_i$'s before renormalization should almost sum to one is not an issue, and approximately taken care of by the $\ell_1$ distance between $q$ and $p$). So the problem is really the last constraint.
Let me know if the above is remotely clear...


text:
Q: Use of _ when invoking a method Output of below :
getNum(_);
  getNum(3);

  def getNum(num: Int) {
    println("Num is " + num)
  }

is
Num is 3

Why is getNum(_); not invoked ? How is _ used in this case ?

A: What you'd expect it to be? getNum(null) ?
The getNum(_); is translated into, something like:
{ x:Int => getNum(x) }

Which is a anonymous function and a value itself.
You could do for example:
val f = getNum(_)
f(42)

Then you'd see:
Num is 42

A: _ is used to partially apply a function.  Partial application of a function produces another function with some of its parameters already applied.
val f = getNum(_) // partially apply
f(3) // apply the function


text:
Q: If I fly a pig off a cliff, but land in water, do I still get the achievement? The determining factor for getting the Fly a Pig Off a Cliff achievement seems to be that the pig takes damage on landing. Is this actually the case? I'm wondering whether landing the pig in water would work, event though it won't take damage.

A: I've just tested this, and the answer is no, the poor piggy must get hurt. :(


text:
Q: Won't display more than one value There is no error but I was expecting 10 values but I only got one. The below is my create and display function.
void create()
{
int random;
for (int i = 0; i < 10; i++)
{
    struct node *new_node, *current;
    new_node = new node;
    random = randomNum();
    new_node->data = random;
    new_node->next = NULL;
    if (start == NULL)
    {
        start = new_node;
        current = new_node;
        new_node = NULL;
    }
    else
    {
        current->next = new_node;
        current = new_node;
    }
 }
}

void display()
{
struct node *new_node;
new_node = start;
while (new_node != NULL)
{
    cout << new_node->data << "->";
    new_node = new_node->next;
}
}

What do I need to change?

A: Try the following line
current = new_node;
current->next = new_node;

Because in your case there is no value of  current pointer so how can you update its next. First of all update/set the current then update/set its next.
if (start == NULL)
    {
        start = new_node;
        current = new_node;
        current->next = NULL;
        new_node = NULL;
    }
    else
    {
        current = new_node;
        current->next = new_node;

    }

A: The problem with the compiler message is that the compiler is unable to determine whether the variable current used in the else statement was early initialized.
If it is a warning you may ignore it.
Or you can rewrite the function the following way
void create()
{
    const int N = 10;

    node **current = &start;

    while ( *current ) current = &( *current )->next;

    for ( int i = 0; i < N; i++ )
    {
        *current = new node;
        ( *current )->data = randomNum();
        ( *current )->next = nullptr;
        current = &( *current )->next;
    }
 }

The body of the for loop can be also written like (I assume that the data member data precedes the data member next in the node definition. Otherwise exchange the initializers.
*current = new node { randomNum(), nullptr };
current = &( *current )->next;


text:
Q: How do I check .net/mono version from within .net I have a .net application that runs under both the MS implementation and Mono. It requires .net 4.5 and also won't run on old versions of Mono (e.g. it's broken under 3.8.0, whereas 3.10.0 is fine).
I thought a good way of checking whether the application can run would be to write a short bit of code that can link against .net 2.0 libraries, and do the checks there. That way it's easy to determine the Mono version, and I can re-use the same code in the main application as a safety check (though it may not get as far as executing that code - e.g. the application just exists without saying anything under .net 4.0).
The problem I have is finding the highest version of .net that is supported under whatever runtime is being used to execute the test code, as opposed to whatever version it was linked against (which seems to be what System.Environment.Version returns). I can get the version of Mono by using reflection to execute Mono.Runtime.GetDisplayName. Perhaps there is some (similar?) solution that would work under Windows .net?

A: In Windows the most reliable way to determine the installed .NET framework version is to use the registry. The subkey you need to check is:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\NET Framework Setup\NDP\

Check out this link for a sample of code to read these values correctly in C#:
http://msdn.microsoft.com/en-us/library/hh925568%28v=vs.110%29.aspx
In Mono the most reliable way to determine the version is probably by running the shell command:
mono --version

I guess you could run that with the Process class and parse the output.


text:
Q: How can I display my images in my viewController the same as the below screen shot? In my iPad program I have an array which holds images. How can I display my all images (from an image array) in my viewController the same as the below screen shot? Is there a good way to do it, any sample application paths to refer or sample code?
I need the following functionality.

*

*Tapping an image will show it full screen

*A close button to close this view as the same as the screen shot.

*Two buttons to display the remaining and previous images.

A sample screen shot is attached below. We can see that the below application is showing all images at the right side of the screen.

A: Alright, this should be easy, though a bit of coding is needed.
Start out with a simple view based app template.
I don't know where the images come from so I just put all the images to be shown in the resources folder.
The view controller PictureViewController will accept an array of UIImages and should be presented modally. I'll post the code below.
The code to show the PictureViewController is placed in the view controller created by the template. I just added a simple UIButton to the view to trigger an action which looks something like this:
- (IBAction)onShowPictures
{
    // Load all images from the bundle, I added 14 images, named 01.jpg ... 14.jpg
    NSMutableArray *images = [NSMutableArray array];
    for (int i = 1; i <= 14; i++) {
        [images addObject:[UIImage imageNamed:[NSString stringWithFormat:@"%02d.jpg", i]]];
    }

    PictureViewController *picViewController = [[PictureViewController alloc] initWithImages:images];

    [self presentModalViewController:picViewController animated:YES];

    [picViewController release];
}

The view controller's view was created with interface builder, looking like this:
PictureViewController.xib

View Hierarchy

The fullscreen image is linked to an outlet fullScreenImage seen in the following header file. Actions are connected as well.
I've set the fullscreen imageView's content mode to Aspect Fit.
The Thumbnails will be added dynamically with code. Here's the view controller's code
PictureViewController.h
@interface PictureViewController : UIViewController
{
    NSMutableArray *imageViews;

    NSArray *images;

    UIImageView *fullScreenImage;

    int currentPage;
}

@property (nonatomic, retain) NSMutableArray *imageViews;
@property (nonatomic, retain) NSArray *images;
@property (nonatomic, retain) IBOutlet UIImageView *fullScreenImage;

- (id)initWithImages:(NSArray *)images;

- (IBAction)onClose;
- (IBAction)onNextThumbnails;
- (IBAction)onPreviousThumbnails;

@end

PictureViewController.m
The define MAX_THUMBNAILS on top defines the maximum of thumbnails seen. A UITapGestureRecognizer will take care of the tap events for the thumbnails. Adjust the CGRectMake in setupThumbnailImageViews to position the thumbnails as you wish. This controller is just a basic approach without orientation support.
#import "PictureViewController.h"

#define MAX_THUMBNAILS 6

@interface PictureViewController ()

- (void)showSelectedImageFullscreen:(UITapGestureRecognizer *)gestureRecognizer;
- (void)setupThumbnailImageViews;
- (void)setThumbnailsForPage:(int)aPage;
- (UIImage *)imageForIndex:(int)anIndex;

@end

@implementation PictureViewController

@synthesize imageViews, images, fullScreenImage;

- (id)initWithImages:(NSArray *)someImages
{
    self = [super init];
    if (self) {
        self.images = someImages;
        self.imageViews = [NSMutableArray array];
        currentPage = 0;
    }
    return self;
}

- (void)viewDidLoad
{
    self.fullScreenImage.image = [images objectAtIndex:0];
    [self setupThumbnailImageViews];
    [self setThumbnailsForPage:0];
}

- (void)showSelectedImageFullscreen:(UITapGestureRecognizer *)gestureRecognizer
{
    UIImageView *tappedImageView = (UIImageView *)[gestureRecognizer view];

    fullScreenImage.image = tappedImageView.image;
}

- (void)setupThumbnailImageViews
{
    for (int i = 0; i < MAX_THUMBNAILS; i++) {
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(20.0,
                                                                               166.0 + (130.0 * i),
                                                                               130.0,
                                                                               90.0)];

        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                action:@selector(showSelectedImageFullscreen:)];
        tapGestureRecognizer.numberOfTapsRequired = 1;
        tapGestureRecognizer.numberOfTouchesRequired = 1;
        [imageView addGestureRecognizer:tapGestureRecognizer];
        [tapGestureRecognizer release];

        imageView.userInteractionEnabled = YES;

        [imageViews addObject:imageView];
        [self.view addSubview:imageView];
    }
}

- (void)setThumbnailsForPage:(int)aPage
{
    for (int i = 0; i < MAX_THUMBNAILS; i++) {
        UIImageView *imageView = (UIImageView *)[imageViews objectAtIndex:i];
        UIImage *image = [self imageForIndex:aPage * MAX_THUMBNAILS + i];

        if (image) {
            imageView.image = image;
            imageView.hidden = NO;
        } else {
            imageView.hidden = YES;
        }
    }
}

- (UIImage *)imageForIndex:(int)anIndex
{
    if (anIndex < [images count]) {
        return [images objectAtIndex:anIndex];
    } else {
        return nil;
    }
}

#pragma mark -
#pragma mark user interface interaction

- (IBAction)onClose
{
    [self dismissModalViewControllerAnimated:YES];
}

- (IBAction)onNextThumbnails
{
    if (currentPage + 1 <= [images count] / MAX_THUMBNAILS) {
        currentPage++;
        [self setThumbnailsForPage:currentPage];
    }
}

- (IBAction)onPreviousThumbnails
{
    if (currentPage - 1 >= 0) {
        currentPage--;
        [self setThumbnailsForPage:currentPage];
    }
}

#pragma mark -
#pragma mark memory management

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

    [images release];
}

- (void)viewDidUnload
{
    [super viewDidUnload];

    [imageViews release];
    [fullScreenImage release];
}

- (void)dealloc
{
    [images release];
    [imageViews release];
    [fullScreenImage release];

    [super dealloc];
}

@end

The result:


text:
Q: Multiple instances of same foreign key in a single table I have a table that references the same foreign key multiple times (4 times) in the same table. Can someone explain why/how this makes sense?

A: Pedantically, A table doesn't reference a foreign key, it references a table via a foreign key.
It makes sense if it's necessary for the data model.
Here's an example. A Sales Order is associated with multiple parties playing different roles, such as the Selling Party, Customer Party, Paying Party, and Order Taking Party.
create table sales_order (
  order_id int primary key,
  seller_party_id int not null references parties(party_id),
  customer_party_id int not null references parties(party_id),
  order_taken_by_party_id int not null references parties(party_id),
  payer_party_id int not null references parties(party_id),
  ...
);

A: So, let's say that you have a company database with two tables, Employees and positions.  Let's say that Employees just contains employee id and username.  Positions could have position id, position name, employee fk, boss fk, and direct report fk.
So each record of positions has three fk's to the Employees table, each referencing a different employee id.
So in essence, you have have multiple foreign keys in a table to the same table, but they might mean something slightly different, but use the same reference data.


text:
Q: Unique solution for implicit multistep method for ODE There is an exercise I came across that I struggle with. Let $f: \mathbb{R}^2 \to \mathbb{R}^2$ be lipschitz continuous in the second argument. How to choose the step size $h$ in the $m$-step method $$ \sum_{k=0}^{m} \alpha_k u_{j+k} = h \sum_{k=0}^{m} \beta_k f(t_{j+k}, u_{j+k}) \quad j= 0, ..., n-m \qquad (1)$$ under the assumption $\beta_m \neq 0$ for the solution of the IVP $$ u'(t) = f(t,y), t > t_0$$ $$ u(t_0) = u_0$$ such that the system of equations in (1) can be uniquely solved for $u_{j+m}$?
I know that implicit methods can only be solved iteratively. Also, I was told to consider Banach's fixed-point theorem.  Nevertheless, I do not seem to get a grip on the general idea behind the exercise.


text:
Q: Floating Label style doesn't apply when FloatingLabelBehavior.always This is quite a straightforward problem. This floatingLabelBehavior was added almost 2 years ago but no one has raised an issue that if you set a specific style to floatingLabelStyle, it doesn't appear as the correct style unless you click on the field or when the field is focused.
Anyone found a solution to this? or should I just search for solutions on how to focus the fields automatically without showing soft keyboard?


text:
Q: No EJB found with interface I get this error when the EAR is deployed:

Caused by:
  org.jboss.as.server.deployment.DeploymentUnitProcessingException:
  WFLYEJB0406: No EJB found with interface of type
  'it.ejb32.ConverterBean' for binding
  it.webtest.SessionBeanTest/converterBean"},

Here's some code:

Interface

package it.ejb32;

public interface Converter {
   float celsiusToFahrenheit(float temperature);
   float fahrenheitToCelsius(float temperature);
}

ConvertBean

package it.ejb32;

import javax.ejb.Local;
import javax.ejb.Stateless;

@Stateless
@Local
public class ConverterBean implements Converter {

    public ConverterBean() {}

    @Override
    public float celsiusToFahrenheit(float temperature) {
        return temperature * 1.8f + 32;
    }

    @Override
    public float fahrenheitToCelsius(float temperature) {
        return (temperature - 32) / 1.8f;
    }
}

Servlet

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import it.ejb32.ConverterBean;

@WebServlet("/SessionBeanTest")
public class SessionBeanTest extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @EJB
    private ConverterBean converterBean;

    public SessionBeanTest() {}

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("Conversion test:"+ converterBean.celsiusToFahrenheit(Float.parseFloat(request.getParameter("p"))));
    }

}

Do I need to use @Inject the interface and not the bean?
Thank you


text:
Q: The size of byte buffer and the shape do not match I got this error and I don't know how to fix .I hope to help me to fix :
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.myapplication, PID: 17550
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.ResultActivity}: java.lang.IllegalArgumentException: The size of byte buffer and the shape do not match.
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
     Caused by: java.lang.IllegalArgumentException: The size of byte buffer and the shape do not match.
        at org.tensorflow.lite.support.common.SupportPreconditions.checkArgument(SupportPreconditions.java:104)
        at org.tensorflow.lite.support.tensorbuffer.TensorBuffer.loadBuffer(TensorBuffer.java:296)
        at org.tensorflow.lite.support.tensorbuffer.TensorBuffer.loadBuffer(TensorBuffer.java:323)
        at com.example.myapplication.ResultActivity.onCreate(ResultActivity.kt:57)
        at android.app.Activity.performCreate(Activity.java:7802)
        at android.app.Activity.performCreate(Activity.java:7791)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)

This is my code:
package com.example.myapplication

import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.TextView
import com.example.myapplication.ml.HeartDisease
import org.tensorflow.lite.DataType
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer
import java.nio.ByteBuffer

class ResultActivity : AppCompatActivity() {

    lateinit var textView : TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_result)

        textView  = findViewById(R.id.textView)

        var myintent :  Intent = intent

        val v1 = myintent.getIntExtra("v1",0)
        val v2 = myintent.getIntExtra("v2",0)
        val v3 = myintent.getIntExtra("v3",0)
        val v4 = myintent.getIntExtra("v4",0)
        val v5 = myintent.getIntExtra("v5",0)
        val v6 = myintent.getIntExtra("v6",0)
        val v7 = myintent.getIntExtra("v7",0)
        val v8 = myintent.getIntExtra("v8",0)
        val v9 = myintent.getIntExtra("v9",0)
        val v10 = myintent.getFloatExtra("v10",0.0f)
        val v11 = myintent.getIntExtra("v11",0)
        val v12 = myintent.getIntExtra("v12",0)
        val v13 = myintent.getIntExtra("v13",0)

        var byteBuffer : ByteBuffer =  ByteBuffer.allocateDirect(13*13)
        byteBuffer.putInt(v1)
        byteBuffer.putInt(v2)
        byteBuffer.putInt(v3)
        byteBuffer.putInt(v4)
        byteBuffer.putInt(v5)
        byteBuffer.putInt(v6)
        byteBuffer.putInt(v7)
        byteBuffer.putInt(v8)
        byteBuffer.putInt(v9)
        byteBuffer.putFloat(v10)
        byteBuffer.putInt(v11)
        byteBuffer.putInt(v12)

               val model = HeartDisease.newInstance(this)

               // Creates inputs for reference.
               val inputFeature0 = TensorBuffer.createFixedSize(intArrayOf(1, 13), DataType.FLOAT32)
               inputFeature0.loadBuffer(byteBuffer)

               // Runs model inference and gets result.
               val outputs = model.process(inputFeature0)
               val outputFeature0 = outputs.outputFeature0AsTensorBuffer

               startActivity(intent)

                // Releases model resources if no longer used.
               model.close()
    }
}


text:
Q: Gatsby GDPR cookies plugin not working - Google analytics script is missing in  section I spent a lot of time troubleshooting my problem. I want to check value of my own cookie using gatsby-plugin-gdpr-cookies. I hardcoded, that value of gatsby-gdpr-google-analytics is always true to demonstrate if plugin is working correctly. Problem is, that my website still doesn't have <script> for Google analytics in <head> section. Any Ideas how to solve this? I tried to move plugin on different levels in gatsby-config.js, but nothing worked.
This is my configuration:
plugins: [
    {
      resolve: `gatsby-plugin-gdpr-cookies`,
      options: {
        googleAnalytics: {
          trackingId: 'MY_TRACKING_ID',
          cookieName: 'gatsby-gdpr-google-analytics',
          anonymize: true,
          allowAdFeatures: false
        }
      },
      environments: ['production', 'development']
    },

A: Google recently applied some changes in their analytics API (migrated to v4) and it seems that some of the plugins haven't updated yet so they won't work. You will notice because the trackingId changed its format.
You can follow the stack trace in this GitHub thread (from the plugin's owner).
At this point, you can make some trials:

*

*Upgrade the dependency keeping in mind that it may won't work yet: npm upgrade gatsby-plugin-gdpr-cookies or yarn upgrade gatsby-plugin-gdpr-cookies

*Switching to the old analytics tracking: set it in your Analytics dashboard, get the new tracking identifier and use it in:
trackingId: 'OLD_TRACKING_ID',

*Swtich to another React-based approach using some other dependencies that supports the v4 tracking, such ga-4-react. You'll need to customize your <head> tag using <Helmet> component to add the tracking identifier. To avoid multiple instances of the same module, you may need to use some of the gatsby-browsers.js API, onClientEntry or onInitialClientRender should fit for your use-case:
exports.onClientEntry = () => {
   yourAnalyticsFunction()
}


text:
Q: Django: Mixed managed and raw db commits - TransactionManagementError I'm writing a bulk insert script using Django's ORM + custom raw SQL. The code has the following outline:
import sys, os
from django.core.management import setup_environ
from my_project import settings
from my_project.my_app.models import Model1, Model2
setup_environ(settings)
from django.db import transaction
from django.db import connection

@transaction.commit_manually
def process_file(relevant_file):

    data_file = open(relevant_file,'r')

    cursor = connection.cursor()

    while 1:
        line = data_file.readline()
        if line == '':
            break

        if not(input_row_i%1000):
            transaction.commit()

        if ([some rare condition]):
            model_1 = Model1([Some assignments based on line])
            model_1.save()

        values = [Some values based on line]
        cursor.execute("INSERT INTO `table_1` ('field_1', 'field_2', 'field_3') VALUES (%i, %f, %s)", values)

    data_file.close()
    transaction.commit()

I keep getting the following error:
django.db.transaction.TransactionManagementError: Transaction managed block ended with pending COMMIT/ROLLBACK

How can I solve this?

A: Use transaction.commit_unless_managed()
I've written a post to explain in greater detail with an example.

A: I started getting this exception in a similar circumstance. The django ORM was actually throwing a django.core.exceptions.ValidationError error because a date was incorrectly formatted. Because I was using manual transaction processing to batch database writes, the Django transactions processing code was trying to cleanup inside the raised django.core.exceptions.ValidationError exception and threw it's own exception of django.db.transaction.TransactionManagementError. Try a try / except around your model_1 code to see if any other exceptions are being thrown. Something like:
try:
    model_1 ...
    model_1.save()
except:
    print "Unexpected error:", sys.exc_info()[0]
    print 'line:', line

to see if there are any problems with the input data to object creation code.

A: You could try a workaround - place a transaction.commit() right after the model_1.save(). I think you need to isolate raw and ORM transactions.


text:
Q: Java switch case statement is returning different type of values(different data-type) and is assigned to same variable of type var Following is my code snippet:
Scanner sc = new Scanner(System.in);
int input = sc.nextInt();

var output = switch (input){
  case 1 -> "one";
  case 2 -> '2';
  case 3 -> 3.14;
  default -> 10;
};

System.out.println(output);

Now if I enter 1 as input, it prints "one", for 2 it prints '2', for 3 it prints 3.14 and for the rest it prints 10.
Does this mean datatype of output is decided at runtime according to the return type?

A: No, the output variable is always determined at compile time as explained here:

With var, the Java compiler infers the type of the variable at compile time, using type information obtained from the variable's initializer. The inferred type is then used as the static type of the variable.

In this particular case, it is a class implementing Serializable, Comparable, and Constable as you can see editing it in a modern ide

Note that this is not a generic Object. Infact you can't reassign the output variable to a generic Object like an ArrayList.
output = new ArrayList<String>());    // It doesn't compile

while you can reassign to any Comparable Constable and Serializable, for example to a Long
output = 10L;    // It compiles!

A: output is inferred to the closest common superclass of all of those types, which is the intersection of Comparable & Serializable. That's slightly more specific than Object, but probably not in a meaningful way in most cases.
Luckily System.out.println accepts any old Object, since it can toString() any possible arguments.
'2' is autoboxed to Character, 3.14 to Double and 10 to Integer.
So output.getClass() would return one of four distinct things.

A: The type of output is determined at compile time as something that is Serializable, Comparable and Constable, because that's the closest common ancestor to all of the result.
The object assigned to the variable is determined at runtime is one of String, Character, Double or Integer.

The actual compile type is Serializable & Comparable<? extends Serializable & Comparable<?> & Constable> & Constable (My IDE told me that!).


text:
Q: Famous Burning Ropes: Optimal Measuring in General Case well known riddle: given two ropes that each take an hour to burn (they do not burn uniformly or identically, necessarily) measure 45 minutes. solution: light 3 out of the 4 ends, and then light the 4th end when the first rope is totally burned up.
generalization (and the topic of discussion):
1) given an infinite number of such ropes, which times are measurable? Assume you can light each rope only a finite number of times.
2) additionally, what is the optimal strategy to measure a given amount of time, i.e. the fastest way to measure?
attempt at solution:
intro:
take the base 2 representation of any amount of time you wish to measure, where 1 represents 1 hour. to measure the time to the left of the decimal point burn the appropriate number of ropes sequentially. to the right of the decimal it gets trickier. for numbers less than 1 I believe it is possible to measure any finite linear combination of elements of the form "sum(1/2^i)" where i ranges from a natural number to infinity. I will sketch an algorithm/proof below.
gaps:
first define the number of gaps g(x) as the number of sequences of consecutive 0's bounded by 1's in the base 2 representation. for example g(.010101) = 2 and g(.0100010101) =3. Now actually modify this definition slightly - we do not count gaps bounded on the left by a 1 in the 1/2 slot, e.g. g(.101) = 0 and g(.10010101) = 2. the intuition here is that measuring 1/2 is as simple as measuring 1 - we can instantly measure 1/2 by burning 2 ends of one rope, whereas smaller numbers require some lead up time, e.g. you must measure 1/2 before you can measure 1/4.
measurement sequence:
note that to measure 1/2^k for k > 1 you must first measure 1/2, 1/4,.., 1/2^(k-1)
convince yourself of this or tell me why I am wrong. from now on I will refer to the sequence of measurements 1/2, 1/4,.., 1/2^k as the "measurement sequence" for 1/2^k.
sketch of an algorithm that takes approximately n hours to measure x, where x<1 and g(x)=n:
1) rewrite x as a sum of numbers with 0 gaps, e.g. .010101 = .01 + .0001 + .000001
2) to measure 1/2^k takes 1-(1/2^k) amount of time, so it seems you should start the "measurement sequence" (1/2, 1/4, ..., 1/2^k) for the smallest number first. Likewise you should start the measurement sequence for the 2nd smallest number a tad later, and so on.
3) You now have g(x) "measurement sequences" that you need to time correctly. continuing with the example: you want to measure .01 immediately followed by .0001 immediately followed by .000001 (note, it seems you should measure the smallest number last since it will have the most expensive "measurement sequence").
notice, the measurement sequence for .0001 should start .00001 after the measurement sequence for .000001. We can time this delay using a measurement sequence for .00001 - let's call this a coordination sequence since it allows us to coordinate a delay between two measurement sequences.
4) we started out with 3 measurement sequences, and obtain two coordination sequences - one coordination sequence to make sure the 2nd measurement sequence starts .00001 after the 1st, and one coordination sequence to make sure the 3rd measurement sequence starts .001 after the 2nd. Now we need to coordinate the two coordination sequences with a "coordination^2" sequence - convince yourself or tell me I'm wrong.
5) convince yourself that for g(x) = n we get n measurement sequences, which we need to coordinate with n-1 coordination sequences, which we need to coordinate with n-2 coordination^2 sequences... which we need to coordinate with 1 coordination^(n-1) sequence, and that the whole process of coordinating and finally measuring takes a little less than n hours.
Under this algorithm, it seems we can measure any time, except times x such that g(x)=infinity. Is there a faster algorithm for measuring different times? Have I properly classified the set of measurable times? Thanks. I know my explanation is not super clear; ready to clarify any points.

A: "We can time this delay using a measurement sequence for .00001" -- this is not obvious for me... However, I agree that the set of measurable times consists of times which have finite binary expansion. Indeed:
on one hand, we can only light an end at a time measured by other ropes, and since the rope is burned up at the time $(t_1+t_2+1)/2$ (where $t_1$ and $t_2$ are the times when the ends were lighted), any one rope allows us to go only one binary digit deeper, so no numbers with infinite binary expansion can be measured by arbitrary large but finite number of ropes (infinite number of ropes with finite time won't help, too);
on the other hand, with $k$ ropes we can easily measure the time $1-2^{-k}$ from the moment when we begin burning the first of these $k$ ropes, so if we measure $g(x)$ such intervals one after another (in any order) while simultaneously burning $g(x)$ whole ropes one after another, the latter process will be exactly $x$ longer than the former, so any number $x$ with finite binary expansion can be measured.


text:
Q: Is the determinant equal to a determinant? Let $\det_d = \det((x_{i,j})_{1 \leq i,j\leq d})$ be the determinant of a generic $d \times d$ matrix. Suppose $k \mid d$, $1 < k < d$. Can $\det_d$ be written as the determinant of a $k \times k$ matrix of forms of degree $d/k$?
Even writing $\det_4$ as the determinant of a $2 \times 2$ matrix of quadratic forms seems impossible, just intuitively. The space of $2 \times 2$ matrices of quadratic forms in $16$ variables has dimension $4 \cdot \binom{17}{2} = 544$, while the space of quartics in $16$ variables has dimension $\binom{19}{4} = 3876$.

A: The answer is that if $1 < k < d$, then such a matrix is equivalent to a diagonal matrix with $\det(x_{ij})=: D$ on the diagonal and the rest of the diagonal entries equal to $1$. This does not require that $k$ divides $d$.
The reason is the following: If $M$ is a $k\times k$ matrix with entries from the polynomial ring $S$ in the $x_{ij}$ over some field and $\det M = D$, then the cokernel of $M$, viewed as an $S$-linear map from $S^k$ to $S^k$  defines a maximal Cohen--Macaulay module of rank one over the hypersurface ring $R=S/(D)$, generated by at most $k$ elements. For this statement see Eisenbud's paper MR0570778 (82d:13013).
In the book by Bruns and Vetter on determinantal rings MR0953963 (89i:13001) all reflexive modules of rank one over a determinantal ring are determined and in the situation here they show that only the cokernel of the generic matrix itself or its transpose gives a nontrivial maximal Cohen-Macaulay module of rank one.
However these need at least $d$ generators.
The trivial module is just $R$ itself and in terms of matrices it means that $k<d$ implies that $M$ is equivalent to a diagonal matrix with $D$ on the diagonal and the rest of the diagonal filled up by $1$'s. (The case I neglected in my original posting...)
Another interesting source for similar questions (and some answers) is the article by G. Bergman MR2205070 (2006k:15037).

A: I will work over a field of characteristic $0$ so that reductive algebraic groups are linearly reductive; presumably there is a way to eliminate this hypothesis.  In this case, for an integer $n>1$ and for a divisor $m$ such that $n>m>1$, there does not exist $f$ as above.  The point is to consider the critical locus of the determinant.  The computation below proves that "cohomology with supports" has cohomological dimension equal to $2(n-1)$ for the pair of the quasi-affine scheme $\textbf{Mat}_{n\times n} \setminus \text{Crit}(\Delta_{n\times n})$ and its closed subset $\text{Zero}(\Delta_{n\times n})\setminus \text{Crit}(\Delta_{n\times n})$.  Since pushforward under affine morphisms preserve cohomology of quasi-coherent sheaves, that leads to a contradiction.
Denote the $m\times m$ determinant polynomial by $$\Delta_{m\times m}:\textbf{Mat}_{m\times m} \to \mathbb{A}^1.$$  For integers $m$ and $n$ such that $m$ divides $n$, you ask whether there exists a homogeneous polynomial morphism $$f:\textbf{Mat}_{n\times n}\to \textbf{Mat}_{m\times m}$$ of degree $n/m$ such that $\Delta_{n\times n}$ equals $\Delta_{m\times m}\circ f$.  Of course that is true if $m$ equals $1$: just define $f$ to be $\text{Delta}_{n\times n}$.  Similarly, this is true if $m$ equals $n$: just define $f$ to be the identity.  Thus, assume that $2\leq m < n$; this manifests below through the fact that the critical locus of $\Delta_{m\times m}$ is nonempty.  By way of contradiction, assume that there exists $f$ with $\Delta_{n\times n}$ equal to $\Delta_{m\times m}\circ f$.
Lemma 1. The inverse image under $f$ of $\text{Zero}(\Delta_{m\times m})$ equals $\text{Zero}(\Delta_{n\times n})$.  In other words, the inverse image under $f$ of the locus of matrices with nullity $\geq 1$ equals the locus of matrices with nullity $\geq 1$.
Proof. This is immediate. QED
Lemma 2. The inverse image under $f$ of the critical locus of $\Delta_{m\times m}$ equals the critical locus of $\Delta_{n\times n}$.  In other words, the inverse image under $f$ of the locus of matrices with nullity $\geq 2$ equals the locus of matrices with nullity $\geq 2$.
Proof.
By the Chain Rule, $$d_A\Delta_{n\times n} = d_{f(A)}\Delta_{m\times m}\circ d_Af.$$  Thus, the critical locus of $\Delta_{n\times n}$ contains the inverse image under $f$ of the critical locus of $\Delta_{m\times m}$.  Since $m\geq 2$, in each case, the critical locus is the nonempty set of those matrices whose kernel has dimension $\geq 2$, this critical locus contains the origin, and this critical locus is irreducible of codimension $4$.  Thus, the inverse image under $f$ of the critical locus of $\Delta_{m\times m}$ is nonempty (it contains the origin) and has codimension $\leq 4$ (since $\textbf{Mat}_{m\times m}$ is smooth).  Since this is contained in the critical locus of $\Delta_{n\times n}$, and since the critical locus of $\Delta_{n\times n}$ is irreducible of codimension $4$, the inverse image of the critical locus of $\Delta_{m\times m}$ equals the critical locus of $\Delta_{n\times n}$. QED
Denote by $U_n\subset \text{Zero}(\Delta_{n\times n})$, resp. $U_m\subset \text{Zero}(\Delta_{m\times m})$, the open complement of the critical locus, i.e., the locus of matrices whose kernel has dimension precisely equal to $1$. By Lemma 1 and Lemma 2, $f$ restricts to an affine morphism $$f_U:U_n\to U_m.$$
Proposition. The cohomological dimension of sheaf cohomology for quasi-coherent sheaves on the quasi-affine scheme $U_n$ equals $2(n-1)$.
Proof.
The quasi-affine scheme $U_n$ admits a morphism, $$\pi_n:U_n \to \mathbb{P}^{n-1}\times (\mathbb{P}^{n-1})^*,$$ sending every singular $n\times n$ matrix $A$ parameterized by $U_n$ to the ordered pair of the kernel of $A$ and the image of $A$.  The morphism $\pi_n$ is Zariski locally projection from a product, where the fiber is the affine group scheme $\textbf{GL}_{n-1}$.  In particular, since $\pi_n$ is affine,  the cohomological dimension of $U_n$ is no greater than the cohomological dimension of $\mathbb{P}^{n-1}\times (\mathbb{P}^{n-1})^*$.  This equals the dimension $2(n-1)$.
More precisely, $U_n$ is simultaneously a principal bundle for both group schemes over $\mathbb{P}^{n-1}\times(\mathbb{P}^{n-1})^*$ that are the pullbacks via the two projections of $\textbf{GL}$ of the tangent bundle.  Concretely, for a fixed $1$-dimension subspace $K$ of the $n$-dimensional vector space $V$ -- the kernel -- and for a fixed codimension $1$ subspace $I$ -- the image -- the set of invertible linear maps from $V/K$ to $I$ is simultaneously a principal bundle under precomposition by $\textbf{GL}(V/K)$ and a principal bundle under postcomposition by $\textbf{GL}(I)$.  In particular, the pushforward of the structure sheaf, $$\mathcal{E}_n:=(\pi_n)_*\mathcal{O}_{U_n},$$ is a quasi-coherent sheaf that has an induced action of each of these group schemes.
The invariants for each of these actions is just $$\pi_n^\#:\mathcal{O}_{\mathbb{P}^{n-1}\times (\mathbb{P}^{n-1})^*}\to \mathcal{E}_n.$$  Concretely, the only functions on an algebraic group that are invariant under pullback by every element of the group are the constant functions.  The group schemes and the principal bundle are each Zariski locally trivial.  Consider the restriction of $\mathcal{E}_n$ on each open affine subset $U$ where the first group scheme is trivialized and the principal bundle is trivialized. The sections on this open affine give a $\mathcal{O}(U)$-linear representation of $\textbf{GL}_{n-1}$. Because $\textbf{GL}_{n-1}$ is linearly reductive, there is a unique splitting of this representation into its invariants, i.e., $\pi_n^\#\mathcal{O}(U)$, and a complementary representation (having trivial invariants and coinvariants).  The uniqueness guarantees that these splittings glue together as we vary the trivializing opens.  Thus, there is a splitting of $\pi_n^\#$ as a homomorphism of quasi-coherent sheaves, $$t_n:(\pi_n)_*\mathcal{O}_{U_n} \to \mathcal{O}_{\mathbb{P}^{n-1}\times (\mathbb{P}^{n-1})^*}.$$
For every invertible sheaf $\mathcal{L}$ on $\mathbb{P}^{n-1}\times (\mathbb{P}^{n-1})^*$, this splitting of $\mathcal{O}$-modules gives rise to a splitting, $$t_{n,\mathcal{L}}:(\pi_n)_*(\pi_n^*\mathcal{L})\to \mathcal{L}.$$  In particular, for every integer $q$, this gives rise to a surjective group homomorphism, $$H^q(t_{n,\mathcal{L}}):H^q(U_n,\pi_n^*\mathcal{L}) \to H^q(\mathbb{P}^{n-1}\times (\mathbb{P}^{n-1})^*,\mathcal{L}) .$$
Now let $\mathcal{L}$ be a dualizing invertible sheaf on $\mathbb{P}^{n-1}\times (\mathbb{P}^{n-1})^*.$  This has nonzero cohomology in degree $2(n-1)$.  Thus, the cohomological dimension of sheaf cohomology for quasi-coherent $\mathcal{O}_{U_n}$-modules also equals $2(n-1)$. QED
Since $f_U$ is affine, the cohomological dimension for $U_n$ is no greater than the cohomological dimension for $U_m$.  However, by the proposition, the cohomological dimension for $U_m$ equals $2(m-1)$.  Since $1<m<n$, this is a contradiction.

A: I think a result of Hochster allows to get a quick proof that it is not possible to express the determinant of the generic $d \times d$ matrix as the determinant of a $k \times k$ matrices with entries being homogeneous forms of degree $\dfrac{d}{k}$, provided that $1 <k <d$.
I will work over an algebraically closed field.
Relying on some cohomological methods (similar to the ones Jason Starr is using in his answer), Hochster proved that the variety of $n \times n$ matrices with $\textrm{rank} < n-1$ can be set-theoretically defined by $2n$ equations and not less (see this paper by Bruns and Schwänzl for some improvement of Hochster's result : http://www.home.uni-osnabrueck.de/wbruns/brunsw/pdf-article/NumbEqDet.published.pdf).
Now, we proceed by absurd. Assume that the determinant of the generic $d \times d$ matrix can be written as the determinant of $k \times k$ matrix (say $A$) with forms homogeneous of degree $\dfrac{d}{k}$. We assume $1 < k < d$. We denote by $P_1, \ldots, P_{k^2}$ the entries $A$, which are homogeneous polynomials in $x_1, \ldots, x_{d^2}$ of degree $\dfrac{d}{k}$.
Let $B$ be the generic $k \times k$ matrix with entries $Y_1, \ldots, Y_{k^2}$. Denote by $Q_1, \ldots Q_{k^2}$ the $k-1$ minors of $B$. The variety defined by the vanishing of the $\{Q_i\}_{i=1\ldots k^2}$ is non-empty of codimension $4$ in $\mathbb{A}^{k^2}$ (here I use that $k>1$). Hence, if we replace $Y_i$ by $P_i(x_1, \ldots, x_{d^2})$, we see that the scheme defined by the vanishing of the $\{Q_i(P_1,\ldots,P_{k^2})\}_{i=1 \ldots k^2}$ has codimension at most $4$ in $\mathbb{A}^{d^2}$.
Furthermore, a simple computation of partial derivatives shows that the scheme defined by the vanishing of the  $\{Q_i(P_1,\ldots,P_{k^2})\}_{i=1 \ldots k^2}$ is included in the singular locus of the variety defined by $\det A = 0$. But $\det A$ is the determinant of the generic $d \times d$ matrix, so that its singular locus is the variety of matrices of $\textrm{rank} < d-1$ : it is irreducible of codimension $4$ in $\mathbb{A}^{d^2}$.
From the above, we deduce that the variety of $d \times d$ matrices of $\textrm{rank} < d-1$ is set-theoretically equal to the scheme defined by the
 $\{Q_i(P_1,\ldots,P_{k^2})\}_{i=1 \ldots k^2}$.
By Hochster's result  (the existence part), one can find $2k$ polynomials (say $T_1, \ldots, T_{2k}$) in the ideal generated by $Q_1, \ldots, Q_{k^2}$ such that $$\textrm{rad}(T_1, \ldots, T_{2k}) = \textrm{rad}(Q_1, \ldots, Q_{k^2}).$$
Replacing $Y_i$ by $P_i(x_1,\ldots, x_{d^2})$ in the $\{T_j\}_{j=1 \ldots 2k}$, we find that the vanishing of the $\{T_j(P_1, \ldots, P_{k^2}) \}_{j=1 \ldots 2k}$ defines set-theoretically the variety of $d \times d$ matrices of $\textrm{rank} < d-1$. Since $2k < 2d$, we get a contradiction with Hochster's result.

A: This is not an answer, but it is to big to be a comment.
Let me write your matrix $X$ blockwise $(M_{\alpha\beta})_{1\le\alpha,\beta\le k}$, where the blocks are $k/d\times k/d$. If the blocks $M_{\alpha\beta}$ commutte to each other, then
$$\det X=\det((d_{\alpha\beta})_{1\le\alpha,\beta\le k}$$
where $d_{\alpha\beta}:=\det M_{\alpha\beta}$.
A particular case of this property is the formula $\det(A\otimes B)=(\det A)^m(\det B)^n$ where $m$ is the size of $B$, $n$ that of $A$ (Thanks to Suvrit !).
As for the general case, I guess that the answer to your question is negative.

A: As others fascinatingly settled negative answer for the general question,
let me give a comment on certain situation when the answer is positive.
So if one has dxd matrix and d=k*n, we may split the matrix into nxn matrix which elements are kxk matrices. Now the statement is -  if these elements satisfy certain commutation relations (i.e. elements in each column commutate and cross-diagonal commutators are equal - see Manin matrix),
then $det_d = det_k det_n $ - i.e. first calculate determinant for nxn matrix whose elements are matrices - get a kxk matrix as an answer and then
calculate usual kxk determinant of the later.
(See section 5.5 page 36 here - sorry for self-advertising ).


text:
Q: Can kibana connect with data sources other than elastic search? Can Kibana connect with data sources other than elastic search and build visualizations on the data in other data sources ?
More specifically I am looking to connect Kibana with Hive.

A: No you cannot connect Kibana directly but you can connect Elasticsearch to hadoop.
using es-hadoop see https://www.elastic.co/products/hadoop
Similarly you can connect other datasources to elasticsearch like Logstash, es-hadoop or 3rd party technologies like Apache Flume, Fluentd, and many others.
see - https://www.elastic.co/products/kibana


text:
Q: Access to stage timing through API In the Stage View plugin, we can see on each of the stages a timestamp that displays number of seconds for the stage, and number of seconds spent waiting within that stage. This is kind of interesting data but I haven't figure out where we may be able to access it outside of the display on the single pipeline. If we want to use these times in our own metrics program, say to measure trends over multiple pipelines and/or projects, is it accessible externally somehow?

A: You can use the existent JSON API: http://[JENKINS_HOST]/job/test/[BUILD_NUMBER]/wfapi/describe
There is timing information in the response.


text:
Q: stopping content from 'jumping' when navbar fixes to top of screen I have a site that utilizes the Bootstrap 3 navbar. It is positioned 280px below a block div and sticks to the top of the page when scrolled to that point
HTML  ( in  tags )

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Header

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

Content content content

A: Don't create a custom class like sticky for it use navbar-fixed-top class like,
if (windowpos >= pos.top) {
    s.addClass("navbar-fixed-top");
} else {
    s.removeClass("navbar-fixed-top");
}

Refer

A: I had this issue too recently. I solved it by putting a position:absolute div behind my nav and using that as my scroll point reference for the addClass. Honestly I'm not quite sure why it worked, but it did!


text:
Q: MySQL slow query log file time elapse Does anybody know when the mysql slow log file delete slow query records?
based on my daily observation. The log file starts at 7am. I have searched for this but nothing answers me clearly. My server version if 5.6.14. Thank you.

A: This is probably done by your log rotation software. On my Ubuntu machine its defined in /etc/logrotate.d/mysql-server.
logrotate is run daily by a cron job. Take a look in /etc/crontab. In my case I have the following:

25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )

So daily jobs get run at 6:25AM.
I also have a file /etc/cron.daily/logrotate which configures log rotate as a daily job.
Most Linux installations would have something similar. If you're running on Windows I'm afraid I have no idea.

A: Never.  It just grows and grows.  All the more reason to fix the slow queries.
(Or you could do something to delete the file.  Of course it will come back.)


text:
Q: What's the difference between "used to like" and 'liked'? What is the difference between used to like and liked?
What is the difference if I say...

When I was 4 years old, I had one pink dress. My cousins used to like it (my dress) very much.

Or

When I was 4 years old, I had one pink dress. My cousins liked it (my dress) very much.

A: It depends on the context or else both quite mean the same. But first, let's clear the definition of used to -

used to - (takes an infinitive or implied infinitive) used as an auxiliary to express habitual or accustomed actions, states, etc, taking place in the past but not continuing into the present.

and liked is a simple word, the past tense of *like.
Let me think of an example to clarify it.

I had a pink dress which I wore on my cousin's wedding ceremony. She liked it very much. = It could be for that one time occasion. She liked the dress and that's it!

On the other hand,

I had a pink dress. My cousin used to like it very much. = Whenever/every time she would meet me, she'd recall that dress. It's not a one time 'liking'.

Also, consider what others said and the dictionary mentions - if your cousin used to 'like' it, she does not like it anymore.

A: *

*used to like it -> it often implies that they don't like it anymore.

*liked it: -> no implication: maybe they still like it.

A: In these contexts both are very similar and could mean that they still do like it, or they don't. It's not so defined here.
The greater relevance is inside using either of these forms.
Used to like refers to a repetition of action in the past - here they saw the dress on various occasions and perhaps, wore the dress as well.
Liked is more matter of fact in the past - maybe they only saw the dress once!
Hope this helps!

A: 'Used to like' means they stopped liking it for some reason. 'Liked' has no such connotation. An example would be the Guns and Roses lyric: 'I used to love her, But I had to kill her...'