text:
Q: How to create PDF using a single worksheet in a loop Current Situation
My Excel workbook contains anywhere from 10 to 32 worksheets used as templates. It also contains 1 worksheet called "Report". I currently loop through all template worksheets and put the information into the Report worksheet, then I create a PDF using that report worksheet.
However this creates 1 PDF per template because it passes through my Report worksheet.
Everytime I send the information to my Report worksheet, that gets turned into a PDF. The problem with that is it generates a PDF everytime my report worksheet gets filled in. I am not exporting my templates as PDF.

Code
Here's the code that generates 1 PDF file per template:
Sub CreatePDF()
Dim currentSerialNumber As String 'Worksheet name is the same as the serial number
Dim ws As Worksheet
Dim pdfFilePath As String

'Create a report for each serial number written in the Summary worksheet and export it to PDF
For i = 10 To Rows.Count 'Start at row #10
    If IsEmpty(Worksheets("Summary").Range("B" & i).Value) = False Then
        'Do work
        currentSerialNumber = Worksheets("Summary").Range("B" & i).Value 'Fetches the serial number
        pdfFilePath = "C:\" & currentSerialNumber & ".pdf" 'Ex: C:\1000.pdf
        Worksheets(currentSerialNumber).Activate 'Activate the template for this current serial number
        GenerateReport (currentSerialNumber) 'Put all the info from the template of this serial # into the report worksheet
        Set ws = Worksheets("Reports") 'Set ws object as the report worksheet
        ws.UsedRange.Select
        ws.ExportAsFixedFormat Type:=xlTypePDF, _
                               Filename:=pdfFilePath, _
                               Quality:=xlQualityStandard, _
                               IncludeDocProperties:=True, _
                               IgnorePrintAreas:=False, _
                               OpenAfterPublish:=False
    Else
        'No more serial numbers found, exit this loop
        Exit For
    End If
Next i
End Sub

Goal
I want to loop through each template, send the information to my report, add that report information as a page in a PDF file, and repeat until no more templates.
The similar question linked would work if I was printing all my templates. But I'm actually sending my template information to a more professional, sleek looking report Worksheet. The report is then the one that I want into a PDF. The problem is, I only have one report worksheet that gets filled in by multiple templates.
Is this possible using VBA in Excel?

A: I think you can handle this in a loop. My idea is to do the following:
After copying the data to the "Report" sheet, create a Copy of that sheet in a new workbook. This new workbook will contain each of the "Report" sheets, and then you can export the entire new workbook
I haven't tested it, but let's try something like this:
Sub CreatePDF()
Dim currentSerialNumber As String 'Worksheet name is the same as the serial number
Dim ws As Worksheet
Dim pdfFilePath As String
Dim reports As Workbook

'## Add a new workbook an
Set reports = Workbooks.Add
ThisWorkbook.Activate
Do Until reports.Worksheets.Count = 1
    reports.Worksheets(reports.Worksheets.Count).Delete
Loop

'Create a report for each serial number written in the Summary worksheet and export it to PDF
For i = 10 To Rows.Count 'Start at row #10
    If IsEmpty(Worksheets("Summary").Range("B" & i).Value) = False Then
        'Do work
        currentSerialNumber = Worksheets("Summary").Range("B" & i).Value 'Fetches the serial number
        pdfFilePath = "C:\" & currentSerialNumber & ".pdf" 'Ex: C:\1000.pdf
        Worksheets(currentSerialNumber).Activate 'Activate the template for this current serial number
        GenerateReport (currentSerialNumber) 'Put all the info from the template of this serial # into the report worksheet
        Set ws = Worksheets("Reports") 'Set ws object as the report worksheet
        '## Copy the Reports sheet to the new workbook
        ws.Copy After:=reports.Worksheets(reports.Worksheets.Count)

    Else
        'No more serial numbers found, exit this loop
        Exit For
    End If
Next i

'## There is an empty worksheet in the Reports file, so we can remove it:
reports.Worksheets(1).Delete
'## select all sheets in reports:
reports.Worksheets.Select
'## Export the entire file as fixedformat:
reports.ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
                           Filename:=pdfFilePath, _
                           Quality:=xlQualityStandard, _
                           IncludeDocProperties:=True, _
                           IgnorePrintAreas:=False, _
                           OpenAfterPublish:=False
End Sub


text:
Q: Why do all links on my Wordpress site show me the homepage? When I click on any link on my Wordpress site it loads homepage, but link URL changes on the address bar?
What could be wrong and how can I fix it?

A: Typically this means that some template files of your theme are missing and default index.php is loaded instead. See 'Template Hierarchy'. Be sure to  have a proper template file for the page/archive you are viewing. For example, you need a single.php or singular.php template to display a single post page and a category.php or archive.php to display a category page.
Another possible reason is wrong configuration of your site permalinks structure (Settings -> Permalinks) or wrong .htaccess file. Or some confilcts of rewrite parameters when registering custom post types/taxonomies.
Your question is too common to find out the exact reason.

A: Sometimes, changes made to the .htaccess file can cause WordPress to redirect all links back to the home page instead of showing the page requested.
In those cases, you need to reset the permalinks within WordPress will resolve this issue and for that.

*

*Go to Settings > Permalinks.

*Make note of the current setting.(If you are using a custom structure, copy or save the custom structure somewhere.)

*Select the Default option.

*Click Save Changes.

*Now select the previous setting you had before Default was selected.

*Click Save Changes.

If you are getting 404 Not Found errors when you click on links in WordPress, then some code may be missing from the .htaccess file.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Deep into ReactJS I'm using react since 6 to 8 month. I've gone through the about the react basics and created some application. But some of the following questions are digging into my mind -

*

*Where do we need to call the API request? In the componentWillMount method or componentDidMount method. I've gone through some answer of hat similar question but I didn't understand properly.Any best case In which componentDidMount is better than the componentWillMount ? In the same scenario.

*Any practical example of when to use the componentWillUnmount method? Don't use timer example, Some real example.

*What is the use of componentWillUpdate and componentDidUpdate method? It calls after the shouldComponentUpdate (when it returns true), It is used for displaying the progress like message i.e. data loading is progress or for what?

*We can write the call type component with or without the constructor method in react. Also, we can initialize the state with and without the constructor. Like below,
class app extends Component {
  state = {name: 'sss'}

  render() {
    return
{this.state.name}

  }
}

So why the constructor method is used? If we can achieve the same without the constructor.

A: Probably not going to be able all your questions but maybe I can be able to give you some direction.
1) componentWillMount VS componentDidMount
It is better to make an API call in componentDidMount because it means your component finished rendering. Use case of this probably showing a loading indicator while still waiting for a response from the server or etc. There is a good blog post here.

This function (refering to componentWillMount) is called right before the component's first render, so
  at first glance it appears to be a perfect place to put data fetching
  logic.
There's a "gotcha," though: An asynchronous call to fetch data will
  not return before the render happens. This means the component will
  render with empty data at least once.

2) componentWillUnmount
There is lots of use cases for this life-cycle event. One of them can be removing any event listeners before un-mounting the component. An example use case for this type of use can be reavt-native's BackHandler
componentDidMount() {
  BackHandler.addEventListener('hardwareBackPress', this.handleBackButton);
}

componentWillUnmount() {
  BackHandler.removeEventListener('hardwareBackPress', this.handleBackButton);
}

3) componentWillUpdate && componentDidUpdate && shouldComponentUpdate
When you have a parent-child relationship in component you sometimes need to pass props to the child components. When some action happen and the value of the parent component change, you pass a new value to the child component. If you are using this value for making API request or render child component you can be notified before the update happens. You will have the access for nextProp and nextState. You can use these to make calculations and run actions between renders. You can use componentDidUpdate to notify parent component that the update has finished and you can use shouldComponentUpdate to prevent unnecessary updates in child component.
For Example
class ParentComponent extends Component {
  constructor(props) {
    this.state = {
      item: {}
    }
  }
  componentDidMount() {
    this.setState({
      item: {
        name: 'Item Name',
        count: '24',
        lastChangeTime: new Date()
    });
    setTimeout(() => {
      this.setState({
        item: {
          name: 'Item Name',
          count: '24',
          lastChangeTime: new Date()
      });
    }, 5000);
    setTimeout(() => {
      this.setState({
        item: {
          name: 'Item Name',
          count: '24',
          lastChangeTime: new Date()
      });
    }, 10000);
  }
  childWillUpdate() {
    console.log('Child component gonna update. Show loading indicator.');
  }
  childUpdated() {
    console.log('Child component finished updating you can close loading indicator inside the parent');
  }
  render() {
      return (
        <ChildComponent
          childWillUpdate={this.childWillUpdate}
          childUpdated={this.childUpdated}
          item={this.state.item}
        />
      )
  }
}

class ChildComponent extends Component {
  constructor(props) {
    this.state = {
      item: props.item || null
    }
  }
  componentWillReceiveProps(nextProps) {
    if(nextProps.item.count !== this.props.item.count || nextProps.item.name !== this.props.item.name) {
      // do not set state if only the change is lastChangeTime
      this.setState({ item: nextProps.item });
    }
  }
  shouldComponentUpdate(nextProps, nextState) {
    // prevent update of the component if only change is on lastChangeTime
    return (nextProps.item.count !== this.props.item.count || nextProps.item.name !== this.props.item.name)
  }
  componentWillUpdate(nextProps, nextState) {
    // notify parent component that child gonna update
    this.props.childWillUpdate();
  }
  componentDidUpdate(prevProps, prevState) {
    // notify parent component that update complete
    this.props.childUpdated();
  }
  render() {
      return (this.state.item ?
{this.state.open}
 :
Loading...
)
  }
}

4) constructor
Although your given examples are correct and can be used there is a different use case like I showed at the previous example. You might need to set state with a value from parent that passed with props. In this case you can use constructor to receive that prop and then set it to state.
class MyClass extends React.component{
    constructor(props){
        super(props);
        this.state = {
          nextCall: props.item.lastChange.getTime() + (1000 * 60 * 5)
    }
}

This might not be a complete explanation or use case example for all the mentioned life-cycle methods but I hope they'll give you some ideas about how you can use them and how you can get better performance out of your applications or websites. At the end it all depends on how you use them and when you use them.


text:
Q: videogular2 set next video and play automatically I made simple player in ionic 2 with videogular-2. When i press start button first video is playing X number of time after getting end event i play video again for X time. For example first.mp4 is playing 2 time after i will set next video in source of videogular video is set successfully but next loaded video is not playing automatically. If i press play button video plays.
html
<ion-content>

    <ion-row>
        <ion-col text-center>

First > Second > Third > Fourth > Fifth > Sixth > Seventh

        </ion-col>
    </ion-row>

    <ion-row>
        <ion-col col-sm-1 col-md-1 col-lg-1 col-xl-1>
        {{duration}}
        </ion-col>
        <ion-col col-sm-11 col-md-11 col-lg-11 col-xl-11>
            <button ion-button (click)="playVideo()" [hidden]="isPlaying">Start Workout</button>

            <vg-player (onPlayerReady)="onPlayerReady($event)" [hidden]="!isPlaying">
                <vg-overlay-play></vg-overlay-play>
                <video [vgMedia]="media" #media id="singleVideo" preload="auto" crossorigin>
                    <source *ngFor="let video of sources" [src]="video.src" [type]="video.type">
                </video>
            </vg-player>
        </ion-col>

    </ion-row>
</ion-content>

ts
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { VgAPI } from 'videogular2/core';
import { VgControlsModule } from 'videogular2/controls';
import { VgOverlayPlayModule } from 'videogular2/overlay-play';
import { VgBufferingModule } from 'videogular2/buffering';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage
{
    isPlaying : any;
    duration : any;
    sources : Array<Object>;
    api:VgAPI;
    constructor(public navCtrl: NavController)
    {
        this.isPlaying = false;

        this.sources = new Array<Object>();
        this.sources.push({
          src: "small.mp4",
          type: "video/mp4"
        });

        //this.setCurrentVideo("small.mp4","video/mp4");
    }
    setCurrentVideo(source : string, type : string)
    {
        this.sources = new Array<Object>();
        this.sources.push({
          src: source,
          type: type
        });
        this.api.getDefaultMedia().currentTime = 0;
    }
    onPlayerReady(api:VgAPI)
    {
        var x = 1;
        this.api = api;

        this.api.getDefaultMedia().subscriptions.ended.subscribe(
            () =>
            {
                x++;
                if(x>2)
                {
                    this.setCurrentVideo("SampleVideo_1280x720_2mb.mp4","video/mp4");
                    x = 2;
                }
                else
                {
                    this.api.play();
                }
            }
        );

    }
    playVideo()
    {
        this.isPlaying = true;
        this.api.play();
        this.duration = Math.ceil((this.api.duration * 5));
    }
}

After setting next video using this line
this.setCurrentVideo("SampleVideo_1280x720_2mb.mp4","video/mp4");

i tried this.api.play(); but they give error like below
Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause().

A: I just fix that following way i dont known that is proper or not.
html

<ion-row>
    <ion-col text-center>

First > Second > Third > Fourth > Fifth > Sixth > Seventh

    </ion-col>
</ion-row>

<ion-row>
    <ion-col col-sm-1 col-md-1 col-lg-1 col-xl-1>
    {{duration}}
    </ion-col>
    <ion-col col-sm-11 col-md-11 col-lg-11 col-xl-11>
        <button ion-button (click)="playVideo()" id="myButton" [hidden]="isPlaying">Start Workout</button>

        <vg-player (onPlayerReady)="onPlayerReady($event)" [hidden]="!isPlaying">
            <vg-overlay-play></vg-overlay-play>
            <video [vgMedia]="media" #media id="singleVideo" preload="auto" crossorigin>
                <source *ngFor="let video of sources" [src]="video.src" [type]="video.type">
            </video>
        </vg-player>
    </ion-col>

</ion-row>

js
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { VgAPI } from 'videogular2/core';
import { VgControlsModule } from 'videogular2/controls';
import { VgOverlayPlayModule } from 'videogular2/overlay-play';
import { VgBufferingModule } from 'videogular2/buffering';
import * as $ from 'jquery'

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage
{
    isPlaying : any;
    duration : any;
    sources : Array<Object>;
    api:VgAPI;
    constructor(public navCtrl: NavController)
    {
        this.isPlaying = false;

        this.sources = new Array<Object>();
        this.sources.push({
          src: "small.mp4",
          type: "video/mp4"
        });

        //this.setCurrentVideo("small.mp4","video/mp4");
    }
    setCurrentVideo(source : string, type : string)
    {
        this.sources = new Array<Object>();
        this.sources.push({
          src: source,
          type: type
        });
        this.api.getDefaultMedia().currentTime = 0;
    }
    onPlayerReady(api:VgAPI)
    {
        var x = 1;
        this.api = api;

        this.api.getDefaultMedia().subscriptions.ended.subscribe(
            () =>
            {
                x++;
                if(x>2)
                {
                    this.setCurrentVideo("SampleVideo_1280x720_2mb.mp4","video/mp4");

                    this.onPlayerReady(this.api);

                    setTimeout(function ()
                    {
                        $("#myButton").trigger( "click" );
                    },1000);

                    x = 0;
                }
                else
                {
                    this.api.play();
                }
            }
        );

    }
    playVideo()
    {
        this.isPlaying = true;
        this.api.play();
        this.duration = Math.ceil((this.api.duration * 5));
    }

}


text:
Q: What selectors can be inside jQuery I cannot find a complete list (or specification).

*

*$(document)

*$(".myclass")

*$("#myid")

*$("css_selector")

*$("jQuery_selector")

What else? For example, name attribute can be used instead of id attribute?

A: There is a lot of selectors
You can find it at  w3school for example : https://www.w3schools.com/jquery/jquery_ref_selectors.asp


text:
Q: Compiling Linux Kernel with headers (AMD FX Piledriver) I have compiled Linux kernel 3.9.7 for my AMD FX 6300 (with AMD selected as processor vendor during kernel compilation). After the installation, I restarted the system, and found that the "linux-headers" are not installed (actually I was able to find only the kernel source, not header files at kernel.org).
The consequence:
Nvidia graphic driver and many softwares (which depends on display settings) are not working anymore.
The previous installation of nvidia graphics drivers is also not working anymore (however if I start with previous kernel 3.2.xx, it works fine). I tried to re-install nvidia graphics but of no use. I suspect that it might be due to missing linux-headers which I can't see in /usr/src/ directory.
The question:
From where can I get the  linux-headers source for 3.9.7 kernel ?
In my opinion it doesn't make  sense to use the linux-headers from Ubuntu repo, because I have compile the kernel on my machine, while headers from ubuntu repos are result of their own compilations (compiler mismatch?).

A: Did you compile it under Debian or Ubuntu (EDIT: after rereading I see it's sort of implied where you say "Ubuntu repo" above) and then make a .deb package for it?  You might have made a package that doesn't contain the headers.
The following is excerpted from here:

If I think about it - it's possible that the kernel headers aren't
  installed because in the Debian kernel howto we create a kernel .deb
  package which doesn't contain the headers.
You can try to combine the Debian kernel howto with this one:
  http://www.howtoforge.com/kernel_compilation_ubuntu_p2
Run
fakeroot make-kpkg --initrd --append-to-version=-custom
  kernel_image kernel_headers
instead of
fakeroot make deb-pkg
This should create a kernel headers deb
  package.
If that doesn't work, you can still compile a kernel the traditional
  way, without creating a deb package, as shown here:
  http://www.howtoforge.com/kernel_compilation_fedora_p2 That way the
  headers will be installed for sure.


text:
Q: Everything works in Sandbox, but I get IdentityException using PayPal Live I am integrating PayPal payments into my website using the PayPal REST API using the .NET SDK (https://www.nuget.org/packages/PayPal). My website is running as an App Service in Microsoft Azure. I have a testing slot configured to use PayPal Sandbox, and a production slot which uses the Live credentials (configuration settings are in the App Settings, and are slot-specific).
Everything works fine in Sandbox, and I am able to authenticate and get an access token using the live configuration, but when I try to process anything I get a PayPal.IdentityException (I tried Payments as well as Billing Plans and Agreements). If I look at the IdentityException Response (or Details), I get this:
{"error":"invalid_token","error_description":"The token passed in was not found in the system"}

Digging further, it seems that the ApiContext that is created has the AccessToken set, but the Config property is null. If I look at the API request (from PayPalResource.LastRequestDetails.Value) I see that even though it's using the live configuration, it's sending the request to api.sandbox.paypal.com, not the live API. This seems to be a problem with my ApiContext, which I establish as follows:
public static APIContext Authenticate()
{
    string clientId = ConfigurationManager.AppSettings["PayPalClientId"];
    string clientSecret = ConfigurationManager.AppSettings["PayPalSecret"];
    string mode = ConfigurationManager.AppSettings["PayPalMode"];

    var config = new Dictionary<string, string>();
    config.Add("mode", mode);
    config.Add("clientId", clientId);
    config.Add("clientSecret", clientSecret);

    accessToken = new OAuthTokenCredential(config).GetAccessToken();
    return new APIContext(accessToken);    // <--- problem here
}

Apart from manually constructing the Config dictionary rather than using the ConfigManager to create it automatically from a custom config section, this follows the .NET SDK documentation very closely. What am I doing wrong?

A: The problem here is that all that is passed to the APIContext constructor is the accessToken. Without having the settings in the custom config section of Web.config or App.config, APIContext defaults to using the sandbox API.
The solution is to explicitly set the Config property using an Object Initializer:
return new APIContext(accessToken) { Config = config };    // <---- fixed


text:
Q: will paginate with multiple tables I have following tables :

*

*users

*accounts ( user has_one account )

*pictures ( user has_many pictures )

I want to display a User along with its related account and pictures. This is a typical N+1 queries problem and I solved it using eager loading.
User.includes(:account, :pictures).all

I am trying to use will_paginate gem. How do I include this eager loading mechanism into will_paginate ?
I found a similar question here: Using will_paginate with multiple models (Rails). But the links in the answer are out of place and the answer itself is quite old. Furthermore, it uses raw sql queries, which I don't prefer.
I want the output as follows :
user.name account.field1 account.field2 picture.count
abc1       abcf1          abcf2           4
zxc        zxcf1          zxcf2           7

So basically when I do user.name , it will not execute a query but just get the data from the variables;
same way when I do user.account.field1 it should fetch it from the variable and not execute a query.

A: The paginate method is similar to all method. So you can simply do this:
User.includes(:account, :pictures).paginate(
  :page => params[:page], :per_page => 30)

OR
User.paginate(:include=> [:account, :pictures],
  :page => params[:page], :per_page => 30)

Note:
The will_paginate gem provides a convenience method on the Array class for pagination:
[1,2,3,4].paginate(:page => 1, :per_page=>2)

A: I finally used pagination on a array rather than the gem itself.
    current_page = Integer(params[:page]||1)
    per_page = 250
    @users_r = User.all(:conditions=>"some condition",:limit=>per_page,:offset=>per_page*(current_page-1),:include=>[:account,:user_info ,:pictures])
    count = @users_r.length
    @users = WillPaginate::Collection.create(current_page, per_page, count) do |user|
      user.replace(@users_r)
    end
    @users.paginate(params)


text:
Q: Not able to create table from CSV in Databricks I am trying to create a table from a CSV file stored in Azure Storage Account. I am using the below code. I am using Azure Databricks. Notebook is in Python.
%sql
drop table if exists customer;
create table customer
using csv
options ( path "/mnt/datalake/data/Customer.csv", header "True", mode "FAILFAST", inferSchema "True");

I am getting the below error.
Unable to infer schema for CSV. It must be specified manually.
Anyone having any idea, on how to resolve this error.

A: I have reproduced above and got the below results.
This my csv file in data container.

This is my mounting:

I have mounted this and when I tried to create table from CSV file, I got same error.

The above error arises when we don't give correct path in the csv file. In file path after /mnt give mount point(here onemount for me) not container name as we already mounted till container.

Result:


text:
Q: Optimization of Pig Script I have written a 'Pig Script' which is processing Sequence files given as input.
It is working fine but there is one problem mentioned below.
I have repetitive statements in my pig script,  as shown below:
Filtered_Data _1= FILTER BagName BY ($0 matches 'RegEx-1');
Filtered_Data_2 = FILTER BagName BY ($0 matches 'RegEx-2');
Filtered_Data_3 = FILTER BagName BY ($0 matches 'RegEx-3');
So on…

Question :
So is there any way by which I can have above statement written once and
then loop through all possible "RegEx" and substitute in Pig script.
For Example:
Filtered_Data _X  =   FILTER BagName BY ($0 matches 'RegEx');  ( have this statement once )
( loop through all possible RegEx and substitute value in the statement )

Right now I am calling Pig script from a shell script, so any way from shell script will be also be welcome or even Java wrapper...
Thanks in advance.
Happy Pigging!!!!


text:
Q: Find IMEI no in wp7? I want to use IMEI no in my application. so I search for how to get IMEI no. in wp7 but every time I got DeviceUniqueId so IMEI no and DeviceUniqueId is same thing or not then how can I get IMEI number in wp7?

A: For privacy and security reasons, the IMEI number is not accessible to third party developers. The DeviceUniqueID is not the same as the IMEI number.

A: Can you use this http://www.nickharris.net/2010/09/how-to-place-a-phone-call-on-windows-phone-7-using-phonecalltask/ to make a phone call on *#06#  - being the code to obtain the IMEI?


text:
Q: Storing XML values as a list using ClosedXML package I'm using the C# CLosedXML package to acquire XML data values and place them into a list. From what I found online, the only example of storing the values into an array in a list is as shown below.
var dataList = new List<string[]>()
{
    table.DataRange.Rows().Select(tableRow => tableRow.Field("Story").GetString()).ToArray(),
    table.DataRange.Rows().Select(tableRow => tableRow.Field("Level").GetString()).ToArray(),
    table.DataRange.Rows().Select(tableRow => tableRow.Field("Combo").GetString()).ToArray(),
    table.DataRange.Rows().Select(tableRow => tableRow.Field("Location").GetString()).ToArray(),
    table.DataRange.Rows().Select(tableRow => tableRow.Field("Asset").GetString()).ToArray(),
}

I have tried to print the details out in a console to visualize if the data was correctly stored in the list array which I've created. However, the dataList count is 5. Is it caused by the array size and is there a better way of coding this?
for (int i = 0; i < dataList.Count ; i++)
{
    for (int j = 0; j < totalRows; j++)//totalRows more than 10
    {
        Console.WriteLine("Column {0} details: {1}", i+1, dataList[i][j]);
    }
}

Thank you!

A: You are explicitly initializing the dataList variable as a list of 5 elements, each of which is an array of strings.

A: You can use a foreach like:
int index = 0;
foreach (string[] item in dataList)
 {
   for (int i = 0; i < item.Length; i++)
   {
      Console.WriteLine("Column {0} details: {1}", index+1, item[i]);
   }
        index++;
}


text:
Q: Как правильно подключиться к базе данных в шаблоне MVC Доброго времени суток я создаю свой сайт с регистрацией, на системе MVC.
Как лучше реализовать подключение к базе данных?
Не хотелось бы в каждой функции класса дублировать создание класса
$pdo = new Pdo

и не хотелось бы делать наследование класса
class my class extends Pdo {}

A: Вот что можно сделать. Чтобы не дублировать код инстанцирования, его надо поместить в метод.
function db() {
    return new PDO();
}

Отличный результат! Если теперь вам надо будет менять параметры подключения, вы сделаете это только в одном месте, а не по всему коду.
Едем дальше. Если вам нужно только одно подключение к базе, то можно сохранить его между вызовами.
function db() {
    static $pdo;

    if ($pdo === null) {
        $pdo = new PDO();
    }

    return $pdo;
}

Кийя! Теперь подключение будет создаваться только один раз. Знающие люди называют это реализацией шаблона Реестр (Registry).
Вообще для начала этого достаточно. Но со временем может обнаружиться, что db() вызывается по всему коду, где можно и где нельзя. Тогда вам понадобится совершить ещё один революционный шаг! Процесс передачи параметров в классы надо будет запрограммировать динамически. То есть, раньше у вас было $model = new Model(db());, а вы сделаете $model = $registry->get(Model::class);. Где db() во втором куске кода? А он должен быть запрятан в недрах конфигурации вашего $registry.
Я делаю это приблизительно так: создаю папку registry со скриптами, возвращающими инстансы всех нужных мне объектов. Рекурсивный код, подключающий эти скрипты проходит по всей цепочке зависимостей и отдаёт укомплектованный объект.
registry/Model.php
<?php

return RegistryItem::init(function(PDO $pdo) {
    return new Model($pdo);
})
->setArgsProvider(['db']);

registry/db.php
<?php

return RegistryItem::init(function() {
    static $pdo;

    if ($pdo === null) {
        $pdo = new PDO();
    }

    return $pdo;
});

Немного служебного кода и ваши контроллеры станут получать всё необходимое по массиву-описанию зависимостей.


text:
Q: How can you detect which view you are passing over when performing a touch event? I want to know how I can detect child views if I move a view from one ViewGroup to another ViewGroup, particularly when doing a touch event. Is there a method I can call that will let me know which views i'm "hovering" over?
What I'm doing right now is when I detect an ACTION_MOVE event on my view i'm raising it to the top level parent so that it can move and be drawn within the entire window ( and not just inside it's original parent bounds ), then I want to move the view across to a different ViewGroup and on ACTION_UP attach the view to that ViewGroup.

A: Inspired by Ami's response, but discovering that MotionEvent#getX()/getY() along with View#getTop()/etc return coordinates wrt the parent View, I ended up doing the following below to operate in screen coordinates, allowing me to work across ViewGroups:
        private boolean inRegion(float x, float y, View v) {
            v.getLocationOnScreen(mCoordBuffer);
            return mCoordBuffer[0] + v.getWidth() > x &&    // right edge
                   mCoordBuffer[1] + v.getHeight() > y &&   // bottom edge
                   mCoordBuffer[0] < x &&                   // left edge
                   mCoordBuffer[1] < y;                     // top edge
        }

whose usage inside an OnTouchListener is e.g.:
        boolean inside = inRegion(event.getRawX(), event.getRawY(), targetView);

A: I think I found a simpler way to do this.

*

*Create an ArrayList of possible targets

*Call this method from your touch event, supplying your targets list and the coords

private View findView(float x, float y, ArrayList<View> targets)
{
    final int count = targets.size();
    for (int i = 0; i < count; i++) {
        final View target = targets.get(i);
        if (target.getRight() > x && target.getTop() < y
                && target.getBottom() > y && target.getLeft() < x) {
            return target;
        }
    }
    return null;
}

A: I found Sebastian Roth's answer very helpful with resources, but since it wasn't really an answer to my question, I thought I'd share what I came up with.
Here is the code I use to detect views ( only views that will accept a drop that is ) given a coordinate on the screen.
            private DropView findDropTarget( int x, int y, int[] dropCoordinates ){
                final Rect r = mRectTemp;
                final ArrayList<DropView> dropTargets = ((main) context).getBoardDropTargets();
                final int count = dropTargets.size();
                for (int i=count-1; i>=0; i--) {
                    final DropView target = dropTargets.get(i);
                    target.getHitRect(r);
                    target.getLocationOnScreen(dropCoordinates);
                    r.offset(dropCoordinates[0] - target.getLeft(), dropCoordinates[1] - target.getTop());
                    if (r.contains(x, y)) {
                        dropCoordinates[0] = x - dropCoordinates[0];
                        dropCoordinates[1] = y - dropCoordinates[1];
                        return target;
                    }
                }
           }

Ok, first off mRectTemp is just an allocated Rectangle so you don't have to keep creating new ones ( I.E. final Rect r = new Rect() )
The next line dropTargets is a list of views that will accept a drop in my app.
Next I loop through each view.
I then use getHitRect(r) to return the screen coordiantes of the view.
I then offset the coordiantes to account for the notification bar or any other view that could displace the coordiantes.
finally I see if x and y are inside the coordinates of the given rectangle r ( x and y are the event.rawX() and event.rawY() ).
It actually turned out to be simpler then expected and works very well.

A: Read this:
http://developer.android.com/reference/android/view/ViewGroup.html#onInterceptTouchEvent(android.view.MotionEvent)
http://developer.android.com/reference/android/view/View.html#onTouchEvent(android.view.MotionEvent)
I had implemented a Drag and Drop using that method.
I also highly recommend  a read of the HomeScreen sourcecode, which contains this thing (kind of):
https://android.googlesource.com/platform/packages/apps/Launcher2


text:
Q: nvidia-prime switching to intel stopped working I can no longer switch between my intel and nvidia cards, it used to work and my default card was intel now for some reason its nvidia and i can no longer switch and the PRIME profile option has disappeared from nvidia-settings. When launching nvidia-settings from terminal i get:

libGL error: failed to load driver: swrast
Failed to open VDPAU backend libvdpau_nvidia.so: cannot open shared object file: No such file or directory
** Message: PRIME: No offloading required. Abort
** Message: PRIME: is it supported? no

I don't really know when it stopped working but some time in the last 3 days i think.
Any one knows what has happend?

A: I had the same portable. This is what I did:
Steps
Install Nouveau driver through "Software & updates"

Remove bumblebee or other installed nvidia drivers:
sudo apt-get purge bumblebee*
sudo apt-get purge nvidia-*

An then reboot
Install nvidia 331-updates driver through "Software & updates" (should also install nvidia-settings and nvidia-prime)
Then reboot


text:
Q: MapServer in WMS mode for geotiff folder I spent a few days trying to configure MapServer to work as a WMS server. I have a folder full of geotiff files (454 GB total, 62 MB per file). Each raster has embedded pyramid and I generated .vrt for that set.
This works in Geoserver, but performance is very poor. So now I am trying to do the same in MapServer (hopefully it will be much faster).
Serving shapefiles in MapServer works, but when I try to publish tif files, in QGIS I get this message:

Invalid Layer: WMS provider Cannot calculate extent Raster layer
  Provider is not valid (provider: wms, URI:
  contextualWMSLegend=0&crs=EPSG:3908&dpiMode=7&featureCount=10&format=image/png&layers=Urbane%20zone%202012&styles=&url=http://localhost:8181/cgi-bin/mapserv.exe?map%3DC:%5C%5Cwmstif.map

Here is my map file content:
MAP
   EXTENT 6304500 4709990 6635000 5027700 #Tile Cache
   TEMPLATEPATTERN "."
   SIZE 512 512
   MAXSIZE 8192
   STATUS ON
   UNITS METERS
   NAME "Test map name"
   IMAGETYPE AGG_PNG
   OUTPUTFORMAT
    NAME "AGG_PNG"
    DRIVER "AGG/PNG"
    MIMETYPE "image/png"
    IMAGEMODE RGBA
    TRANSPARENT ON
    EXTENSION "png"
   END
   CONFIG "PROJ_LIB" "C:\ms4w\proj\nad"
   PROJECTION
      "init=epsg:3908"
   END
   WEB
      METADATA
         ows_title "Zoran example"
         ows_enable_request "*"
         ows_srs "EPSG:3908" #Recommended
         ows_abstract "This is an example WMS server from MapServer"
      END
      LOG "C:/ms.log"
   END
   LAYER
      NAME "Urbane zone 2012"
      STATUS ON
      TYPE RASTER
      UNITS METERS
      DATA "F:\geoserver_data\data\urbane_zone\index.vrt"
      METADATA
         ows_title "Urbane zone 2012"
         ows_abstract "rezolucija 25 cm"
         wms_extent "6304500 4709990 6635000 5027700" #Can use the map level extent values
      END
      TEMPLATE "blank.html"
   END
END

In QGIS I tried "Ignore axis orientation" options, but it doesn't help.
I am running MapServer on Windows Server 2012 R2, SSD disk, CPU i7-4790K, RAM 32GB. Raster files are on WD 3TB Green HDD.


text:
Q: Error while running TensorBox ReInspect implementation on TensorFlow I am trying to train TensorBox ReInspect implementation (https://github.com/Russell91/TensorBox/) on my machine with one GPU (NVidia GeForce GTX 750 Ti).
When I run the train.py script:
python train.py --hypes hypes/overfeat_rezoom.json --gpu 0 --logdir output

I get the following error:
Traceback (most recent call last):
  File "train.py", line 543, in <module>
    main()
  File "train.py", line 540, in main
    train(H, test_images=[])
  File "train.py", line 453, in train
    smooth_op, global_step, learning_rate, encoder_net) = build(H, q)
  File "train.py", line 346, in build
    boxes_loss[phase]) = build_forward_backward(H, x, encoder_net, phase, boxes, flags)
  File "train.py", line 245, in build_forward_backward
    pred_confidences, pred_confs_deltas, pred_boxes_deltas) = build_forward(H, x, googlenet, phase, reuse)
  File "train.py", line 167, in build_forward
    lstm_outputs = build_lstm_inner(H, lstm_input)
  File "train.py", line 50, in build_lstm_inner
    state = tf.zeros([batch_size, lstm.state_size])
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/array_ops.py", line 1136, in zeros
    shape = ops.convert_to_tensor(shape, dtype=dtypes.int32, name="shape")
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 628, in convert_to_tensor
    ret = conversion_func(value, dtype=dtype, name=name, as_ref=as_ref)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/constant_op.py", line 180, in _constant_tensor_conversion_function
    return constant(v, dtype=dtype, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/constant_op.py", line 163, in constant
    tensor_util.make_tensor_proto(value, dtype=dtype, shape=shape))
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_util.py", line 354, in make_tensor_proto
    nparray = np.array(values, dtype=np_dt)
ValueError: setting an array element with a sequence.

This does not happen if I run the same code on a machine without GPU and just on CPU.
What can be the cause of this error? Is there any way to debug it?

A: It appeared that the problem was because of state_is_true flag. Refer this thread for the solution:
https://github.com/Russell91/TensorBox/issues/59#issuecomment-245566316


text:
Q: Eclipse deleted 3 of my projects I had a bunch of files open from 3 different projects, I opened another file to copy code into it, and then all of a sudden my tabs get closed out. 3 of my projects' code is completely gone and only thing inside each of them is an empty gen folder. Is this common, is there anything I can do to recover my code?
I got an error saying that project is 1.7 and need to fix, but this is clearly not the case. I never changed it to 1.7, and I tried doing android tools fix but that didn't work. Errors don't show up anymore
When I try and restore from local history, I see the file but when i try and restore it it says, "Cannot replace resource(resaon: state is not valid or might have expired.)."
I have about 20 hours worth of work in it, so that'd be cool if it can be recovered...
I tried restarting eclipse, and restarting my computer, both didn't work
EDIT: i'm now getting an error:
[2014-02-28 10:08:58 - Chat-Server-Oneway] Project has no project.properties file! Edit the project properties to set one.

Recent log file:
!SUBENTRY 1 com.android.ide.eclipse.adt 4 75 2014-02-28 09:46:33.937
!MESSAGE Errors running builder 'Android Resource Manager' on project 'Chat-Server-Oneway'.
!STACK 0
java.lang.NullPointerException
    at com.android.ide.eclipse.adt.internal.build.builders.BaseBuilder.abortOnBadSetup(BaseBuilder.java:326)
    at com.android.ide.eclipse.adt.internal.build.builders.ResourceManagerBuilder.build(ResourceManagerBuilder.java:88)
    at org.eclipse.core.internal.events.BuildManager$2.run(BuildManager.java:733)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:206)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:246)
    at org.eclipse.core.internal.events.BuildManager$1.run(BuildManager.java:299)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.core.internal.events.BuildManager.basicBuild(BuildManager.java:302)
    at org.eclipse.core.internal.events.BuildManager.basicBuildLoop(BuildManager.java:358)
    at org.eclipse.core.internal.events.BuildManager.build(BuildManager.java:381)
    at org.eclipse.core.internal.events.AutoBuildJob.doBuild(AutoBuildJob.java:143)
    at org.eclipse.core.internal.events.AutoBuildJob.run(AutoBuildJob.java:241)
    at org.eclipse.core.internal.jobs.Worker.run(Worker.java:53)

!ENTRY com.android.ide.eclipse.adt 4 0 2014-02-28 09:47:09.275
!MESSAGE Failed to load properties file for project 'Chat-Server-Oneway'

!ENTRY org.eclipse.jface 4 2 2014-02-28 09:47:09.369
!MESSAGE Problems occurred when invoking code from plug-in: "org.eclipse.jface".
!STACK 0
java.lang.NullPointerException
    at com.android.ide.eclipse.adt.internal.properties.AndroidPropertyPage.fillUi(AndroidPropertyPage.java:172)
    at com.android.ide.eclipse.adt.internal.properties.AndroidPropertyPage.createContents(AndroidPropertyPage.java:96)
    at org.eclipse.jface.preference.PreferencePage.createControl(PreferencePage.java:232)
    at org.eclipse.jface.preference.PreferenceDialog.createPageControl(PreferenceDialog.java:1502)
    at org.eclipse.jface.preference.PreferenceDialog$14.run(PreferenceDialog.java:1259)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
    at org.eclipse.jface.preference.PreferenceDialog.showPage(PreferenceDialog.java:1253)
    at org.eclipse.ui.internal.dialogs.FilteredPreferenceDialog.showPage(FilteredPreferenceDialog.java:675)
    at org.eclipse.jface.preference.PreferenceDialog$10.run(PreferenceDialog.java:709)
    at org.eclipse.swt.custom.BusyIndicator.showWhile(BusyIndicator.java:70)
    at org.eclipse.jface.preference.PreferenceDialog$9.selectionChanged(PreferenceDialog.java:705)
    at org.eclipse.jface.viewers.StructuredViewer$3.run(StructuredViewer.java:888)
    at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
    at org.eclipse.ui.internal.JFaceUtil$1.run(JFaceUtil.java:49)
    at org.eclipse.jface.util.SafeRunnable.run(SafeRunnable.java:175)
    at org.eclipse.jface.viewers.StructuredViewer.firePostSelectionChanged(StructuredViewer.java:886)
    at org.eclipse.jface.viewers.StructuredViewer.handlePostSelect(StructuredViewer.java:1226)
    at org.eclipse.jface.viewers.StructuredViewer$5.widgetSelected(StructuredViewer.java:1251)
    at org.eclipse.jface.util.OpenStrategy.firePostSelectionEvent(OpenStrategy.java:262)
    at org.eclipse.jface.util.OpenStrategy.access$5(OpenStrategy.java:256)
    at org.eclipse.jface.util.OpenStrategy$3.run(OpenStrategy.java:433)
    at org.eclipse.swt.widgets.RunnableLock.run(RunnableLock.java:35)
    at org.eclipse.swt.widgets.Synchronizer.runAsyncMessages(Synchronizer.java:135)
    at org.eclipse.swt.widgets.Display.runAsyncMessages(Display.java:4145)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3762)
    at org.eclipse.jface.window.Window.runEventLoop(Window.java:826)
    at org.eclipse.jface.window.Window.open(Window.java:802)
    at org.eclipse.ui.dialogs.PropertyDialogAction.run(PropertyDialogAction.java:158)
    at org.eclipse.jface.action.Action.runWithEvent(Action.java:499)
    at org.eclipse.jface.action.ActionContributionItem.handleWidgetSelection(ActionContributionItem.java:584)
    at org.eclipse.jface.action.ActionContributionItem.access$2(ActionContributionItem.java:501)
    at org.eclipse.jface.action.ActionContributionItem$5.handleEvent(ActionContributionItem.java:411)
    at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
    at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1057)
    at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4170)
    at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3759)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine$9.run(PartRenderingEngine.java:1113)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.e4.ui.internal.workbench.swt.PartRenderingEngine.run(PartRenderingEngine.java:997)
    at org.eclipse.e4.ui.internal.workbench.E4Workbench.createAndRunUI(E4Workbench.java:138)
    at org.eclipse.ui.internal.Workbench$5.run(Workbench.java:610)
    at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
    at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:567)
    at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:150)
    at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:124)
    at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
    at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:354)
    at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:181)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
    at java.lang.reflect.Method.invoke(Unknown Source)
    at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:636)
    at org.eclipse.equinox.launcher.Main.basicRun(Main.java:591)
    at org.eclipse.equinox.launcher.Main.run(Main.java:1450)
    at org.eclipse.equinox.launcher.Main.main(Main.java:1426)
!SESSION 2014-02-28 09:50:11.461 -----------------------------------------------
eclipse.buildId=4.3.0.M20130911-1000
java.version=1.7.0_51
java.vendor=Oracle Corporation
BootLoader constants: OS=win32, ARCH=x86_64, WS=win32, NL=en_US
Framework arguments:  -product org.eclipse.epp.package.standard.product
Command-line arguments:  -os win32 -ws win32 -arch x86_64 -product org.eclipse.epp.package.standard.product

!ENTRY org.eclipse.core.resources 2 10035 2014-02-28 09:50:14.659
!MESSAGE The workspace exited with unsaved changes in the previous session; refreshing workspace to recover changes.

!ENTRY com.android.ide.eclipse.adt 4 0 2014-02-28 09:50:16.687
!MESSAGE projectOpenedWithWorkspace: failed to find manifest package for project BookStoreBasic

!ENTRY com.android.ide.eclipse.adt 4 0 2014-02-28 09:50:16.780
!MESSAGE projectOpenedWithWorkspace: failed to find manifest package for project Chat-Client-Oneway

!ENTRY com.android.ide.eclipse.adt 4 0 2014-02-28 09:50:16.889
!MESSAGE projectOpenedWithWorkspace: failed to find manifest package for project Chat-Server-Oneway

!ENTRY com.android.ide.eclipse.adt 4 0 2014-02-28 09:50:17.295
!MESSAGE Failed to load properties file for project 'Chat-Server-Oneway'

!ENTRY com.android.ide.eclipse.adt 4 0 2014-02-28 09:50:17.451
!MESSAGE Failed to load properties file for project 'Chat-Server-Oneway'

!ENTRY com.android.ide.eclipse.adt 4 0 2014-02-28 09:50:17.545
!MESSAGE Failed to load properties file for project 'Chat-Server-Oneway'

!ENTRY org.eclipse.egit.ui 2 0 2014-02-28 09:50:23.550
!MESSAGE Warning: EGit couldn't detect the installation path "gitPrefix" of native Git. Hence EGit can't respect system level
Git settings which might be configured in ${gitPrefix}/etc/gitconfig under the native Git installation directory.
The most important of these settings is core.autocrlf. Git for Windows by default sets this parameter to true in
this system level configuration. The Git installation location can be configured on the
Team > Git > Configuration preference page's 'System Settings' tab.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.

!ENTRY org.eclipse.egit.ui 2 0 2014-02-28 09:50:23.661
!MESSAGE Warning: The environment variable HOME is not set. The following directory will be used to store the Git
user global configuration and to define the default location to store repositories: 'C:\Users\Bling'. If this is
not correct please set the HOME environment variable and restart Eclipse. Otherwise Git for Windows and
EGit might behave differently since they see different configuration options.
This warning can be switched off on the Team > Git > Confirmations and Warnings preference page.

!ENTRY com.android.ide.eclipse.adt 4 0 2014-02-28 09:50:28.128
!MESSAGE Failed to load properties file for project 'BookStoreBasic'

!ENTRY com.android.ide.eclipse.adt 4 0 2014-02-28 09:50:28.227
!MESSAGE Failed to load properties file for project 'Chat-Client-Oneway'

A: Did you look into the actual workspace? The project could be deleted from eclipse but I doubt that the workspace was also deleted.
Go to your default location for your workspaces and look for your projects. You could re-import them from there as desired.


text:
Q: Most concise way to convert Julian date (yyyy[day of year]) to SQL datetime I'm working with an existing database where all dates are stored as integers in the following format: yyyy[3 digit day of year].
For example:
2010-01-01 == 2010001
2010-12-31 == 2010365

I'm using the following SQL to convert to a datetime:
DATEADD(d,
    CAST(SUBSTRING(
            CAST(NEW_BIZ_OBS_DATE AS VARCHAR), 5, LEN(NEW_BIZ_OBS_DATE) - 4
        ) AS INT) - 1,
    CAST('1/1/' + SUBSTRING(CAST(NEW_BIZ_OBS_DATE AS VARCHAR),1,4) AS DATETIME))

Does anyone have a more concise way to do this?

A: You can do it numerically instead of usings strings:
dateadd(day, NEW_BIZ_OBS_DATE % 1000 - 1,
  dateadd(year, NEW_BIZ_OBS_DATE / 1000 - 2000, '2000-1-1')
)

(Note that 2010356 is not 2010-12-31 but 2010-12-22. 2010365 is 2010-12-31.)

A: I think at least one simplification can be made:
DATEADD(d,
    NEW_BIZ_OBS_DATE % 1000 - 1,
    CAST('1/1/' + SUBSTRING(CAST(NEW_BIZ_OBS_DATE AS VARCHAR),1,4) AS DATETIME)
)

The second term could also be done as follows I think.
    CAST('1/1/' + CAST(NEW_BIZ_OBS_DATE/1000 AS VARCHAR) AS DATETIME)


text:
Q: Is it possible to load a javascript containing `document.write` in a non-blocking way? Hello a have an add that is loaded with a simple script tag:
<script src="http://...(external)" type="text/javascript" language="Javascript">

It contains something like :
document.write('...(some html code)');

The problem is that this script execution is blocking. In the case that the ad domain is not reachable, the page containing this add is only displayed, once the timeout is reached.
I tried to load the script asynchronously with <script async and with <script defer, but this keeps the content from being added.
Is there a way I can change this script to be loaded in a non-blocking way ?
Or is the way the ad provider uses (document.write) just evil ?


text:
Q: JQuery draggable intersect is being thrown off by margin I have a draggable with a large margin and a tolerance of intersect.  When I drag it to the droppable box, most of the time it works.  However, if I try to drop it near the TOP of the droppable box, it does not drop properly because the margin is calculated as part of the height.
Could someone suggest a workaround for this?  I tried removing the margin at the start of drag, but that results in a weird jumping of the draggable when you first grab hold of it.
$(".draggable").draggable({
    helper: 'clone',
    cursor: 'move'
})

$( ".droppable" ).droppable({
tolerance: 'intersect',
drop: function( event, ui ) {
$( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}})

http://jsfiddle.net/wQvWK/6/

A: I looked into the matter and I believe that you will need to either drop the margin (do margin bottom on element above it)  OR monkeypatch the jQuery ui code to account for margin in this case.
I moved the tolerance of the droppable in this fiddle: http://jsfiddle.net/wQvWK/2/
Before I did this, it never dropped.
 $( ".droppable" ).droppable({
   tolerance: 'intersect',
 drop: function( event, ui ) {
 $( this )
.addClass( "ui-state-highlight" )
.find( "p" )
.html( "Dropped!" );
}})

A: Here is one way to do it.. The drop test is coded manually in order to work with the margin you have set.
var marginTop = 150;
$(".draggable").draggable({
        helper: 'clone',
        cursor: 'move',
        stop: function(event, ui){
            if($('.droppable').position().top-$(this).height()/2 < ui.position.top+marginTop
              && $('.droppable').position().top+$('.droppable').height() > ui.position.top+marginTop+$(this).height()-$(this).height()/2
              && $('.droppable').position().left-$(this).width()/2 < ui.position.left
              && $('.droppable').position().left+$('.droppable').width() > ui.position.left+$(this).width()-$(this).width()/2)
               {
                $('.droppable')
                .addClass( "ui-state-highlight" )
                .find( "p" )
                .html( "Dropped!" );
            }
        }
    });

Example:
http://jsfiddle.net/trevordowdle/wQvWK/5/


text:
Q: python program syntax error on `else:` when I run my program which finds the inverse permutation of numbers, it returns me with the follow error:
python inverse_permutation.py 1 2 3 4 5
  File "inverse_permutation.py", line 18
    else:
       ^
SyntaxError: invalid syntax

Prior to asking this question I tried looking at similar posts, but could not find a solution to my specific problem. Here is my code:
import stdarray
import stdio
import sys

q = input().split()
for i in range(len(q)):
    q[i] = int(q[i])
l = len(q)
s = int((l*(l+1))/2-(l))
s2 = 0
b = [0 for i in range(l)]
for i in range(l):
    s2 = s2+q[i]
if(s == s2):
    for i in range(l):
        b[q[i]] = i
print(b)
else:
    print('Not a permutation')

A: if should be followed by else, but you have put the print statement between if and else, you can do something like this
import stdarray
import stdio
import sys

q = input().split()
for i in range(len(q)):
    q[i] = int(q[i])
l = len(q)
s = int((l*(l+1))/2-(l))
s2 = 0
b = [0 for i in range(l)]
for i in range(l):
    s2 = s2+q[i]
if(s == s2):
    for i in range(l):
        b[q[i]] = i
else:
    print('Not a permutation')

print(b)


text:
Q: Given $\{A_n\}$ with $P(A_n)\to 0$ show that for every $\alpha>0$ there exists a subsequence $\{A_{n_k}\}$, such that $P(\cup_k A_{n_k})\leq\alpha$ Given $\{A_n\}$ with $P(A_n)\to 0$ show that for every $\alpha>0$ there exists a subsequence $\{A_{n_k}\}$, such that
$$P(\cup_k A_{n_k})\leq\alpha$$
I found this variation of the problem I am trying to solve. I figure the solution to my problem is similar, but I don't exactly see through it.
Because $P(A_n)\to 0$ then I figure there exists a subsequence $A_{n_k}$ such that $\sum_{k=1}^\infty P(A_{n_k})< \infty$ and from Borel-Cantelli I have $P(\lim\sup A_{n_k})=0$. Moreover I get that $\lim_{k\to\infty} P(\cup_k A_{n_k})=0$ from the properties of limit superior. Does this reasoning help to get to the needed result?
I am grateful for any suggestions.

A: I think the standard trick here is to find some absolutely convergent series$\sum_{k=1}^\infty a_k$ and then a subsequence $\{ A_{n_k}\}_{k=1}^\infty $ such that $\mathbb{P}(A_{n_k})\leq a_k$.
I claim that this should imply your result from the properties of a measure. Can you see why?

A: Your problem is pretty much the same as the variation that you quoted. See this excerpt from the accepted solution, which avoids the Borel-Cantelli lemma:

Now because $P(A_n^c)\to0$, we can choose a subsequence $n_k$ such that
$$ P(A_{n_k}^c)< 3^{-(k+1)}$$

You can use this same idea. Since $P(A_n)\to0$, you can choose $n_k$ so that $P(A_{n_k})$ is as small as you please -- so small that the sum of $P(A_{n_k})$ is less than $\alpha$.


text:
Q: update Trigger - Mysql tengo que crear un trigger asociado a la tabla pedidos de manera que cuando se actualice un registro de la tabla pedidos lo actualice en la tabla detallepedidos, lo he intentado de la siguiente forma pero no hay manera, si alguien lo pudiera resolver....
drop table if exists updatepedidos;
create table updatepedidos (
  CodigoPedido integer NOT NULL,
  FechaPedido date NOT NULL,
  FechaEsperada date NOT NULL,
  FechaEntrega date DEFAULT NULL,
  Estado varchar(15) NOT NULL,
  Comentarios text,
  CodigoCliente integer NOT NULL,
  PRIMARY KEY (CodigoPedido),
  CONSTRAINT Pedidos_Cliente FOREIGN KEY (CodigoCliente) REFERENCES Clientes (CodigoCliente)
);

drop trigger if exists controlpedidos;

DELIMITER //

create trigger controlpedidos before update on pedidos for each row
begin

if new.CodigoPedido<>old.CodigoPedido then
insert into updatepedidos values (new.CodigoPedido, old.FechaPedido, old.FechaEsperada, old.FechaEntrega, old.Estado, old.Comentarios, old.CodigoCliente);
end if;

if new.FechaPedido<>old.FechaPedido then
insert into updatepedidos values (old.CodigoPedido, new.FechaPedido, old.FechaEsperada, old.FechaEntrega, old.Estado, old.Comentarios, old.CodigoCliente);
end if;

if new.FechaEsperada<>old.FechaEsperada then
insert into updatepedidos values (old.CodigoPedido, old.FechaPedido, new.FechaEsperada, old.FechaEntrega, old.Estado, old.Comentarios, old.CodigoCliente);
end if;

if new.FechaEntrega<>old.FechaEntrega then
insert into updatepedidos values (old.CodigoPedido, old.FechaPedido, old.FechaEsperada, new.FechaEntrega, old.Estado, old.Comentarios, old.CodigoCliente);
end if;

if new.Estado<>old.Estado then
insert into updatepedidos values (old.CodigoPedido, old.FechaPedido, old.FechaEsperada, old.FechaEntrega, new.Estado, old.Comentarios, old.CodigoCliente);
end if;

if new.Comentarios<>old.Comentarios then
insert into updatepedidos values (old.CodigoPedido, old.FechaPedido, old.FechaEsperada, old.FechaEntrega, old.Estado, new.Comentarios, old.CodigoCliente);
end if;

if new.CodigoCliente<>old.CodigoCliente then
insert into updatepedidos values (old.CodigoPedido, new.FechaPedido, old.FechaEsperada, old.FechaEntrega, old.Estado, old.Comentarios, new.CodigoCliente);
end if;

end//
DELIMITER ;

update pedidos set CodigoCliente=22 where CodigoPedido=1;

A: Estas insertando no haces ningún UPDATE en el disparador, imagino que usas IF para saber si existe el registro o no en la tabla updatepedidos.
Otro detalle es que no puedes hacer un update con CodigoPedido porque es un PK. (en realidad te permite pero no es una buena practica)
Lo que tendrías que hacer es con el código CodigoPedido buscar si existe datos registro en tu tabla updatepedidos, si es null usas insert sino update filtrando con el CodigoPedido.
Ejecuta describe pedidos; para saber que datos contiene la tabla.


text:
Q: NonlinearModelFit I was trying to fit a model to the following experimental data:
data1 = {{0.00000000001, 100}, {1, 0.7}, {4, 0.03}, {24, 0.001}}

The first value was supposed to be 0.
NonlinearModelFit[data1, a x^-b, {a, b}, x]

resulted in the following equation: 0.390336/x^0.21896
The problem is that it does not fit the data.
Using the same set of data in Excel the following equation was obtained: 0.62/x^-2.03
and this equation fits the data.
What is wrong with the Mathematica model fit?

A: Nothing is wrong with NonlinearModelFit (at least for the data and model given).  My guess is that you fit a model in Excel using LINEST which fits a model of the form
$$\log y=\log a + b \log t + error$$
But if not, please add the Excel command that performed the regression.
The first element of data is {0,100}.  But that is not a data point.  That is simply a known point that better be on the curve to be fitted.  (One might want to call it an "anchor point".)
In addition, if your survival rates are based on counts, then you shouldn't be performing a regression which assumes among other things a constant variance at each time especially with a model that can't predict 100% at time zero.  (The variance certainly goes to zero as time increases.)
Fitting 3 parameters ($a$, $b$, and the error variance) with just 3 data points is at best not recommended.
You should consult with a statistician about Survival Analysis or at least ask this question on CrossValidated after including a more detailed description of your data (describing if the response variable is a ratio of two counts, for example).

A: Clear["Global`*"]

data1 = {{0.00000000001, 100}, {1, 0.7}, {4, 0.03}, {24, 0.001}};

{xmin, xmax} = MinMax@data1[[All, 1]];

model[a_, b_, x_] := a x^-b

For an exponential model it is better to deal with the log of the data.
logData = {#[[1]], Log[#[[2]]]} & /@ data1;

Include a constraint that the parameters must be positive
(nlm = NonlinearModelFit[logData,
    {Log[model[a, b, x]], a > 0, b > 0}, {a, b}, x])["BestFitParameters"]

(* {a -> 0.0403419, b -> 0.321499} *)

f[x_] = E^nlm[x]

(* 0.0403419/x^0.321499 *)

The reason that x == 0 should be avoided is that the model cannot handled x == 0
Limit[f[x], x -> 0]

(* Indeterminate *)

Visually comparing the fit to the data
Plot[f[x], {x, xmin, xmax}, PlotRange -> {-0.05, 0.8},
 Epilog -> {Red, AbsolutePointSize[4], Point[data1]}]

You have too few data points to get a good fit.


text:
Q: Possibilities for structuring ingested json data using Nifi Is it possible, using Nifi, to load a json file into a structured table?
I've called the following weather forecast data (from 6000 weather stations), which i'm currently loading into HDFS. It all appears on one line:
{"SiteRep":{"Wx":{"Param":[{"name":"F","units":"C","$":"Feels Like Temperature"},{"name":"G","units":"mph","$":"Wind Gust"},{"name":"H","units":"%","$":"Screen Relative Humidity"},{"name":"T","units":"C","$":"Temperature"},{"name":"V","units":"","$":"Visibility"},{"name":"D","units":"compass","$":"Wind Direction"},{"name":"S","units":"mph","$":"Wind Speed"},{"name":"U","units":"","$":"Max UV Index"},{"name":"W","units":"","$":"Weather Type"},{"name":"Pp","units":"%","$":"Precipitation Probability"}]},"DV":{"dataDate":"2017-01-12T22:00:00Z","type":"Forecast","Location":[{"i":"14","lat":"54.9375","lon":"-2.8092","name":"CARLISLE AIRPORT","country":"ENGLAND","continent":"EUROPE","elevation":"50.0","Period":{"type":"Day","value":"2017-01-13Z","Rep":{"D":"WNW","F":"-3","G":"25","H":"67","Pp":"0","S":"13","T":"2","V":"EX","W":"1","U":"1","$":"720"}}},{"i":"22","lat":"53.5797","lon":"-0.3472","name":"HUMBERSIDE AIRPORT","country":"ENGLAND","continent":"EUROPE","elevation":"24.0","Period":{"type":"Day","value":"2017-01-13Z","Rep":{"D":"NW","F":"-2","G":"43","H":"63","Pp":"3","S":"25","T":"4","V":"EX","W":"3","U":"1","$":"720"}}}, .....

Ideally, I want the schema structuring into a 6000 row table.
I've tried writing a schema to pass the above into Pig, but haven't been successful, probably because I'm not familiar enough with json to translate this correctly.
Casting around for an easy way to add some structure to the data, I've spotted that there's a PutHBaseJson processor in Nifi.
Can anyone advise if this PutHBaseJson processor would work with the above data structure? And if so, can anyone point me towards a decent tutorial to give me a starting point on the configuration?
Greatly appreciate any guidance.

A: You probably want to use the SplitJson processor to split the 6000 record JSON structure into 6000 individual flowfiles. If you need to "inject" the parameter definitions from the top-level response, you can do a ReplaceText or JoltTransformJSON operation to manipulate the individual JSON records. Here is a good article by Yolanda Davis describing how to perform Jolt transforms (JSON -> JSON) in NiFi.
Once you have the individual flowfiles containing a single JSON record, putting them into HBase is very easy. Bryan Bende wrote an article describing the necessary configurations for the PutHBaseJson processor.


text:
Q: How to pass a parameter to url from controller using angularjs I am doing add and edit in 1 page. Listing is showing below in a table. From the list while I click on edit button, I want to pass the id of that item in url. So that if accidentally page is being refreshed, the data will remain in the edit form. And also I am using nested view(eg: settings.couriers)
My html
<button class="btn btn-primary btn-xs" ng-click="editCourier({id: x.id})">

                                    </button>

My controller.js to edit
$scope.editCourier = function(id, index) {
        $.ajax({
            'type': "POST",
            'async': false,
            'global': false,
            'url':'settings/editCourier',
            'data': 'id='+id,
            'dataType': "json",
            'success': function (data) {
                $scope.formData = data[0];
            }
        });
    }

Is there any way out. please help. Thank you

A: change:
<button class="btn btn-primary btn-xs" ng-click="editCourier({id: x.id})">

</button>

to:

and in the controller, get the Id using Angular's RouteParams.
Refer to this link

A: You can directly pass id to Function  editCourier(x.id)
 <button class="btn btn-primary btn-xs" ng-click="editCourier(x.id)">

  </button>

And In Controller
  $scope.editCourier = function(id, index) {
       console.log(id);//Check here whether the click id is coming or not
}

A: Changed my HTML to
<button class="btn btn-primary btn-xs" ng-click="editCourier(index)">

                                    </button>

I have changed my controller function.
$scope.editCourier = function(index) {
        $.ajax({
            'type': "POST",
            'async': false,
            'global': false,
            'url':'settings/editCourier',
            'data': 'id='+ $stateParams.id,
            'dataType': "json",
            'success': function (data) {
                $scope.formData = data[0];
                $scope.couriers.splice(index, 1);
                $state.go('statename', {id: $stateParams.id}, {reload: true});
            }
        });
    }


text:
Q: PHPStorm Live Edit for php or an alternative (for firefox) PHPStorm has a nice little plugin called "Live Edit", however it works only for javascript, html, etc. Exept for php...
My question would be simple - is there any way to make it work for php on firefox? I already have local MySQL and Apache server running. Documentation say no, but who knows?

A: Just as I posted my question, I found an answer myself (happens constantly). Instead of using Live Edit I found quite a nice alternative (and on firefox too!).
What you need is "Auto Reload", a firefox plugin, which detects file changes and reloads page.
Here's a little guide (assuming that you have PHPStorm and XAMMP configured):

*

*Open plugin's settings.

*Create new rule.

*For Url type: http://localhost/<MyPage>/*

*For files, add file or select directory: C:\xampp\htdocs\<MyPage>

*Make sure autosych is enabled between PHPStorm and local server.

*Click Open in Browser '*.php' on XAMMP Apache

*Edit code and see results.


text:
Q: Asynchronous IO in C++11 I need to run some iterative algorithm of which I don't know whether it will converge to the desired accuracy within reasonable time. It would therefore be cool if I could print the residual after each iteration and once I'm satisfied/out of patience I could tell the program to write the current solution to disk and terminate.
Usually, to achieve this the program would have to ask after every iteration whether it should terminate now, and most of the time I would have to tell it not to. This is clearly annoying. Can't I tell the program to run until I hit a certain key, and once I do it should finish the current iteration, write the approximation to disk and terminate?

A: Yes, you can, and you can even do it using only standard C++11 features. The trick is to spawn a new thread whose only job it is to listen to std::cin. Once the user writes anything, the listening thread sets a flag which tells the worker thread to abort. In the following small example, I implement a "stopwatch" using this technique.
#include <iostream>
#include <thread>
#include <atomic>

int main() {
    std::atomic<bool> abort(false);
    std::thread t([&abort] () {
        std::cout << "Abort?";
        std::cin.peek();
        abort = true;
    });

    unsigned long i = 0;
    while (!abort) ++i;

    t.join();
    std::cout << "Counted to " << i << std::endl;

    return 0;
}

You may now try to terminate the program exactly when it reached 100000000. :-)


text:
Q: Laravel collection count() takes too long I have a contacts table and a contact_list table, a contact_list has many contacts, contacts table has a is_active field.

to get the number of active contacts for a contact_list i use the query builder as follows:
$contact_list->contacts()->where('is_active', 1)->count();
if the number of contacts is too big the query takes too long.
is there a better way to implement this?

A: as I can see you want to optimize the performance of your request.
to achieve that you should use eager-loading, so your new request should be like below:
$contactList = App\ContactList::with(['contacts' => function ($query) {
    $query->where('is_active', 1);
}])->count();

For more information about how Laravel implement eager-loading please check the link of documentation: eager-loading documentation

A: With InnoDB COUNT() works slowly for tables with million rows.
That's a problem with count() as the InnoDB engine locks the table per row, and if the table is being changed on a regular bases the count() function is not trivial.
The Eloquent ORM doesn't differenciatie between InnoDB or MyISAM so the count() process always triggers something like SELECT COUNT(*) AS aggregate FROM table.
If you change the query with this one SELECT COUNT(1) FROM table you will realize that the count() process is way faster.
So in Laravel that would be reduced to something like:
Model::select(DB:raw('count(1)'))->first();

Or in your case
$contact_list->contacts()->select()->where('is_active', 1)->count();


text:
Q: What would Cramer's conjecture teach us about the zeroes of Zeta? Hello,
I have just read this: Refinements of the Riemann hypothesis and I came up with the following question: what would Cramer's conjecture, if proven, teach us about the zeroes of Zeta? For example, does this conjecture imply that all non trivial zeroes of Zeta are on the critical line and simple? Or can we expect even much more?
Thanks in advance.


text:
Q: Comparing textures for matching pixel colours I am exploring some GLSL and have something I want to try to implement. Here is the situation:
Say I have a texture for what will be displayed on-screen (e.g. 1920x1080), and another (power of 2, e.g. 1024x1024) texture. Every single pixel of both of these textures is 110% guaranteed to be unique in colour (no 2 pixels in one texture are the same colour).
Is it possible to compare the second (1024x1024) texture to the first (1920x1080) texture to determine if any of the pixels of the second have a matching colour to the first?
If this doesn't make any sense, let me know and I will endeavor to re-word it.

A: What you're attempting to do is a very poor fit for an OpenGL shader. In general, shaders should try to minimize the number of samples they take of each of their textures, and in fact, may be limited in the number they are allowed to use. In order to do what you're suggesting, you would need to sample the comparison image 1024 * 1024 times for every pixel in the input image. That's not going to scale well and it's not the type of work that a GPU is geared towards.
For that task you'd probably be better off doing it on the CPU. You could sort the pixels in the second image first by red, then by green, then by blue. Then for each pixel in the input image do a binary search for that color in the sorted list. You could multithread it for additional speed. But it doesn't seem like a very good fit for a GPU.


text:
Q: On Android, is it possible to send an intent to the Google maps application with a custom marker image specified in the intent? The default Google maps marker is a red pin. Is it possible to replace the default marker image with a custom image through an intent?
Edit:
This is when sending a geouri intent to launch an external map app. Not when doing it within the app with a MapActivity subclass.

A: Yes. I just hope that I've got your question correctly:
You can do it through Overlay Items. Just check THIS example from Google itself:
You can customize any marker by specifying a drawable.

A: You can send an Integer with the image position in the array:
Intent i = new Intent (yourClass.this, MapActivity.class)
i.putExtra("pinPosition",2);
startActivity(i);

And in your map activity:
 public class MyMapActivity extends MapActivity {
    private int drawables[] = { R.drawable.pin1, R.drawable.pin2, R.drawable.tutorial_pin3 };
    int position;

    public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            if (getIntent().getSerializableExtra("pinPosition")!=null) {
        position = getIntent().getSerializableExtra("pinPosition");
            }

            setContentView(R.layout.publish_map_activity);
            map = (MapView) findViewById(R.id.mapview);
            ImageView pin = (ImageView) findViewById(R.id.drag);
            pin.setImageResource(drawables[position]);
    ....

    }

    }

If you use a similar google code, your xml should be:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mapLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <com.google.android.maps.MapView
        android:id="@+id/mapview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:apiKey="@string/googlemaps_key"
        android:clickable="true" />

    <ImageView
        android:id="@+id/drag"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:contentDescription="@string/contentDescription"
        android:src="@drawable/mapitempng"
        android:visibility="gone" />
</RelativeLayout>


text:
Q: Using same ID for multiple HTML tags?
Possible Duplicate:
Several elements with the same ID responding to one CSS ID selector

Below is the example code that I was testing and I got confused. Every one says that we can use or we should use only one time per id, but I have testes using using it multiple times but its giving me the correct output.
What should I do?
It's kinda working same like class for me in this example
code:

This paragraph has an ID name of "exampleID1" and has a blue CSS defined background.

This paragraph has an ID name of "exampleID2" and has had its text transformed to uppercase letters.

<address id="exampleID1">

Written by W3Schools.com

Email us

Address: Box 564, Disneyland

Phone: +12 34 56 78
</address>

Here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation.

Please see the above code and answer me that why we should not use id selector two times in a page while its working fine.

A: I think the easier way to understand is doing an analogy with a product. Imagine that an ID works like a Serial Number, in other words, it must be unique, this way you can identify a product that have milions of equal copies.
Then, imagine the class as the Product Code, can be the bar code for example. In a supermarket all equal products have the same bar code to be read by optical reader.
So, an ID is an unique identifiquer and a class groups a group of elements.
But if i am using the same ID in my HTML/CSS i am get a perfect result, why should i be worried about unique IDs?
Reason number 1:
In the future, if you need to use Javascript and if you need to manipulate an specific element and it has a duplicated ID, your code will not generate the expected result.
Reason number 2
Your code will not be valited by W3C, what means that you can have headaches with your website's compability accross browsers. It can works fine in one browser and in other not.
Using a real example, imagine that you want to update dinamically, using Javascript, the text of this element:

Here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation.

With Javascript/JQuery you will use a code like this:
$("#exampleID1").html("Changing element content");

And then the text of the element
 will be updated, but the below element will be updated too, because it has the same ID.

This paragraph has an ID name of "exampleID1" and has a blue CSS defined background.

So, if you want to update just one element, they must have unique IDs.
I hope you can use this explanation to understand better the difference between ID and class.

A: It's working, but that's not the way IDs are meant to be used (according to the HTML specifications).
An ID must refer only to one object.
Describing multiple objects must be done with class, not id.

A: An id must be unique in a page. Use a class if you want to describe a group of elements.

why we should not use id selector two times in a page while its working fine.

You are making an error and depending on every browser that will ever view the page to compensate for it. You can't be sure they all will.

A: You should use unique Ids to ensure the HTML is valid.
The reasoning behind this is simply that Ids are used to identify unique elements.
The page will still render, despite being invalid, but the biggest practical problem is that JavaScript and other libraries are optimised to work on the assumption that Ids are unique so, if you are trying to fetch all elements with an Id and hide them e.g. using jQuery
$('#exampleID1').hide();

Only the first element will be hidden, since to select by Id should only return a single item and once a single element is found the query is short circuited to return the single element. Without knowing this you can get some seemingly odd behaviour and hard to diagnose defects.

A:
why we should not use id selector two times in a page while its
  working fine

Because you don't know if it's working fine in every browser.
The specifications says that an id has to be unique in the page, so when browsers find your duplicate id:s they will try to handle it as best they can. Most browsers seem to handle it by using the identity only for the first element, but leaving the id attribute on the elements so that your CSS still works, but there is no guarantee that all browsers handle it that way.
Different browser vendors use different tactics for handling incorrect markup, and each vendor finds a "new, better" way, so incorrect markup is typically handled in as many different ways as possible.


text:
Q: API to check Periscope User is Online I've scoured for any information regarding an Open API for Periscope.
I have a twitter feed, that should only show if Periscope is Live (the said user will share the broadcast via Twitter).
I can parse the word "IS LIVE" but then I'd have to parse multiple languages.
I'm looking to check an API if the user is Online in periscope, if so, then display the latest twitter feed (which is the broadcast).
There was this User Online button that could be generated
https://www.periscope.tv/embed
it calls an api like https://embed.periscope.tv/user/bpsdmik.json
but it seems that the certificate is invalid, so I keep getting errors ..
Any help / workarounds would be much appreciated!
I've Searched OPEN Periscope, but mostly requires an Authentication token etc.

A: There is no open API for Periscope. At least, not that I'm aware of. Which would explain your difficulty in finding anything. The closest thing would be the Unofficial Periscope API, documented by Pmmlabs (the same folks who run the OpenPeriscope project). However, as you've already discovered, most of the calls to the Periscope API, including all user-related calls, require an auth token.
Outside of using the API or screen scraping, the only other way I can think of to tell if a user is live or not is to try accessing their Periscope page directly. When you go to a user's Periscope page at https://www.pscp.tv/{userId}, Periscope will redirect you to that users most recent broadcast, where you can parse the broadcast id from the redirect URL. Once you have the broadcast id of the most recent broadcast, you can use the following API call (which does not require an auth token):
https://api.periscope.tv/api/v2/getAccessPublic?token={broadcastId}
... to determine whether the broadcast is live or not. Look at the JSON response and if the "type" field equals "StreamTypeReplay", then it's a replay, otherwise it's a live broadcast.


text:
Q: SqlBulkCopy prevent insert data that null or not in relationship table I using to extract data from excel and put in sql table as below:
public bool ExtractExcelToDB(int activityId, string tableName, string fileName)
{
    try
    {
        var path = GetPath(activityId);
        path = Path.Combine(path, fileName);

        using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream))
            {
                DataSet result = excelReader.AsDataSet();
                DataTable dt = result.Tables["sheet"];
                DataTable newDt = dt.Select().Skip(1).Take(dt.Rows.Count).CopyToDataTable();

                using (SqlBulkCopy sqlBulk = new SqlBulkCopy(GetConnectionString()))
                {
                    sqlBulk.DestinationTableName = tableName;
                    sqlBulk.WriteToServer(newDt);
                }
            }

            return true;
        }
    }
}

Here is my relationship:

My issue is that the table that I insert the data has primary key and the data insert to table even the primary key is null or does not exist in the relationship table

How to prevent the data to insert to target table if on of the primary
  key is null or doesn't exist..

A: Using the constructor SqlBulkCopy(String, SqlBulkCopyOptions) set the options to check the constraints while performing the insert:
using (SqlBulkCopy sqlBulk = new SqlBulkCopy(GetConnectionString(), SqlBulkCopyOptions.CheckConstraints))
{
    sqlBulk.DestinationTableName = tableName;
    sqlBulk.WriteToServer(newDt);
}

by default the constraints are not checked.

A: If you can access your Authority table in the same manner you could check the ID values manually as well as follows:
public bool ExtractExcelToDB(int activityId, string tableName, string fileName)
{
    try
    {
        var path = GetPath(activityId);
        path = Path.Combine(path, fileName);

        using (FileStream stream = File.Open(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
        {
            using (IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream))
            {
                DataSet result = excelReader.AsDataSet();
                DataTable dt = result.Tables["sheet"];

                // EDIT: Perhaps you can get access the "Authority Table" here as well? e.g.
                DataTable AuthorityTable = result.Tables["AuthoritySheet"];

                // I'll try to do something equivalent
                //DataTable newDt = dt.Select().Skip(1).Take(dt.Rows.Count).CopyToDataTable();
                DataTable newDt = dt.Clone();
                bool firstRow = true;

                foreach (DataRow dr in dt.Rows)
                {
                    if (dr["Id"] != null && !firstRow && AuthorityContainsKey(Convert.ToInt32(dr["Id"]), AuthorityTable))
                        newDt.Rows.Add(dr);
                    else
                        firstRow = false;
                }

                using (SqlBulkCopy sqlBulk = new SqlBulkCopy(GetConnectionString()))
                {
                    sqlBulk.DestinationTableName = tableName;
                    sqlBulk.WriteToServer(newDt);
                }
            }
            return true;
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex.Message);
        return false;
    }
}

public bool AuthorityContainsKey(int id, DataTable Auth)
{
    bool result = false;

    foreach (DataRow dr in Auth.Rows)
    {
        if (dr["Id"] != null && Convert.ToInt32(dr["Id"]) == id)
            return true;
    }

    return result;
}


text:
Q: RStudio: Save data from Viewer Due to a stupid mistake and a defective USB stick I lost a bunch of data and I am now trying to recover it.
Some of the the data is still displayed in the Viewer tabs when I open RStudio. However, I can only save R Scripts and R Markdownfiles out of the Viewer. The displayed data frames are nice and complete, I can sort and filter them in the Viewer, however, I cannot find a "save" option. Is there a possibility to save this displayed data into Rdata or csv or something similar?

A: I would suggest three different approaches, but none of them will necessarily work. I sort them according to my prior expectations of success.
1) You can copy all your data frame from the viewer and paste it into an external spreadsheet software to obtain a .csv file. E.g. through the "convert text to columns" button in MS Excel.
2) You can copy and paste the character string into an object that is passed to the text option of read.table or to dput(). Check out the "Copy your data" section of this famous SO question
3) Finally, you can get google Chrome's "Inspect Element" function to inspect the html code of the object in the viewer. Once you find the table you can copy paste and scrape with an html parser, e.g. using the rvest package. Good luck!

A: Thanks everybody, there is a way to access the data as Rdata files, which was kindly explained to me here
I used the second method and located the files in %localappdata%\RStudio-Desktop\viewer-cache.


text:
Q: How can I execute Legacy Scala Code Base in Databricks with pyspark I have a number of legacy scala packages/ code base that needs to be migrated to Databricks.
Currently, these scala packages are translated to jar files which are invoked from a shell script.
I can run scala in Databricks, but how can I call a package file/ scala code base within pyspark? Is that possible, if so how do I do that?

A: If you want to migrate them 1:1, then you just need to run them as a Jar task or Spark Submit task in Databricks Workflows.  Wrapping them as PySpark makes no sense from my point of view, until you provide more information what do you mean by that.


text:
Q: How to remove the gap between the bar in my barchart with barwidth defined in highcharts I'm trying to remove the gaps between the bars in Highcharts with the {pointWidth: 30} option defined, using {pointPadding: 0, groupPadding: 0, borderWidth: 0} has no effect. (see JSFiddle)
How do I achieve the following result without the gaps:

Thanks in advance.

A: Highchart does not seems to calulate padding on x-axis after pointWidth is defined. Refer
https://api.highcharts.com/highcharts/series.column.pointWidth. Not sure if that limitation Highchart.
Although, it not perfect solution, I tried to do using css3 (scss) to position the bar. The solution is quite odd.
Please have a look and hopefully you can come up with better idea than this one.
https://jsfiddle.net/6f9yvcan/105
SCSS
$columns-list: 1 3 5 7 9 11 13;
$column-left-offset: 200px;
@each $col in $columns-list {
    $i: index($columns-list, $col);

    $column-left: (30px * $i) + $column-left-offset;
    .highcharts-series:nth-child(#{$col}) {
      rect {
       x: $column-left;
      }
    }

    .highcharts-data-labels:nth-child(#{$i}) .highcharts-data-label {
      background-color: red;
      left: ($column-left - 20px) !important;
    }
}


text:
Q: Highcharts change crosshairs color by number of visible series What we are trying to do is to:

*

*display crosshairs only if number of visible series > 1 (color: black)

*otherwise disable crosshairs or alternatively set color transparent

Here are our problems:

*

*independent of the number of visible series the crosshairs is not shown for the first hover (but for all subsequent hovers)

*our main problem is that the color is not changing although the console.log displays that the color is correctly set due to the number of visible series

Please see the fiddle: example
Thanks for your suggestions!
$(function () {
var chart = new Highcharts.Chart({
    chart: {
        type: 'area',
        renderTo: 'container'
    },
    title: {
        text: 'Historic and Estimated Worldwide Population Growth by Region'
    },
    subtitle: {
        text: 'Source: Wikipedia.org'
    },
    xAxis: {
        categories: ['1750', '1800', '1850', '1900', '1950', '1999', '2050'],
        tickmarkPlacement: 'on',
        title: {
            enabled: false
        }
    },
    yAxis: {
        title: {
            text: 'Billions'
        },
        labels: {
            formatter: function () {
                return this.value / 1000;
            }
        }
    },
    tooltip: {
        formatter: function () {

            // show crosshairs only if visible series >1, else transparent
            var nVisible = 0;
            for (var i = 0; i < chart.series.length; i++) {
                if (chart.series[i].visible) {
                    nVisible++;
                };
                if (nVisible > 1) {
                    break;
                };
            };

            if (nVisible > 1) {
                chart.options.tooltip.crosshairs = {
                    width: 1.5,
                    dashStyle: 'solid',
                    color: 'black'
                };
            } else {
                chart.options.tooltip.crosshairs = {
                    color: 'transparent'
                };

            };
            console.log(chart.options.tooltip.crosshairs.color);
            return this.y + ' Billions';
        },
        backgroundColor: 'rgba(255,255,255,0.95)'
    },
    plotOptions: {
        area: {
            stacking: 'normal',
            lineColor: '#666666',
            lineWidth: 1,
            marker: {
                lineWidth: 1,
                lineColor: '#666666'
            }
        }
    },
    series: [{
        name: 'Asia',
        data: [502, 635, 809, 947, 1402, 3634, 5268]
    }, {
        name: 'Africa',
        data: [106, 107, 111, 133, 221, 767, 1766]
    }, {
        name: 'Europe',
        data: [163, 203, 276, 408, 547, 729, 628]
    }, {
        name: 'America',
        data: [18, 31, 54, 156, 339, 818, 1201]
    }, {
        name: 'Oceania',
        data: [2, 2, 2, 6, 13, 30, 46]
    }]
});
});

A: Don't add crosshair in real time, instead when chart is initialized, enable crosshair and then manage color by attr() updating. For example: http://jsfiddle.net/D5DME/3/
Code:
    tooltip: {
        crosshairs: [{
            width: 1.5,
            dashStyle: 'solid',
            color: 'black'
        }, false],
        formatter: function () {

            // show crosshairs only if visible series >1, else transparent
            var nVisible = 0;
            for (var i = 0; i < this.series.chart.series.length; i++) {
                if (this.series.chart.series[i].visible) {
                    nVisible++;
                };
            };

            if(this.series.chart.tooltip.crosshairs[0]) {
                if (nVisible > 1) {
                    this.series.chart.tooltip.crosshairs[0].attr({
                        stroke: 'black'
                    });
                } else {
                    this.series.chart.tooltip.crosshairs[0].attr({
                        stroke: 'rgba(0,0,0,0)'
                    });
                }
            }
            return this.y + ' Billions';
        },
        backgroundColor: 'rgba(255,255,255,0.95)'
    },

A: It looks to me that the tooltip code is the wrong place to be trying this. I would use the series hide and show event handlers to detect how many series were showing (a simple counter which increments in show and decrements in hide would work).
http://api.highcharts.com/highstock#plotOptions.series.events.hide
You could try the chart setting options depending on the count.
However, I'm not sure that simply settting chart.options.tootlip. will work dynamically the way you want.


text:
Q: js format string to pretty url since I'm not so proficient in js so I apologize in advance for a possibly unnecessary question, but as with js, rewrite plain text to pretty url.
So this:
hello world
To this:
hello-world
And then insert the rewritten form into the form input

        Nadpis
        <input type="text" name="title" id="title" class="form-control" value="{{ old('title') }}" required minlength="3" maxlength="80" onblur="this.form.url.value=this.value"/>

        URL
        <input type="text" name="url" id="url" class="form-control" value="{{ old('url') }}" required minlength="3" maxlength="80" readonly/>

A: *

*Add event listeners

*Execute on load if needed

*Remove inline event handlers

*Perform a replace before URIEncoding

Change encodeURIComponent(this.value.replace(/ /g, "-"))
to this.value.replace(/ /g, "-") if you just want the replace
Additionally we could use new URL() and URL SearchParams on the result if it is supposed to be an actual URL

//const re1 = /[\;\,\/\?\:\@\&\=\+\$\_\.!\~\*\'\(\)\#]/g
const re2 = /[^a-zA-Z0-9 ]/g

window.addEventListener("load", function() { // on page load
  const title = document.getElementById("title"); // store the field
  title.addEventListener("input", function() { // on any input
    document.getElementById("url").value = encodeURIComponent(
      // this.value.replace(/ /g, "-").replace(re1,"") // left out the "-"
      this.value.replace(re2,"").replace(/ /g, "-") // using re 2
    ); // encode after replace
  });
  title.dispatchEvent(new Event('input')); // trigger the change
});

  Nadpis
  <input type="text" name="title" id="title" class="form-control" value="Hello world;,/?:@&=+$_.!~*'()#" required minlength="3" maxlength="80" />

  URL
  <input type="text" name="url" id="url" class="form-control" value="What is the old URL?" required minlength="3" maxlength="80" readonly/>

A: You can use this replace code to format your Pretty URL:
var prettyUrl = oldUrl.split(' ').join('-');

A: if i understand your problem, i hope this code helps you

function prettyUrl(value)
{
  return value.replace(/ /g, "-").replace(/@/g, "").replace(/\$/g, "").replace(/!/g, "").replace(/#/g, "").toLowerCase();
}
<form>

    Nadpis
    <input type="text" name="title" id="title" class="form-control" required minlength="3" maxlength="80" onblur="this.form.url.value=prettyUrl(this.value)" />

    URL
    <input type="text" name="url" id="url" class="form-control" required minlength="3" maxlength="80" readonly/>

</form>

Updated
replace special character with Nothing and lowercase all letters


text:
Q: nodejs - private REST API I have created a simple REST api for my application using node/ express. I am using AngularJS on the front end to serve pages to the user.
I would like to add functionality such that the API can only be accessed via my front-end and anyone should not be able to do a GET/POST request to my site and get the data?
What strategies can I use to achieve this?

A: HTTP request can be formatted and sent to sever by many other means beside a browser (curl for example), so any server always detecting correct source of a request is not guaranteed.
The basic method to protect an endpoint would be to use some kind of authentication. The requesting client must present something uniquely identifying it. API should provide clients a token after it proves itself authentic (via login etc), and all subsequent requests would be checked for this token.