Programs & Examples On #Query parser

Check if a parameter is null or empty in a stored procedure

I sometimes use NULLIF like so...

IF NULLIF(@PreviousStartDate, '') IS NULL

There's probably no reason it's better than the way suggested by @Oded and @bluefeet, just stylistic preference.

@danihp's method is really cool but my tired old brain wouldn't go to COALESCE when I'm thinking is null or empty :-)

Guid is all 0's (zeros)?

Try this instead:

var responseObject = proxy.CallService(new RequestObject
{
    Data = "misc. data",
    Guid = new Guid.NewGuid()
});

This will generate a 'real' Guid value. When you new a reference type, it will give you the default value (which in this case, is all zeroes for a Guid).

When you create a new Guid, it will initialize it to all zeroes, which is the default value for Guid. It's basically the same as creating a "new" int (which is a value type but you can do this anyways):

Guid g1;                    // g1 is 00000000-0000-0000-0000-000000000000
Guid g2 = new Guid();       // g2 is 00000000-0000-0000-0000-000000000000
Guid g3 = default(Guid);    // g3 is 00000000-0000-0000-0000-000000000000
Guid g4 = Guid.NewGuid();   // g4 is not all zeroes

Compare this to doing the same thing with an int:

int i1;                     // i1 is 0
int i2 = new int();         // i2 is 0
int i3 = default(int);      // i3 is 0

Flask raises TemplateNotFound error even though template file exists

When render_template() function is used it tries to search for template in the folder called templates and it throws error jinja2.exceptions.TemplateNotFound when :

  1. the html file do not exist or
  2. when templates folder do not exist

To solve the problem :

create a folder with name templates in the same directory where the python file is located and place the html file created in the templates folder.

CSS Disabled scrolling

overflow-x: hidden;
would hide any thing on the x-axis that goes outside of the element, so there would be no need for the horizontal scrollbar and it get removed.

overflow-y: hidden;
would hide any thing on the y-axis that goes outside of the element, so there would be no need for the vertical scrollbar and it get removed.

overflow: hidden;
would remove both scrollbars

Import CSV to mysql table

I have google search many ways to import csv to mysql, include " load data infile ", use mysql workbench, etc.

when I use mysql workbench import button, first you need to create the empty table on your own, set each column type on your own. Note: you have to add ID column at the end as primary key and not null and auto_increment, otherwise, the import button will not visible at later. However, when I start load CSV file, nothing loaded, seems like a bug. I give up.

Lucky, the best easy way so far I found is to use Oracle's mysql for excel. you can download it from here mysql for excel

This is what you are going to do: open csv file in excel, at Data tab, find mysql for excel button

select all data, click export to mysql. Note to set a ID column as primary key.

when finished, go to mysql workbench to alter the table, such as currency type should be decimal(19,4) for large amount decimal(10,2) for regular use. other field type may be set to varchar(255).

Sending XML data using HTTP POST with PHP

Another option would be file_get_contents():

// $xml_str = your xml
// $url = target url

$post_data = array('xml' => $xml_str);
$stream_options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
        'content' =>  http_build_query($post_data)));

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);

Editing dictionary values in a foreach loop

You can make a list copy of the dict.Values, then you can use the List.ForEach lambda function for iteration, (or a foreach loop, as suggested before).

new List<string>(myDict.Values).ForEach(str =>
{
  //Use str in any other way you need here.
  Console.WriteLine(str);
});

How to pass a parameter like title, summary and image in a Facebook sharer URL

The only parameter you need right now is ?u=<YOUR_URL>. All other data will be fetched from page or (better) from your open graph meta tags:

<meta property="og:url"                content="http://www.nytimes.com/2015/02/19/arts/international/when-great-minds-dont-think-alike.html" />
<meta property="og:type"               content="article" />
<meta property="og:title"              content="When Great Minds Don’t Think Alike" />
<meta property="og:description"        content="How much does culture influence creative thinking?" />
<meta property="og:image"              content="http://static01.nyt.com/images/2015/02/19/arts/international/19iht-btnumbers19A/19iht-btnumbers19A-facebookJumbo-v2.jpg" />

Example & description here

You can test your page for accordance in the debugger.

How to study design patterns?

I recommend HeadFirst DesignPattern. Reading the book is not enough, after assimilating the concepts you need to findout the answers for lot of questions arise in your mind and try to findout the real life applications where in these patterns can be used. I am doing the same and started asking questions even those questions look silly.

Position a CSS background image x pixels from the right?

I was trying to do a similar task to get a dropdown arrow always on the right side of the table header and came up with this which seemed to work in Chrome and Firefox, but safari was telling me it was an invalid property.

background: url(http://goo.gl/P93P5Q) center right 10px no-repeat;

After doing a bit of messing around in the inspector, I came up with this cross-browser solution that works in IE8+, Chrome, Firefox, and Safari, as well as responsive designs.

background: url(http://goo.gl/P93P5Q) no-repeat 95% center;

Here is a codepen of how it looks and works. Codepen is written with SCSS - http://cdpn.io/xqGbk

Instagram: Share photo from webpage

The short answer is: No. The only way to post images is through the mobile app.

From the Instagram API documentation: http://instagram.com/developer/endpoints/media/

At this time, uploading via the API is not possible. We made a conscious choice not to add this for the following reasons:

  • Instagram is about your life on the go – we hope to encourage photos from within the app. However, in the future we may give whitelist access to individual apps on a case by case basis.
  • We want to fight spam & low quality photos. Once we allow uploading from other sources, it's harder to control what comes into the Instagram ecosystem.

All this being said, we're working on ways to ensure users have a consistent and high-quality experience on our platform.

Mongoose, Select a specific field with find

The _id field is always present unless you explicitly exclude it. Do so using the - syntax:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select('name -_id');

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

Or explicitly via an object:

exports.someValue = function(req, res, next) {
    //query with mongoose
    var query = dbSchemas.SomeValue.find({}).select({ "name": 1, "_id": 0});

    query.exec(function (err, someValue) {
        if (err) return next(err);
        res.send(someValue);
    });
};

How can I remove the gloss on a select element in Safari on Mac?

Sorry to pile on to an old item. I found partial answers to my questions here but had to do some work so I wanted to share my results for the next person.

I ended up using the same approach as the other contributors, but with a few tweaks to fix the following

  1. Long text was covering the arrows in the other solutions
  2. The image being used was a somewhat old and ugly up/down combo arrow.

The below will give you a working solution with the above issues fixed. Note: I used a white arrow for my use case, you may need to change the color of the arrow for yours.

here's a preview:

select with white arrow

select{    
  -webkit-appearance: none;
  -moz-appearance: none;
  appearance: none;
  background: url(data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiBlbmNvZGluZz0iVVRGLTgiIHN0YW5kYWxvbmU9Im5vIj8+PHN2ZyAgIHhtbG5zOmRjPSJodHRwOi8vcHVybC5vcmcvZGMvZWxlbWVudHMvMS4xLyIgICB4bWxuczpjYz0iaHR0cDovL2NyZWF0aXZlY29tbW9ucy5vcmcvbnMjIiAgIHhtbG5zOnJkZj0iaHR0cDovL3d3dy53My5vcmcvMTk5OS8wMi8yMi1yZGYtc3ludGF4LW5zIyIgICB4bWxuczpzdmc9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIiAgIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgICB4bWxuczpzb2RpcG9kaT0iaHR0cDovL3NvZGlwb2RpLnNvdXJjZWZvcmdlLm5ldC9EVEQvc29kaXBvZGktMC5kdGQiICAgeG1sbnM6aW5rc2NhcGU9Imh0dHA6Ly93d3cuaW5rc2NhcGUub3JnL25hbWVzcGFjZXMvaW5rc2NhcGUiICAgaWQ9IkxheWVyXzEiICAgZGF0YS1uYW1lPSJMYXllciAxIiAgIHZpZXdCb3g9IjAgMCA0Ljk1IDEwIiAgIHZlcnNpb249IjEuMSIgICBpbmtzY2FwZTp2ZXJzaW9uPSIwLjkxIHIxMzcyNSIgICBzb2RpcG9kaTpkb2NuYW1lPSJkb3dubG9hZC5zdmciPiAgPG1ldGFkYXRhICAgICBpZD0ibWV0YWRhdGE0MjAyIj4gICAgPHJkZjpSREY+ICAgICAgPGNjOldvcmsgICAgICAgICByZGY6YWJvdXQ9IiI+ICAgICAgICA8ZGM6Zm9ybWF0PmltYWdlL3N2Zyt4bWw8L2RjOmZvcm1hdD4gICAgICAgIDxkYzp0eXBlICAgICAgICAgICByZGY6cmVzb3VyY2U9Imh0dHA6Ly9wdXJsLm9yZy9kYy9kY21pdHlwZS9TdGlsbEltYWdlIiAvPiAgICAgIDwvY2M6V29yaz4gICAgPC9yZGY6UkRGPiAgPC9tZXRhZGF0YT4gIDxzb2RpcG9kaTpuYW1lZHZpZXcgICAgIHBhZ2Vjb2xvcj0iI2ZmZmZmZiIgICAgIGJvcmRlcmNvbG9yPSIjNjY2NjY2IiAgICAgYm9yZGVyb3BhY2l0eT0iMSIgICAgIG9iamVjdHRvbGVyYW5jZT0iMTAiICAgICBncmlkdG9sZXJhbmNlPSIxMCIgICAgIGd1aWRldG9sZXJhbmNlPSIxMCIgICAgIGlua3NjYXBlOnBhZ2VvcGFjaXR5PSIwIiAgICAgaW5rc2NhcGU6cGFnZXNoYWRvdz0iMiIgICAgIGlua3NjYXBlOndpbmRvdy13aWR0aD0iMTkyMCIgICAgIGlua3NjYXBlOndpbmRvdy1oZWlnaHQ9IjEwMjciICAgICBpZD0ibmFtZWR2aWV3NDIwMCIgICAgIHNob3dncmlkPSJmYWxzZSIgICAgIGlua3NjYXBlOnpvb209Ijg0LjMiICAgICBpbmtzY2FwZTpjeD0iMi40NzQ5OTk5IiAgICAgaW5rc2NhcGU6Y3k9IjUiICAgICBpbmtzY2FwZTp3aW5kb3cteD0iMTkyMCIgICAgIGlua3NjYXBlOndpbmRvdy15PSIyNyIgICAgIGlua3NjYXBlOndpbmRvdy1tYXhpbWl6ZWQ9IjEiICAgICBpbmtzY2FwZTpjdXJyZW50LWxheWVyPSJMYXllcl8xIiAvPiAgPGRlZnMgICAgIGlkPSJkZWZzNDE5MCI+ICAgIDxzdHlsZSAgICAgICBpZD0ic3R5bGU0MTkyIj4uY2xzLTJ7ZmlsbDojNDQ0O308L3N0eWxlPiAgPC9kZWZzPiAgPHRpdGxlICAgICBpZD0idGl0bGU0MTk0Ij5hcnJvd3M8L3RpdGxlPiAgPHBvbHlnb24gICAgIGNsYXNzPSJjbHMtMiIgICAgIHBvaW50cz0iMy41NCA1LjMzIDIuNDggNi44MiAxLjQxIDUuMzMgMy41NCA1LjMzIiAgICAgaWQ9InBvbHlnb240MTk4IiAgICAgc3R5bGU9ImZpbGw6I2ZmZmZmZjtmaWxsLW9wYWNpdHk6MSIgLz48L3N2Zz4=) no-repeat 101% 50%;
  padding-right:20px;
}

How to declare local variables in postgresql?

Postgresql historically doesn't support procedural code at the command level - only within functions. However, in Postgresql 9, support has been added to execute an inline code block that effectively supports something like this, although the syntax is perhaps a bit odd, and there are many restrictions compared to what you can do with SQL Server. Notably, the inline code block can't return a result set, so can't be used for what you outline above.

In general, if you want to write some procedural code and have it return a result, you need to put it inside a function. For example:

CREATE OR REPLACE FUNCTION somefuncname() RETURNS int LANGUAGE plpgsql AS $$
DECLARE
  one int;
  two int;
BEGIN
  one := 1;
  two := 2;
  RETURN one + two;
END
$$;
SELECT somefuncname();

The PostgreSQL wire protocol doesn't, as far as I know, allow for things like a command returning multiple result sets. So you can't simply map T-SQL batches or stored procedures to PostgreSQL functions.

Multi-select dropdown list in ASP.NET

You could use the System.Web.UI.WebControls.CheckBoxList control or use the System.Web.UI.WebControls.ListBox control with the SelectionMode property set to Multiple.

What is the best way to merge mp3 files?

Personally I would use something like mplayer with the audio pass though option eg -oac copy

How to trigger a build only if changes happen on particular set of files

If the logic for choosing the files is not trivial, I would trigger script execution on each change and then write a script to check if indeed a build is required, then triggering a build if it is.

Why is "cursor:pointer" effect in CSS not working

I had this issue using Angular and SCSS. I had all my CSS nested so I decided to remove cursor: pointer; out of it. And it worked.

Example:

.container{
  .Approved{
    color:green;
  }

  .ApprovedAndVerified{
    color:black;
  }

  .lock_button{
    font-size:35px;
    display:block;
    text-align:center;
  }
}

.lock_button{
  cursor:pointer;
}

jQuery hasAttr checking to see if there is an attribute on an element

Late to the party, but... why not just this.hasAttribute("name")?

Refer This

Why is this rsync connection unexpectedly closed on Windows?

I had this problem, but only when I tried to rsync from a Linux (RH) server to a Solaris server. My fix was to make sure rsync had the same path on both boxes, and that the ownership of rsync was the same.

On the linux box, rsync path was /usr/bin, on Solaris box it was /usr/local/bin. So, on the Solaris box I did ln -s /usr/local/bin/rsync /usr/bin/rsync.

I still had the same problem, and noticed ownership differences. On linux it was root:root, on solaris it was bin:bin. Changing solaris to root:root fixed it.

How to auto adjust the div size for all mobile / tablet display formats?

I use something like this in my document.ready

var height = $(window).height();//gets height from device
var width = $(window).width(); //gets width from device

$("#container").width(width+"px");
$("#container").height(height+"px");

What is the best way to exit a function (which has no return value) in python before the function ends (e.g. a check fails)?

You could simply use

return

which does exactly the same as

return None

Your function will also return None if execution reaches the end of the function body without hitting a return statement. Returning nothing is the same as returning None in Python.

How to fix Error: this class is not key value coding-compliant for the key tableView.'

You have your storyboard set up to expect an outlet called tableView but the actual outlet name is myTableView.

If you delete the connection in the storyboard and reconnect to the right variable name, it should fix the problem.

Remove item from list based on condition

prods.Remove(prods.Single(p=>p.ID == 1));

you can't modify collection in foreach, as Vincent suggests

What is Java EE?

J(2)EE, strictly speaking, is a set of APIs (as the current top answer has it) which enable a programmer to build distributed, transactional systems. The idea was to abstract away the complicated distributed, transactional bits (which would be implemented by a Container such as WebSphere or Weblogic), leaving the programmer to develop business logic free from worries about storage mechanisms and synchronization.

In reality, it was a cobbled-together, design-by-committee mish-mash, which was pushed pretty much for the benefit of vendors like IBM, Oracle and BEA so they could sell ridicously over-complicated, over-engineered, over-useless products. Which didn't have the most basic features (such as scheduling)!

J2EE was a marketing construct.

showing that a date is greater than current date

In sql server, you can do

SELECT *
FROM table t
WHERE t.date > DATEADD(dd,90,now())

What's the difference between equal?, eql?, ===, and ==?

I love jtbandes answer, but since it is pretty long, I will add my own compact answer:

==, ===, eql?, equal?
are 4 comparators, ie. 4 ways to compare 2 objects, in Ruby.
As, in Ruby, all comparators (and most operators) are actually method-calls, you can change, overwrite, and define the semantics of these comparing methods yourself. However, it is important to understand, when Ruby's internal language constructs use which comparator:

== (value comparison)
Ruby uses :== everywhere to compare the values of 2 objects, eg. Hash-values:

{a: 'z'}  ==  {a: 'Z'}    # => false
{a: 1}    ==  {a: 1.0}    # => true

=== (case comparison)
Ruby uses :=== in case/when constructs. The following code snippets are logically identical:

case foo
  when bar;  p 'do something'
end

if bar === foo
  p 'do something'
end

eql? (Hash-key comparison)
Ruby uses :eql? (in combination with the method hash) to compare Hash-keys. In most classes :eql? is identical with :==.
Knowledge about :eql? is only important, when you want to create your own special classes:

class Equ
  attr_accessor :val
  alias_method  :initialize, :val=
  def hash()           self.val % 2             end
  def eql?(other)      self.hash == other.hash  end
end

h = {Equ.new(3) => 3,  Equ.new(8) => 8,  Equ.new(15) => 15}    #3 entries, but 2 are :eql?
h.size            # => 2
h[Equ.new(27)]    # => 15

Note: The commonly used Ruby-class Set also relies on Hash-key-comparison.

equal? (object identity comparison)
Ruby uses :equal? to check if two objects are identical. This method (of class BasicObject) is not supposed to be overwritten.

obj = obj2 = 'a'
obj.equal? obj2       # => true
obj.equal? obj.dup    # => false

pycharm running way slow

Regarding the freezing issue, we found this occurred when processing CSV files with at least one extremely long line.

To reproduce:

[print(x) for x in (['A' * 54790] + (['a' * 1421] * 10))]

However, it appears to have been fixed in PyCharm 4.5.4, so if you experience this, try updating your PyCharm.

How do you select a particular option in a SELECT element in jQuery?

$('#select option[data-id-estado="3"]').prop("selected",true).trigger("change");

or

$('#select option[value="myValue"]').prop("selected",true).trigger("change");

onKeyDown event not working on divs in React

You're thinking too much in pure Javascript. Get rid of your listeners on those React lifecycle methods and use event.key instead of event.keyCode (because this is not a JS event object, it is a React SyntheticEvent). Your entire component could be as simple as this (assuming you haven't bound your methods in a constructor).

onKeyPressed(e) {
  console.log(e.key);
}

render() {
  let player = this.props.boards.dungeons[this.props.boards.currentBoard].player;
  return (
    <div 
      className="player"
      style={{ position: "absolute" }}
      onKeyDown={this.onKeyPressed}
    >
      <div className="light-circle">
        <div className="image-wrapper">
          <img src={IMG_URL+player.img} />
        </div>
      </div>
    </div>
  )
}

JQuery: 'Uncaught TypeError: Illegal invocation' at ajax request - several elements

function do_ajax(elem, mydata, filename)
{
    $.ajax({
        url: filename,
        context: elem,
        data: mydata,
        **contentType: false,
        processData: false**
        datatype: "html",
        success: function (data, textStatus, xhr) {
            elem.innerHTML = data;
        }
    });
}

T-SQL: Export to new Excel file

This is by far the best post for exporting to excel from SQL:

http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49926

To quote from user madhivanan,

Apart from using DTS and Export wizard, we can also use this query to export data from SQL Server2000 to Excel

Create an Excel file named testing having the headers same as that of table columns and use these queries

1 Export data to existing EXCEL file from SQL Server table

insert into OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;', 
    'SELECT * FROM [SheetName$]') select * from SQLServerTable

2 Export data from Excel to new SQL Server table

select * 
into SQLServerTable FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [Sheet1$]')

3 Export data from Excel to existing SQL Server table (edited)

Insert into SQLServerTable Select * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
    'Excel 8.0;Database=D:\testing.xls;HDR=YES', 
    'SELECT * FROM [SheetName$]')

4 If you dont want to create an EXCEL file in advance and want to export data to it, use

EXEC sp_makewebtask 
    @outputfile = 'd:\testing.xls', 
    @query = 'Select * from Database_name..SQLServerTable', 
    @colheaders =1, 
    @FixedFont=0,@lastupdated=0,@resultstitle='Testing details'

(Now you can find the file with data in tabular format)

5 To export data to new EXCEL file with heading(column names), create the following procedure

create procedure proc_generate_excel_with_columns
(
    @db_name    varchar(100),
    @table_name varchar(100),   
    @file_name  varchar(100)
)
as

--Generate column names as a recordset
declare @columns varchar(8000), @sql varchar(8000), @data_file varchar(100)
select 
    @columns=coalesce(@columns+',','')+column_name+' as '+column_name 
from 
    information_schema.columns
where 
    table_name=@table_name
select @columns=''''''+replace(replace(@columns,' as ',''''' as '),',',',''''')

--Create a dummy file to have actual data
select @data_file=substring(@file_name,1,len(@file_name)-charindex('\',reverse(@file_name)))+'\data_file.xls'

--Generate column names in the passed EXCEL file
set @sql='exec master..xp_cmdshell ''bcp " select * from (select '+@columns+') as t" queryout "'+@file_name+'" -c'''
exec(@sql)

--Generate data in the dummy file
set @sql='exec master..xp_cmdshell ''bcp "select * from '+@db_name+'..'+@table_name+'" queryout "'+@data_file+'" -c'''
exec(@sql)

--Copy dummy file to passed EXCEL file
set @sql= 'exec master..xp_cmdshell ''type '+@data_file+' >> "'+@file_name+'"'''
exec(@sql)

--Delete dummy file 
set @sql= 'exec master..xp_cmdshell ''del '+@data_file+''''
exec(@sql)

After creating the procedure, execute it by supplying database name, table name and file path:

EXEC proc_generate_excel_with_columns 'your dbname', 'your table name','your file path'

Its a whomping 29 pages but that is because others show various other ways as well as people asking questions just like this one on how to do it.

Follow that thread entirely and look at the various questions people have asked and how they are solved. I picked up quite a bit of knowledge just skimming it and have used portions of it to get expected results.

To update single cells

A member also there Peter Larson posts the following: I think one thing is missing here. It is great to be able to Export and Import to Excel files, but how about updating single cells? Or a range of cells?

This is the principle of how you do manage that

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = -99

You can also add formulas to Excel using this:

update OPENROWSET('Microsoft.Jet.OLEDB.4.0', 
'Excel 8.0;Database=c:\test.xls;hdr=no', 
'SELECT * FROM [Sheet1$b7:b7]') set f1 = '=a7+c7'

Exporting with column names using T-SQL

Member Mladen Prajdic also has a blog entry on how to do this here

References: www.sqlteam.com (btw this is an excellent blog / forum for anyone looking to get more out of SQL Server). For error referencing I used this

Errors that may occur

If you get the following error:

OLE DB provider 'Microsoft.Jet.OLEDB.4.0' cannot be used for distributed queries

Then run this:

sp_configure 'show advanced options', 1;
GO
RECONFIGURE;
GO
sp_configure 'Ad Hoc Distributed Queries', 1;
GO
RECONFIGURE;
GO

Best way to get the max value in a Spark dataframe column

In case some wonders how to do it using Scala (using Spark 2.0.+), here you go:

scala> df.createOrReplaceTempView("TEMP_DF")
scala> val myMax = spark.sql("SELECT MAX(x) as maxval FROM TEMP_DF").
    collect()(0).getInt(0)
scala> print(myMax)
117

How can I print out C++ map values?

If your compiler supports (at least part of) C++11 you could do something like:

for (auto& t : myMap)
    std::cout << t.first << " " 
              << t.second.first << " " 
              << t.second.second << "\n";

For C++03 I'd use std::copy with an insertion operator instead:

typedef std::pair<string, std::pair<string, string> > T;

std::ostream &operator<<(std::ostream &os, T const &t) { 
    return os << t.first << " " << t.second.first << " " << t.second.second;
}

// ...
std:copy(myMap.begin(), myMap.end(), std::ostream_iterator<T>(std::cout, "\n"));

MVC 4 @Scripts "does not exist"

Import System.Web.Optimization on top of your razor view as follows:

@using System.Web.Optimization

Illegal Character when trying to compile java code

In Android Studio

1. Menu -> Edit -> Select All
2. Menu -> Edit -> Copy
  1. Open new Notepad.exe

In Notepad

4. Menu -> Edit -> Paste
5. Menu -> Edit -> Select All
6. Menu -> Edit -> Copy 

Back In Android Studio

7. Menu -> Edit -> Paste

List all files from a directory recursively with Java

In Java 8, it's a 1-liner via Files.find() with an arbitrarily large depth (eg 999) and BasicFileAttributes of isRegularFile()

public static printFnames(String sDir) {
    Files.find(Paths.get(sDir), 999, (p, bfa) -> bfa.isRegularFile()).forEach(System.out::println);
}

To add more filtering, enhance the lambda, for example all jpg files modified in the last 24 hours:

(p, bfa) -> bfa.isRegularFile()
  && p.getFileName().toString().matches(".*\\.jpg")
  && bfa.lastModifiedTime().toMillis() > System.currentMillis() - 86400000

How does "cat << EOF" work in bash?

Long story short, EOF marker(but a different literal can be used as well) is a heredoc format that allows you to provide your input as multiline. A lot of confusion comes from how cat actually works it seems. You can use cat with >> or > as follows:

$ cat >> temp.txt
line 1
line 2

While cat can be used this way when writing manually into console, it's not convenient if I want to provide the input in a more declarative way so that it can be reused by tools and also to keep indentations, whitespaces, etc.
Heredoc allows to define your entire input as if you are not working with stdin but typing in a separate text editor. This is what Wikipedia article means by:

it is a section of a source code file that is treated as if it were a separate file.

Tips for debugging .htaccess rewrite rules

Regarding 4., you still need to ensure that your "dummy script stub" is actually the target URL after all the rewriting is done, or you won't see anything!

A similar/related trick (see this question) is to insert a temporary rule such as:

RewriteRule (.*) /show.php?url=$1 [END]

Where show.php is some very simple script that just displays its $_GET parameters (you can display environment variables too, if you want).

This will stop the rewriting at the point you insert it into the ruleset, rather like a breakpoint in a debugger.

If you're using Apache <2.3.9, you'll need to use [L] rather than [END], and you may then need to add:

RewriteRule ^show.php$ - [L]

At the very top of your ruleset, if the URL /show.php is itself being rewritten.

How can I display a tooltip on an HTML "option" tag?

I don't think this would be possible to do across all browsers.

W3Schools reports that the option events exist in all browsers, but after setting up this test demo. I can only get it to work for Firefox (not Chrome or IE), I haven't tested it on other browsers.

Firefox also allows mouseenter and mouseleave but this is not reported on the w3schools page.


Update: Honestly, from looking at the example code you provided, I wouldn't even use a select box. I think it would look nicer with a slider. I've updated your demo. I had to make a few minor changes to your ratings object (adding a level number) and the safesurf tab. But I left pretty much everything else intact.

What are the differences between .so and .dylib on osx?

The difference between .dylib and .so on mac os x is how they are compiled. For .so files you use -shared and for .dylib you use -dynamiclib. Both .so and .dylib are interchangeable as dynamic library files and either have a type as DYLIB or BUNDLE. Heres the readout for different files showing this.

libtriangle.dylib:
Mach header
      magic cputype cpusubtype  caps    filetype ncmds sizeofcmds      flags
MH_MAGIC_64  X86_64        ALL  0x00       DYLIB    17       1368   NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS



libtriangle.so:
Mach header
      magic cputype cpusubtype  caps    filetype ncmds sizeofcmds      flags
MH_MAGIC_64  X86_64        ALL  0x00       DYLIB    17       1256   NOUNDEFS DYLDLINK TWOLEVEL NO_REEXPORTED_DYLIBS

triangle.so:
Mach header
      magic cputype cpusubtype  caps    filetype ncmds sizeofcmds      flags
MH_MAGIC_64  X86_64        ALL  0x00      BUNDLE    16       1696   NOUNDEFS DYLDLINK TWOLEVEL

The reason the two are equivalent on Mac OS X is for backwards compatibility with other UNIX OS programs that compile to the .so file type.

Compilation notes: whether you compile a .so file or a .dylib file you need to insert the correct path into the dynamic library during the linking step. You do this by adding -install_name and the file path to the linking command. If you dont do this you will run into the problem seen in this post: Mac Dynamic Library Craziness (May be Fortran Only).

How do I make a WPF TextBlock show my text on multiple lines?

Use the property TextWrapping of the TextBlock element:

<TextBlock Text="StackOverflow Forum"
           Width="100"
           TextWrapping="WrapWithOverflow"/>

How to loop through a JSON object with typescript (Angular2)

Assuming your json object from your GET request looks like the one you posted above simply do:

let list: string[] = [];

json.Results.forEach(element => {
    list.push(element.Id);
});

Or am I missing something that prevents you from doing it this way?

Split list into smaller lists (split in half)

f = lambda A, n=3: [A[i:i+n] for i in range(0, len(A), n)]
f(A)

n - the predefined length of result arrays

Setting graph figure size

 figure (1)
 hFig = figure(1);
 set(gcf,'PaperPositionMode','auto')
 set(hFig, 'Position', [0 0 xwidth ywidth])
 plot(x,y)
 print -depsc2 correlation.eps;       % for saving in eps, look up options for saving as png or other formats you may need

This saves the figure in the dimensions specified

how to check for null with a ng-if values in a view with angularjs?

You can also use ng-template, I think that would be more efficient while run time :)

<div ng-if="!test.view; else somethingElse">1</div>
<ng-template #somethingElse>
    <div>2</div>
</ng-template>

Cheers

pandas: best way to select all columns whose names start with X

Now that pandas' indexes support string operations, arguably the simplest and best way to select columns beginning with 'foo' is just:

df.loc[:, df.columns.str.startswith('foo')]

Alternatively, you can filter column (or row) labels with df.filter(). To specify a regular expression to match the names beginning with foo.:

>>> df.filter(regex=r'^foo\.', axis=1)
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
3     4.7         0             0        0          0
4     5.6         0             0        0          0
5     6.8         1             0        5          0

To select only the required rows (containing a 1) and the columns, you can use loc, selecting the columns using filter (or any other method) and the rows using any:

>>> df.loc[(df == 1).any(axis=1), df.filter(regex=r'^foo\.', axis=1).columns]
   foo.aa  foo.bars  foo.fighters  foo.fox foo.manchu
0     1.0         0             0        2         NA
1     2.1         0             1        4          0
2     NaN         0           NaN        1          0
5     6.8         1             0        5          0

How to write loop in a Makefile?

Maybe you can use:

xxx:
    for i in `seq 1 4`; do ./a.out $$i; done;

How do you change the datatype of a column in SQL Server?

ALTER TABLE [dbo].[TableName]
ALTER COLUMN ColumnName VARCHAR(Max) NULL

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

HTML5 video - show/hide controls programmatically

CARL LANGE also showed how to get hidden, autoplaying audio in html5 on a iOS device. Works for me.

In HTML,

<div id="hideme">
    <audio id="audioTag" controls>
        <source src="/path/to/audio.mp3">
    </audio>
</div>

with JS

<script type="text/javascript">
window.onload = function() {
    var audioEl = document.getElementById("audioTag");
    audioEl.load();
    audioEl.play();
};
</script>

In CSS,

#hideme {display: none;}

What is Dependency Injection?

Dependency Injection is passing dependency to other objects or framework( dependency injector).

Dependency injection makes testing easier. The injection can be done through constructor.

SomeClass() has its constructor as following:

public SomeClass() {
    myObject = Factory.getObject();
}

Problem: If myObject involves complex tasks such as disk access or network access, it is hard to do unit test on SomeClass(). Programmers have to mock myObject and might intercept the factory call.

Alternative solution:

  • Passing myObject in as an argument to the constructor
public SomeClass (MyClass myObject) {
    this.myObject = myObject;
}

myObject can be passed directly which makes testing easier.

  • One common alternative is defining a do-nothing constructor. Dependency injection can be done through setters. (h/t @MikeVella).
  • Martin Fowler documents a third alternative (h/t @MarcDix), where classes explicitly implement an interface for the dependencies programmers wish injected.

It is harder to isolate components in unit testing without dependency injection.

In 2013, when I wrote this answer, this was a major theme on the Google Testing Blog. It remains the biggest advantage to me, as programmers not always need the extra flexibility in their run-time design (for instance, for service locator or similar patterns). Programmers often need to isolate the classes during testing.

What is the Git equivalent for revision number?

The problem with using the git hash as the build number is that it's not monotonically increasing. OSGi suggests using a time-stamp for the build number. It looks like the number of commits to the branch could be used in place of the subversion or perforce change number.

Detect if a page has a vertical scrollbar?

Simply compare the width of the documents root element (i.e. html element) against the inner portion of the window:

if ((window.innerWidth - document.documentElement.clientWidth) >0) console.log('V-scrollbar active')

If you also need to know the scrollbar width:

vScrollbarWidth = window.innerWidth - document.documentElement.clientWidth;

Import Package Error - Cannot Convert between Unicode and Non Unicode String Data Type

Get to the registry to configuration of the client and change the LANG. For Oracle, go to HLM\SOFTWARE\ORACLE\KEY_ORACLIENT...HOME\NLS_LANG and change to appropriate language.

Join a list of items with different types as string in Python

There's nothing wrong with passing integers to str. One reason you might not do this is that myList is really supposed to be a list of integers e.g. it would be reasonable to sum the values in the list. In that case, do not pass your ints to str before appending them to myList. If you end up not converting to strings before appending, you can construct one big string by doing something like

', '.join(map(str, myList))

Simple InputBox function

It would be something like this

function CustomInputBox([string] $title, [string] $message, [string] $defaultText) 
{
$inputObject = new-object -comobject MSScriptControl.ScriptControl
$inputObject.language = "vbscript" 
$inputObject.addcode("function getInput() getInput = inputbox(`"$message`",`"$title`" , `"$defaultText`") end function" ) 
$_userInput = $inputObject.eval("getInput") 

return $_userInput
}

Then you can call the function similar to this.

$userInput = CustomInputBox "User Name" "Please enter your name." ""
if ( $userInput -ne $null ) 
{
 echo "Input was [$userInput]"
}
else
{
 echo "User cancelled the form!"
}

This is the most simple way to do this that I can think of.

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

You have to include one more jar.

xmlbeans-2.3.0.jar

Add this and try.

Note: It is required for the files with .xlsx formats only, not for just .xls formats.

Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM

As ROM size does not count one does not need any additional RAM besides the TCP buffers. Just implement a big finite-state machine. Each state represents a multi-set of numbers read in. After reading a million numbers one has just to print the numbers corresponding to the reached state.

Converting a double to an int in C#

In the provided example your decimal is 8.6. Had it been 8.5 or 9.5, the statement i1 == i2 might have been true. Infact it would have been true for 8.5, and false for 9.5.

Explanation:

Regardless of the decimal part, the second statement, int i2 = (int)score will discard the decimal part and simply return you the integer part. Quite dangerous thing to do, as data loss might occur.

Now, for the first statement, two things can happen. If the decimal part is 5, that is, it is half way through, a decision is to be made. Do we round up or down? In C#, the Convert class implements banker's rounding. See this answer for deeper explanation. Simply put, if the number is even, round down, if the number is odd, round up.

E.g. Consider:

        double score = 8.5;
        int i1 = Convert.ToInt32(score); // 8
        int i2 = (int)score;             // 8

        score += 1;
        i1 = Convert.ToInt32(score);     // 10
        i2 = (int)score;                 // 9

How do I check if an object has a specific property in JavaScript?

Showing how to use this answer

const object= {key1: 'data', key2: 'data2'};

Object.keys(object).includes('key1') //returns true

We can use indexOf as well, I prefer includes

How to compare dates in c#

Firstly, understand that DateTime objects aren't formatted. They just store the Year, Month, Day, Hour, Minute, Second, etc as a numeric value and the formatting occurs when you want to represent it as a string somehow. You can compare DateTime objects without formatting them.

To compare an input date with DateTime.Now, you need to first parse the input into a date and then compare just the Year/Month/Day portions:

DateTime inputDate;
if(!DateTime.TryParse(inputString, out inputDate))
    throw new ArgumentException("Input string not in the correct format.");

if(inputDate.Date == DateTime.Now.Date) {
    // Same date!
}

How to iterate a table rows with JQuery and access some cell values?

$("tr.item").each(function() {
  $this = $(this);
  var value = $this.find("span.value").html();
  var quantity = $this.find("input.quantity").val();
});

Importing modules from parent folder

It seems that the problem is not related to the module being in a parent directory or anything like that.

You need to add the directory that contains ptdraft to PYTHONPATH

You said that import nib worked with you, that probably means that you added ptdraft itself (not its parent) to PYTHONPATH.

Can't concatenate 2 arrays in PHP

This works for non-associative arrays:

while(($item = array_shift($array2)) !== null && array_push($array1, $item));

How do you follow an HTTP Redirect in Node.js?

If you have https server, change your url to use https:// protocol.

I got into similar issue with this one. My url has http:// protocol and I want to make a POST request, but the server wants to redirect it to https. What happen is that, turns out to be node http behavior sends the redirect request (next) in GET method which is not the case.

What I did is to change my url to https:// protocol and it works.

How to create a sticky left sidebar menu using bootstrap 3?

Bootstrap 3

Here is a working left sidebar example:

http://bootply.com/90936 (similar to the Bootstrap docs)

The trick is using the affix component along with some CSS to position it:

  #sidebar.affix-top {
    position: static;
    margin-top:30px;
    width:228px;
  }

  #sidebar.affix {
    position: fixed;
    top:70px;
    width:228px;
  }

EDIT- Another example with footer and affix-bottom


Bootstrap 4

The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top class is explained in this answer.

Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?

What's the difference between an id and a class?

Classes are like categories. Many HTML elements can belong to a class, and an HTML element can have more than one class. Classes are used to apply general styles or styles that can be applied across multiple HTML elements.

IDs are identifiers. They're unique; no one else is allowed to have that same ID. IDs are used to apply unique styles to an HTML element.

I use IDs and classes in this fashion:

<div id="header">
  <h1>I am a header!</h1>
  <p>I am subtext for a header!</p>
</div>
<div id="content">
  <div class="section">
    <p>I am a section!</p>
  </div>
  <div class="section special">
    <p>I am a section!</p>
  </div>
  <div class="section">
    <p>I am a section!</p>
  </div>
</div>

In this example, the header and content sections can be styled via #header and #content. Each section of the content can be applied a common style through #content .section. Just for kicks, I added a "special" class for the middle section. Suppose you wanted a particular section to have a special styling. This can be achieved with the .special class, yet the section still inherits the common styles from #content .section.

When I do JavaScript or CSS development, I typically use IDs to access/manipulate a very specific HTML element, and I use classes to access/apply styles to a broad range of elements.

How to send custom headers with requests in Swagger UI?

I ended up here because I was trying to conditionally add header parameters in Swagger UI, based on my own [Authentication] attribute I added to my API method. Following the hint that @Corcus listed in a comment, I was able to derive my solution, and hopefully it will help others.

Using Reflection, it's checking if the method nested down in apiDescription has the desired attribute (MyApiKeyAuthenticationAttribute, in my case). If it does, I can append my desired header parameters.

public void Apply(Operation operation, SchemaRegistry schemaRegistry, ApiDescription apiDescription) {
    if (operation.parameters == null)
        operation.parameters = new List<Parameter>();


    var attributes = ((System.Web.Http.Controllers.ReflectedHttpActionDescriptor)
        ((apiDescription.ActionDescriptor).ActionBinding.ActionDescriptor)).MethodInfo
        .GetCustomAttributes(false);
    if(attributes != null && attributes.Any()) {
        if(attributes.Where(x => x.GetType() 
            == typeof(MyApiKeyAuthenticationAttribute)).Any()) {

            operation.parameters.Add(new Parameter {
                name = "MyApiKey",
                @in = "header",
                type = "string",
                description = "My API Key",
                required = true
            });
            operation.parameters.Add(new Parameter {
                name = "EID",
                @in = "header",
                type = "string",
                description = "Employee ID",
                required = true
            });
        }
    }


}

MySQL Workbench not opening on Windows

I have uninstalled 8.0.19 (64) and installed 8.0.18 (64 bit) and now it Opens.

Impact of Xcode build options "Enable bitcode" Yes/No

  • What does the ENABLE_BITCODE actually do, will it be a non-optional requirement in the future?

I'm not sure at what level you are looking for an answer at, so let's take a little trip. Some of this you may already know.

When you build your project, Xcode invokes clang for Objective-C targets and swift/swiftc for Swift targets. Both of these compilers compile the app to an intermediate representation (IR), one of these IRs is bitcode. From this IR, a program called LLVM takes over and creates the binaries needed for x86 32 and 64 bit modes (for the simulator) and arm6/arm7/arm7s/arm64 (for the device). Normally, all of these different binaries are lumped together in a single file called a fat binary.

The ENABLE_BITCODE option cuts out this final step. It creates a version of the app with an IR bitcode binary. This has a number of nice features, but one giant drawback: it can't run anywhere. In order to get an app with a bitcode binary to run, the bitcode needs to be recompiled (maybe assembled or transcoded… I'm not sure of the correct verb) into an x86 or ARM binary.

When a bitcode app is submitted to the App Store, Apple will do this final step and create the finished binaries.

Right now, bitcode apps are optional, but history has shown Apple turns optional things into requirements (like 64 bit support). This usually takes a few years, so third party developers (like Parse) have time to update.

  • can I use the above method without any negative impact and without compromising a future appstore submission?

Yes, you can turn off ENABLE_BITCODE and everything will work just like before. Until Apple makes bitcode apps a requirement for the App Store, you will be fine.

  • Are there any performance impacts if I enable / disable it?

There will never be negative performance impacts for enabling it, but internal distribution of an app for testing may get more complicated.

As for positive impacts… well that's complicated.

For distribution in the App Store, Apple will create separate versions of your app for each machine architecture (arm6/arm7/arm7s/arm64) instead of one app with a fat binary. This means the app installed on iOS devices will be smaller.

In addition, when bitcode is recompiled (maybe assembled or transcoded… again, I'm not sure of the correct verb), it is optimized. LLVM is always working on creating new a better optimizations. In theory, the App Store could recreate the separate version of the app in the App Store with each new release of LLVM, so your app could be re-optimized with the latest LLVM technology.

How to convert a byte array to Stream

In your case:

MemoryStream ms = new MemoryStream(buffer);

Create a GUID in Java

java.util.UUID.randomUUID();

Dump Mongo Collection into JSON format

Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.

mongoexport -d <database> -c <collection_name>

Also helpful:

-o: write the output to file, otherwise standard output is used (docs)

--jsonArray: generates a valid json document, instead of one json object per line (docs)

--pretty: outputs formatted json (docs)

C# SQL Server - Passing a list to a stored procedure

No, arrays/lists can't be passed to SQL Server directly.

The following options are available:

  1. Passing a comma-delimited list and then having a function in SQL split the list. The comma delimited list will most likely be passed as an Nvarchar()
  2. Pass xml and have a function in SQL Server parse the XML for each value in the list
  3. Use the new defined User Defined table type (SQL 2008)
  4. Dynamically build the SQL and pass in the raw list as "1,2,3,4" and build the SQL statement. This is prone to SQL injection attacks, but it will work.

Run JavaScript code on window close or page refresh?

Sometimes you may want to let the server know that the user is leaving the page. This is useful, for example, to clean up unsaved images stored temporarily on the server, to mark that user as "offline", or to log when they are done their session.

Historically, you would send an AJAX request in the beforeunload function, however this has two problems. If you send an asynchronous request, there is no guarantee that the request would be executed correctly. If you send a synchronous request, it is more reliable, but the browser would hang until the request has finished. If this is a slow request, this would be a huge inconvenience to the user.

Later came navigator.sendBeacon(). By using the sendBeacon() method, the data is transmitted asynchronously to the web server when the User Agent has an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. This solves all of the problems with submission of analytics data: the data is sent reliably, it's sent asynchronously, and it doesn't impact the loading of the next page.

Unless you are targeting only desktop users, sendBeacon() should not be used with unload or beforeunload since these do not reliably fire on mobile devices. Instead you can listen to the visibilitychange event. This event will fire every time your page is visible and the user switches tabs, switches apps, goes to the home screen, answers a phone call, navigates away from the page, closes the tab, refreshes, etc.

Here is an example of its usage:

document.addEventListener('visibilitychange', function() {
    if (document.visibilityState == 'hidden') { 
        navigator.sendBeacon("/log.php", analyticsData);
    }
});

When the user returns to the page, document.visibilityState will change to 'visible', so you can also handle that event as well.

sendBeacon() is supported in:

  • Edge 14
  • Firefox 31
  • Chrome 39
  • Safari 11.1
  • Opera 26
  • iOS Safari 11.4

It is NOT currently supported in:

  • Internet Explorer
  • Opera Mini

Here is a polyfill for sendBeacon() in case you need to add support for unsupported browsers. If the method is not available in the browser, it will send a synchronous AJAX request instead.

Update:

It might be worth mentioning that sendBeacon() only sends POST requests. If you need to send a request using any other method, an alternative would be to use the fetch API with the keepalive flag set to true, which causes it to behave the same way as sendBeacon(). Browser support for the fetch API is about the same.

fetch(url, {
   method: ..., 
   body: ...,            
   headers: ...,       
   credentials: 'include',
   mode: 'no-cors',
   keepalive: true,
})

Spring-Boot: How do I set JDBC pool properties like maximum number of connections?

At the current version of Spring-Boot (1.4.1.RELEASE) , each pooling datasource implementation has its own prefix for properties.

For instance, if you are using tomcat-jdbc:

spring.datasource.tomcat.max-wait=10000

You can find the explanation out here

spring.datasource.max-wait=10000

this have no effect anymore.

Disable Chrome strict MIME type checking

also had same problem once,

if you are unable to solve the problem you can run the following command on command line
chrome.exe --user-data-dir="C://Chrome dev session" --disable-web-security

Note: you have to navigate to the installation path of your chrome.
For example:cd C:\Program Files\Google\Chrome\Application

A developer session chrome browser will be opened, you can now launch your app on the new chrome browse.
I hope this should be helpful

Creating a class object in c++

First of all, both cases calls a constructor. If you write

Example *example = new Example();

then you are creating an object, call the constructor and retrieve a pointer to it.

If you write

Example example;

The only difference is that you are getting the object and not a pointer to it. The constructor called in this case is the same as above, the default (no argument) constructor.

As for the singleton question, you must simple invoke your static method by writing:

Example *e = Singleton::getExample();

Prevent onmouseout when hovering child element of the parent absolute div WITHOUT jQuery

var elem = $('#some-id');
elem.mouseover(function () {
   // Some code here
}).mouseout(function (event) {
   var e = event.toElement || event.relatedTarget;
   if (elem.has(e).length > 0) return;

   // Some code here
});

Creating a LinkedList class from scratch

Sure, a Linked List is a bit confusing for programming n00bs, pretty much the temptation is to look at it as Russian Dolls, because that's what it seems like, a LinkedList Object in a LinkedList Object. But that's a touch difficult to visualize, instead look at it like a computer.

LinkedList = Data + Next Member

Where it's the last member of the list if next is NULL

So a 5 member LinkedList would be:

LinkedList(Data1, LinkedList(Data2, LinkedList(Data3, LinkedList(Data4, LinkedList(Data5, NULL)))))

But you can think of it as simply:

Data1 -> Data2 -> Data3 -> Data4 -> Data5 -> NULL

So, how do we find the end of this? Well, we know that the NULL is the end so:

public void append(LinkedList myNextNode) {
  LinkedList current = this; //Make a variable to store a pointer to this LinkedList
  while (current.next != NULL) { //While we're not at the last node of the LinkedList
    current = current.next; //Go further down the rabbit hole.
  }
  current.next = myNextNode; //Now we're at the end, so simply replace the NULL with another Linked List!
  return; //and we're done!
}

This is very simple code of course, and it will infinitely loop if you feed it a circularly linked list! But that's the basics.

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

just look at cv2.randu() or cv.randn(), it's all pretty similar to matlab already, i guess.

let's play a bit ;) :

import cv2
import numpy as np

>>> im = np.empty((5,5), np.uint8) # needs preallocated input image
>>> im
array([[248, 168,  58,   2,   1],  # uninitialized memory counts as random, too ?  fun ;) 
       [  0, 100,   2,   0, 101],
       [  0,   0, 106,   2,   0],
       [131,   2,   0,  90,   3],
       [  0, 100,   1,   0,  83]], dtype=uint8)
>>> im = np.zeros((5,5), np.uint8) # seriously now.
>>> im
array([[0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0],
       [0, 0, 0, 0, 0]], dtype=uint8)
>>> cv2.randn(im,(0),(99))         # normal
array([[  0,  76,   0, 129,   0],
       [  0,   0,   0, 188,  27],
       [  0, 152,   0,   0,   0],
       [  0,   0, 134,  79,   0],
       [  0, 181,  36, 128,   0]], dtype=uint8)
>>> cv2.randu(im,(0),(99))         # uniform
array([[19, 53,  2, 86, 82],
       [86, 73, 40, 64, 78],
       [34, 20, 62, 80,  7],
       [24, 92, 37, 60, 72],
       [40, 12, 27, 33, 18]], dtype=uint8)

to apply it to an existing image, just generate noise in the desired range, and add it:

img = ...
noise = ...

image = img + noise

Adding an HTTP Header to the request in a servlet filter

Extend HttpServletRequestWrapper, override the header getters to return the parameters as well:

public class AddParamsToHeader extends HttpServletRequestWrapper {
    public AddParamsToHeader(HttpServletRequest request) {
        super(request);
    }

    public String getHeader(String name) {
        String header = super.getHeader(name);
        return (header != null) ? header : super.getParameter(name); // Note: you can't use getParameterValues() here.
    }

    public Enumeration getHeaderNames() {
        List<String> names = Collections.list(super.getHeaderNames());
        names.addAll(Collections.list(super.getParameterNames()));
        return Collections.enumeration(names);
    }
}

..and wrap the original request with it:

chain.doFilter(new AddParamsToHeader((HttpServletRequest) request), response);

That said, I personally find this a bad idea. Rather give it direct access to the parameters or pass the parameters to it.

jQuery not working with IE 11

For me the issue turned out to be I was using es6's right arrow functions => as opposed to function ().

Replacing => with function () resolved for me.

I had assumed it was a jQuery issue.

How to read from stdin with fgets()?

You have a wrong idea of what fgets returns. Take a look at this: http://www.cplusplus.com/reference/clibrary/cstdio/fgets/

It returns null when it finds an EOF character. Try running the program above and pressing CTRL+D (or whatever combination is your EOF character), and the loop will exit succesfully.

How do you want to detect the end of the input? Newline? Dot (you said sentence xD)?

How to save user input into a variable in html and js

I mean a prompt script would work if the variable was not needed for the HTML aspect, even then in certain situations, a function could be used.

_x000D_
_x000D_
var save_user_input = prompt('what needs to be saved?');
//^ makes a variable of the prompt's answer
if (save_user_input == null) {
//^ if the answer is null, it is nothing
//however, if it is nothing, it is cancelled (as seen below). If it is "null" it is what the user said, then assigned to the variable(i think), but also null as in nothing in the prompt answer window, but ok pressed. So you cant do an or "null" (which would look like: if (save_user_input == null || "null") {)because (I also don't really know if this is right) the variable is "null". Very confusing
alert("cancelled");
//^ alerts the user the cancel button was pressed. No long explanation this time.
}
//^ is an end for the if (i got stumped as to why it wasn’t working and then realised this. very important to remember.)
else {
alert(save_user_input + " is what you said");
//^ alerts the user the variable and adds the string " is what you said" on the end
}
_x000D_
_x000D_
_x000D_

Setting Curl's Timeout in PHP

There is a quirk with this that might be relevant for some people... From the PHP docs comments.

If you want cURL to timeout in less than one second, you can use CURLOPT_TIMEOUT_MS, although there is a bug/"feature" on "Unix-like systems" that causes libcurl to timeout immediately if the value is < 1000 ms with the error "cURL Error (28): Timeout was reached". The explanation for this behavior is:

"If libcurl is built to use the standard system name resolver, that portion of the transfer will still use full-second resolution for timeouts with a minimum timeout allowed of one second."

What this means to PHP developers is "You can't use this function without testing it first, because you can't tell if libcurl is using the standard system name resolver (but you can be pretty sure it is)"

The problem is that on (Li|U)nix, when libcurl uses the standard name resolver, a SIGALRM is raised during name resolution which libcurl thinks is the timeout alarm.

The solution is to disable signals using CURLOPT_NOSIGNAL. Here's an example script that requests itself causing a 10-second delay so you can test timeouts:

if (!isset($_GET['foo'])) {
    // Client
    $ch = curl_init('http://localhost/test/test_timeout.php?foo=bar');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 200);
    $data = curl_exec($ch);
    $curl_errno = curl_errno($ch);
    $curl_error = curl_error($ch);
    curl_close($ch);

    if ($curl_errno > 0) {
        echo "cURL Error ($curl_errno): $curl_error\n";
    } else {
        echo "Data received: $data\n";
    }
} else {
    // Server
    sleep(10);
    echo "Done.";
}

From http://www.php.net/manual/en/function.curl-setopt.php#104597

if statements matching multiple values

Alternatively, and this would give you more flexibility if testing for values other than 1 or 2 in future, is to use a switch statement

switch(value)
{
case 1:
case 2:
   return true;
default:
   return false
}

How do I set response headers in Flask?

This work for me

from flask import Flask
from flask import Response

app = Flask(__name__)

@app.route("/")
def home():
    return Response(headers={'Access-Control-Allow-Origin':'*'})

if __name__ == "__main__":
    app.run()

Get Windows version in a batch file

Just starting a new cmd-level from the command line gives you directly the version!

C:> cmd

Microsoft Windows [Version 10.0.17130.1233]

(c) 2018 Microsoft Corporation. All rights reserved.

Why does Google prepend while(1); to their JSON responses?

Since the <script> tag is exempted from the Same Origin Policy which is a security necessity in the web world, while(1) when added to the JSON response prevents misuse of it in the <script> tag.

html text input onchange event

When I'm doing something like this I use the onKeyUp event.

<script type="text/javascript">
 function bar() {
      //do stuff
 }
<input type="text" name="foo" onKeyUp="return bar()" />

but if you don't want to use an HTML event you could try to use jQuerys .change() method

$('.target').change(function() {
   //do stuff
});

in this example, the input would have to have a class "target"

if you're going to have multiple text boxes that you want to have done the same thing when their text is changed and you need their data then you could do this:

$('.target').change(function(event) {
   //do stuff with the "event" object as the object that called the method
)};

that way you can use the same code, for multiple text boxes using the same class without having to rewrite any code.

How to get Printer Info in .NET?

This should work.

using System.Drawing.Printing;

...

PrinterSettings ps = new PrinterSettings();
ps.PrinterName = "The printer name"; // Load the appropriate printer's setting

After that, the various properties of PrinterSettings can be read.

Note that ps.isValid() can see if the printer actually exists.

Edit: One additional comment. Microsoft recommends you use a PrintDocument and modify its PrinterSettings rather than creating a PrinterSettings directly.

Checkboxes in web pages – how to make them bigger?

Try this CSS

input[type=checkbox] {width:100px; height:100px;}

How do I view the list of functions a Linux shared library is exporting?

Among other already mentioned tools you can use also readelf (manual). It is similar to objdump but goes more into detail. See this for the difference explanation.

$ readelf -sW /lib/liblzma.so.5 |head -n10

Symbol table '.dynsym' contains 128 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND
     1: 00000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutex_unlock@GLIBC_2.0 (4)
     2: 00000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutex_destroy@GLIBC_2.0 (4)
     3: 00000000     0 NOTYPE  WEAK   DEFAULT  UND _ITM_deregisterTMCloneTable
     4: 00000000     0 FUNC    GLOBAL DEFAULT  UND memmove@GLIBC_2.0 (5)
     5: 00000000     0 FUNC    GLOBAL DEFAULT  UND free@GLIBC_2.0 (5)
     6: 00000000     0 FUNC    GLOBAL DEFAULT  UND memcpy@GLIBC_2.0 (5)

how to display data values on Chart.js

From my experience, once you include the chartjs-plugin-datalabels plugin (make sure to place the <script> tag after the chart.js tag on your page), your charts begin to display values.

If you then choose you can customize it to fit your needs. The customization is clearly documented here but basically, the format is like this hypothetical example:

var myBarChart = new Chart(ctx, {
    type: 'bar',
    data: yourDataObject,
    options: {
        // other options
        plugins: {
            datalabels: {
                anchor :'end',
                align :'top',
                // and if you need to format how the value is displayed...
                formatter: function(value, context) {
                    return GetValueFormatted(value);
                }
            }
        }
    }
});

How to loop through an array of objects in swift

You can try using the simple NSArray in syntax for iterating over the array in swift which makes for shorter code. The following is working for me:

class ModelAttachment {
    var id: String?
    var url: String?
    var thumb: String?
}

var modelAttachementObj = ModelAttachment()
modelAttachementObj.id = "1"
modelAttachementObj.url = "http://www.google.com"
modelAttachementObj.thumb = "thumb"

var imgs: Array<ModelAttachment> = [modelAttachementObj]

for img in imgs  {
    let url = img.url
    NSLog(url!)
}

See docs here

What is __main__.py?

If your script is a directory or ZIP file rather than a single python file, __main__.py will be executed when the "script" is passed as an argument to the python interpreter.

How do I update the GUI from another thread?

Most of the other answers are a little complex for me on this question (I'm new to C#), so I am writing mine:

I have a WPF application and have defined a worker as below:

Issue:

BackgroundWorker workerAllocator;
workerAllocator.DoWork += delegate (object sender1, DoWorkEventArgs e1) {
    // This is my DoWork function.
    // It is given as an anonymous function, instead of a separate DoWork function

    // I need to update a message to textbox (txtLog) from this thread function

    // Want to write below line, to update UI
    txt.Text = "my message"

    // But it fails with:
    //  'System.InvalidOperationException':
    //  "The calling thread cannot access this object because a different thread owns it"
}

Solution:

workerAllocator.DoWork += delegate (object sender1, DoWorkEventArgs e1)
{
    // The below single line works
    txtLog.Dispatcher.BeginInvoke((Action)(() => txtLog.Text = "my message"));
}

I am yet to find out what the above line means, but it works.

For WinForms:

Solution:

txtLog.Invoke((MethodInvoker)delegate
{
    txtLog.Text = "my message";
});

How can I insert vertical blank space into an html document?

While the above answers are probably best for this situation, if you just want to do a one-off and don't want to bother with modifying other files, you can in-line the CSS.

<p style="margin-bottom:3cm;">This is the first question?</p>

Checking if a key exists in a JavaScript object?

The accepted answer refers to Object. Beware using the in operator on Array to find data instead of keys:

("true" in ["true", "false"])
// -> false (Because the keys of the above Array are actually 0 and 1)

To test existing elements in an Array: Best way to find if an item is in a JavaScript array?

Oracle Trigger ORA-04098: trigger is invalid and failed re-validation

in my case, this error is raised due to sequence was not created..

CREATE SEQUENCE  J.SOME_SEQ  MINVALUE 1 MAXVALUE 9999999999999999999999999999 INCREMENT BY 1 START WITH 1 CACHE 20 NOORDER  NOCYCLE ;

wget/curl large file from google drive

Update as of March 2018.

I tried various techniques given in other answers to download my file (6 GB) directly from Google drive to my AWS ec2 instance but none of them work (might be because they are old).

So, for the information of others, here is how I did it successfully:

  1. Right-click on the file you want to download, click share, under link sharing section, select "anyone with this link can edit".
  2. Copy the link. It should be in this format: https://drive.google.com/file/d/FILEIDENTIFIER/view?usp=sharing
  3. Copy the FILEIDENTIFIER portion from the link.
  4. Copy the below script to a file. It uses curl and processes the cookie to automate the downloading of the file.

    #!/bin/bash
    fileid="FILEIDENTIFIER"
    filename="FILENAME"
    curl -c ./cookie -s -L "https://drive.google.com/uc?export=download&id=${fileid}" > /dev/null
    curl -Lb ./cookie "https://drive.google.com/uc?export=download&confirm=`awk '/download/ {print $NF}' ./cookie`&id=${fileid}" -o ${filename}
    
  5. As shown above, paste the FILEIDENTIFIER in the script. Remember to keep the double quotes!

  6. Provide a name for the file in place of FILENAME. Remember to keep the double quotes and also include the extension in FILENAME (for example, myfile.zip).
  7. Now, save the file and make the file executable by running this command in terminal sudo chmod +x download-gdrive.sh.
  8. Run the script using `./download-gdrive.sh".

PS: Here is the Github gist for the above given script: https://gist.github.com/amit-chahar/db49ce64f46367325293e4cce13d2424

phpMyAdmin on MySQL 8.0

As many pointed out in other answers, changing the default authentication plugin of MySQL to native does the trick.

Still, since I can't use the new caching_sha2_password plugin, I'll wait until compatibility is developed to close the topic.

How to POST a JSON object to a JAX-RS service

Jersey makes the process very easy, my service class worked well with JSON, all I had to do is to add the dependencies in the pom.xml

@Path("/customer")
public class CustomerService {

    private static Map<Integer, Customer> customers = new HashMap<Integer, Customer>();

    @POST
    @Path("save")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public SaveResult save(Customer c) {

        customers.put(c.getId(), c);

        SaveResult sr = new SaveResult();
        sr.sucess = true;
        return sr;
    }

    @GET
    @Produces(MediaType.APPLICATION_JSON)
    @Path("{id}")
    public Customer getCustomer(@PathParam("id") int id) {
        Customer c = customers.get(id);
        if (c == null) {
            c = new Customer();
            c.setId(id * 3);
            c.setName("unknow " + id);
        }
        return c;
    }
}

And in the pom.xml

<dependency>
    <groupId>org.glassfish.jersey.containers</groupId>
    <artifactId>jersey-container-servlet</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-json-jackson</artifactId>
    <version>2.7</version>
</dependency>
<dependency>
    <groupId>org.glassfish.jersey.media</groupId>
    <artifactId>jersey-media-moxy</artifactId>
    <version>2.7</version>
</dependency>

In vb.net, how to get the column names from a datatable

This is how to retrieve a Column Name from a DataColumn:

MyDataTable.Columns(1).ColumnName 

To get the name of all DataColumns within your DataTable:

Dim name(DT.Columns.Count) As String
Dim i As Integer = 0
For Each column As DataColumn In DT.Columns
  name(i) = column.ColumnName
  i += 1
Next

References

How do I remove time part from JavaScript date?

Parse that string into a Date object:

var myDate = new Date('10/11/1955 10:40:50 AM');

Then use the usual methods to get the date's day of month (getDate) / month (getMonth) / year (getFullYear).

var noTime = new Date(myDate.getFullYear(), myDate.getMonth(), myDate.getDate());

Why doesn't calling a Python string method do anything unless you assign its output?

This is because strings are immutable in Python.

Which means that X.replace("hello","goodbye") returns a copy of X with replacements made. Because of that you need replace this line:

X.replace("hello", "goodbye")

with this line:

X = X.replace("hello", "goodbye")

More broadly, this is true for all Python string methods that change a string's content "in-place", e.g. replace,strip,translate,lower/upper,join,...

You must assign their output to something if you want to use it and not throw it away, e.g.

X  = X.strip(' \t')
X2 = X.translate(...)
Y  = X.lower()
Z  = X.upper()
A  = X.join(':')
B  = X.capitalize()
C  = X.casefold()

and so on.

Set up DNS based URL forwarding in Amazon Route53

The AWS support pointed a simpler solution. It's basically the same idea proposed by @Vivek M. Chawla, with a more simple implementation.

AWS S3:

  1. Create a Bucket named with your full domain, like aws.example.com
  2. On the bucket properties, select Redirect all requests to another host name and enter your URL: https://myaccount.signin.aws.amazon.com/console/

AWS Route53:

  1. Create a record set type A. Change Alias to Yes. Click on Alias Target field and select the S3 bucket you created in the previous step.

Reference: How to redirect domains using Amazon Web Services

AWS official documentation: Is there a way to redirect a domain to another domain using Amazon Route 53?

Selecting fields from JSON output

Assume you stored that dictionary in a variable called values. To get id in to a variable, do:

idValue = values['criteria'][0]['id']

If that json is in a file, do the following to load it:

import json
jsonFile = open('your_filename.json', 'r')
values = json.load(jsonFile)
jsonFile.close()

If that json is from a URL, do the following to load it:

import urllib, json
f = urllib.urlopen("http://domain/path/jsonPage")
values = json.load(f)
f.close()

To print ALL of the criteria, you could:

for criteria in values['criteria']:
    for key, value in criteria.iteritems():
        print key, 'is:', value
    print ''

Setting DIV width and height in JavaScript

These are several ways to apply style to an element. Try any one of the examples below:

1. document.getElementById('div_register').className = 'wide';
  /* CSS */ .wide{width:500px;}
2. document.getElementById('div_register').setAttribute('class','wide');
3. document.getElementById('div_register').style.width = '500px';

How to create a simple map using JavaScript/JQuery

Just use plain objects:

var map = { key1: "value1", key2: "value2" }
function get(k){
  return map[k];
}

Splitting strings in PHP and get last part

You can do it like this:

$str = "abc-123-xyz-789";
$last = array_pop( explode('-', $str) );
echo $last; //echoes 789

ERROR: Sonar server 'http://localhost:9000' can not be reached

When you allow the 9000 port to firewall on your desired operating System the following error "ERROR: Sonar server 'http://localhost:9000' can not be reached" will remove successfully.In ubuntu it is just like as by typing the following command in terminal "sudo ufw allow 9000/tcp" this error will removed from the Jenkins server by clicking on build now in jenkins.

Replace words in a string - Ruby

You can try using this way :

sentence ["Robert"] = "Roger"

Then the sentence will become :

sentence = "My name is Roger" # Robert is replaced with Roger

How can strings be concatenated?

For cases of appending to end of existing string:

string = "Sec_"
string += "C_type"
print(string)

results in

Sec_C_type

What's the environment variable for the path to the desktop?

KB's answer to use [Environment]::GetFolderPath("Desktop") is obviously the official Windows API for doing this.

However, if you're working interactively at the prompt, or just want something that works on your machine, the tilda (~) character refers to the current user's home folder. So ~/desktop is the user's desktop folder.

Access Controller method from another controller in Laravel 5

First of all, requesting a method of a controller from another controller is EVIL. This will cause many hidden problems in Laravel's life-cycle.

Anyway, there are many solutions for doing that. You can select one of these various ways.

Case 1) If you want to call based on Classes

Way 1) The simple way

But you can't add any parameters or authentication with this way.

app(\App\Http\Controllers\PrintReportContoller::class)->getPrintReport();

Way 2) Divide the controller logic into services.

You can add any parameters and something with this. The best solution for your programming life. You can make Repository instead Service.

class PrintReportService
{
    ...
    public function getPrintReport() {
        return ...
    }
}

class PrintReportController extends Controller
{
    ...
    public function getPrintReport() {
        return (new PrintReportService)->getPrintReport();
    }
}

class SubmitPerformanceController
{
    ...
    public function getSomethingProxy() {
        ...
        $a = (new PrintReportService)->getPrintReport();
        ...
        return ...
    }
}

Case 2) If you want to call based on Routes

Way 1) Use MakesHttpRequests trait that used in Application Unit Testing.

I recommend this if you have special reason for making this proxy, you can use any parameters and custom headers. Also this will be an internal request in laravel. (Fake HTTP Request) You can see more details for the call method in here.

class SubmitPerformanceController extends \App\Http\Controllers\Controller
{
    use \Illuminate\Foundation\Testing\Concerns\MakesHttpRequests;

    protected $baseUrl = null;
    protected $app = null;

    function __construct()
    {
        // Require if you want to use MakesHttpRequests
        $this->baseUrl = request()->getSchemeAndHttpHost();
        $this->app     = app();
    }

    public function getSomethingProxy() {
        ...
        $a = $this->call('GET', '/printer/report')->getContent();
        ...
        return ...
    }
}

However this is not a 'good' solution, too.

Way 2) Use guzzlehttp client

This is the most terrible solution I think. You can use any parameters and custom headers, too. But this would be making an external extra http request. So HTTP Webserver must be running.

$client = new Client([
    'base_uri' => request()->getSchemeAndhttpHost(),
    'headers' => request()->header()
]);
$a = $client->get('/performance/submit')->getBody()->getContents()

Finally I am using Way 1 of Case 2. I need parameters and

How to join two sets in one line without using "|"

You can use union method for sets: set.union(other_set)

Note that it returns a new set i.e it doesn't modify itself.

Insert images to XML file

XML is not a format for storing images, neither binary data. I think it all depends on how you want to use those images. If you are in a web application and would want to read them from there and display them, I would store the URLs. If you need to send them to another web endpoint, I would serialize them, rather than persisting manually in XML. Please explain what is the scenario.

How to efficiently calculate a running standard deviation?

The basic answer is to accumulate the sum of both x (call it 'sum_x1') and x2 (call it 'sum_x2') as you go. The value of the standard deviation is then:

stdev = sqrt((sum_x2 / n) - (mean * mean)) 

where

mean = sum_x / n

This is the sample standard deviation; you get the population standard deviation using 'n' instead of 'n - 1' as the divisor.

You may need to worry about the numerical stability of taking the difference between two large numbers if you are dealing with large samples. Go to the external references in other answers (Wikipedia, etc) for more information.

Loop and get key/value pair for JSON array using jQuery

var obj = $.parseJSON(result);
for (var prop in obj) {
    alert(prop + " is " + obj[prop]);
}

Spring: How to inject a value to static field?

Spring uses dependency injection to populate the specific value when it finds the @Value annotation. However, instead of handing the value to the instance variable, it's handed to the implicit setter instead. This setter then handles the population of our NAME_STATIC value.

    @RestController 
//or if you want to declare some specific use of the properties file then use
//@Configuration
//@PropertySource({"classpath:application-${youeEnvironment}.properties"})
public class PropertyController {

    @Value("${name}")//not necessary
    private String name;//not necessary

    private static String NAME_STATIC;

    @Value("${name}")
    public void setNameStatic(String name){
        PropertyController.NAME_STATIC = name;
    }
}

POST unchecked HTML checkboxes

$('input[type=checkbox]').on("change",function(){
    var target = $(this).parent().find('input[type=hidden]').val();
    if(target == 0)
    {
        target = 1;
    }
    else
    {
        target = 0;
    }
    $(this).parent().find('input[type=hidden]').val(target);
});

<p>
    <input type="checkbox" />
    <input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
    <input type="checkbox" />
    <input type="hidden" name="test_checkbox[]" value="0" />
</p>
<p>
    <input type="checkbox" />
    <input type="hidden" name="test_checkbox[]" value="0" />
</p>

If you leave out the name of the checkbox it doesn't get passed. Only the test_checkbox array.

UnsupportedClassVersionError unsupported major.minor version 51.0 unable to load class

Well presumably it's not using the same version of Java when running it externally. Look through the startup scripts carefully to find where it picks up the version of Java to run. You should also check the startup logs to see whether they indicate which version is running.

Alternatively, unless you need the Java 7 features, you could always change your compiler preferences in Eclipse to target 1.6 instead.

Where is the user's Subversion config file stored on the major operating systems?

@Baxter's is mostly correct but it is missing one important Windows-specific detail.

Subversion's runtime configuration area is stored in the %APPDATA%\Subversion\ directory. The files are config and servers.

However, in addition to text-based configuration files, Subversion clients can use Windows Registry to store the client settings. It makes it possible to modify the settings with PowerShell in a convenient manner, and also distribute these settings to user workstations in Active Directory environment via AD Group Policy. See SVNBook | Configuration and the Windows Registry (you can find examples and a sample *.reg file there).

enter image description here

Right way to write JSON deserializer in Spring or extend it

I've searched a lot and the best way I've found so far is on this article:

Class to serialize

package net.sghill.example;

import net.sghill.example.UserDeserializer
import net.sghill.example.UserSerializer
import org.codehaus.jackson.map.annotate.JsonDeserialize;
import org.codehaus.jackson.map.annotate.JsonSerialize;

@JsonDeserialize(using = UserDeserializer.class)
public class User {
    private ObjectId id;
    private String   username;
    private String   password;

    public User(ObjectId id, String username, String password) {
        this.id = id;
        this.username = username;
        this.password = password;
    }

    public ObjectId getId()       { return id; }
    public String   getUsername() { return username; }
    public String   getPassword() { return password; }
}

Deserializer class

package net.sghill.example;

import net.sghill.example.User;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.ObjectCodec;
import org.codehaus.jackson.map.DeserializationContext;
import org.codehaus.jackson.map.JsonDeserializer;

import java.io.IOException;

public class UserDeserializer extends JsonDeserializer<User> {

    @Override
    public User deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException {
        ObjectCodec oc = jsonParser.getCodec();
        JsonNode node = oc.readTree(jsonParser);
        return new User(null, node.get("username").getTextValue(), node.get("password").getTextValue());
    }
}

Edit: Alternatively you can look at this article which uses new versions of com.fasterxml.jackson.databind.JsonDeserializer.

How can I catch a ctrl-c event?

signal isn't the most reliable way as it differs in implementations. I would recommend using sigaction. Tom's code would now look like this :

#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

void my_handler(int s){
           printf("Caught signal %d\n",s);
           exit(1); 

}

int main(int argc,char** argv)
{

   struct sigaction sigIntHandler;

   sigIntHandler.sa_handler = my_handler;
   sigemptyset(&sigIntHandler.sa_mask);
   sigIntHandler.sa_flags = 0;

   sigaction(SIGINT, &sigIntHandler, NULL);

   pause();

   return 0;    
}

isset() and empty() - what to use

Here are the outputs of isset() and empty() for the 4 possibilities: undeclared, null, false and true.

$a=null;
$b=false;
$c=true;

var_dump(array(isset($z1),isset($a),isset($b),isset($c)),true); //$z1 previously undeclared
var_dump(array(empty($z2),empty($a),empty($b),empty($c)),true); //$z2 previously undeclared

//array(4) { [0]=> bool(false) [1]=> bool(false) [2]=> bool(true) [3]=> bool(true) } 
//array(4) { [0]=> bool(true) [1]=> bool(true) [2]=> bool(true) [3]=> bool(false) } 

You'll notice that all the 'isset' results are opposite of the 'empty' results except for case $b=false. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for by isset and false when tested by 'empty'.

So use isset() when you're concerned about the existence of a variable. And use empty when you're testing for true or false. If the actual type of emptiness matters, use is_null and ===0, ===false, ===''.

Singleton: How should it be used

I use Singletons as an interview test.

When I ask a developer to name some design patterns, if all they can name is Singleton, they're not hired.

Throw keyword in function's signature

Well, while googling about this throw specification, I had a look at this article :- (http://blogs.msdn.com/b/larryosterman/archive/2006/03/22/558390.aspx)

I am reproducing a part of it here also, so that it can be used in future irrespective of the fact that the above link works or not.

   class MyClass
   {
    size_t CalculateFoo()
    {
        :
        :
    };
    size_t MethodThatCannotThrow() throw()
    {
        return 100;
    };
    void ExampleMethod()
    {
        size_t foo, bar;
        try
        {
            foo = CalculateFoo();
            bar = foo * 100;
            MethodThatCannotThrow();
            printf("bar is %d", bar);
        }
        catch (...)
        {
        }
    }
};

When the compiler sees this, with the "throw()" attribute, the compiler can completely optimize the "bar" variable away, because it knows that there is no way for an exception to be thrown from MethodThatCannotThrow(). Without the throw() attribute, the compiler has to create the "bar" variable, because if MethodThatCannotThrow throws an exception, the exception handler may/will depend on the value of the bar variable.

In addition, source code analysis tools like prefast can (and will) use the throw() annotation to improve their error detection capabilities - for example, if you have a try/catch and all the functions you call are marked as throw(), you don't need the try/catch (yes, this has a problem if you later call a function that could throw).

Twitter Bootstrap dropdown menu

It's also possible to customise your bootstrap build by using:

http://twitter.github.com/bootstrap/customize.html

All the plugins are included by default.

string encoding and decoding?

Aside from getting decode and encode backwards, I think part of the answer here is actually don't use the ascii encoding. It's probably not what you want.

To begin with, think of str like you would a plain text file. It's just a bunch of bytes with no encoding actually attached to it. How it's interpreted is up to whatever piece of code is reading it. If you don't know what this paragraph is talking about, go read Joel's The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets right now before you go any further.

Naturally, we're all aware of the mess that created. The answer is to, at least within memory, have a standard encoding for all strings. That's where unicode comes in. I'm having trouble tracking down exactly what encoding Python uses internally for sure, but it doesn't really matter just for this. The point is that you know it's a sequence of bytes that are interpreted a certain way. So you only need to think about the characters themselves, and not the bytes.

The problem is that in practice, you run into both. Some libraries give you a str, and some expect a str. Certainly that makes sense whenever you're streaming a series of bytes (such as to or from disk or over a web request). So you need to be able to translate back and forth.

Enter codecs: it's the translation library between these two data types. You use encode to generate a sequence of bytes (str) from a text string (unicode), and you use decode to get a text string (unicode) from a sequence of bytes (str).

For example:

>>> s = "I look like a string, but I'm actually a sequence of bytes. \xe2\x9d\xa4"
>>> codecs.decode(s, 'utf-8')
u"I look like a string, but I'm actually a sequence of bytes. \u2764"

What happened here? I gave Python a sequence of bytes, and then I told it, "Give me the unicode version of this, given that this sequence of bytes is in 'utf-8'." It did as I asked, and those bytes (a heart character) are now treated as a whole, represented by their Unicode codepoint.

Let's go the other way around:

>>> u = u"I'm a string! Really! \u2764"
>>> codecs.encode(u, 'utf-8')
"I'm a string! Really! \xe2\x9d\xa4"

I gave Python a Unicode string, and I asked it to translate the string into a sequence of bytes using the 'utf-8' encoding. So it did, and now the heart is just a bunch of bytes it can't print as ASCII; so it shows me the hexadecimal instead.

We can work with other encodings, too, of course:

>>> s = "I have a section \xa7"
>>> codecs.decode(s, 'latin1')
u'I have a section \xa7'
>>> codecs.decode(s, 'latin1')[-1] == u'\u00A7'
True

>>> u = u"I have a section \u00a7"
>>> u
u'I have a section \xa7'
>>> codecs.encode(u, 'latin1')
'I have a section \xa7'

('\xa7' is the section character, in both Unicode and Latin-1.)

So for your question, you first need to figure out what encoding your str is in.

  • Did it come from a file? From a web request? From your database? Then the source determines the encoding. Find out the encoding of the source and use that to translate it into a unicode.

    s = [get from external source]
    u = codecs.decode(s, 'utf-8') # Replace utf-8 with the actual input encoding
    
  • Or maybe you're trying to write it out somewhere. What encoding does the destination expect? Use that to translate it into a str. UTF-8 is a good choice for plain text documents; most things can read it.

    u = u'My string'
    s = codecs.encode(u, 'utf-8') # Replace utf-8 with the actual output encoding
    [Write s out somewhere]
    
  • Are you just translating back and forth in memory for interoperability or something? Then just pick an encoding and stick with it; 'utf-8' is probably the best choice for that:

    u = u'My string'
    s = codecs.encode(u, 'utf-8')
    newu = codecs.decode(s, 'utf-8')
    

In modern programming, you probably never want to use the 'ascii' encoding for any of this. It's an extremely small subset of all possible characters, and no system I know of uses it by default or anything.

Python 3 does its best to make this immensely clearer simply by changing the names. In Python 3, str was replaced with bytes, and unicode was replaced with str.

What is the iOS 6 user agent string?

Some more:

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_3 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B329 Safari/8536.25

Mozilla/5.0 (iPhone; CPU iPhone OS 6_1_4 like Mac OS X) AppleWebKit/536.26 (KHTML, like Gecko) Version/6.0 Mobile/10B350 Safari/8536.25

How to dynamically build a JSON object with Python?

You build the object before encoding it to a JSON string:

import json

data = {}
data['key'] = 'value'
json_data = json.dumps(data)

JSON is a serialization format, textual data representing a structure. It is not, itself, that structure.

Change bootstrap navbar collapse breakpoint without using LESS

Finally worked out how to change the collapse width by fiddling with '@grid-float-breakpoint' at http://getbootstrap.com/customize/.

Go to line 2923 in bootstrap.css(also min version) and change @media screen and (min-width: 768px) { to @media screen and (min-width: 1000px) {

So the code will end up being:

@media screen and (min-width: 1000px) {
  .navbar-brand {
    float: left;
    margin-right: 5px;
    margin-left: -15px;
  }
  .navbar-nav {
    float: left;
    margin-top: 0;
    margin-bottom: 0;
  }
  .navbar-nav > li {
    float: left;
  }
  .navbar-nav > li > a {
    border-radius: 0;
  }
  .navbar-nav.pull-right {
    float: right;
    width: auto;
  }
  .navbar-toggle {
    position: relative;
    top: auto;
    left: auto;
    display: none;
  }
  .nav-collapse.collapse {
    display: block !important;
    height: auto !important;
    overflow: visible !important;
  }
}

How to call javascript from a href?

JavaScript code is usually called from the onclick event of a link. For example, you could instead do:

In Head Section of HTML Document

<script type='text/javascript'>
function myFunction(){
//...script code
}
</script>

In Body of HTML Document

<a href="#" id="mylink" onclick="myFunction(); return false">Call JavaScript </a>

Alternatively, you can also attach your function to the link using the links' ID, and HTML DOM or a framework like JQuery.

For example:

In Head Section of HTML Document

<script type='text/javascript'>
document.getElementById("mylink").onclick = function myFunction(){ ...script code};
</script>

In Body of HTML Document

<a href="#" id="mylink">Call JavaScript </a>

How to get year and month from a date - PHP

Probably not the most efficient code, but here it goes:

$dateElements = explode('-', $dateValue);
$year = $dateElements[0];

echo $year;    //2012

switch ($dateElements[1]) {

   case '01'    :  $mo = "January";
                   break;

   case '02'    :  $mo = "February";
                   break;

   case '03'    :  $mo = "March";
                   break;

     .
     .
     .

   case '12'    :  $mo = "December";
                   break;


}

echo $mo;      //January

Full screen background image in an activity

The easiest way:

Step 1: Open AndroidManifest.xml file

You can see the file here!

Step 2: Locate android:theme="@style/AppTheme" >

Step 3: Change to android:theme="@style/Theme.AppCompat.NoActionBar" >

Step 4: Then Add ImageView & Image

Step 4: That's it!

Database Structure for Tree Data Structure

Having a table with a foreign key to itself does make sense to me.

You can then use a common table expression in SQL or the connect by prior statement in Oracle to build your tree.

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

Swift 3 / Alamofire 4.0 (Addendum to the accepted answer)

To append to multipartFormData in Swift 3 / Alamofire 4.0, use the following method of MultipartFormData:

public func append(_ data: Data, withName name: String) { /* ... */ }

And, to convert String to Data, the data(using:) method of String. E.g.,

multipartFormData.append("comment".data(using: .utf8)!, withName: "comment")

How to complete the RUNAS command in one line

The runas command does not allow a password on its command line. This is by design (and also the reason you cannot pipe a password to it as input). Raymond Chen says it nicely:

The RunAs program demands that you type the password manually. Why doesn't it accept a password on the command line?

This was a conscious decision. If it were possible to pass the password on the command line, people would start embedding passwords into batch files and logon scripts, which is laughably insecure.

In other words, the feature is missing to remove the temptation to use the feature insecurely.

How to delete a record by id in Flask-SQLAlchemy

Just want to share another option:

# mark two objects to be deleted
session.delete(obj1)
session.delete(obj2)

# commit (or flush)
session.commit()

http://docs.sqlalchemy.org/en/latest/orm/session_basics.html#deleting

In this example, the following codes shall works fine:

obj = User.query.filter_by(id=123).one()
session.delete(obj)
session.commit()

Oracle SQL query for Date format

if you are using same date format and have select query where date in oracle :

   select count(id) from Table_name where TO_DATE(Column_date)='07-OCT-2015';

To_DATE provided by oracle

Comparing two branches in Git?

git diff branch_1..branch_2

That will produce the diff between the tips of the two branches. If you'd prefer to find the diff from their common ancestor to test, you can use three dots instead of two:

git diff branch_1...branch_2

How do I make Visual Studio pause after executing a console application in debug mode?

It would actually be more effort, but you could just build in VS.Net, run it from the regular command line (cmd.exe), and then attach to the process after it starts running. This is probably not the solution you are looking for however.

How to sort a list of lists by a specific index of the inner list?

multiple criteria can also be implemented through lambda function

sorted_list = sorted(list_to_sort, key=lambda x: (x[1], x[0]))

How can I manually set an Angular form field as invalid?

Adding to Julia Passynkova's answer

To set validation error in component:

formData.form.controls['email'].setErrors({'incorrect': true});

To unset validation error in component:

formData.form.controls['email'].setErrors(null);

Be careful with unsetting the errors using null as this will overwrite all errors. If you want to keep some around you may have to check for the existence of other errors first:

if (isIncorrectOnlyError){
   formData.form.controls['email'].setErrors(null);
}

Using git to get just the latest revision

Use git clone with the --depth option set to 1 to create a shallow clone with a history truncated to the latest commit.

For example:

git clone --depth 1 https://github.com/user/repo.git

To also initialize and update any nested submodules, also pass --recurse-submodules and to clone them shallowly, also pass --shallow-submodules.

For example:

git clone --depth 1 --recurse-submodules --shallow-submodules https://github.com/user/repo.git

Python 2.7: %d, %s, and float()

Try the following:

print "First is: %f" % (first)
print "Second is: %f" % (second)

I am unsure what answer is. But apart from that, this will be:

print "DONE: %f DIVIDED BY %f EQUALS %f, SWEET MATH BRO!" % (first, second, ans)

There's a lot of text on Format String Specifiers. You can google it and get a list of specifiers. One thing I forgot to note:

If you try this:

print "First is: %s" % (first)

It converts the float value in first to a string. So that would work as well.

How to get different colored lines for different plots in a single figure?

Matplot colors your plot with different colors , but incase you wanna put specific colors

    import matplotlib.pyplot as plt
    import numpy as np
            
    x = np.arange(10)
            
    plt.plot(x, x)
    plt.plot(x, 2 * x,color='blue')
    plt.plot(x, 3 * x,color='red')
    plt.plot(x, 4 * x,color='green')
    plt.show()

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

In my case, I tried everything above, nothing worked. I am pretty sure, my database looks like below.

mysql  Ver 14.14 Distrib 5.7.17, for Linux (x86_64) using  EditLine wrapper

Connection id:      12
Current database:   xxx
Current user:       yo@localhost
SSL:            Not in use
Current pager:      stdout
Using outfile:      ''
Using delimiter:    ;
Server version:     5.7.17-0ubuntu0.16.04.1 (Ubuntu)
Protocol version:   10
Connection:     Localhost via UNIX socket
Server characterset:    utf8
Db     characterset:    utf8
Client characterset:    utf8
Conn.  characterset:    utf8
UNIX socket:        /var/run/mysqld/mysqld.sock
Uptime:         42 min 49 sec

Threads: 1  Questions: 372  Slow queries: 0  Opens: 166  Flush tables: 1  Open tables: 30  Queries per second avg: 0.144

so, I look up the column charset in every table

show create table company;

It turns out the column charset is latin. That's why, I can not insert Chinese into database.

 ALTER TABLE company CONVERT TO CHARACTER SET utf8;

That might help you. :)

How to change the interval time on bootstrap carousel?

You can simply use the data-interval attribute of the carousel class.

It's default value is set to data-interval="3000" i.e 3seconds.

All you need to do is set it to your desired requirements.

How to enter command with password for git pull?

I did not find the answer to my question after searching Google & stackoverflow for a while so I would like to share my solution here.

git config --global credential.helper "/bin/bash /git_creds.sh"
echo '#!/bin/bash' > /git_creds.sh
echo "sleep 1" >> /git_creds.sh
echo "echo username=$SERVICE_USER" >> /git_creds.sh
echo "echo password=$SERVICE_PASS" >> /git_creds.sh

# to test it
git clone https://my-scm-provider.com/project.git

I did it for Windows too. Full answer here

Changing text color onclick

Do something like this:

<script>
function changeColor(id)
{
  document.getElementById(id).style.color = "#ff0000"; // forecolor
  document.getElementById(id).style.backgroundColor = "#ff0000"; // backcolor
}
</script>

<div id="myid">Hello There !!</div>

<a href="#" onclick="changeColor('myid'); return false;">Change Color</a>

Get the current cell in Excel VB

Try this

Dim app As Excel.Application = Nothing
Dim Active_Cell As Excel.Range = Nothing

Try
            app = CType(Marshal.GetActiveObject("Excel.Application"), Excel.Application)
 Active_Cell = app.ActiveCell

Catch ex As Exception
            MsgBox(ex.Message)
            Exit Sub
        End Try

'             .address will return the cell reference :)

How to delete specific columns with VBA?

To answer the question How to delete specific columns in vba for excel. I use Array as below.

sub del_col()

dim myarray as variant
dim i as integer

myarray = Array(10, 9, 8)'Descending to Ascending
For i = LBound(myarray) To UBound(myarray)
    ActiveSheet.Columns(myarray(i)).EntireColumn.Delete
Next i

end sub

How to replace url parameter with javascript/jquery?

Here is modified stenix's code, it's not perfect but it handles cases where there is a param in url that contains provided parameter, like:

/search?searchquery=text and 'query' is provided.

In this case searchquery param value is changed.

Code:

function replaceUrlParam(url, paramName, paramValue){
    var pattern = new RegExp('(\\?|\\&)('+paramName+'=).*?(&|$)')
    var newUrl=url
    if(url.search(pattern)>=0){
        newUrl = url.replace(pattern,'$1$2' + paramValue + '$3');
    }
    else{
        newUrl = newUrl + (newUrl.indexOf('?')>0 ? '&' : '?') + paramName + '=' + paramValue
    }
    return newUrl
}

Primitive type 'short' - casting in Java

Java always uses at least 32 bit values for calculations. This is due to the 32-bit architecture which was common 1995 when java was introduced. The register size in the CPU was 32 bit and the arithmetic logic unit accepted 2 numbers of the length of a cpu register. So the cpus were optimized for such values.

This is the reason why all datatypes which support arithmetic opperations and have less than 32-bits are converted to int (32 bit) as soon as you use them for calculations.

So to sum up it mainly was due to performance issues and is kept nowadays for compatibility.

What is the default scope of a method in Java?

The default scope is package-private. All classes in the same package can access the method/field/class. Package-private is stricter than protected and public scopes, but more permissive than private scope.

More information:
http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
http://mindprod.com/jgloss/scope.html

Set CFLAGS and CXXFLAGS options using CMake

The easiest solution working fine for me is this:

export CFLAGS=-ggdb
export CXXFLAGS=-ggdb

CMake will append them to all configurations' flags. Just make sure to clear CMake cache.

pandas three-way joining multiple dataframes on columns

Assumed imports:

import pandas as pd

John Galt's answer is basically a reduce operation. If I have more than a handful of dataframes, I'd put them in a list like this (generated via list comprehensions or loops or whatnot):

dfs = [df0, df1, df2, dfN]

Assuming they have some common column, like name in your example, I'd do the following:

df_final = reduce(lambda left,right: pd.merge(left,right,on='name'), dfs)

That way, your code should work with whatever number of dataframes you want to merge.

Edit August 1, 2016: For those using Python 3: reduce has been moved into functools. So to use this function, you'll first need to import that module:

from functools import reduce

How to set Oracle's Java as the default Java in Ubuntu?

I put the line:

export JAVA_HOME=/usr/lib/jvm/java-7-oracle

in my ~/.bashrc file.

/usr/lib/jvm/java7-oracle should be a symbolic link pointing to /usr/lib/jvm/java-7-oracle-[version number here].

The reason it's a symbolic link is that in case there's a new version of the JVM, you don't need to update your .bashrc file, it should automatically point to the new version.

If you want to set JAVA_HOME environment variables globally and at system level means use should set in /etc/environment file.

Build the full path filename in Python

Um, why not just:

>>>> import os
>>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'

creating charts with angularjs

AngularJS charting plugin along with FusionCharts library to add interactive JavaScript graphs and charts to your web/mobile applications - with just a single directive. Link: http://www.fusioncharts.com/angularjs-charts/#/demos/ex1

cannot connect to pc-name\SQLEXPRESS

try using IP instead of pc name. If the ip working, then it might be the name pipe is not enable. If it;s still not working then the login using windows might be disabled.

What does 'git blame' do?

The git blame command is used to examine the contents of a file line by line and see when each line was last modified and who the author of the modifications was.

If there was a bug in code,use it to identify who cased it,then you can blame him. Git blame is get blame(d).

If you need to know history of one line code,use git log -S"code here", simpler than git blame.

git log vs git blame

How to determine if a list of polygon points are in clockwise order?

An implementation of Sean's answer in JavaScript:

_x000D_
_x000D_
function calcArea(poly) {_x000D_
    if(!poly || poly.length < 3) return null;_x000D_
    let end = poly.length - 1;_x000D_
    let sum = poly[end][0]*poly[0][1] - poly[0][0]*poly[end][1];_x000D_
    for(let i=0; i<end; ++i) {_x000D_
        const n=i+1;_x000D_
        sum += poly[i][0]*poly[n][1] - poly[n][0]*poly[i][1];_x000D_
    }_x000D_
    return sum;_x000D_
}_x000D_
_x000D_
function isClockwise(poly) {_x000D_
    return calcArea(poly) > 0;_x000D_
}_x000D_
_x000D_
let poly = [[352,168],[305,208],[312,256],[366,287],[434,248],[416,186]];_x000D_
_x000D_
console.log(isClockwise(poly));_x000D_
_x000D_
let poly2 = [[618,186],[650,170],[701,179],[716,207],[708,247],[666,259],[637,246],[615,219]];_x000D_
_x000D_
console.log(isClockwise(poly2));
_x000D_
_x000D_
_x000D_

Pretty sure this is right. It seems to be working :-)

Those polygons look like this, if you're wondering:

Open youtube video in Fancybox jquery

Thanx, Alexander!

And to set the fancy-close button above the youtube's flash-content add 'wmode' to 'swf' parameters:

'swf': {'allowfullscreen':'true', 'wmode':'transparent'}

How do I write a RGB color value in JavaScript?

Here's a simple function that creates a CSS color string from RGB values ranging from 0 to 255:

function rgb(r, g, b){
  return "rgb("+r+","+g+","+b+")";
}

Alternatively (to create fewer string objects), you could use array join():

function rgb(r, g, b){
  return ["rgb(",r,",",g,",",b,")"].join("");
}

The above functions will only work properly if (r, g, and b) are integers between 0 and 255. If they are not integers, the color system will treat them as in the range from 0 to 1. To account for non-integer numbers, use the following:

function rgb(r, g, b){
  r = Math.floor(r);
  g = Math.floor(g);
  b = Math.floor(b);
  return ["rgb(",r,",",g,",",b,")"].join("");
}

You could also use ES6 language features:

const rgb = (r, g, b) => 
  `rgb(${Math.floor(r)},${Math.floor(g)},${Math.floor(b)})`;

Connection reset by peer: mod_fcgid: error reading data from FastCGI server

I managed to solved this by adding FcgidBusyTimeout . Just in case if anyone have similar issue with me.

Here is my settings on my apache.conf:

<VirtualHost *:80>
.......
<IfModule mod_fcgid.c>
FcgidBusyTimeout 3600
</IfModule>
</VirtualHost>

Laravel back button

You can use javascript for this provblem. It's retrieve link from browser history.

_x000D_
_x000D_
<script>_x000D_
function goBack() {_x000D_
  window.history.back();_x000D_
}_x000D_
</script>
_x000D_
<button onclick="goBack()">Go Back</button>
_x000D_
_x000D_
_x000D_

How to reset form body in bootstrap modal box?

I went with a slightly modified version of @shibbir's answer:

// Clear form fields in a designated area of a page
$.clearFormFields = function(area) {
  $(area).find('input[type="text"],input[type="email"],textarea,select').val('');
};

Called this way:

$('#my-modal').on('hidden', function(){
  $.clearFormFields(this)
});

What is process.env.PORT in Node.js?

When hosting your application on another service (like Heroku, Nodejitsu, and AWS), your host may independently configure the process.env.PORT variable for you; after all, your script runs in their environment.

Amazon's Elastic Beanstalk does this. If you try to set a static port value like 3000 instead of process.env.PORT || 3000 where 3000 is your static setting, then your application will result in a 500 gateway error because Amazon is configuring the port for you.

This is a minimal Express application that will deploy on Amazon's Elastic Beanstalk:

var express = require('express');
var app = express();

app.get('/', function (req, res) {
  res.send('Hello World!');
});

// use port 3000 unless there exists a preconfigured port
var port = process.env.PORT || 3000;

app.listen(port);

How to change the window title of a MATLAB plotting figure?

First you must create an empty figure with the following command.

figure('name','Title of the window here');

By doing this, the newly created figure becomes you active figure. Immediately after calling a plot() command, it will print your plotting onto this figure. So your window will have a title.

This is the code you must use:

figure('name','Title of the window here');

hold on

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [0; 0.198669; 0.389418; 0.564642; 0.717356; 0.841471; 0.932039; 0.98545; 0.999574; 0.973848; 0.909297; 0.808496; 0.675463; 0.515501; 0.334988; 0.14112; -0.0583741; -0.255541; -0.44252; -0.611858; -0.756802; -0.871576; -0.951602; -0.993691; -0.996165; -0.958924; -0.883455; -0.772764; -0.631267; -0.464602; -0.279415; -0.0830894; 0.116549; 0.311541; 0.494113; 0.656987; 0.793668; 0.898708; 0.96792; 0.998543; 0.989358; 0.940731; 0.854599; 0.734397; 0.584917; 0.412118; 0.22289; 0.0247754; -0.174327; -0.366479; -0.544021; -0.699875; -0.827826; -0.922775; -0.980936; -0.99999; -0.979178; -0.919329; -0.822829; -0.693525; -0.536573; -0.358229; -0.165604; 0.033623; 0.23151; 0.420167; 0.592074; 0.740376; 0.859162; 0.943696; 0.990607; 0.998027; 0.965658; 0.894791; 0.788252; 0.650288; 0.486399; 0.303118; 0.107754; -0.0919069; -0.287903; -0.472422; -0.638107; -0.778352; -0.887567; -0.961397; -0.9969; -0.992659; -0.948844; -0.867202; -0.750987; -0.604833; -0.434566; -0.246974; -0.0495356];
plot(x, y, '--b');

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [-1; -0.980133; -0.921324; -0.825918; -0.697718; -0.541836; -0.364485; -0.172736; 0.0257666; 0.223109; 0.411423; 0.583203; 0.731599; 0.850695; 0.935744; 0.983355; 0.991629; 0.960238; 0.890432; 0.784994; 0.648128; 0.48529; 0.302972; 0.108443; -0.0905427; -0.286052; -0.470289; -0.635911; -0.776314; -0.885901; -0.960303; -0.996554; -0.993208; -0.950399; -0.869833; -0.754723; -0.609658; -0.44042; -0.253757; -0.057111; 0.141679; 0.334688; 0.514221; 0.673121; 0.805052; 0.904756; 0.968256; 0.993023; 0.978068; 0.923987; 0.832937; 0.708548; 0.555778; 0.380717; 0.190346; -0.00774649; -0.205663; -0.395514; -0.56973; -0.721365; -0.844375; -0.933855; -0.986238; -0.999436; -0.972923; -0.907755; -0.806531; -0.673287; -0.513333; -0.333047; -0.139617; 0.0592467; 0.255615; 0.44166; 0.609964; 0.753818; 0.867487; 0.946439; 0.987526; 0.989111; 0.95113; 0.875097; 0.764044; 0.622398; 0.455806; 0.27091; 0.0750802; -0.123876; -0.318026; -0.499631; -0.66145; -0.797032; -0.900972; -0.969126; -0.998776];
plot(x, y, '-r');

hold off

title('My plot title');
xlabel('My x-axis title');
ylabel('My y-axis title');

How to preview a part of a large pandas DataFrame, in iPython notebook?

To see the first n rows of DataFrame:

df.head(n) # (n=5 by default)

To see the last n rows:

df.tail(n) 

How do I enable MSDTC on SQL Server?

Use this for windows Server 2008 r2 and Windows Server 2012 R2

  1. Click Start, click Run, type dcomcnfg and then click OK to open Component Services.

  2. In the console tree, click to expand Component Services, click to expand Computers, click to expand My Computer, click to expand Distributed Transaction Coordinator and then click Local DTC.

  3. Right click Local DTC and click Properties to display the Local DTC Properties dialog box.

  4. Click the Security tab.

  5. Check mark "Network DTC Access" checkbox.

  6. Finally check mark "Allow Inbound" and "Allow Outbound" checkboxes.

  7. Click Apply, OK.

  8. A message will pop up about restarting the service.

  9. Click OK and That's all.

Reference : https://msdn.microsoft.com/en-us/library/dd327979.aspx

Note: Sometimes the network firewall on the Local Computer or the Server could interrupt your connection so make sure you create rules to "Allow Inbound" and "Allow Outbound" connection for C:\Windows\System32\msdtc.exe

How to set Grid row and column positions programmatically

Try this:

                Grid grid = new Grid(); //Define the grid
                for (int i = 0; i < 36; i++) //Add 36 rows
                {
                    ColumnDefinition columna = new ColumnDefinition()
                    {
                        Name = "Col_" + i,
                        Width = new GridLength(32.5),
                    };
                    grid.ColumnDefinitions.Add(columna);
                }

                for (int i = 0; i < 36; i++) //Add 36 columns
                {
                    RowDefinition row = new RowDefinition();
                    row.Height = new GridLength(40, GridUnitType.Pixel);
                    grid.RowDefinitions.Add(row);
                }

                for (int i = 0; i < 36; i++)
                {
                    for (int j = 0; j < 36; j++)
                    {
                        Label t1 = new Label()
                        {
                            FontSize = 10,
                            FontFamily = new FontFamily("consolas"),
                            FontWeight = FontWeights.SemiBold,
                            BorderBrush = Brushes.LightGray,
                            BorderThickness = new Thickness(2),
                            HorizontalContentAlignment = HorizontalAlignment.Center,
                            VerticalContentAlignment = VerticalAlignment.Center,
                        };
                        Grid.SetRow(t1, i);
                        Grid.SetColumn(t1, j);
                        grid.Children.Add(t1); //Add the Label Control to the Grid created
                    }
                }

While loop in batch

A while loop can be simulated in cmd.exe with:

:still_more_files
    if %countfiles% leq 21 (
        rem change countfile here
        goto :still_more_files
    )

For example, the following script:

    @echo off
    setlocal enableextensions enabledelayedexpansion
    set /a "x = 0"

:more_to_process
    if %x% leq 5 (
        echo %x%
        set /a "x = x + 1"
        goto :more_to_process
    )

    endlocal

outputs:

0
1
2
3
4
5

For your particular case, I would start with the following. Your initial description was a little confusing. I'm assuming you want to delete files in that directory until there's 20 or less:

    @echo off
    set backupdir=c:\test

:more_files_to_process
    for /f %%x in ('dir %backupdir% /b ^| find /v /c "::"') do set num=%%x
    if %num% gtr 20 (
        cscript /nologo c:\deletefile.vbs %backupdir%
        goto :more_files_to_process
    )

How can I put strings in an array, split by new line?

That's my way:

$lines = preg_split('/[\r\n]+/', $db_text, NULL, PREG_SPLIT_NO_EMPTY);

This also will skip all empty lines too.

Difference between framework vs Library vs IDE vs API vs SDK vs Toolkits?

An IDE is an integrated development environment - a suped-up text editor with additional support for developing (such as forms designers, resource editors, etc), compiling and debugging applications. e.g Eclipse, Visual Studio.

A Library is a chunk of code that you can call from your own code, to help you do things more quickly/easily. For example, a Bitmap Processing library will provide facilities for loading and manipulating bitmap images, saving you having to write all that code for yourself. Typically a library will only offer one area of functionality (processing images or operating on zip files)

An API (application programming interface) is a term meaning the functions/methods in a library that you can call to ask it to do things for you - the interface to the library.

An SDK (software development kit) is a library or group of libraries (often with extra tool applications, data files and sample code) that aid you in developing code that uses a particular system (e.g. extension code for using features of an operating system (Windows SDK), drawing 3D graphics via a particular system (DirectX SDK), writing add-ins to extend other applications (Office SDK), or writing code to make a device like an Arduino or a mobile phone do what you want). An SDK will still usually have a single focus.

A toolkit is like an SDK - it's a group of tools (and often code libraries) that you can use to make it easier to access a device or system... Though perhaps with more focus on providing tools and applications than on just code libraries.

A framework is a big library or group of libraries that provides many services (rather than perhaps only one focussed ability as most libraries/SDKs do). For example, .NET provides an application framework - it makes it easier to use most (if not all) of the disparate services you need (e.g. Windows, graphics, printing, communications, etc) to write a vast range of applications - so one "library" provides support for pretty much everything you need to do. Often a framework supplies a complete base on which you build your own code, rather than you building an application that consumes library code to do parts of its work.

There are of course many examples in the wild that won't exactly match these descriptions though.

How to get current route

import { Router } from '@angular/router';
constructor(router: Router) { 
      console.log(router.routerState.snapshot.url);
}

laravel collection to array

Use collect($comments_collection).

Else, try json_encode($comments_collection) to convert to json.

C# How to determine if a number is a multiple of another?

bool isMultiple = a % b == 0;

This will be true if a is a multiple of b

php: Get html source code with cURL

I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

In C/C++ what's the simplest way to reverse the order of bits in a byte?

See the bit twiddling hacks for many solutions. Copypasting from there is obviously simple to implement. =)

For example (on a 32-bit CPU):

uint8_t b = byte_to_reverse;
b = ((b * 0x0802LU & 0x22110LU) | (b * 0x8020LU & 0x88440LU)) * 0x10101LU >> 16;

If by “simple to implement” one means something that can be done without a reference in an exam or job interview, then the safest bet is probably the inefficient copying of bits one by one into another variable in reverse order (already shown in other answers).

How to add,set and get Header in request of HttpClient?

You can use HttpPost, there are methods to add Header to the Request.

DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("header-name" , "header-value");

HttpResponse response = httpclient.execute(httpPost);

How to square or raise to a power (elementwise) a 2D numpy array?

The fastest way is to do a*a or a**2 or np.square(a) whereas np.power(a, 2) showed to be considerably slower.

np.power() allows you to use different exponents for each element if instead of 2 you pass another array of exponents. From the comments of @GarethRees I just learned that this function will give you different results than a**2 or a*a, which become important in cases where you have small tolerances.

I've timed some examples using NumPy 1.9.0 MKL 64 bit, and the results are shown below:

In [29]: a = np.random.random((1000, 1000))

In [30]: timeit a*a
100 loops, best of 3: 2.78 ms per loop

In [31]: timeit a**2
100 loops, best of 3: 2.77 ms per loop

In [32]: timeit np.power(a, 2)
10 loops, best of 3: 71.3 ms per loop

Update Multiple Rows in Entity Framework from a list of ids

I have created a library to batch delete or update records with a round trip on EF Core 5.

Sample code as follows:

await ctx.DeleteRangeAsync(b => b.Price > n || b.AuthorName == "zack yang");

await ctx.BatchUpdate()
.Set(b => b.Price, b => b.Price + 3)
.Set(b=>b.AuthorName,b=>b.Title.Substring(3,2)+b.AuthorName.ToUpper())
.Set(b => b.PubTime, b => DateTime.Now)
.Where(b => b.Id > n || b.AuthorName.StartsWith("Zack"))
.ExecuteAsync();

Github repository: https://github.com/yangzhongke/Zack.EFCore.Batch Report: https://www.reddit.com/r/dotnetcore/comments/k1esra/how_to_batch_delete_or_update_in_entity_framework/

Initializing array of structures

It's a designated initializer, introduced with the C99 standard; it allows you to initialize specific members of a struct or union object by name. my_data is obviously a typedef for a struct type that has a member name of type char * or char [N].

Disable Pinch Zoom on Mobile Web

To everyone who said that this is a bad idea I want to say it is not always a bad one. Sometimes it is very boring to have to zoom out to see all the content. For example when you type on an input on iOS it zooms to get it in the center of the screen. You have to zoom out after that cause closing the keyboard does not do the work. Also I agree that when you put many I hours in making a great layout and user experience you don't want it to be messed up by a zoom.

But the other argument is valuable as well for people with vision issues. However In my opinion if you have issues with your eyes you are already using the zooming features of the system so there is no need to disturb the content.

How can I change the font-size of a select option?

try this

http://jsfiddle.net/VggvD/2/

CSS add your code

.select_join option{
    font-size:13px;
}

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

PUT vs. POST in REST

Short Answer:

Simple rule of thumb: Use POST to create, use PUT to update.

Long Answer:

POST:

  • POST is used to send data to server.
  • Useful when the resource's URL is unknown

PUT:

  • PUT is used to transfer state to the server
  • Useful when a resource's URL is known

Longer Answer:

To understand it we need to question why PUT was required, what were the problems PUT was trying to solve that POST couldn't.

From a REST architecture's point of view there is none that matters. We could have lived without PUT as well. But from a client developer's point of view it made his/her life a lot simpler.

Prior to PUT, clients couldn't directly know the URL that the server generated or if all it had generated any or whether the data to be sent to the server is already updated or not. PUT relieved the developer of all these headaches. PUT is idempotent, PUT handles race conditions, and PUT lets the client choose the URL.