text:
Q: How can i get the content of a subview in a UiScrollview I have a UIScrollview in a tab, i added some UIView (NIB) to the UIScrollview. Each UIView has some UISwictch, labels, buttons, etc. How can i get the the label.text inside of the view added to the UIScrollview.
I tried a lot of things but i can access to the content of the UIView added to the UIScrollview.

A: Check with this,
for (UIView *addedView in [self.scrollView subviews])
{
        for (UIView *sub in [addedView subviews])
        {
            if([sub isKindOfClass:[UILabel class]])
            {
                UILabel *myLabel = (UILabel *)sub;
                NSLog(@"My label :%@",myLabel .text);
            }
        }
}

Here scrollView  is your scroll view. It will print all label's text.
If you need to print any particular label's text. Then add a tag to it and check the tag before printing it, like if(myLabel.tag == 7)

A: set a unique tag for your label.
eg: label.tag = 10345 (some random number, which is a unique tag)
and you can search for the label in the parentView like this
UILabel *theLabel = (UILabel *)[parentView viewWithTag: 10345];

and then you can do what ever you want with the Label.

A: Step 1: Add this code in your scrollview
UITapGestureRecognizer *singleTapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTap:)];
singleTapGestureRecognizer.numberOfTapsRequired = 1;
singleTapGestureRecognizer.enabled = YES;
singleTapGestureRecognizer.cancelsTouchesInView = NO;
[scrollView addGestureRecognizer:singleTapGestureRecognizer];

Step 2: Implement this method
-(void)singleTap:(UITapGestureRecognizer *)gesture
 {
    // Convert gesture into view for getting subviews
    CGPoint point = [gesture locationInView:mainScrollView];
    UIView *tappedView = [mainScrollView hitTest:point withEvent:nil];

    // Get the subviews of the view
    NSArray *subviews = [view tappedView];

    // Return if there are no subviews
    if ([subviews count] == 0) return;

    for (UIView *subview in subviews) {

        NSLog(@"%@", subview);

        // List the subviews of subview
        [self your_method:subview];
    }
}


text:
Q: Is it possible to run javascript code based on template variables in Tornado? If a handler returns a variable along with a template:
self.render('page.html', enabled=enabled)

where enabled is a boolean variable.
So far I know I can do things like:
{% if enabled %}
    ...
{% end %}

within the HTML part of the template.
But can we conditionally run some javascript code based on this enabled variable in the Tornado template? In other words, can we access the value of this variable in javascript embedded in the template?

A: Of course - Whatever is in the template between the {% if ... %}  and the  { % end %} directives will only be sent to the browser in case the if the expression is True. So, anything in there, be it a <script > tag with inline javascript, or a <link> tag  importing a javascript file from somewhere will only be transmited over the network in that case.
You could even place a template if or fordirective inside Javascript code itself, to enable or disable parts of code based on conditions known to the server code. This, unlinke embedding or not a whole piece of code, I think would not be considered a good pratice - because it would entangle the server and client sides of your code in undesirable ways.
To access the variable from javascript, just do:

    var enabled = {{ enabled }};

The value inside the {{...}} marker is rendered with the server variable.
In this case, to ensure the value in enabled to be compatible across Python and Javascript, you should  use the number 0 for False and 1 for True (because if you use Python booleans, the template will render as
var enabled = True; - which is not what javascript would expect, as the reserved "true" in Javascript is lowercase)
The only restriction is that you can only set teh server-side variables before the page is sent to the browser. So, if you need to set any any variable on the server side that depends on user's action on the page displayed, this way of doing things won't cut it anymore (only with a page reload). the way to make a page to be interactvely  updated without reloading is to rely on asynchronous comunications from javascript (formerly known exclusively as "ajax").
edit - The O.P further asked:

here is a problem: when I return a string variable such as
  myvar='foo-bar' to the template, and when this {{myvar}} get evaluated
  in JS code, JS apparently interprets foo-bar as a variable name
  instead of a string. In this case, it will cause error because -
  denotes subtraction. How do I make JS recognize foo-bar as a string
  value?

Again, what is going on is quite simple: the {{ <expr>  }} template operator inserts the
string representation of the rsulting expression - so if you have in python
myvar = "bla" and on the template var myvar = {{ myvar }}, that gets rendered (and sent to the client browser this way) as var myvar = bla - without quotes around bla - that's why javascript treats it as a variable name. The workarounds for this are putting extra quotes around your variable, if it is a string, either on Python side or on the template.
On the template you can do:
var myvar="{{ myvar }}" - or, on the Python side, when defining myvar: myvar = '"%s"' % "bla"

redpajama_set_name: RedPajamaStackExchange


text:
Q: Spatial Join Layer Derived from Zonal Raster on Original Polygon I'm trying to do a 1:1 spatial join between polygons created from the zonal max of a slope raster on the original zonal features. The problem is that the jagged edges cause the target features to overlap neighboring polygons as well so it just uses the first join feature in the 1:1 join.

So basically, in this picture, I want to use a spatial join to add the grid code 300 from the blue layer to the polygon (red outline) on the right and 100 to the polygon on the left. The overlap from the jagged lines are causing it to assign whichever value is first instead of whichever one has the greatest overlap.

A: In the screen shot you have given I think this can be easily done with a spatial join. You just need to set the match option to HAVE_THEIR_CENTER_IN. Be mindful that if you have tortuous shapes with holes in then this may fail for those scenarios.

A: I ended up creating a temporary unique id and doing a tabular join (Join Field) between the table I created via zonal statistics and the original polygon layer.


text:
Q: iOS: UIScrollView zooming programmatically not working I have a pageable UIScrollView which contains different kind of informations like UITables but also zoomable images. Therefore I set up a pageable main-ScrollView and as subviews I added zoomable image-ScrollViews with the images as content.
Works everything fine, just I fail to set the smaller current zoom scale of the imageScrollViews.
UIImageView *imageView = [[UIImageView alloc] initWithImage:Image];

//storing a link to the imageView
[imagelinkArray addObject:imageView];

CGRect ScrollViewImageRect;
ScrollViewImageRect = CGRectMake((self.scrollView.frame.size.width) * i, 0, 320, self.scrollView.frame.size.height);

float widthfactor = ScrollViewImageRect.size.width / imageView.frame.size.width;
float heightfactor = ScrollViewImageRect.size.height / imageView.frame.size.height;
float zoomscale = MIN(widthfactor, heightfactor);

UIScrollView *imageScrollView = [[UIScrollView alloc] initWithFrame:ScrollViewImageRect];
imageScrollView.contentSize = CGSizeMake(imageView.frame.size.width, imageView.frame.size.height);

imageScrollView.delegate = self;

[imageScrollView setMinimumZoomScale:zoomscale];
[imageScrollView setMaximumZoomScale:1.5];

[imageScrollView addSubview:imageView];

//doesn't work:
[imageScrollView setZoomScale:0.5 animated:YES];

[self.scrollView addSubview:imageScrollView];

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return [imagelinkArray objectAtIndex:page];
}

The main-ScrollView and the image-ScrollViews are drawn perfectly and it's possible to zoom and page properly. The minimum zoom factor is calculated also correct. When I zoom out I can zoom until the image limits are reached. However the first time I page to the image-ScrollView it's current zoom scale is always 1.0 while it should be the minimum scale.
Wherever I set the zoom scale in the code above it doesn't work:
[changeScrollView setZoomScale:changeScrollView.minimumZoomScale animated:YES];

If I log the current zoom scale i always get 1.0;
The only thing which works is changing the zoom scale in the - (void)scrollViewDidScroll: method, which of course doesn't help a lot since zooming also calls it which resets the zoom immediately. But at least I could figure out, that the code somehow works. I have the feeling a UIScrollView doesn't zoom when it's not visible on the screen right now. How can I fix this?
Update:
Okay. In the meantime I figured out that the problem most likely comes from my base layout of "sub-viewing" ScrollViews into another ScrollView. When I zoom one of the images and log the current zoom factor of the ScrollViews they are all the same (main ScrollView as well as ALL sub-ScrollViews).
What could be the reason for it or how could I solve it with a different layout?

A: I think viewForZoomingInScrollView: may not be getting called by the scrollview. Try to add a breakpoint and check what you're returning there.

A: Your code doesn't work because you havent set minimumZoomScale ,which has default value of 1.0 . Since you are trying to set 0.5 which is below the default value, it wouldn't work.
Add following line just after the line which sets maximumZoomScale.
[imageScrollView setMinimumZoomScale:0.25];

A: As user Rivera pointed out the return value of viewForZoomingInScrollView: was off course not right.
I always returned the current visible page shown in the scrollView. Which means setting the zoom in viewDidAppear doesn't change anything.
Here is the correct code: I made a function which will always resets both images left and right of the current visible scroll page:
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self updateImageSize];
}

- (void)updateImageSize
{
    updatePage = updatePage + 1;

    if (updatePage < imagescrolllinkArray.count) {
        UIScrollView *changeScrollView = (UIScrollView*)[imagescrolllinkArray objectAtIndex:updatePage];
        [changeScrollView setZoomScale:changeScrollView.minimumZoomScale];
    }

    updatePage = updatePage - 2;

    if (updatePage > -1) {
        UIScrollView *changeScrollView = (UIScrollView*)[imagescrolllinkArray objectAtIndex:updatePage];
        [changeScrollView setZoomScale:changeScrollView.minimumZoomScale];
    }

    //reset to current view
    updatePage = updatePage + 1;
}

- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView
{
    return [imagelinkArray objectAtIndex:updatePage];
}

and in viewDidAppear I added the following to update the first image before any dragging.
if (i == 1) {
    updatePage = 0;
    [imageScrollView setZoomScale:imageScrollView.minimumZoomScale];
}

A: In the meantime I figured out that the code below can under certain circumstances make problems. Sometimes when I zoom in and out from an image the main ScrollView can't be scrolled anymore, so there is no way to get to the next image, except of triggering the pageControl or except of zooming into the image and then scrolling to its borders so the main ScrollView jumps to the next page.
Means the problem only occurs when the image is fully zoomed out (.scale = .minimumscale). I don't understand exactly when and why it happens. Logging viewDidScroll returns nothing in this situations.
Anybody experienced similar problems?


text:
Q: Only CSS rotate box-shadow without original element I have a small problem, I want to create 45 degree shadow for a picture. But if I use my code my object is rotating too. So I would like to ask for help with this problem.
My code:
.item {
    box-shadow: -50px 80px 4px 10px #555;
    -webkit-transform: rotate(10deg);
    -moz-transform: rotate(10deg);
    -o-transform: rotate(10deg);
    -ms-transform: rotate(10deg);
    transform: rotate(10deg);
}

A: Most flexible answer using only CSS is probably this:
.item {
    position: relative; /* or absolute */
}

.item:before {
    content: "";
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: transparent;

    box-shadow: -50px 80px 4px 10px #555;
    -webkit-transform: rotate(10deg);
    -moz-transform: rotate(10deg);
    -o-transform: rotate(10deg);
    -ms-transform: rotate(10deg);
    transform: rotate(10deg);
}

A: You can do it using peudo-element (I've used arbitrary values, you need to tweak it yourself) :

.item {
  margin-left: 50%;
  position: relative;
  width: 100px;
  height: 100px;
  background-color: red;
}
.item:before {
  z-index: -1;
  position: absolute;
  content: "";
  display: block;
  width: 100px;
  height: 100px;
  top: -30px;
  left: 0;
  background-color: transparent;
  box-shadow: -50px 120px 4px 10px #555;
  -webkit-transform: rotate(10deg);
  -moz-transform: rotate(10deg);
  -o-transform: rotate(10deg);
  -ms-transform: rotate(10deg);
  transform: rotate(10deg);
}


text:
Q: Max number of permutations of a dynamic field name across documents in solr? Let's say my solr schema has 9 predefined fields and 1 dynamic field like this:
<dynamicField name="*_i" type="int" indexed="true" stored="true" docValues="true"/>

Also, for this question only a single "*_i" prefix will be used on each document so that the total count of fields on every solr document is always 10.  But what if the prefix which is used varies widely across the documents?  To give an example, what if I create a hundred million solr documents (again, each with only 10 total fields) and there was a million different prefixes used across them for that dynamic field.
This would be for solr 6.x and any solr searches would always be filtering on some of the other predefined fields (like a group_id field) plus the dynamic field.  Let's also assume that knowing which dynamic field to use in the solr search has been figured out.
What are the implications of that kind of set up?  Does solr care more about how many fields exist on each document vs the cardinality of the dynamic field names themselves across documents?


text:
Q: jQuery Mobile nested listview weird behaviour + back button exit I am pretty new to jQuery Mobile.
I encountered some weird behaviour with my code when I deploy my app on my android phone.
For the first problem, my web application got exit when I press the physical back button.
How do I prevent my app from exiting when I press the physical backbutton?
I want my app to get back to the previous page when I press the backbutton.
For the second problem,
I am reading in some xml data and parsing them into a listview.
This occurs with the onload function which is called when I press the pizza button.
However, only the first result get listed out in the listview.
Any one can help with my problems?
Pastebin of my html code : http://pastebin.com/RYcF6eBn
<!DOCTYPE html>

        <meta charset="ISO-8859-1">
        <title>IS3261 Project</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" type="text/css" media="all" />

Food Delivery @SG

                 Pizza

                 Fast Food.

                 Indian Food

                 Korean Food

                 Restaurant

List of Pizza deliverer

            Back

Korean

A: This is how you can handle back button issue.
function onDeviceReady()
{
    // Register the event listener
    document.addEventListener("backbutton", onBackKeyDown, false);
}

//Handle back button press
function onBackKeyDown()
{
    navigator.app.backHistory();
}

This will take the user to previous page available in history.
No idea so far about your second issue.


text:
Q: How to add/change a variable across django test functions This question might be silly, but I did not find an answer.
I want to add a test function to a class of TestCase to check the completion of the test. For example, the urls were tested, the forms were tested et.al. As such, I would like to have a variable to keep the record of each test. If urls were tested, then VARIABLE["urls"] = True.
Unfortunately, it looks like all the variable were reset in each test function. The message recorded in urls test VARIABLE["urls"] can not been carried on to one other test. Is there any way to have a global variable across all test functions?
Here are the revised working code
class Test(TestCase):
    test = {}
    to_be_test = ["urls","ajax","forms","templates"]

    def test_urls(self):
        ...
        self.test['urls'] = True

    def test_ajax(self):
        ...
        self.test['ajax'] = True

    def test_z_completion(self):
        for t in self.to_be_test:
            if not t in self.test:
                print "Warning: %s test is missing!" % t

The expected result should be:
Warning: forms test is missing!
Warning: templates test is missing!

A: How about a class level attribute?
import unittest

class FakeTest(unittest.TestCase):
    cl_att = []

    def test_a1(self):

        self.assert_(True)
        self.cl_att.append('a1')
        print "cl_att:", self.cl_att

    def test_a2(self):

        self.assert_(True)
        self.cl_att.append('a2')
        print "cl_att:", self.cl_att

if __name__ == "__main__":
    unittest.main()


text:
Q: Select most common domain from list of email addresses I have a function that generates a random email address:
def emails
    names = ["alfred", "daniel", "elisa", "ana", "ramzes"]
    surnames = ["oak", "leaf", "grass", "fruit"]
    providers = ["gmail", "yahoo", "outlook", "icloud"]
    address = "#{names.sample}.#{surnames.sample}#{rand(100..5300)}@#{providers.sample}.com"
end

Given a list of randomly generated email address:
email_list = 100.times.map { emails }

that looks like this:
daniel.oak3985@icloud.com
ramzes.grass1166@icloud.com
daniel.fruit992@yahoo.com
...

how can I select the most common provider ("gmail", "yahoo", etc.)?

A: Your question is similar to this one. There's a twist though : you don't want to analyze the frequency of email addresses, but their providers.
def random_email
  names = ["alfred", "daniel", "elisa", "ana", "ramzes"]
  surnames = ["oak", "leaf", "grass", "fruit"]
  providers = ["gmail", "yahoo", "outlook", "icloud"]
  address = "#{names.sample}.#{surnames.sample}#{rand(100..5300)}@#{providers.sample}.com"
end

emails = Array.new(100){ random_email }

freq = emails.each_with_object(Hash.new(0)) do |email,freq|
  provider = email.split('@').last
  freq[provider] += 1
end

p freq
#=> {"outlook.com"=>24, "yahoo.com"=>28, "gmail.com"=>32, "icloud.com"=>16}

p freq.max_by{|provider, count| count}.first
#=> "gmail.com"

A: email_list = 10.times.map { emails }
  #=> ["alfred.grass426@gmail.com", "elisa.oak239@icloud.com",
  #    "daniel.fruit1600@outlook.com", "ana.fruit3761@icloud.com",
  #    "daniel.grass742@yahoo.com", "elisa.oak3891@outlook.com",
  #    "alfred.leaf1321@gmail.com", "alfred.grass5295@outlook.com",
  #    "ramzes.fruit435@gmail.com", "ana.fruit4233@yahoo.com"]

email_list.group_by { |s| s[/@\K.+/] }.max_by { |_,v| v.size }.first
  #=> "gmail.com"

\K in the regex means disregard everything matched so far. Alternatively, @\K could be replaced by the positive lookbehind (?<=@).
The steps are as follows.
h = email_list.group_by { |s| s[/@\K.+/] }
  #=> {"gmail.com"  =>["alfred.grass426@gmail.com", "alfred.leaf1321@gmail.com",
  #                    "ramzes.fruit435@gmail.com"],
  #    "icloud.com" =>["elisa.oak239@icloud.com", "ana.fruit3761@icloud.com"],
  #    "outlook.com"=>["daniel.fruit1600@outlook.com",  "elisa.oak3891@outlook.com",
  #                    "alfred.grass5295@outlook.com"],
  #    "yahoo.com"  =>["daniel.grass742@yahoo.com", "ana.fruit4233@yahoo.com"]}
a = h.max_by { |_,v| v.size }
  #=> ["gmail.com", ["alfred.grass426@gmail.com", "alfred.leaf1321@gmail.com",
  #                  "ramzes.fruit435@gmail.com"]]
a.first
  #=> "gmail.com"

If, as here, there is a tie for most frequent, modify the code as follows to get all winners.
h = email_list.group_by { |s| s[/@\K.+/] }
  # (same as above)
mx_size = h.map { |_,v| v.size }.max
  #=> 3
h.select { |_,v| v.size == mx_size }.keys
  #=> ["gmail.com", "outlook.com"]


text:
Q: javascript hotkey for button? I have searching for a time now but I did not find proper solution.
What I am doing: I have two keys post bill and post and print.
What I want to do: When I press F7 then post bill(button) should be pressed and when F8 then post and print(button) should be pressed.
I have seen accesskey function but it need Alt+key for it and it does not work with F8 and it also have some oprationg system problem(different keys in every oprating system). Is there any JavaScript or jquery function to achive this task.
Any advice will be very helpful.

A: There is no built-in way to do this in JS, but you can capture key events and determine which keys are pressed to execute your logic on desired keys.
A good practice is to capture keyup events on the DOM document with an listener attached via addEventListener, e.g.:
document.addEventListener('keyup', function(evt) {
  console.log(evt.keyCode);
  switch(evt.keyCode) {
    case 118 :                // key code for F7
      // your code
      break;

    case 119 :                // key code for F8
      // your code
      break;
  }
});


text:
Q: Possible to present UIView without UIViewController in UIPopoverController? Is it possible to quickly present a UIView in a UIPopoverController without having a UIViewController managing the UIView?
Currently I have a "DelegateViewController" that gets my view passed. Then I use that controller for presentation. But I'm wondering if there is an easier way?

A: If you have a UIView, then you can easily create a plain UIViewController as a container.
UIViewController* controller = [[[UIViewController alloc] init] autorelease];
controller.view = myView;

A:
Is it possible to quickly present a UIView in a UIPopoverController
  without having a UIViewController managing the UIView?

No. UIPopoverController manages a view controller, not a view. When you create a popover controller, you have to provide the view controller that will manage the content. That doesn't mean that you have to create a special view controller subclass in every place where you use a popover -- as bendytree points out, you can use a plain old UIViewController if you want. But you can't just pass UIPopoverController a view -- it has no way to accept it, and wouldn't know what to do with it if did.

A: It usually makes sense to have a UIViewController for a view since the controller handles all the interaction and setting up of the view. Although you can in some situations put "naked" views on screen the UIPopoverController is designed to work with a UIViewController and the ViewController paradigm is very well established and encouraged in the iOS world, so even if you think you don't seem to need a view controller it should not be harmful to have one and you might always want to extend the current functionality, right?
Please Note: If you are on iOS 5.0 creating views in Popovers is very simple and a matter of dragging-and-dropping the view controllers and hooking them up on the storyboard. Example: How to create Popovers with Xcode Storyboards


text:
Q: Decidability of theory of modules over a ring of finite representation type I have read from Mike Prest's model theory for modules (London lecture note series) chapter 17 that a Ring of finite representation type has a decidable theory of modules.  Here decidability was defined in the usual sense for theories : A theory is decidable if there is an effective method that decides whether the formula is in the theory or not.
I could not find a relevant literature or paper where this statement has been proved. I needed this result to assert a crucial proposition in my thesis. Any help would be greatly appreciated.
As a follow up question, are there specific papers investigating the syntactic completeness of the theory of modules over Artin Algebras? I can't seem to find much literature for this topic.
Thank you very much


text:
Q: Unable to boot Debian Hurd in Virtual Box due to missing hd0s1 I'm trying to setup a Debian Hurd test machine to duplicate a privately reported issue on the platform. According to the README.txt:

To give Debian GNU/Hurd a try, it is probably easier to simply run the
  preinstalled image, which is provided here:
$ wget http://ftp.debian-ports.org/debian-cd/hurd-i386/current/debian-hurd.img.tar.xz
$ tar xJf debian-hurd.img.tar.xz

...
It can also be run in virtualbox, by first converting to VDI format :
  $ VBoxManage convertfromraw debian-hurd*.img debian-hurd.vdi --format vdi

You can then just log in as root without a password...

I fetched and unpacked debian-hurd.img.tar.xz. Then I created a new Linux 32-bit VM, and used debian-hurd.vdi as the disk.
After working through the process, the machine encounters an error during boot. The error occurs during regular boot and recovery boot. The error is:
start ext2fs: ext2fs: device:hd0s1: No such device or address

According to GNU Hurd | VirtualBox | Installation on the Debian wiki, this could be caused by a SATA controller rather than and IDE controller. Unfortunately, the selection for a new IDE controller is greyed out, and there is no apparent way to add one (SATA is available).
Why am I receiving the error, and how can I fix it?

A: Try selecting "Other"  and "other" on the iirc in the 2 drop-down box selections.  I'm running VBox 5.1.12.  I specifically did not select Linux, because I don't know what assumptions VBox makes for optimization for Linux.

A: This can be fixed by turning off the virtual machine, going to Machine settings, Storage - removing the downloaded vdi from "Controller: SATA", and adding it instead to the IDE controller, at "Controller: IDE". Then the system will find the hard drive in the correct place.


text:
Q: Using Height/Width 100% After Rotating an Element with CSS I have an element (a video) that I want to rotate, and then use 100% width and height. Before applying the rotation, the video occupies 100% width and height. After the rotation, the size seems to remain the same as it was before I rotated it. I'd like to re-apply width and height 100% to adapt the video the the new state.
The goal is to try and present the video in landscape even though the div (or phone) is in portrait orientation mode.
Here's a JSFiddle of what I'm trying to do:
http://jsfiddle.net/a1sLp5gn/2/
In the fiddle, click the button to see the video in the desired state.
The video is contained within a container div that demonstrates it being framed by something like a phone screen (the red border, I want to fill this div with the video).
Using the JS that runs after clicking the button, I am able to achieve my goal, but I am doing it in a hackish ugly way - and I was wondering what is the appropriate/best way to achieve what I am doing.
This is the CSS (better check out the fiddle link I provided, I'm only putting it here because stackoverflow requires some code when there's a fiddle link):
video {
      transform:rotate(90deg);
      height:100%;
      width:100%;
}

.container {
      border-style:solid;
      border-width:1px;
      border-color: red;
      height:640px;
      width:360px;
}

A: I hope this can help you:
even you rotate an element, height, width, left and top properties are calculated on unrotaded element. You must consider container dimension and manually invert value.
Normally rotation make element's center point as reference. (you can change with transorm-origin, but in this case is not necessary if video element is already centered)
$(function() {
 $('button').click(function() {

   var container = $("video").parent()

   $('video').height($(container).width());
   $('video').width($(container).height());

   $('video').css('position', 'absolute')
   var px = $(container).width() / 2
   var py = $(container).height() / 2
   $('video').css('left', px-py).css('top', py-px);
   //$("video").css({"transform":"rotate(90deg)"})
 });
});


text:
Q: Non printable chars in Eclipse window header (DBeaver plugin) I have non printable chars in eclipse ide window header, check screenshot. Locale ru_RU.UTF8. Webdings and windings fonts installed for ubuntu - dont known if java need some additional installation steps, also dont know is this chars belong to this fonts. Java version openjdk-8 on ubuntu17.10, default from repo. Also tried oracle-8-jre.
Non ascii chars work fine in editor.
Have read similar questions and google for it.
This not so important but interesting to fix it.

A: Not a bug. Just such header with \n in that plugin.
@Luis should add comment as answer.


text:
Q: Change event being called on click I am making a chrome extension and the popup has a single input element to which I'm programmatically assigning an on-change event listener.
$(".search").change(function() {
    console.log($(this).val());
});

Here is the html

extension

                    <input class="search" id="search" />

Add to list

I have a search icon with class search-icon next to it which has no event listeners attached to it.
The onchange event never gets fired when the input value changes. Instead when i click on the search icon it fires the onchange event. Chrome dev tools doesn't even show any listener being attached to the search icon. I have tried replacing the class of search with an id and attaching a listener to it, but in any case the behaviour remains the same.

A: The onchange event is always fired when the element loses focus, after the content has been changed. If you're looking for an event that fires immediately after each input, try the oninput event like so:
$(".search").on("input", function() {
    console.log($(this).val());
});


text:
Q: Add Checkbox to Word I want to add checkboxes in a word 2010 .doc file and also keep everything else editable.
I tried the following options from Developer->Restrict Editing:

*

*"Filling in forms" but it blocks editing on the entire document

*"No changes (Read only)" to block editing on sections, but the checkbox doesn't work

Is this possible?
Thanks!

A: Checkbox in word 2010.

*

*Go to File > Options.

*Customize Ribbon > (RIGHT SIDE) uncheck Developer, RE-Check Developer > OK

*Go to Developer Tab in your Ribbon (to the right) > Click on Check Mark Icon.

*Enjoy.


text:
Q: JSON image parsing from localhost I'm working on a project. That could populate list through json. I've parse the data from http://10.0.2.2/mobile_version/get_supplier_pro_list.php, and it is displaying me the text but not image, what i've done is
// Hashmap for ListView
    ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();

    // Creating JSON Parser instance
    JSONParser jParser = new JSONParser();

    // getting JSON string from URL
    JSONObject json = jParser.getJSONFromUrl(url);

    try {
        // Getting Array of Contacts
        sup_pd_list = json.getJSONArray(TAG_SUPPLIERS);

        // looping through All Contacts
        for (int i = 0; i < sup_pd_list.length(); i++) {
            JSONObject c = sup_pd_list.getJSONObject(i);

            // Storing each json item in variable
            String suply_id = c.getString(TAG_ID);
            String pd_name = c.getString(TAG_PRO_NAME);
            String pd_price = c.getString(TAG_PRO_PRICE);
            String pd_thumbnail = c.getString(TAG_PRO_THUMBNAIL);

            // creating new HashMap
            HashMap<String, String> map = new HashMap<String, String>();

            // adding each child node to HashMap key => value
            map.put(TAG_ID, suply_id);
            map.put(TAG_PRO_NAME, pd_name);
            map.put(TAG_PRO_PRICE, pd_price);
            map.put(TAG_PRO_THUMBNAIL, pd_thumbnail);

            // adding HashList to ArrayList
            contactList.add(map);
        }

    } catch (JSONException e) {
        e.printStackTrace();
    }

    /**
     * Updating parsed JSON data into ListView
     * */
    ListAdapter adapter = new SimpleAdapter(this, contactList,
            R.layout.single_list_item, new String[] { TAG_PRO_NAME,
                    TAG_PRO_PRICE, TAG_PRO_THUMBNAIL}, new int[] {
                    R.id.pd_name, R.id.pd_price , R.id.pd_thumbnail });

    setListAdapter(adapter);
}

and in logcat, it shows me
12-14 03:47:12.743: I/System.out(314): resolveUri failed on bad bitmap uri: fceacd5431438f9d93fb4f885a3b2990.png
12-14 03:47:12.762: I/System.out(314): resolveUri failed on bad bitmap uri: d254d82762217f8e1005013c8926f53e.jpg

And through parsing, what i get is
{"suppliers":[{"suply_id":null,"pd_name":"car","pd_price":"200000.00","pd_thumbnail":"fceacd5431438f9d93fb4f885a3b2990.png"}],"success":1}

Help needed. Thanks in advance.

A: A couple of things need to happen in order to display the image.  First, you need to change your HashMap to HashMap<String, Object>() to accept a drawable object.
Next, you need to get the drawable object from your string name by doing something like this:
Resources r = getResources();
int thumb = r.getIdentifier(pd_thumbnail, "com.mypackage");
map.put(TAG_PRO_THUMBNAIL, thumb);

Here is a tutorial that you can use to derive things from minus the string to drawable conversion
http://www.androidpractice.com/2012/01/static-listview-with-images-in-android.html
Finally, I'm not sure if R.layout.single_list_item is the right type of list item for this, but I may be mistaken, so please don't quote me on that one.


text: Q: How to backup maas database Is there any recommended way to backup/restore maasdb ? I tried simple dump, then reinstall and restore but i ended up with 2 clusters, one which was disconnected with nodes and one connected but with 0 nodes. The idea behind this is to be able to migrate maas to different server or perform restore in case of hw failure.


text:
Q: Set up a predicate and delete a specific NSManagedObject I am trying to delete a specific attribute
tipdescription | tip number | tipindex

go to school   |  001       |   21

come home      |  004       |   54

lock home      |  008       |   86

How will I delete the whole column 'lock home'?
I have tried the following code
app = [[ UIApplication sharedApplication] delegate];

NSFetchRequest *req = [[NSFetchRequest alloc]init];

[req setEntity:[NSEntityDescription entityForName:@"Tips" inManagedObjectContext:app.managedObjectContext]];
NSString *deletestatement =[[NSString alloc] initWithFormat:@"lock home"];

[req setPredicate:[NSPredicate predicateWithFormat:@"tipdescription LIKE  %@", deletestatement]];
NSError *error;
Tips *std = [[app.managedObjectContext executeFetchRequest:req error:&error] lastObject];

[app.managedObjectContext deleteObject:std];

After running it I get the following error:

Terminating app due to uncaught exception
  'NSInvalidArgumentException', reason: '-deleteObject: requires a
  non-nil argument

A: Why don't you use a predicate like the following:
[req setPredicate:[NSPredicate predicateWithFormat:@"tipdescription ==  %@", deletestatement]];

a more clean approach is to predicate against the tip number (I suppose it's an identifier and is a NSString)
[req setPredicate:[NSPredicate predicateWithFormat:@"tipnumber ==  %@", @"001"]];

Furthermore, put some condition control when you execute the fetch request:
NSManagedObjectContext* myContext = app.managedObjectContext;

NSArray* result = [myContext executeFetchRequest:req error:&error];
if([result count] > 0) {

    Tips *std = (Tips*)[result objectAtIndex:0];
    [myContext deleteObject:std];
} else {

    NSLog(@"No result");
}


text:
Q: Hover effect in
*
* list with Headings I have a <ul> <li> list where in HELP, MISC and POLICIES are the headings with no <a> tag.
other <li> elements have hover effect as font-size:16px (normal size is 14px).
how can i remove hover of headings??

FIDDLE

A: you can use
.footer_ul li.bold1:hover {
    font-size:14px;
    text-decoration:none;
}

to remove the hover of headings
updated jsFiddle File
or alternate you can use .footer_ul li a:hover instate of .footer_ul li:hover
.footer_ul li a:hover {
    text-decoration:underline;
    font-size:16px;
}

jsFiddle

A: I checked you fiddle it was good.

The only change you need to make is you have to add :hover class for a tag and not li tag

`

.footer_ul li a:hover {
    text-decoration:underline;
    font-size:16px;
}

`

A: Use :not() selector. A single change is required like so.
.footer_ul li:hover:not(.bold1) {
    text-decoration:underline;
    font-size:16px;
}

Working demo

A: Add this css after ".footer_ul li:hover"
.footer_ul li:hover:first-child {
    text-decoration:none;
    font-size:14px;
}


text:
Q: How to find word and change only next second line word The file name staff.txt and sample contents are:
JHON
MANAGER
10000

I want to find JHON in a file and I want to change whatever's in the 2nd line after that one with another word/number.
How can I accomplish this?

A: Use ed, man!
ed -s staff.txt <<< $'/JHON/+2s/.*/4242\nw\nq'

This calls ed in scripting mode (-s) on the staff.txt file and sends it the following commands in an ANSI-quoted here-string:

*

*find the line containing JHON and go two lines beyond that (+2)

*on that line, search and replace anything and everything that's there (.*) with 4242

*write the file out to disk

*quit ed

The intermediate \n's separate the various ed commands.
Alternatively, you could use the c command to change the line:
ed -s staff.txt <<< $'/JHON/+2c\n4242\n.\nw\nq'

Here, the replacement text needs to be entered separately (after) the c command, and ended with a period on its own (\.\n).

A: With sed you can move to next line with n:
sed '/JHON/{n;n;s/.*/42/}'

A: Using awk:
awk 'f{$0="newvalue";f=0}/JHON/{print;getline;f=1}1'

f{$0="newvalue";f=0} - If f is true set line to newvalue and reset f to 0
/JHON/{print;getline;f=1} - If pattern JHON is found print it, print the next line, and set f to 1
1 - print

A: Yet another awk solution:
awk '/JHON/{c=0};(c!=""&&c++==2){$0="42"};{print};'

sets a counter c when JHON is found. Then, if c is set, increment and when c==2, change line ($0) to "42".

A: if you have only one person (one register), you can use this code:
awk '/JHON/{print $0; getline; print "SUPERVISOR"; getline; print "99999"; }' staff.txt

If you staff.txt file has many persons (many registers) and you should replace only JHON data:
awk '/.*/{if($0=="JHON"){print $0; getline; print "SUPERVISOR"; getline; print "99999"; } else {print $0;}}' staff2.txt

Example of staff2.txt:
JHON
MANAGER
10000
ROGER
TEACHER
3000
ROBERT
SCIENTIST
20000

You should get this output:
JHON
SUPERVISOR
99999
ROGER
TEACHER
3000
ROBERT
SCIENTIST
20000

Another short way, to get the same output, could be:
awk '/JHON/{print;getline; print "SUPERVISOR"; getline; $0="99999"}1' staff2.txt

Explanation: if line is JHON, print JHON, go to the next line, print SUPERVISOR, go to the next line, replace it with 99999.
if line is NOT JHON, only print it.

A: When I am using this command
ed -s staff.txt <<< $'/JHON/+2s/.*/4242\nw\nq'

Its working fine but in some case JHON word is in a Bracket [ ]
at that time this command not working properly. Its changing some another word that start with [xyz ]
example. 1)
ed -s staff.txt <<< $'/[JHON]/+2s/.*/4242\nw\nq'
[JHON]
[MANAGER]
[10000]

Its changing first bracket word in file not changing [JHON].


text:
Q: Adding a character to every row in a MySQL database I have a table in which I inserted a large batch of records. All these records have a certain column in which one character is missing: they're missing a slash / at the beginning. Is there a way to add this character to the beginning of this column in every row, using purely SQL?
It wouldn't be a problem in PHP, but I'd like to know a solution in SQL. I know of the SQL UPDATE statement, of course, but I'm not sure how to let it rely on the current value. The best I can come up with is using a subquery:
UPDATE the_table t
SET the_column =
    CONCAT('/', SELECT the_column FROM the_table WHERE id=t.id)

Would this work, and is this the easiest solution? I'm on MySQL 5.5.31.

A: Simply use this:
UPDATE the_table t
SET the_column =
    CONCAT('/', the_column )

A: Your version might work.  But you really just want to do:
UPDATE the_table t
    SET the_column = CONCAT('/', the_column)

A: Have you tried this ?
UPDATE t SET column = Concat('/', column);

A: Try this
UPDATE table t SET column = CONCAT('/', column)


text:
Q: Ways to arrange groups of books I've got a simple probability question similar to this.
It is as follows:

Given a collection of books, of which 25 are blue, 10 are green and 5 are black, in how many ways can someone arrange 10 books if they want a green on on each end and alternate blue and black ones for the rest. Books of the same color are distinguishable from each other.

I believe the answer is $n = 10*25*5*24*4*23*3*22*2*9$, alternating blue and then black. But I was unsure if it was instead $2n$, because it could be ordered with black and then blue. Is my thinking correct?
Thanks

A: Yes, your count should be doubled because the second book could be blue or black.  You have required that the second book be blue.  The order of factors will be different if the second book is black, but the factors will be the same and the product will be the same.


text:
Q: Compute a Real Integral using Residue Theorem My question is related to the computation of the integral:
$$I(z)=\frac{1}{2\pi}\int_{-\infty}^{+\infty}\frac{e^{-iz~p}}{p^2}dp,$$
where $z\in \mathbb R$.
Using the Residue Theorem I found the solution: $I(z)=-|z|/2$. But when I checked the answer with mathematica it tells me that the integral does not converge...
I believe that either I did something wrong in the calculation or in the Mathematica input... So the question is (summarized as) does the above integral converge? If it does what is it's value?


text:
Q: Generating monthly report based on unix timestamps in php/mysql Sorry if this is a noob php/mysql question.
I have a database where each entry has a unix timestamp associated to it.
Lets say it has a structure like
| UniqueID | TimeStamp | Item | Buy | Sell
And lets say it has entries spanning a few years.
I would like to generate reports for each month lets say to count each item.
What is the best way of doing this in PHP/Mysql ?
Thanks !

A: You should be able to generate reports directly in SQL with statements like:
SELECT MONTH(TimeSTamp), Item, COUNT(Buy), COUNT(Sell) FROM your_table GROUP BY MONTH(TimeStamp), Item

which would list Items buys and sells by month. You can run this statement in PHP using e.g. @mysql_query (check the php manual for your php version).
If you need to convert from UNIX to another time format check out php function getdate.

A: I probably would not take this route but to do what you want I would convert the timestamps into DateTime objects and do whatever I needed with them. I will use a timestamp as an example
<?php
    $time = time();//Get a timestamp. This is just for an example, you will assign the value of your timestamp here
    $date = new DateTime(date('Y-m-d h:i:s',$time));
    echo $date->format('M'); //Prints out the month from the unix timestamp
?>

You can get the date directly from the date() function, but you have a lot of flexibility when you use the DateTime object


text:
Q: Combine 2 queries from different tables with different fields names I would like to select and retrieve results from two separate database tables and then loop them within one html table. I could do commands and name them separately, combine the results and loop through them. Is there a way of doing this with one query though?
The example below would not work, but that is the logic behind what i'd like to achieve.
$SQL = "SELECT * FROM table3 WHERE column5 = 'YES'";
$Data = mysql_query($SQL);

$SQL = "SELECT * FROM table1 WHERE column1 = 'YES'";
$Data = mysql_query($SQL);

// loops through records displaying in table format
for($Loop = 0; $Loop < mysql_num_rows($Data); $Loop++)
{
     $Row = mysql_fetch_assoc($Data);
     $Ref = $Row["Ref"];
     // rest of fields
}

Note: I know mysql is deprecated. I will be moving over to pdo when I rebuild the site but for now i need to use a mysql function.

A: SELECT * FROM table3
JOIN table1 ON table3.column5=table1.column1 AND table3.column5='YES'

Or,change it to mysqli and use http://docs.php.net/mysqli.multi-query

A: You could have used UNION in the sql query if both the tables had same no. of attributes-
(SELECT * FROM table3 WHERE column5 = 'YES')
UNION
(SELECT * FROM table1 WHERE column1 = 'YES')

So use the following code snippet-
$SQL = "(SELECT * FROM table3 WHERE column5 = 'YES') UNION (SELECT * FROM table1 WHERE column1 = 'YES')";
$Data = mysql_query($SQL);

// loops through records displaying in table format
for($Loop = 0; $Loop < mysql_num_rows($Data); $Loop++)
{
     $Row = mysql_fetch_assoc($Data);
     $Ref = $Row["Ref"];
     // rest of fields
}

In that case there should be an attribute Ref in the 1st table specified in the UNION query i.e. table3 here.


text:
Q: .net dropdownlist align text I am trying to align the text in my .net dropdownlist to the right. Using CssClass I am able to align text to the right in Firefox.
IE doesn't not align text to the right it aligns to the left.
I have read that IE 6 doesn't support this.

*

*Is this true?

I am using IE7 but most of my users will be in IE 6 so, both need to work.
<asp:DropDownList ID="ddlNomination" Width="250px" CssClass="ddlnomination"
    runat="server" DataSourceID="Azoa" DataTextField="nomination_type"
    DataValueField="nomination_type">
    <asp:ListItem> </asp:ListItem>
</asp:DropDownList>

css
.ddlnomination
{
   text-align:right;
}

A: Setting it (text-align="right") on the Select or Option elements in IE6, IE7 & IE8 (even in standards mode) does not appear to work.
Some quick stats after testing.
Browser    |  Result
 Firefox 3     Passes
 Opera 9.5     Passes
 IE 6          Fails
 IE 7          Fails
 IE 8          Fails
 Safari 3      Fails
 Safari 4      Fails
 Chrome        Fails on the Option element, Passes on the Select element

A: It's sadly true Dedrick...
If right-aligning it in IE6 is really important, maybe you could add blank spaces to fill the left of the elements and make them measure the same. A real pain anyway... -1 reputation points for IE6 in this one!


text:
Q: Hypertuning a logistic regression pipeline model in pyspark I am trying to hypertune a logistic regression model. I keep getting an error as 'label does not exist'.
This is an income classifier model where label is the income column. I have tried to resolve this problem using the solutions provided on the internet but I am unable to do so and stuck on this from last 2 days. If anyone could help me find out my mistake that would be of great help.
cat_cols=['workclass','education','marital_status','occupation','relationship','race','sex','native_country','income']

StringIndexer_workclass=StringIndexer(inputCol='workclass',outputCol='workclass_Ind')
StringIndexer_education=StringIndexer(inputCol='education',outputCol='education_Ind')
StringIndexer_marital_status=StringIndexer(inputCol='marital_status',outputCol='marital_status_Ind')
StringIndexer_occupation=StringIndexer(inputCol='occupation',outputCol='occupation_Ind')
StringIndexer_relationship=StringIndexer(inputCol='relationship',outputCol='relationship_Ind')
StringIndexer_race=StringIndexer(inputCol='race',outputCol='race_Ind')
StringIndexer_sex=StringIndexer(inputCol='sex',outputCol='sex_Ind')
StringIndexer_native_country=StringIndexer(inputCol='native_country',outputCol='native_country_Ind')

StringIndexer_income=StringIndexer(inputCol='income', outputCol='income_class')

OneHotEncoder_workclass=OneHotEncoder(inputCol='workclass_Ind',outputCol='workclass_feat')
OneHotEncoder_education=OneHotEncoder(inputCol='education_Ind',outputCol='education_feat')
OneHotEncoder_marital_status=OneHotEncoder(inputCol='marital_status_Ind',outputCol='marital_status_feat')
OneHotEncoder_occupation=OneHotEncoder(inputCol='occupation_Ind',outputCol='occupation_feat')
OneHotEncoder_relationship=OneHotEncoder(inputCol='relationship_Ind',outputCol='relationship_feat')
OneHotEncoder_race=OneHotEncoder(inputCol='race_Ind',outputCol='race_feat')
OneHotEncoder_sex=OneHotEncoder(inputCol='sex_Ind',outputCol='sex_feat')
OneHotEncoder_native_country = OneHotEncoder(inputCol='native_country_Ind', outputCol='native_country_feat')

num_cols= ['age', 'fnlwgt', 'education_num', 'capital_gain', 'capital_loss', 'hours_per_week']
for col in num_cols:
    data = data.withColumn(col, data[col].cast("integer"))

assemble_cols=['age','workclass_feat','fnlwgt','education_feat','education_num','marital_status_feat','occupation_feat','relationship_feat',
               'race_feat','sex_feat','capital_gain','capital_loss','hours_per_week','native_country_Ind']
assemble_features=VectorAssembler(inputCols=assemble_cols,outputCol='features')

# Generate  base pipeline
basePipeline=[StringIndexer_workclass, StringIndexer_education, StringIndexer_marital_status, StringIndexer_occupation,
              StringIndexer_relationship, StringIndexer_race, StringIndexer_sex, StringIndexer_native_country,
              OneHotEncoder_workclass, OneHotEncoder_education, OneHotEncoder_marital_status,
              OneHotEncoder_occupation, OneHotEncoder_relationship, OneHotEncoder_race, OneHotEncoder_sex, OneHotEncoder_native_country,
              StringIndexer_income, assemble_features]

log_reg = LogisticRegression(maxIter=5, featuresCol='features', labelCol='income_class')
pl_log_reg = basePipeline + [log_reg]
log_reg_pipeline = Pipeline(stages=pl_log_reg)

training_data, testing_data = data.randomSplit([0.8, 0.2], 3)
print("Number of training records: " + str(training_data.count()))
print("Number of testing records : " + str(testing_data.count()))
testing_data = testing_data.drop('income')

from pyspark.ml.tuning import CrossValidator, ParamGridBuilder
paramGrid = ParamGridBuilder()\
    .addGrid(log_reg.elasticNetParam,[0.2, 0.6])\
    .addGrid(log_reg.regParam, [0.1, 0.01])\
    .build()

crossval = CrossValidator().setEstimator(log_reg_pipeline).setEvaluator(BinaryClassificationEvaluator())\
                    .setEstimatorParamMaps(paramGrid).setNumFolds(2)

# Run cross-validation, and choose the best set of parameters.
print(training_data.columns)
cvModel = crossval.fit(training_data)

# Make predictions on test documents. cvModel uses the best model found (lrModel).
prediction = cvModel.transform(testing_data)
selected = prediction.select("features",  "probability", "prediction")
for row in selected.collect():
    print(row)

Without Hyperparameter tuning:
# fit the pipeline for the trained data
log_reg_model = log_reg_pipeline.fit(training_data)

# transform the data
testing_data = log_reg_model.transform(testing_data)

# view some of the columns generated
print(testing_data.columns)

testing_data.select("features",  "probability", "prediction").show(n=5)

+--------------------+--------------------+----------+
|            features|         probability|prediction|
+--------------------+--------------------+----------+
|(67,[0,3,10,21,27...|[0.98746926802062...|       0.0|
|(67,[0,3,10,16,27...|[0.96126191802708...|       0.0|
|(67,[0,3,10,21,27...|[0.98753467015818...|       0.0|
|(67,[0,3,10,16,27...|[0.97845137714609...|       0.0|
|(67,[0,3,10,16,27...|[0.97542170455525...|       0.0|
+--------------------+--------------------+----------+

A: After lots of research and findings, I finally managed to get a working pipeline model.
cat_cols=['workclass','education','marital_status','occupation','relationship','race','sex','native_country','income']

StringIndexer_workclass=StringIndexer(inputCol='workclass',outputCol='workclass_Ind')
StringIndexer_education=StringIndexer(inputCol='education',outputCol='education_Ind')
StringIndexer_marital_status=StringIndexer(inputCol='marital_status',outputCol='marital_status_Ind')
StringIndexer_occupation=StringIndexer(inputCol='occupation',outputCol='occupation_Ind')
StringIndexer_relationship=StringIndexer(inputCol='relationship',outputCol='relationship_Ind')
StringIndexer_race=StringIndexer(inputCol='race',outputCol='race_Ind')
StringIndexer_sex=StringIndexer(inputCol='sex',outputCol='sex_Ind')
StringIndexer_native_country=StringIndexer(inputCol='native_country',outputCol='native_country_Ind')

StringIndexer_income=StringIndexer(inputCol='income', outputCol='income_class')

OneHotEncoder_workclass=OneHotEncoder(inputCol='workclass_Ind',outputCol='workclass_feat')
OneHotEncoder_education=OneHotEncoder(inputCol='education_Ind',outputCol='education_feat')
OneHotEncoder_marital_status=OneHotEncoder(inputCol='marital_status_Ind',outputCol='marital_status_feat')
OneHotEncoder_occupation=OneHotEncoder(inputCol='occupation_Ind',outputCol='occupation_feat')
OneHotEncoder_relationship=OneHotEncoder(inputCol='relationship_Ind',outputCol='relationship_feat')
OneHotEncoder_race=OneHotEncoder(inputCol='race_Ind',outputCol='race_feat')
OneHotEncoder_sex=OneHotEncoder(inputCol='sex_Ind',outputCol='sex_feat')
OneHotEncoder_native_country = OneHotEncoder(inputCol='native_country_Ind', outputCol='native_country_feat')

num_cols= ['age', 'fnlwgt', 'education_num', 'capital_gain', 'capital_loss', 'hours_per_week']
for col in num_cols:
    data = data.withColumn(col, data[col].cast("integer"))

pipeline=Pipeline(stages=[])

# Generate  base pipeline
basePipeline=[StringIndexer_workclass, StringIndexer_education, StringIndexer_marital_status, StringIndexer_occupation,
              StringIndexer_relationship, StringIndexer_race, StringIndexer_sex, StringIndexer_native_country,
              OneHotEncoder_workclass, OneHotEncoder_education, OneHotEncoder_marital_status,
              OneHotEncoder_occupation, OneHotEncoder_relationship, OneHotEncoder_race, OneHotEncoder_sex, OneHotEncoder_native_country,
              StringIndexer_income, assemble_features]

pipeline = Pipeline(stages=basePipeline)
pipelineModel = pipeline.fit(data)
model = pipelineModel.transform(data)

model.take(1)

from pyspark.ml.linalg import DenseVector
input_data = model.rdd.map(lambda x: (x["income_class"], DenseVector(x["features"])))

final_df = spark.createDataFrame(input_data, ["label", "features"])

final_df.show(2)

training_data, testing_data = final_df.randomSplit([0.8, 0.2], 3)

log_reg = LogisticRegression(maxIter=5, featuresCol='features', labelCol='label')

paramGrid = ParamGridBuilder().addGrid(log_reg.regParam,[0.02,0.08])\
            .addGrid(log_reg.elasticNetParam,[0.2,0.6]).build()

evaluator_lr = MulticlassClassificationEvaluator(labelCol='label', metricName='accuracy')

crossval = CrossValidator(estimator=log_reg,
                          estimatorParamMaps=paramGrid,
                          evaluator=evaluator_lr,
                          numFolds=2)

start_time = time()

# Run cross-validation, and choose the best set of parameters.
cvModel = crossval.fit(training_data)

end_time = time()

training_time = end_time - start_time

print("The time taken to train the data is: %0.3f seconds" %training_time)

# Make predictions on testing data and calculating ROC metrics and model accuracy.
prediction = cvModel.transform(testing_data)
output= prediction.select("features",  "probability", "prediction")

acc = evaluator_lr.evaluate(output, {evaluator_lr.metricName: "accuracy"})
f1 = evaluator_lr.evaluate(output, {evaluator_lr.metricName: "f1"})
weightedPrecision = evaluator_lr.evaluate(output, {evaluator_lr.metricName: "weightedPrecision"})
weightedRecall = evaluator_lr.evaluate(output, {evaluator_lr.metricName: "weightedRecall"})
auc = evaluator_lr.evaluate(output)

print(acc)
print(f1)
print(weightedPrecision)
print(weightedRecall)
print(auc)


text:
Q: Adobe CC Flash AS3 Click tag I recently switched over from Adobe CS6 to Adobe CC. In the new Adobe CC Flash, it no longer supports action script 2. I need to create an AS3, click tag. Is there a universal AS3 clickTag code you know of that is used? I've googled it, but found some unreliable results.

A: I'm assuming that you mean you want to have a button react to a click? If so, you simply have to create a button object, and then add a listener for that button where you choose 1) the event you want to listen for, in this case a click, and 2) the code you wish to execute when that event is fired, in most cases this is a function call.
For exaxmple, the following code was placed on the first frame of an .FLA:
import flash.events.MouseEvent;

var myButton:SimpleButton = new SimpleButton();
var myButtonSprite:Sprite = new Sprite();
myButtonSprite.graphics.lineStyle(1, 0x555555);
myButtonSprite.graphics.beginFill(0xff000,1);
myButtonSprite.graphics.drawRect(0,0,200,30);
myButtonSprite.graphics.endFill();
myButton.overState = myButton.downState = myButton.upState = myButton.hitTestState = myButtonSprite;

myButton.addEventListener(MouseEvent.CLICK,buttonClickHandler);
addChild(myButton);

function buttonClickHandler(e:MouseEvent):void {
    trace("YAY! My Button was clicked!");
}

To give credit where it is due, the code for creating the button dynamically that you see above is showcased here: Create a Button with only code AS3
If you already have a button on your stage that you want to wire up with a click event you simply have to give the button an instance name and then use that instance name in the code.  In the following example, the instance name of the button on the stage is myButton:
myButton.addEventListener(MouseEvent.CLICK,buttonClickHandler);

function buttonClickHandler(e:MouseEvent):void {
    trace("YAY! My Button was clicked!");
}


text:
Q: What is a signal in Unix? This comment confuses me: "kill -l generally lists all signals". I thought that a signal means a quantized amount of energy.
[Added] Please, clarify the (computational) signal in Unix and the physical signal. Are they totally different concepts?
[Added] Are there major differences between paradigms? Is the meaning the same in languages such as C, Python and Haskell? The signal seems to be a general term.

A: A signal is a message, either to the target process, or to the OS about the target process. It is part of the unix API (and is defined in various POSIX standards).
Read man kill, man signal, and man sigaction.
Other SO questions that might be helpful:

*

*What is the difference between sigaction and signal?

A: Some from my notes :
Allows asynchronous communication

*

*Between processes belonging to the
same user

*From the system to any process

*From the system manager to any process

*All associated information is in the signal itself

*Many different signals

SIGINT

*

*From the system to all processes
associated to a terminal

*Trigger: ^C pressed

*Usual way to stop a running process

SIGFPE

*

*From the kernel to a single process

*Trigger: error in floating point operation

SIGKILL

*

*To a single process

*Stops the execution of the destination process

SIGALRM

*

*From the kernel to a single process

*Trigger: timer expiration

SIGTERM

*

*To a single process

*Recommends the process to terminate gracefully

SIGUSR1, SIGUSR2

*

*From any process to any other

*Without a predefined semantic

*Freely usable by programmers

Sending a signal to another process

*

*int kill(pid, signal_ID)

The programmer can decide what to do when a signal
is received

*

*Use the default behavior

*Ignore it

*Execute a user function

Detecting an interrupted write
if (write(fd, buff, SIZE)<0) {
  switch (errno) {
   case EINTR:
    warning("Interrupted write\n");
    break;
  }
}…

A: A signal is a message which can be sent to a running process.
For example, to tell the Internet Daemon (inetd) to re-read its configuration file, it should be sent a SIGHUP signal.
For example, if the current process ID (PID) of inetd is 1234, you would type:
kill -SIGHUP 1234

A: A signal is "an event, message, or data structure transmitted between computational processes" (from Wikipedia).

A: The manual refers to a very basic mechanism that allow processes or the operation system to notify other processes by sending a signal. The operation system can use it to notify programs about abortions of them (signal SIGABRT) or about a segmentation fault (often caused by accessing a null-pointer, SIGSEGV), to name two of them.
Some unix servers use signals so the administrator can use kill to send them a signal, causing them to re-read their configuration file, without requiring them to restart.
There are default actions taken for some signals and other signals are just ignored. For example on receive of a SIGSEGV, the program terminates, while receiving a SIGCHLD, meaning a child-process died, will by default result in nothing special.
There is a ANSI C standard function that installs a signal handler, which is a function that can execute some code when receiving a signal, called signal (read in man signal). In different unix's, that function behave different, so its usage is discouraged. Its manpage refers to the sigaction function (read man sigaction), which behaves consistent, and is also more powerful.

A: I cannot believe that people are not comparing things such as hardware and software or stressing OS at some points.
Comparison between a signal and an interrupt:

The difference is that while
  interrupts are sent to the operating
  system by the hardware, signals are
  sent to the process by the operating
  system, or by other processes. Note
  that signals have nothing to do with
  software interrupts, which are still
  sent by the hardware (the CPU itself,
  in this case). (source)

Definitions

*

*process = a program in execution, according to the book below

Further reading

*

*compare the signal to Interrupts and Exceptions

*Tanenbaum's book Modern Operating Systems

A: A physical signal and a Unix signal are indeed different concepts. When a Unix signal is sent from one process to another, there is no specific corresponding physical signal. Unix signals are merely an abstraction so programmers can talk about processes communicating with one another.
Unix signals could have been called messages, events, notifications, or even a made-up term like "frobs". The designers just chose the name "signal", and it stuck.

A: In this case signal means 'message'. So it's sending a message to a process which can tell the process to do various things.

A: A unix signal is a kind of message that can be sent to and from unix processes.  They can do things like tell a process to quit (SIGKILL) or that a process had an invalid memory reference (SIGSEGV) or that the process was killed by the user hitting control-c (SIGINT).
from a *nix command line type in:

man signal

that will should you all the signals available.

A: Signal is basically an interrupt that tells the process that a particular event has happened.
Signal generally send by the kernel, meanwhile a process can also send the signal to other process (depends on permission ans all ) by using kill and killall command and a process can send signal to itself by using raise.
Major use of signal:

*

*To handle the interrupt.

*Process synchronization.

A: *

*Signal is an interrupt that used to intimate a process that a particular event has happened.

*Signal can be send by kernel to running process or one process to another process.

*In bash kill and killall command used to send the signal.


text:
Q: What is the relation between CAS vs SAML? I understand that CAS and SAML are different protocols used for Single-sign on purposes but, what confuses me is articles that say "CAS has an SAML implementation".
Aren't CAS and SAML different ways of how Single Sign-on can be implemented ?
Lets say, the client's enterprise has a SAML Server but, a 3rd party website says they support CAS based SSO. In this case, the end-user would have initially logged into the enterprise system. When accessing the 3rd party website will it connect to the Enterprise SAML Server looking for a SAML assertion ?

*

*What exactly is the relation between CAS and SAML ?

*Where exactly would CAS come in the above said set-up ?

A: While the accepted answer is accurate, it is incomplete. The CAS 3.0 (protocol) specification incorporates SAML 1.1 messages directly. They are used for interacting with the /SAMLvalidate endpoint as described here: https://apereo.github.io/cas/5.0.x/protocol/CAS-Protocol-Specification.html#42-samlvalidate-cas-30

A: There is CAS, the protocol. Then there is CAS, the software implementing that protocol and many many others.
The software is located here:
https://github.com/apereo/cas
Note the README: "CAS is an open and well-documented authentication protocol. The primary implementation of the protocol is an open-source Java server component by the same name, hosted here."
Many software products, like the Apereo CAS server, support more than one protocol at the same time. So the Apereo CAS software can support CAS, SAML2 and OAuth, etc protocols at the same time. The Shibboleth IdP for instance can support SAML2, SAML1 and CAS at the same time.
So your question of:

Aren't CAS and SAML different ways of how Single Sign-on can be implemented ?

Yes, they are different protocols in many ways providing or achieving the same thing.

Where exactly would CAS come in the above said set-up ?

The SAML server needs to also support the CAS protocol for that 3rd party website, or you need a separate CAS deployment that delegates authentication to the SAML server...or it's not happening.


text:
Q: Struct with array of variable size I want to have a struct which contains arrays of variable size. I want to be able to initialize p lists with different sizes n=[2,4,7].
Since I am new to C, this is a little bit tricky for me. I tried the following:
#include <stdlib.h>
#include <stdio.h>

typedef struct{
    double **plist;
} ParticleList;

void sendPar(ParticleList *pl, int *n, int np){
    pl -> plist = malloc(sizeof(double*) * np);
    for(int p=0; p<np; p++){
        pl->plist[p] = malloc(sizeof(double) * n[p]);
    }

    for(int p=0; p<np; p++){
        for(int k=0; k<n[p]; k++){
            pl->plist[p][k] = k+1;
        }
    }
}

int main(){
    ParticleList pl;
    int np = 3;
    int n[np];
    n[0] = 2;
    n[1] = 4;
    n[2] = 7;

    sendPar(&pl, n, np);

    // Listsizes
    for(int p=0; p<np; p++){
        printf("Size of List %d is %lu\n", p, sizeof(pl.plist[p]));
    }
}

When I try this, all my lists plist[] have the same size. What am I doing wrong?
The output is
Size of List 0 is 8
Size of List 1 is 8
Size of List 2 is 8

But I would expect something like
Size of List 0 is 16
Size of List 1 is 32
Size of List 2 is 56

A: To keep the size of allocated arrays of double and maintain the 2D array access algorithm, you can modify the ParticleList structure as follow:
Step 1 - add a array of int to store individual size
typedef struct{
    int *pSize;
    double **plist;
} ParticleList;

Step 2 - during the allocation in sendPar() function, allocate and initialize the pSize array
void sendPar(ParticleList *pl, int *n, int np){
    pl->plist = malloc(sizeof(double*) * np);
    pl->pSize = malloc(sizeof(int) * np); // allocate the pSize array
    for (int p=0; p<np; p++){
        pl->pSize[p] = n[p]; // initialize the pSize Arry
        pl->plist[p] = malloc(sizeof(double) * n[p]);
    }

    ...
}

Step 3 - from main to manage each array of double with its own size
// Listsizes
for(int p=0; p<np; p++){
    printf("Size of List %d is %lu\n", p, (pl.pSize[p]*sizeof(double))));
}


text:
Q: How to create pdf from downloaded photos (python) **I want to create pdf after downloading photos,it's not save pdf file. Where have error?
**
from fpdf import FPDF
import random
import urllib.request

for i in range(1,10):
 def image(url):
  name=random.randrange(1,80)
  fullname=str(name)+"."+"jpg"
  a=urllib.request.urlretrieve(url,'/Users/Dato/Desktop/python/photo/{}.jpg'.format(name))
  image("https://img.yumpu.com/54761731/{}/950x950/7uhbctpd0.jpg".format(random.randrange(1, 80)))

  pdf = FPDF()
  pdf.add_page()
  pdf.image('{}'.format(a), x=0, y=0)
  pdf.output("1.pdf",)

A: Your code doesn't do much. Here's what happens when your code runs:
from fpdf import FPDF
import random
import urllib.request

for i in range(1,10):

Here you import your packages and then you start a for loop. The code in the loop will be run once for each loop, and will have access to variable i which will change each time the loop runs.
def image(url):
    ...

The rest of your code consists of a function definition inside a for loop. The function you define can be called image("example.com") but you never do this. So the for loop runs and defines a function many times but never calls it. The function never runs.
Edit: to actually run the code, you could just delete the function definition and supply the URLs directly. The code would run if it wasn't in a function definition.

A: With the def statement, you are defining a function. It is just building the structure of what that particular piece of code should do. It is not actually executing it.
With the def inside the for loop, you are building the struture again and again, but never actually executing that piece of code.
If you'd insist on using functions, you can define the function outside the loop (once), and then call it using function_name() inside the for loop.
Or, you can eliminate the use of function altogehter, and simply remove the def portion nside the loop, and let the instructions be executed directly.
I had a very similar project way back which made use of similar pdf concepts. If some issue still exists, I hope it can guide you further: GitHub Link.


text:
Q: How to fix 'Cannot POST /index.html' in Nginx, Express and NodeJS I'm setting up my MERN project on my production server and whilst
making sure you can manually type in URL (such as myproject.com/dashboard) I added the following line to the server section of my Nginx configuration file try_files $uri /index.html; to allow this(as stated by the react-router training page). This has now caused the following response when trying to login Cannot POST /index.html.
If I remove the line all calls to the api work(i can login again) but I cannot enter url manually.
I've tried moving the try_files line to the top of the server section incase the server section is sensitive to this.
server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name myproject.com;
    root /home/forge/myproject.com/client/build;
    ...
    location / {
        try_files $uri /index.html;
        proxy_pass http://127.0.0.1:8080;
    }
    ...
}

const express = require('express');

const app = express();

app.use( express.static( `${__dirname}/client/build` ) );

app.use('/api/users', usersRouter);
app.use('/api/playlists', playlistRouter);

app.get('*', (req, res) => {
    res.sendFile(`${__dirname}/client/build/index.html`);
});

I expect to be able to login(make calls to my api) and enter URLs manually to my project.

A: I think your configuration is not valid. In your config if requested file does not exists you are sending the file index.html no matter what. Will never call proxy.
Since your server has /api prefix configure that on your nginx server like this. So request starts with /api will be proxy to your backend server.
server {
  listen 443 ssl http2;
  listen [::]:443 ssl http2;
  server_name myproject.com;
  root /home/forge/myproject.com/client/build;

  location /api/ {
    proxy_pass http://127.0.0.1:8080;
  }

  location / {
    try_files $uri /index.html;
  }

}


text:
Q: HERE location services API freemium plan question I am looking at HERE location services API as an alternative to Google Maps JavaScript API to use with an autosuggest input.
They state that they include 250,000 free transactions per month on the free plan. They also state 'Assets: per month 250'. What are these assets they are referring to? I can't find anything in their docs. Is an asset a single 'place details' object returned or something else?
Hopefully someone here has experience with their freemium plan and knows. Because if it's one 'place details' object that is counted as one asset, it makes this freemium plan option insufficient for my needs. I am hoping that any new character input is counted as 1/250,000 requests and subsequent 'place details' request also considered as a single request, not an asset request.

A: From the FAQs:

*What is an Asset?

An Asset is a person (including an end user), animal, device, cargo, means of transportation, vehicle or any other object which is located, tracked or displayed on a map, or provided route calculations or orders of destinations and/or routes, or has analytics derived by using the HERE Materials in a customer application or service for business purposes.
For example, HERE services are often used to help logistics providers manage vehicles in a fleet or a field workforce. If you manage 250 or fewer Assets, the Freemium and Pro plans will support your app. Contact us to license applications that manage more than 250 Assets.
Source: HERE FAQs


text:
Q: how to get the NEXT item in struts2 iterator tag I know stackoverflow doesnt have a big struts2 community.  But am still trying my luck :)
I have scriplet code such as this:
<%
                ArrayList statisticsList = something.getStatistics();
                Iterator itr1 = statisticsList.iterator();

                while (itr1.hasNext())
                {
                 dvo3_a = (VerificationVO) itr1.next();
                 dvo3_b = (VerificationVO) itr1.next();
                 dvo3_c = (VerificationVO) itr1.next();
                 ....
                    ....
                }
%>

dvo3_a, dvo_b, dvo_c are used in each iteration of the loop.  Notice that iter1.next() gets the next item.  So basically in one iteration I am getting 3 elements.
I am trying to convert the above to struts2 iterator tag However, looking at the examples and information provided in documentation I dont think it is possible?  I would REALLY REALLY hate and it would SUCK if I have to change my dataset to overcome this drawback of struts2 iterator tag.

A: Struts2 Iterator doesn't support what you want to do. Your code is just fine, what is the reason you want to move to struts iterator. If it is to not use java code in your jsp but use a tag then you have write your own custom tag for iterator which provides the functionality you need.


text:
Q: How to Use Two Different PHP Versions on One Server I have 2 websites on a single server, but one site's PHP version must be 5.2.17,
 and the other must be 5.5+.
I am using Ubuntu 14.04.2 LTS with Apache2 and PHP.
I have already installed PHP 5.5 (via apt-get) and 5.2.17 (via installation from source). Can somebody tell me how to configure and use different PHP versions for each specified website? Thanks.

A: You can get it by using PHP version manager and there are so many available, explore these:

*

*https://github.com/wilmoore/php-version

*https://github.com/CHH/phpenv

*https://github.com/c9s/phpbrew

A: You can run multiple PHP versions on one server using Docker, see my answer in another thread: Multiple PHP versions on the same box
Note that with this solution different PHP versions will be available on different ports.


text:
Q: How do i pass array values obtained from multiselection in dropdown as filter in url of ajax call I have a project dropdown.A user can multiselect projects.
I want to pass the values selected from multiselection in dropdown as filter parameters in ajax url.
The code is as follows:
             function CheckIfPresent(callback)
    {
        var proj = [];
        var urlprograms;
        if ($("#projNameDropdown :selected").text() != 'Select all projects') {
            $('#projNameDropdown :selected').each(function (i, sel) {
                proj[i++] = $(sel).val();
                if (proj.length == 1)
                    urlprograms = "(Project_Name/Project_Name eq '" + proj[0] + "')";
            });
            if (proj.length > 1) {
                for (i = 1; i < proj.length; i++) {
                    urlprograms += " or (Project_Name/Project_Name eq '" + proj[i] + "')";
                }
            }
        }

        $.ajax({
            url: _spPageContextInfo.webAbsoluteUrl + "/_api/web/lists('')/items?$select=*,Project_Name/Project_Name&$expand=Project_Name&$filter=" + urlprograms + "'",
            method: "GET",
            headers: {
                "Accept": "application/json; odata=verbose"
            },
             success: function (dataActive) {
             }
               error: function (dataActive) {
                console.log(dataActive);
            }

        });
        }

I am not able to reach the success method and get error.What is that I am doing wrong?


text:
Q: Difference in Django object creation call I'd like to know if there's a difference between the following two calls to create an object in Django
Animal.objects.create(name="cat", sound="meow")

and
Animal(name="cat", sound="meow")

I see both in test cases and I want to make sure I am not missing something.
thanks

A: The former also inserts a row in the database as well as creating the object.


text:
Q: Using Django to Create Child Sites I am creating a series of small sites, I'm using the django framework.  The theory goes a user comes to a master site, signs up, then he gets his own child site.
Example:

*

*navigate to example.com

*user creates an account "mysite"

*user then gets his own site:  mysite.example.com and he can configure this all he wants

My question:
* would it be better to have a "gold" version of the site that gets created for each site?
for instance:
cp ~/goldsite ~/mysite  and change the database pointers appropriately
** the downside is if I ever have to do maintenance on a file, I would have to change all subsites.
...or
* have one host and configure the database to support multiple sites.  The DB might get messy.
Any feedback would be great.

A: My suggestion would be to create a separate django base server which will serve as a web service api.
This web server will use rpcdjango which, when used with any method as a decorator, converts it to a HTTP callable method.
You will have to put little more effort on database design so that it does not become too complex.
Then create your individual web application using any technology (I prefer AngularJS and Bootstrap) which will connect to the django server using Ajax methods.
Here is an example django rpc4django:

*

*First, you need to add a new URL pattern to your root urls.py file. You can replace r'^RPC2$' with anything you like.

urls.py
urlpatterns = patterns('',
    # rpc4django will need to be in your Python path
    (r'^RPC2$', 'rpc4django.views.serve_rpc_request'),
)

*Second, add rpc4django to the list of installed applications in your settings.py.

settings.py
INSTALLED_APPS = (
    'rpc4django',
)

*Lastly, you need to let rpc4django know which methods to make available. Rpc4django recursively imports all the apps in INSTALLED_APPS and makes any methods importable via __init__.py*** with the @rpcmethod decorator available as RPC methods. You can always write your RPC methods in another module and simply import it in __init__.py.

testapp/__init__.py
from rpc4django import rpcmethod
# The doc string supports reST if docutils is installed
@rpcmethod(name='mynamespace.add', signature=['int', 'int', 'int'])
def add(a, b):
    '''Adds two numbers together
    >>> add(1, 2)
    3
    '''
    return a+b

rpc4django documentation


text:
Q: C# Linked list nested for loops Let's say I have a simple linked list in C#. For example Creating a very simple linked list any of these. And I want to iterate through that list with triple nested for loop. I can show an example with array of what I want to achieve:
int[] a = new int[10];
//some code to place elements into that array
for(int i = 0; i<a.length; i++){
 for(int q = i; q<a.length; q++){
  for(int z = q; z<a.length; z++){
    //do stuff with a[i], a[q], a[z], for example send them to a function
  }
 }
}

How would could I do that if I had a linked list instead of an array? Let's say I need to send all these 3 elements to a function.
Thank you for your answers in advance.

A: Generally speaking, you're going to iterate the type of linked list you're talking about with a while loop, e.g.
LinkedList a = new LinkedList();
//some code to place elements into that array
var node = a.Head;
while(node != null)
{
   var nodeQ = node;
   while (nodeQ != null)
   {
       var nodeZ = nodeQ;
       while (nodeZ != null)
       {
           // do stuff with node, nodeQ, nodeZ
          nodeZ = nodeZ.Next;
       }
       nodeQ = nodeQ.Next;
   }
   node = node.Next;
}


text:
Q: Slow insert on conflict do nothing for Postgres 13 I'have rather odd case.
I have a "cache" table in Postgres and I need to insert 100K - 1M records in parallel from different sources. Sources can try to insert duplicated data (by Primary key).
I'm too lazy to write complex sync code around INSERT process that is why I do it this way:

*

*create UNLOGGED table WITH (autovacuum_enabled=false)

*do insert into TABLE (foo,bar) values (1,2) on conflict do nothing.

I'm fine with lower perf compared to the COPY command since writing synchronisation logic is 100 times more expensive from business point of view than slow insert. We can live with relatively slow inserts.
BUT the performance is waaay to slow.

*

*It takes around 12.000 ms to insert 50.000 rows. around 4-5 records per millisecond.

*Each row has 150 columns.

*insert batch size in 50.000

*Table has single PK (I can't drop it)

*The pattern is to insert 100K-1M records.

*Table won't grow more than 10M records.

*Postgres version is 13.2

*I'm using JDBC driver 42.0.0

*Table has only on PK (varchar, long)

Why is it so slow?
Can I do something with it?


text:
Q: Simple click image opens the image in bigger version like lightbox 2 I'm looking for a simple javascript that when clicked on an image, makes it appear in bigger version in front of the html, on the middle of the page.
When picture is big, then if clicked anywhere on the page, it dissapears.
Hope you can help me :)

A: http://jquery-lightbox.com/fr/jquery-popup-simple-lightbox.html?x=44&y=15
Why not lightbox 2, it's easy to use and powerfull


text:
Q: nginx не хочет работать на 80 порту Если кратко, то если поставить nginx прослушивать 80 порт, он его прослушивает, но при открытии сайта: connection refused, если ставить любой другой порт, то все работает. Apache при этом присутствует, но выключен, и там стоит другой порт, поэтому конфликт с ним исключен. В качестве файрвола стоит iptables.
CentOS Linux 7.5.1804, nginx 1.15.2
Хостинг Digitalocean. Мало ли, это поможет как-то (файрвол в DO отключен).
Подробнее
nginx.conf
user  user;
worker_processes  auto;
worker_rlimit_nofile 100000;

pid        /var/run/nginx.pid;

events {
    worker_connections  4096;
    multi_accept on;
}

http   {
    index         index.html index.php;
    include       mime.types;
    types { application/font-woff2; }
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" $status $body_bytes_sent "$http_referer" "$http_user_agent" - "$request_id"';
    log_format  error403  '$remote_addr - [$time_local] "$request" "$http_user_agent" - "$request_id"';

    keepalive_timeout   5;
    autoindex       off;
    server_tokens       off;
    port_in_redirect    off;
    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    etag        off;

    client_max_body_size 64m;
    client_body_buffer_size 128k;
    client_header_buffer_size 16k;
    large_client_header_buffers 4 16k;

    fastcgi_buffer_size 16k;
    fastcgi_buffers 4 16k;

    include /etc/nginx/sites-enabled/*.conf;

}

default.conf
server {
        listen 80 default_server;
        listen [::]:80 default_server ipv6only=on;
        root /home/user/public_html;
        index index.html;

        location / {
             try_files $uri $uri.html $uri/ =404;
        }
}

sub.domain.ru.conf
server {
    listen 80;
    server_name sub.domain.ru;

    access_log  /var/log/nginx/access.sub.domain.ru.log;
    error_log   /var/log/nginx/error.sub.domain.ru.log  error;

    set $USER_ROOT /home/user/web/sub.domain.ru/public_html;
    root $USER_ROOT/public;

        gzip off;

    location / {
              try_files $uri $uri/ /index.php?$query_string;
        }

        location ~ \.php$ {
                try_files $uri =404;
                fastcgi_split_path_info ^(.+\.php)(/.+)$;

                add_header X-Processing-Time $request_time always;
                add_header X-Request-ID $request_id always;
                add_header X-UA-Compatible 'IE=Edge,chrome=1';
                add_header Link "<$scheme://$http_host$request_uri>; rel=\"canonical\"" always;

                fastcgi_pass            127.0.0.1:9000;
                fastcgi_index           index.php;
                include                 fastcgi_params;
                fastcgi_keep_conn       on;
        }

        location ~ /\.ht {
                deny all;
        }
}

netstat -tupln
netstat -tupln
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address           Foreign Address         State       PID/Program name
tcp        0      0 127.0.0.1:9000          0.0.0.0:*               LISTEN      879/php-fpm: master
tcp        0      0 127.0.0.1:3306          0.0.0.0:*               LISTEN      1577/mysqld
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      1184/sshd
tcp        0      0 127.0.0.1:6379          0.0.0.0:*               LISTEN      860/redis-server 12
tcp        0      0 127.0.0.1:11211         0.0.0.0:*               LISTEN      861/memcached
tcp        0      0 127.0.0.1:6380          0.0.0.0:*               LISTEN      876/redis-server 12
tcp        0      0 0.0.0.0:111             0.0.0.0:*               LISTEN      535/rpcbind
tcp        0      0 0.0.0.0:80              0.0.0.0:*               LISTEN      1200/nginx: master
tcp        0      0 127.0.0.1:9080          0.0.0.0:*               LISTEN      16639/docker-proxy
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1153/master
tcp        0      0 255.255.255.255:10010    0.0.0.0:*               LISTEN      15801/docker-contai
tcp        0      0 0.0.0.0:17000           0.0.0.0:*               LISTEN      1496/perl
tcp6       0      0 :::9443                 :::*                    LISTEN      16627/docker-proxy
tcp6       0      0 :::22                   :::*                    LISTEN      1184/sshd
tcp6       0      0 :::111                  :::*                    LISTEN      535/rpcbind
tcp6       0      0 :::80                   :::*                    LISTEN      1200/nginx: master
tcp6       0      0 ::1:25                  :::*                    LISTEN      1153/master
udp        0      0 127.0.0.1:323           0.0.0.0:*                           533/chronyd
udp        0      0 0.0.0.0:702             0.0.0.0:*                           535/rpcbind
udp        0      0 0.0.0.0:17000           0.0.0.0:*                           1496/perl
udp        0      0 0.0.0.0:111             0.0.0.0:*                           535/rpcbind
udp6       0      0 ::1:323                 :::*                                533/chronyd
udp6       0      0 :::702                  :::*                                535/rpcbind
udp6       0      0 :::111                  :::*                                535/rpcbind

iptables -L
iptables -L
Chain INPUT (policy ACCEPT)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:8099
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:http
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:22
ACCEPT     tcp  --  anywhere             anywhere             tcp dpt:17000
ACCEPT     all  --  anywhere             anywhere             state RELATED,ESTABLISHED
ACCEPT     icmp --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     tcp  --  anywhere             anywhere             state NEW tcp dpt:ssh
REJECT     all  --  anywhere             anywhere             reject-with icmp-host-prohibited

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination
DOCKER-USER  all  --  anywhere             anywhere
DOCKER-ISOLATION-STAGE-1  all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere             ctstate RELATED,ESTABLISHED
DOCKER     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
ACCEPT     all  --  anywhere             anywhere
REJECT     all  --  anywhere             anywhere             reject-with icmp-host-prohibited

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

Chain DOCKER (1 references)
target     prot opt source               destination
ACCEPT     tcp  --  anywhere             255.255.255.255           tcp dpt:https
ACCEPT     tcp  --  anywhere             255.255.255.255           tcp dpt:http

Chain DOCKER-ISOLATION-STAGE-1 (1 references)
target     prot opt source               destination
DOCKER-ISOLATION-STAGE-2  all  --  anywhere             anywhere
RETURN     all  --  anywhere             anywhere

Chain DOCKER-ISOLATION-STAGE-2 (1 references)
target     prot opt source               destination
DROP       all  --  anywhere             anywhere
RETURN     all  --  anywhere             anywhere

Chain DOCKER-USER (1 references)
target     prot opt source               destination
RETURN     all  --  anywhere             anywhere

IP адреса, некоторые порты и домен изменены.
Логи nginx почти пустые, при рестарте nginx
2018/07/26 09:25:04 [notice] 18566#18566: signal process started

Единственное что в логах насторожило, постоянное подключение с этого IP:
198.199.74.88 - - [26/Jul/2018:05:37:37 +0300] "GET /users/sign_in HTTP/1.1" 404 162 "-" "Go-http-client/1.1"

Если nginx находится на любом другом порту, например, там в iptables был разрешен 8099, то все работает, но стоит порт сменить на 80, то connection refused и в логи access не пишется что было подключение.

A: Проверьте настройки SELinux, возможно порт 80 не добавлен в список разрешённых:
semanage port -l | grep -w 80


text:
Q: Add database data to every razor view page So I'm looking to get data from the database and add it to EVERY view page. So adding it to the Views/Shared/_Layout.cshtml
How can I do this without adding the models to the view in every controller?
I want to add menu items dynamically from the database to every view, I've got this in _Layout.cshtml:
@foreach (var item in Model)
{

@item.Title

}

And this in my HomeController:
return View(db.Menus.ToList());

But I don't want to do this in every controller action, how can I make this simpler?

A: Use RenderAction method to render only the part you want.
I strongly encourage you to check MVC Music Store project - it has a lot of best practices in it. The solution for your exact problem lies in _Layout.cshtml file, the code:
   @{Html.RenderAction("GenreMenu", "Store");}

A: Lets assume you have a model, which represents your menu in your database
class MenuItem()
{
  public int Id { get; set; }
  public string Name { get; set; }
  //...
}

In order to get this into every viewpage, you need to create a "BaseController", from which every other controller inherits. In this controller you define the menu in the constructor.
 public class BaseController : Controller
 {
    public BaseController()
    {
        //I don't know how you get your data
        ViewBag.DatabaseMenu =  repository.GetMenuItems();
    }
 }

Fromn this point on add : BaseController to all your controllers and you'll have a DatabaseMenu available in your ViewBag on all pages to build your menu from.
How you do this in your view, is up to you. You can create a collection of type List<MenuItem> and say List<MenuItem> Menu = ViewBag.DatabaseMenu; and iterate with foreach over your items to create the menu


text:
Q: Remove Gaps When Wrapping Different Height Elements I have this html...

... And this css...
.img-panel {
    height: 60vh;
    width: 95vw;
    overflow-y: scroll;
    overflow-x: hidden;
    display: flex;
    padding: 0 1vw;
    justify-content: start;
    flex-wrap: wrap;
    align-content: start;
}

.img {
    width: 18vw;
    border-radius: 1vmin;
    margin: 1vh 0.5vw;

    height: 8vh;
    border: 1px solid black;
}

.img--high {
    height: 18vh;
}

I'd like to remove the gaps when wrapping and make the images flow to the bottom of each other so that instead of having this, I have something like this.
Is there a way to achieve that using just css?

A: This functionality used to require Javascript using libraries like Packery but with css grid you can accomplish it without Javascript (See snippet below). It's is not quite as good a Javascript assisted layout like Packery but it will do in a pinch.
This article has good insight into masonry with css
https://www.smashingmagazine.com/native-css-masonry-layout-css-grid/

body {
  background-color: white;
}

.container {
  column-count: 4;
  column-gap: 12px;
}
img {
  max-width: 100%;
}

.container div {
  display: grid;
  break-inside: avoid;
  grid-template-rows: 1fr auto;
  margin: 0 0 12px 0;
}

.container div > img {
  grid-row: 1 / -1;
  grid-column: 1;
}


text:
Q: Calculate coordinates on the circle to draw N number of equal height rectangles I am trying to divide a circle into several rows with each row containing multiple cells of equal height and width. In order to do this I would like to figure out how to divide the circle into N number of rows first and then divide that row into Mn number of cells for each row n.
For clarity below is the information available to draw the circle and rectangular cells inside the circle.

*

*center cx, cy and radius r.

*Number of rows is N.

*All cells in all rows should have equal width and height.

I am specifically looking for a way to calculate all the x,y locations of both the ends of the rectangles that represent each row. These x,y coordinates must be on the circumference of the circle as in the sample picture below. But some edges of the row with in the circle may not be part of a full cell to meet the criteria of equal sides for each cell.
Sample picture here
And my attempt to draw this with Javascript is here jsfiddle But you can see the ends of my rectangles or not on the circle and I don't have a way to calculate the x,y coordinates.