Programs & Examples On #Fpc

FPC (Free Pascal Compiler) is a 32/64-bit multi-architecture Object Pascal compiler with both Turbo Pascal, Apple Pascal and Delphi dialects.

Add Header and Footer for PDF using iTextsharp

Easy codes that work successfully:

protected void Page_Load(object sender, EventArgs e)
{
 .
 .       
 using (MemoryStream ms = new MemoryStream())
 {
  .
  .
  iTextSharp.text.Document doc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 36, 36, 54, 54);
  iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(doc, ms);
  writer.PageEvent = new HeaderFooter();
  doc.Open();
  .
  .
  // make your document content..
  .
  .                   
  doc.Close();
  writer.Close();

  // output
  Response.ContentType = "application/pdf;";
  Response.AddHeader("Content-Disposition", "attachment; filename=clientfilename.pdf");
  byte[] pdf = ms.ToArray();
  Response.OutputStream.Write(pdf, 0, pdf.Length);
 }
 .
 .
 .
}
class HeaderFooter : PdfPageEventHelper
{
public override void OnEndPage(PdfWriter writer, Document document)
{

    // Make your table header using PdfPTable and name that tblHeader
    .
    . 
    tblHeader.WriteSelectedRows(0, -1, page.Left + document.LeftMargin, page.Top, writer.DirectContent);
    .
    .
    // Make your table footer using PdfPTable and name that tblFooter
    .
    . 
    tblFooter.WriteSelectedRows(0, -1, page.Left + document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent);
}
}

How to get info on sent PHP curl request

The request is printed in a request.txt with details

$ch = curl_init();
$f = fopen('request.txt', 'w');
curl_setopt_array($ch, array(
CURLOPT_URL            => $url, 
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_FOLLOWLOCATION => 1,
CURLOPT_VERBOSE        => 1,
CURLOPT_STDERR         => $f,
));
$response = curl_exec($ch);
fclose($f);
curl_close($ch);

You can also use curl_getinfo() function.

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

how to set width for PdfPCell in ItextSharp

Why not use a PdfPTable object for this? Create a fixed width table and use a float array to set the widths of the columns

PdfPTable table = new PdfPTable(10);
table.HorizontalAlignment = 0;
table.TotalWidth = 500f;
table.LockedWidth = true;
float[] widths = new float[] { 20f, 60f, 60f, 30f, 50f, 80f, 50f, 50f, 50f, 50f };
table.SetWidths(widths);

addCell(table, "SER.\nNO.", 2);

addCell(table, "TYPE OF SHIPPING", 1);
addCell(table, "ORDER NO.", 1);
addCell(table, "QTY.", 1);
addCell(table, "DISCHARGE PPORT", 1);

addCell(table, "DESCRIPTION OF GOODS", 2);

addCell(table, "LINE DOC. RECL DATE", 1);

addCell(table, "CLEARANCE DATE", 2);
addCell(table, "CUSTOM PERMIT NO.", 2);
addCell(table, "DISPATCH DATE", 2);

addCell(table, "AWB/BL NO.", 1);
addCell(table, "COMPLEX NAME", 1);
addCell(table, "G. W. Kgs.", 1);
addCell(table, "DESTINATION", 1);
addCell(table, "OWNER DOC. RECL DATE", 1);

....

private static void addCell(PdfPTable table, string text, int rowspan)
{
    BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
    iTextSharp.text.Font times = new iTextSharp.text.Font(bfTimes, 6, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);

    PdfPCell cell = new PdfPCell(new Phrase(text, times));
    cell.Rowspan = rowspan;
    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
    cell.VerticalAlignment = PdfPCell.ALIGN_MIDDLE;
    table.AddCell(cell);
}

have a look at this tutorial too...

How do I get row id of a row in sql server

SQL does not do that. The order of the tuples in the table are not ordered by insertion date. A lot of people include a column that stores that date of insertion in order to get around this issue.

Print directly from browser without print popup window

AttendStar created a free add-on that suppresses the print dialog box and removes all headers and footers for most versions of Firefox.

https://addons.mozilla.org/en-US/firefox/addon/attendprint/

With that feature on you can use $('img').jqprint(); and jqprint for jquery will only print that image automatically called from your web application.

How to make FileFilter in java?

Another simple example:

public static void listFilesInDirectory(String pathString) {
  // A local class (a class defined inside a block, here a method).
  class MyFilter implements FileFilter {
    @Override
    public boolean accept(File file) {
      return !file.isHidden() && file.getName().endsWith(".txt");
    }
  }

  File directory = new File(pathString);
  File[] files = directory.listFiles(new MyFilter());

  for (File fileLoop : files) {
    System.out.println(fileLoop.getName());
  }
}

// Call it
listFilesInDirectory("C:\\Users\\John\\Documents\\zTemp");

// Output
Cool.txt
RedditKinsey.txt
...

How does Python's super() work with multiple inheritance?

I understand this doesn't directly answer the super() question, but I feel it's relevant enough to share.

There is also a way to directly call each inherited class:


class First(object):
    def __init__(self):
        print '1'

class Second(object):
    def __init__(self):
        print '2'

class Third(First, Second):
    def __init__(self):
        Second.__init__(self)

Just note that if you do it this way, you'll have to call each manually as I'm pretty sure First's __init__() won't be called.

PHP - add 1 day to date format mm-dd-yyyy

The format you've used is not recognized by strtotime(). Replace

$date = "04-15-2013";

by

$date = "04/15/2013";

Or if you want to use - then use the following line with the year in front:

$date = "2013-04-15";

How to use \n new line in VB msgbox() ...?

msgbox "This is the first line" & vbcrlf & "and this is the second line"

or in .NET msgbox "This is the first line" & Environment.NewLine & "and this is the second line"

How to create a session using JavaScript?

<script type="text/javascript">
function myfunction()
{
    var IDSes= "10200";
    '<%Session["IDDiv"] = "' + $(this).attr('id') + '"; %>'
    '<%Session["IDSes"] = "' + IDSes+ '"; %>';
     alert('<%=Session["IDSes"] %>');
}
</script>

link

How to SHUTDOWN Tomcat in Ubuntu?

For a more graceful way, try the following:

Caveat: I'm running Debian 7, not Ubuntu, though it is a Debian derivative

If you're running Tomcat as a service, you can get a list of all running services by typing:

sudo service --status-all

I'm running Tomcat 7, which is displayed as tomcat7 in said list. Then, to shut it down just type:

sudo service tomcat7 stop

Can regular JavaScript be mixed with jQuery?

Or no JavaScript load function at all...

<html>
<head></head>
<body>
    <canvas id="canvas" width="150" height="150"></canvas>
</body>
<script type="text/javascript">
    var draw = function() {
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect (10, 10, 55, 50);

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
            ctx.fillRect (30, 30, 55, 50);
        }
    }
    draw();

    //or self executing...

    (function(){
        var canvas = document.getElementById("canvas");
        if (canvas.getContext) {
            var ctx = canvas.getContext("2d");

            ctx.fillStyle = "rgb(200,0,0)";
            ctx.fillRect (50, 50, 55, 50);

            ctx.fillStyle = "rgba(0, 0, 200, 0.5)";
            ctx.fillRect (70, 70, 55, 50);
        }
    })();
</script>
</html>

Convert a negative number to a positive one in JavaScript

You can use ~ operator that logically converts the number to negative and adds 1 to the negative:

_x000D_
_x000D_
var x = 3;_x000D_
x = (~x + 1);_x000D_
console.log(x)_x000D_
// result = -3
_x000D_
_x000D_
_x000D_

What is the best way to programmatically detect porn images?

A graduate student from National Cheng Kung University in Taiwan did a research on this subject in 2004. He was able to achieve success rate of 89.79% in detecting nude pictures downloaded from the Internet. Here is the link to his thesis: The Study on Naked People Image Detection Based on Skin Color
It's in Chinese therefore you may need a translator in case you can't read it.

How do I correctly upgrade angular 2 (npm) to the latest version?

If you are looking like me for just updating your project to the latest these is what works form me since Angular 6:

Open the console on your project folder: If you type: ng update then you will get the below message:

        We analyzed your package.json, there are some packages to update:

          Name                               Version                  Command to update
         --------------------------------------------------------------------------------
          @angular/cli                       7.0.7 -> 7.2.2           ng update @angular/cli
          @angular/core                      7.0.4 -> 7.2.1           ng update @angular/core

There might be additional packages that are outdated.
    Run "ng update --all" to try to update all at the same time.

So I usually go straight and do:

ng update --all

Finally you can check your new version:

ng version
Angular CLI: 7.2.2
Node: 8.12.0
OS: win32 x64
Angular: 7.2.1
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.12.2
@angular-devkit/build-angular     0.12.2
@angular-devkit/build-optimizer   0.12.2
@angular-devkit/build-webpack     0.12.2
@angular-devkit/core              7.2.2
@angular-devkit/schematics        7.2.2
@angular/cli                      7.2.2
@ngtools/webpack                  7.2.2
@schematics/angular               7.2.2
@schematics/update                0.12.2
rxjs                              6.3.3
typescript                        3.2.4
webpack                           4.28.4

Error - is not marked as serializable

If you store an object in session state, that object must be serializable.

http://www.hpenterprisesecurity.com/vulncat/en/vulncat/dotnet/asp_dotnet_bad_practices_non_serializable_object_stored_in_session.html


edit:

In order for the session to be serialized correctly, all objects the application stores as session attributes must declare the [Serializable] attribute. Additionally, if the object requires custom serialization methods, it must also implement the ISerializable interface.

https://vulncat.hpefod.com/en/detail?id=desc.structural.dotnet.asp_dotnet_bad_practices_non_serializable_object_stored_in_session#C%23%2fVB.NET%2fASP.NET

MySQL: Fastest way to count number of rows

EXPLAIN SELECT id FROM .... did the trick for me. and I could see the number of rows under rows column of the result.

How to set border's thickness in percentages?

Box Sizing
set the box sizing to border box box-sizing: border-box; and set the width to 100% and a fixed width for the border then add a min-width so for a small screen the border won't overtake the whole screen

How to get the list of properties of a class?

Try this:

var model = new MyObject();
foreach (var property in model.GetType().GetProperties())
{
    var descricao = property;
    var type = property.PropertyType.Name;
}

How to create an on/off switch with Javascript/CSS?

You can achieve this using HTML and CSS and convert a checkbox into a HTML Switch.

HTML

      <div class="switch">
        <input id="cmn-toggle-1" class="cmn-toggle cmn-toggle-round"  type="checkbox">
        <label for="cmn-toggle-1"></label>
      </div>

CSS

input.cmn-toggle-round + label {
  padding: 2px;
  width: 100px;
  height: 30px;
  background-color: #dddddd;
  -webkit-border-radius: 30px;
  -moz-border-radius: 30px;
  -ms-border-radius: 30px;
  -o-border-radius: 30px;
  border-radius: 30px;
}
input.cmn-toggle-round + label:before, input.cmn-toggle-round + label:after {
  display: block;
  position: absolute;
  top: 1px;
  left: 1px;
  bottom: 1px;
  content: "";
}
input.cmn-toggle-round + label:before {
  right: 1px;
  background-color: #f1f1f1;
  -webkit-border-radius: 30px;
  -moz-border-radius: 30px;
  -ms-border-radius: 30px;
  -o-border-radius: 30px;
  border-radius: 30px;
  -webkit-transition: background 0.4s;
  -moz-transition: background 0.4s;
  -o-transition: background 0.4s;
  transition: background 0.4s;
}
input.cmn-toggle-round + label:after {
  width: 40px;
  background-color: #fff;
  -webkit-border-radius: 100%;
  -moz-border-radius: 100%;
  -ms-border-radius: 100%;
  -o-border-radius: 100%;
  border-radius: 100%;
  -webkit-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  -moz-box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.3);
  -webkit-transition: margin 0.4s;
  -moz-transition: margin 0.4s;
  -o-transition: margin 0.4s;
  transition: margin 0.4s;
}
input.cmn-toggle-round:checked + label:before {
  background-color: #8ce196;
}
input.cmn-toggle-round:checked + label:after {
  margin-left: 60px;
}

.cmn-toggle {
  position: absolute;
  margin-left: -9999px;
  visibility: hidden;
}
.cmn-toggle + label {
  display: block;
  position: relative;
  cursor: pointer;
  outline: none;
  -webkit-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  user-select: none;
}

DEMO

What is the difference between BIT and TINYINT in MySQL?

From my experience I'm telling you that BIT has problems on linux OS types(Ubuntu for ex). I developped my db on windows and after I deployed everything on linux, I had problems with queries that inserted or selected from tables that had BIT DATA TYPE.

Bit is not safe for now. I changed to tinyint(1) and worked perfectly. I mean that you only need a value to diferentiate if it's 1 or 0 and tinyint(1) it's ok for that

How to get access token from FB.login method in javascript SDK

You can get access token using FB.getAuthResponse()['accessToken']:

FB.login(function(response) {
   if (response.authResponse) {
     var access_token =   FB.getAuthResponse()['accessToken'];
     console.log('Access Token = '+ access_token);
     FB.api('/me', function(response) {
     console.log('Good to see you, ' + response.name + '.');
     });
   } else {
     console.log('User cancelled login or did not fully authorize.');
   }
 }, {scope: ''});

Edit: Updated to use Oauth 2.0, required since December 2011. Now uses FB.getAuthResponse(); If you are using a browser that does not have a console, (I'm talking to you, Internet Explorer) be sure to comment out the console.log lines or use a log-failsafe script such as:

if (typeof(console) == "undefined") { console = {}; } 
if (typeof(console.log) == "undefined") { console.log = function() { return 0; } }

List of all unique characters in a string?

if the result does not need to be order-preserving, then you can simply use a set

>>> ''.join(set( "aaabcabccd"))
'acbd'
>>>

Write HTML string in JSON

You should escape the forward slash too, here is the correct JSON:

[{
"id": "services.html",
"img": "img/SolutionInnerbananer.jpg",
"html": "<h2class=\"fg-white\">AboutUs<\/h2><pclass=\"fg-white\">developing and supporting complex IT solutions.Touchingmillions of lives world wide by bringing in innovative technology <\/p>"
}]

Change DIV content using ajax, php and jQuery

You could achieve this quite easily with jQuery by registering for the click event of the anchors (with class="movie") and using the .load() method to send an AJAX request and replace the contents of the summary div:

$(function() {
    $('.movie').click(function() {
        $('#summary').load(this.href);

        // it's important to return false from the click
        // handler in order to cancel the default action
        // of the link which is to redirect to the url and
        // execute the AJAX request
        return false;
    });
});

compare two list and return not matching items using linq

Try,

  public class Sent
{
    public int MsgID;
    public string Content;
    public int Status;

}

public class Messages
{
    public int MsgID;
    public string Content;
}

  List<Sent> SentList = new List<Sent>() { new Sent() { MsgID = 1, Content = "aaa", Status = 0 }, new Sent() { MsgID = 3, Content = "ccc", Status = 0 } };
            List<Messages> MsgList = new List<Messages>() { new Messages() { MsgID = 1, Content = "aaa" }, new Messages() { MsgID = 2, Content = "bbb" }, new Messages() { MsgID = 3, Content = "ccc" }, new Messages() { MsgID = 4, Content = "ddd" }, new Messages() { MsgID = 5, Content = "eee" }};

            int [] sentMsgIDs = SentList.Select(v => v.MsgID).ToArray();
            List<Messages> result1 = MsgList.Where(o => !sentMsgIDs.Contains(o.MsgID)).ToList<Messages>();

Hope it should help.

lexical or preprocessor issue file not found occurs while archiving?

Few things to try, Ensure the Framework and all it's headers are imported into your project properly.

Also in your Build Settings set YES to Always search user paths, and make sure your User header paths are pointing to the Framework.

Finally, Build->Clean and Restart Xcode.

Hope this helps !

UPDATE: According to SDWebImage's installation, it's required you make a modification to Header Search Path and not User header paths, As seen below.

enter image description here

Have you done this as well? I suggest slowly, re-doing all the installation steps from the beginning.

Writing a dictionary to a text file?

For list comprehension lovers, this will write all the key : value pairs in new lines in dog.txt

my_dict = {'foo': [1,2], 'bar':[3,4]}

# create list of strings
list_of_strings = [ f'{key} : {my_dict[key]}' for key in my_dict ]

# write string one by one adding newline
with open('dog.txt', 'w') as my_file:
    [ my_file.write(f'{st}\n') for st in list_of_strings ]

How do I display local image in markdown?

I suspect the path is not correct. As mentioned by user7412219 ubuntu and windows deal with path differently. Try to put the image in the same folder as your Notebook and use:

![alt text](Isolated.png "Title")

On windows the desktop should be at: C:\Users\jzhang\Desktop

Loop through files in a folder using VBA?

Dir seems to be very fast.

Sub LoopThroughFiles()
    Dim MyObj As Object, MySource As Object, file As Variant
   file = Dir("c:\testfolder\")
   While (file <> "")
      If InStr(file, "test") > 0 Then
         MsgBox "found " & file
         Exit Sub
      End If
     file = Dir
  Wend
End Sub

Check cell for a specific letter or set of letters

Some options without REGEXMATCH, since you might want to be case insensitive and not want say blast or ablative to trigger a YES. Using comma as the delimiter, as in the OP, and for the moment ignoring the IF condition:

First very similar to @user1598086's answer:

=FIND("bla",A1)

Is case sensitive but returns #VALUE! rather than NO and a number rather than YES (both of which can however be changed to NO/YES respectively).

=SEARCH("bla",A1)  

Case insensitive, so treats Black and black equally. Returns as above.

The former (for the latter equivalent) to indicate whether bla present after the first three characters in A1:

=FIND("bla",A1,4)  

Returns a number for blazer, black but #VALUE! for blazer, blue.

To find Bla only when a complete word on its own (ie between spaces - not at the start or end of a 'sentence'):

=SEARCH(" Bla ",A1) 

Since the return in all cases above is either a number ("found", so YES preferred) or #VALUE! we can use ISERROR to test for #VALUE! within an IF formula, for instance taking the first example above:

 =if(iserror(FIND("bla",A1)),"NO","YES")  

Longer than the regexmatch but the components are easily adjustable.

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

To track down the correct parameters you need to go first to ?plot.default, which refers you to ?par and ?axis:

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=1.5,    #  for the xlab and ylab
           col="green")                   #  for the points

ExecuteReader: Connection property has not been initialized

After SqlCommand cmd=new SqlCommand ("insert into time(project,iteration)values('.... Add

cmd.Connection = conn;

Hope this help

Conversion failed when converting the varchar value to data type int in sql

The problem located on the following line

SELECT  @Prefix + LEN(CAST(@maxCode AS VARCHAR(10))+1) + CAST(@maxCode AS VARCHAR(100))

Use this instead

SELECT  @Prefix + CAST(LEN(CAST(@maxCode AS VARCHAR(10))+1) AS VARCHAR(100)) + CAST(@maxCode AS VARCHAR(100))

Full Code:

CREATE PROC [dbo].[getVoucherNo]

AS

BEGIN

    DECLARE @Prefix VARCHAR(10)='J'

    DECLARE @startFrom INT=1

    DECLARE @maxCode VARCHAR(100)

    DECLARE @sCode INT

    IF((SELECT COUNT(*) FROM dbo.Journal_Entry) > 0)
    BEGIN
        SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(VoucharNo,LEN(@startFrom)+1,LEN(VoucharNo)- LEN(@Prefix)) AS INT))+1 AS varchar(100)) FROM dbo.Journal_Entry;
        SET @sCode=CAST(@maxCode AS INT)
        SELECT  @Prefix + CAST(LEN(CAST(@maxCode AS VARCHAR(10))+1) AS VARCHAR(100)) + CAST(@maxCode AS VARCHAR(100))
    END
    ELSE
    BEGIN
        SELECT(@Prefix + CAST(@startFrom AS VARCHAR)) 
    END
END

GSON throwing "Expected BEGIN_OBJECT but was BEGIN_ARRAY"?

public ChannelSearchEnum[] getChannelSearchEnum(Response response) {
        return response.as(ChannelSearchEnum[].class, ObjectMapperType.GSON);
}

Above will solve and passing response will returned mapped object array of the class

How do I specify local .gem files in my Gemfile?

You can force bundler to use the gems you deploy using "bundle package" and "bundle install --local"

On your development machine:

bundle install

(Installs required gems and makes Gemfile.lock)

bundle package

(Caches the gems in vendor/cache)

On the server:

bundle install --local

(--local means "use the gems from vendor/cache")

How to delete rows from a pandas DataFrame based on a conditional expression

You can assign the DataFrame to a filtered version of itself:

df = df[df.score > 50]

This is faster than drop:

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test[test.x < 0]
# 54.5 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test.drop(test[test.x > 0].index, inplace=True)
# 201 ms ± 17.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test.drop(test[test.x > 0].index)
# 194 ms ± 7.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

WPF chart controls

Visifire supports wide range of 2D and 3D charts with zooming and panning functionality.

Visifire Line chart with zooming

Full Disclosure: I have been involved in the development of Visifire.

Python/Json:Expecting property name enclosed in double quotes

This:

{
    'http://example.org/about': {
        'http://purl.org/dc/terms/title': [
            {'type': 'literal', 'value': "Anna's Homepage"}
        ]
     }
}

is not JSON.
This:

{
     "http://example.org/about": {
         "http://purl.org/dc/terms/title": [
             {"type": "literal", "value": "Anna's Homepage"}
          ]
      }
}

is JSON.

EDIT:
Some commenters suggested that the above is not enough.
JSON specification - RFC7159 states that a string begins and ends with quotation mark. That is ".
Single quoute ' has no semantic meaning in JSON and is allowed only inside a string.

Print multiple arguments in Python

In Python 3.6, f-string is much cleaner.

In earlier version:

print("Total score for %s is %s. " % (name, score))

In Python 3.6:

print(f'Total score for {name} is {score}.')

will do.

It is more efficient and elegant.

How to do associative array/hashing in JavaScript

Use JavaScript objects as associative arrays.

Associative Array: In simple words associative arrays use Strings instead of Integer numbers as index.

Create an object with

var dictionary = {};

JavaScript allows you to add properties to objects by using the following syntax:

Object.yourProperty = value;

An alternate syntax for the same is:

Object["yourProperty"] = value;

If you can, also create key-to-value object maps with the following syntax:

var point = { x:3, y:2 };

point["x"] // returns 3
point.y // returns 2

You can iterate through an associative array using the for..in loop construct as follows

for(var key in Object.keys(dict)){
  var value = dict[key];
  /* use key/value for intended purpose */
}

How to define an enum with string value?

For people arriving here looking for an answer to a more generic question, you can extend the static class concept if you want your code to look like an enum.

The following approach works when you haven't finalised the enum names you want and the enum values are the string representation of the enam name; use nameof() to make your refactoring simpler.

public static class Colours
{
    public static string Red => nameof(Red);
    public static string Green => nameof(Green);
    public static string Blue => nameof(Blue);
}

This achieves the intention of an enum that has string values (such as the following pseudocode):

public enum Colours
{
    "Red",
    "Green",
    "Blue"
}

Changing case in Vim

See the following methods:

 ~    : Changes the case of current character

 guu  : Change current line from upper to lower.

 gUU  : Change current LINE from lower to upper.

 guw  : Change to end of current WORD from upper to lower.

 guaw : Change all of current WORD to lower.

 gUw  : Change to end of current WORD from lower to upper.

 gUaw : Change all of current WORD to upper.

 g~~  : Invert case to entire line

 g~w  : Invert case to current WORD

 guG : Change to lowercase until the end of document.

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

Console output in a Qt GUI app?

First of all you can try flushing the buffer

std::cout << "Hello, world!"<<std::endl;

For more Qt based logging you can try using qDebug.

Run a shell script with an html button

As stated by Luke you need to use a server side language, like php. This is a really simple php example:

<?php
if ($_GET['run']) {
  # This code will run if ?run=true is set.
  exec("/path/to/name.sh");
}
?>

<!-- This link will add ?run=true to your URL, myfilename.php?run=true -->
<a href="?run=true">Click Me!</a>

Save this as myfilename.php and place it on a machine with a web server with php installed. The same thing can be accomplished with asp, java, ruby, python, ...

How to insert Records in Database using C# language?

You should change your code to make use of SqlParameters and adapt your insert statement to the following

string connetionString = "Data Source=UMAIR;Initial Catalog=Air; Trusted_Connection=True;" ;
// [ ] required as your fields contain spaces!!
string insStmt = "insert into Main ([First Name], [Last Name]) values (@firstName,@lastName)";

using (SqlConnection cnn = new SqlConnection(connetionString))
{
    cnn.Open();
    SqlCommand insCmd = new SqlCommand(insStmt, cnn);
    // use sqlParameters to prevent sql injection!
    insCmd.Parameters.AddWithValue("@firstName", textbox2.Text);
    insCmd.Parameters.AddWithValue("@lastName", textbox3.Text);
    int affectedRows = insCmd.ExecuteNonQuery();
    MessageBox.Show (affectedRows + " rows inserted!");
}

TCP: can two different sockets share a port?

No. It is not possible to share the same port at a particular instant. But you can make your application such a way that it will make the port access at different instant.

Is there a way to view past mysql queries with phpmyadmin?

you can run your past mysql with run /PATH_PAST_MYSQL/bin/mysqld.exe

it run your last mysql and you can see it in phpmyadmin and other section of your system.

notice: stop your current mysql version.

S F My English.

How to avoid "cannot load such file -- utils/popen" from homebrew on OSX

This issue should be fixed in the newest version of Homebrew. Try reinstalling it, which is described on the Homebrew home page.

Single controller with multiple GET methods in ASP.NET Web API

With the newer Web Api 2 it has become easier to have multiple get methods.

If the parameter passed to the GET methods are different enough for the attribute routing system to distinguish their types as is the case with ints and Guids you can specify the expected type in the [Route...] attribute

For example -

[RoutePrefix("api/values")]
public class ValuesController : ApiController
{

    // GET api/values/7
    [Route("{id:int}")]
    public string Get(int id)
    {
       return $"You entered an int - {id}";
    }

    // GET api/values/AAC1FB7B-978B-4C39-A90D-271A031BFE5D
    [Route("{id:Guid}")]
    public string Get(Guid id)
    {
       return $"You entered a GUID - {id}";
    }
} 

For more details about this approach, see here http://nodogmablog.bryanhogan.net/2017/02/web-api-2-controller-with-multiple-get-methods-part-2/

Another options is to give the GET methods different routes.

    [RoutePrefix("api/values")]
    public class ValuesController : ApiController
    {
        public string Get()
        {
            return "simple get";
        }

        [Route("geta")]
        public string GetA()
        {
            return "A";
        }

        [Route("getb")]
        public string GetB()
        {
            return "B";
        }
   }

See here for more details - http://nodogmablog.bryanhogan.net/2016/10/web-api-2-controller-with-multiple-get-methods/

Get checkbox list values with jQuery

You can try this...

$(document).ready(function() {
        $("button").click(function(){
            var checkBoxValues = [];
            $.each($("input[name='check_name']:checked"), function(){
                checkBoxValues.push($(this).val());
            });

            console.log(checkBoxValues);

        });
    });

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

For react-native-firebase, adding this to app/build.gradle dependencies section made it work for me:

implementation('com.squareup.okhttp3:okhttp:3.12.1') { force = true }
implementation('com.squareup.okio:okio:1.15.0') { force = true }
implementation('com.google.code.findbugs:jsr305:3.0.2') { force = true}

error: (-215) !empty() in function detectMultiScale

Please do not copy paste the content of xml file, because once you paste it to notepad it will be saved a s text file. So directly download the file from the given source.

iPhone - Grand Central Dispatch main thread

Async means asynchronous and you should use that most of the time. You should never call sync on main thread cause it will lock up your UI until the task is completed. You Here is a better way to do this in Swift:

runThisInMainThread { () -> Void in
    // Run your code like this:
    self.doStuff()
}

func runThisInMainThread(block: dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), block)
}

Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions

Java: getMinutes and getHours

int hr=Time.valueOf(LocalTime.now()).getHours();
int minutes=Time.valueOf(LocalTime.now()).getMinutes();

These functions will return int values in hours and minutes.

What's the difference between eval, exec, and compile?

  1. exec is not an expression: a statement in Python 2.x, and a function in Python 3.x. It compiles and immediately evaluates a statement or set of statement contained in a string. Example:

     exec('print(5)')           # prints 5.
     # exec 'print 5'     if you use Python 2.x, nor the exec neither the print is a function there
     exec('print(5)\nprint(6)')  # prints 5{newline}6.
     exec('if True: print(6)')  # prints 6.
     exec('5')                 # does nothing and returns nothing.
    
  2. eval is a built-in function (not a statement), which evaluates an expression and returns the value that expression produces. Example:

     x = eval('5')              # x <- 5
     x = eval('%d + 6' % x)     # x <- 11
     x = eval('abs(%d)' % -100) # x <- 100
     x = eval('x = 5')          # INVALID; assignment is not an expression.
     x = eval('if 1: x = 4')    # INVALID; if is a statement, not an expression.
    
  3. compile is a lower level version of exec and eval. It does not execute or evaluate your statements or expressions, but returns a code object that can do it. The modes are as follows:

  4. compile(string, '', 'eval') returns the code object that would have been executed had you done eval(string). Note that you cannot use statements in this mode; only a (single) expression is valid.

  5. compile(string, '', 'exec') returns the code object that would have been executed had you done exec(string). You can use any number of statements here.

  6. compile(string, '', 'single') is like the exec mode but expects exactly one expression/statement, eg compile('a=1 if 1 else 3', 'myf', mode='single')

How to disable copy/paste from/to EditText

For smartphone with clipboard, is possible prevent like this.

editText.setFilters(new InputFilter[]{new InputFilter() {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            if (source.length() > 1) {
                return "";
            }  return null;
        }
    }});

What is the JavaScript equivalent of var_dump or print_r in PHP?

I put this forward to help anyone needing something readily practical for giving you a nice, prettified (indented) picture of a JS Node. None of the other solutions worked for me for a Node ("cyclical error" or whatever...). This walks you through the tree under the DOM Node (without using recursion) and gives you the depth, tagName (if applicable) and textContent (if applicable).

Any other details from the nodes you encounter as you walk the tree under the head node can be added as per your interest...

function printRNode( node ){
    // make sort of human-readable picture of the node... a bit like PHP print_r

    if( node === undefined || node === null ){
        throwError( 'node was ' + typeof node );
    }
    let s = '';

    // NB walkDOM could be made into a utility function which you could 
    // call with one or more callback functions as parameters...

    function walkDOM( headNode ){
      const stack = [ headNode ];
      const depthCountDowns = [ 1 ];
      while (stack.length > 0) {
        const node = stack.pop();
        const depth = depthCountDowns.length - 1;
        // TODO non-text, non-BR nodes could show more details (attributes, properties, etc.)
        const stringRep = node.nodeType === 3? 'TEXT: |' + node.nodeValue + '|' : 'tag: ' + node.tagName;
        s += '  '.repeat( depth ) + stringRep + '\n';
        const lastIndex = depthCountDowns.length - 1;
        depthCountDowns[ lastIndex ] = depthCountDowns[ lastIndex ] - 1;
        if( node.childNodes.length ){
            depthCountDowns.push( node.childNodes.length );
            stack.push( ... Array.from( node.childNodes ).reverse() );
        }
        while( depthCountDowns[ depthCountDowns.length - 1 ] === 0 ){
            depthCountDowns.splice( -1 );
        }
      }
    } 
    walkDOM( node );
    return s;
}

How to get JSON response from http.Get

The results from json.Unmarshal (into var data interface{}) do not directly match your Go type and variable declarations. For example,

package main

import (
    "encoding/json"
    "fmt"
    "io/ioutil"
    "net/http"
    "os"
)

type Tracks struct {
    Toptracks []Toptracks_info
}

type Toptracks_info struct {
    Track []Track_info
    Attr  []Attr_info
}

type Track_info struct {
    Name       string
    Duration   string
    Listeners  string
    Mbid       string
    Url        string
    Streamable []Streamable_info
    Artist     []Artist_info
    Attr       []Track_attr_info
}

type Attr_info struct {
    Country    string
    Page       string
    PerPage    string
    TotalPages string
    Total      string
}

type Streamable_info struct {
    Text      string
    Fulltrack string
}

type Artist_info struct {
    Name string
    Mbid string
    Url  string
}

type Track_attr_info struct {
    Rank string
}

func get_content() {
    // json data
    url := "http://ws.audioscrobbler.com/2.0/?method=geo.gettoptracks&api_key=c1572082105bd40d247836b5c1819623&format=json&country=Netherlands"
    url += "&limit=1" // limit data for testing
    res, err := http.Get(url)
    if err != nil {
        panic(err.Error())
    }
    body, err := ioutil.ReadAll(res.Body)
    if err != nil {
        panic(err.Error())
    }
    var data interface{} // TopTracks
    err = json.Unmarshal(body, &data)
    if err != nil {
        panic(err.Error())
    }
    fmt.Printf("Results: %v\n", data)
    os.Exit(0)
}

func main() {
    get_content()
}

Output:

Results: map[toptracks:map[track:map[name:Get Lucky (feat. Pharrell Williams) listeners:1863 url:http://www.last.fm/music/Daft+Punk/_/Get+Lucky+(feat.+Pharrell+Williams) artist:map[name:Daft Punk mbid:056e4f3e-d505-4dad-8ec1-d04f521cbb56 url:http://www.last.fm/music/Daft+Punk] image:[map[#text:http://userserve-ak.last.fm/serve/34s/88137413.png size:small] map[#text:http://userserve-ak.last.fm/serve/64s/88137413.png size:medium] map[#text:http://userserve-ak.last.fm/serve/126/88137413.png size:large] map[#text:http://userserve-ak.last.fm/serve/300x300/88137413.png size:extralarge]] @attr:map[rank:1] duration:369 mbid: streamable:map[#text:1 fulltrack:0]] @attr:map[country:Netherlands page:1 perPage:1 totalPages:500 total:500]]]

Automated Python to Java translation

Actually, this may or may not be much help but you could write a script which created a Java class for each Python class, including method stubs, placing the Python implementation of the method inside the Javadoc

In fact, this is probably pretty easy to knock up in Python.

I worked for a company which undertook a port to Java of a huge Smalltalk (similar-ish to Python) system and this is exactly what they did. Filling in the methods was manual but invaluable, because it got you to really think about what was going on. I doubt that a brute-force method would result in nice code.

Here's another possibility: can you convert your Python to Jython more easily? Jython is just Python for the JVM. It may be possible to use a Java decompiler (e.g. JAD) to then convert the bytecode back into Java code (or you may just wish to run on a JVM). I'm not sure about this however, perhaps someone else would have a better idea.

How do I calculate someone's age based on a DateTime type birthday?

With fewer conversions and UtcNow, this code can take care of someone born on the Feb 29 in a leap year:

public int GetAge(DateTime DateOfBirth)
{
    var Now = DateTime.UtcNow;
    return Now.Year - DateOfBirth.Year -
        (
            (
                Now.Month > DateOfBirth.Month ||
                (Now.Month == DateOfBirth.Month && Now.Day >= DateOfBirth.Day)
            ) ? 0 : 1
        );
}

How do servlets work? Instantiation, sessions, shared variables and multithreading

The Servlet Specification JSR-315 clearly defines the web container behavior in the service (and doGet, doPost, doPut etc.) methods (2.3.3.1 Multithreading Issues, Page 9):

A servlet container may send concurrent requests through the service method of the servlet. To handle the requests, the Servlet Developer must make adequate provisions for concurrent processing with multiple threads in the service method.

Although it is not recommended, an alternative for the Developer is to implement the SingleThreadModel interface which requires the container to guarantee that there is only one request thread at a time in the service method. A servlet container may satisfy this requirement by serializing requests on a servlet, or by maintaining a pool of servlet instances. If the servlet is part of a Web application that has been marked as distributable, the container may maintain a pool of servlet instances in each JVM that the application is distributed across.

For servlets not implementing the SingleThreadModel interface, if the service method (or methods such as doGet or doPost which are dispatched to the service method of the HttpServlet abstract class) has been defined with the synchronized keyword, the servlet container cannot use the instance pool approach, but must serialize requests through it. It is strongly recommended that Developers not synchronize the service method (or methods dispatched to it) in these circumstances because of detrimental effects on performance

How to get the <td> in HTML tables to fit content, and let a specific <td> fill in the rest

Define width of .absorbing-column

Set table-layout to auto and define an extreme width on .absorbing-column.

Here I have set the width to 100% because it ensures that this column will take the maximum amount of space allowed, while the columns with no defined width will reduce to fit their content and no further.

This is one of the quirky benefits of how tables behave. The table-layout: auto algorithm is mathematically forgiving.

You may even choose to define a min-width on all td elements to prevent them from becoming too narrow and the table will behave nicely.

_x000D_
_x000D_
table {_x000D_
    table-layout: auto;_x000D_
    border-collapse: collapse;_x000D_
    width: 100%;_x000D_
}_x000D_
table td {_x000D_
    border: 1px solid #ccc;_x000D_
}_x000D_
table .absorbing-column {_x000D_
    width: 100%;_x000D_
}
_x000D_
<table>_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th>Column A</th>_x000D_
      <th>Column B</th>_x000D_
      <th>Column C</th>_x000D_
      <th class="absorbing-column">Column D</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <td>Data A.1 lorem</td>_x000D_
      <td>Data B.1 ip</td>_x000D_
      <td>Data C.1 sum l</td>_x000D_
      <td>Data D.1</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.2 ipsum</td>_x000D_
      <td>Data B.2 lorem</td>_x000D_
      <td>Data C.2 some data</td>_x000D_
      <td>Data D.2 a long line of text that is long</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>Data A.3</td>_x000D_
      <td>Data B.3</td>_x000D_
      <td>Data C.3</td>_x000D_
      <td>Data D.3</td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

vertical & horizontal lines in matplotlib

This may be a common problem for new users of Matplotlib to draw vertical and horizontal lines. In order to understand this problem, you should be aware that different coordinate systems exist in Matplotlib.

The method axhline and axvline are used to draw lines at the axes coordinate. In this coordinate system, coordinate for the bottom left point is (0,0), while the coordinate for the top right point is (1,1), regardless of the data range of your plot. Both the parameter xmin and xmax are in the range [0,1].

On the other hand, method hlines and vlines are used to draw lines at the data coordinate. The range for xmin and xmax are the in the range of data limit of x axis.

Let's take a concrete example,

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 5, 100)
y = np.sin(x)

fig, ax = plt.subplots()

ax.plot(x, y)
ax.axhline(y=0.5, xmin=0.0, xmax=1.0, color='r')
ax.hlines(y=0.6, xmin=0.0, xmax=1.0, color='b')

plt.show()

It will produce the following plot: enter image description here

The value for xmin and xmax are the same for the axhline and hlines method. But the length of produced line is different.

Browse for a directory in C#

string folderPath = "";
FolderBrowserDialog folderBrowserDialog1 = new FolderBrowserDialog();
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK) {
    folderPath = folderBrowserDialog1.SelectedPath ;
}

When maven says "resolution will not be reattempted until the update interval of MyRepo has elapsed", where is that interval specified?

To finally answer the title question: It is (a client side setting) in (project, profile or settings)

[plugin]?[r|R]epository/[releases|snapshots]/updatePolicy

... tag.

The (currently, maven: 3.6.0, but I suppose "far backwards" compatible) possible values are :

/**
 * Never update locally cached data.
 */
public static final String UPDATE_POLICY_NEVER = "never";
/**
 * Always update locally cached data.
 */
public static final String UPDATE_POLICY_ALWAYS = "always";
/**
 * Update locally cached data once a day.
 */
public static final String UPDATE_POLICY_DAILY = "daily";
/**
 * Update locally cached data **every X minutes** as given by "interval:X".
 */
public static final String UPDATE_POLICY_INTERVAL = "interval";

The current (maven 3.6.0) evaluation of this tag is implemented as follows:

public boolean isUpdatedRequired( RepositorySystemSession session, long lastModified, String policy )
{
    boolean checkForUpdates;
    if ( policy == null )
    {
        policy = "";
    }
    if ( RepositoryPolicy.UPDATE_POLICY_ALWAYS.equals( policy ) )
    {
        checkForUpdates = true;
    }
    else if ( RepositoryPolicy.UPDATE_POLICY_DAILY.equals( policy ) )
    {
        Calendar cal = Calendar.getInstance();
        cal.set( Calendar.HOUR_OF_DAY, 0 );
        cal.set( Calendar.MINUTE, 0 );
        cal.set( Calendar.SECOND, 0 );
        cal.set( Calendar.MILLISECOND, 0 );
        checkForUpdates = cal.getTimeInMillis() > lastModified;
    }
    else if ( policy.startsWith( RepositoryPolicy.UPDATE_POLICY_INTERVAL ) )
    {
        int minutes = getMinutes( policy );
        Calendar cal = Calendar.getInstance();
        cal.add( Calendar.MINUTE, -minutes );
        checkForUpdates = cal.getTimeInMillis() > lastModified;
    }
    else
    {
        // assume "never"
        checkForUpdates = false;
        if ( !RepositoryPolicy.UPDATE_POLICY_NEVER.equals( policy ) )
        {
            LOGGER.warn( "Unknown repository update policy '{}', assuming '{}'",
                    policy, RepositoryPolicy.UPDATE_POLICY_NEVER );
        }
    }
    return checkForUpdates;
}

..with:

private int getMinutes( String policy )
{
    int minutes;
    try
    {
        String s = policy.substring( RepositoryPolicy.UPDATE_POLICY_INTERVAL.length() + 1 );
        minutes = Integer.valueOf( s );
    }
    catch ( RuntimeException e )
    {
        minutes = 24 * 60;
        LOGGER.warn( "Non-parseable repository update policy '{}', assuming '{}:1440'",
                policy, RepositoryPolicy.UPDATE_POLICY_INTERVAL );
    }
    return minutes;
}

...where lastModified is the (local file) "modified timestamp" of an/each underlying artifact.


In particular for the interval:x setting:

  • the colon : is not that strict - any "non-empty" character could do it (=, , ...).
  • negative values x < 0 should yield to "never".
  • interval:0 I would assume a "minutely" (0-59 secs. or above...) interval.
  • number format exceptions result in 24 * 60 minutes (~"daily").

..see: DefaultUpdatePolicyAnalyzer, DefaultMetadataResolver#resolveMetadata() and RepositoryPolicy

How can I output UTF-8 from Perl?

You can use the open pragma.

For eg. below sets STDOUT, STDIN & STDERR to use UTF-8....

use open qw/:std :utf8/;

how to solve Error cannot add duplicate collection entry of type add with unique key attribute 'value' in iis 7

The ideal scenario is to have <add value="default.aspx" /> in config so the application can be deployed to any server without having to reconfigure. IMHO I think the implementation within IIS is poor.

We've used the following to make our default document setup more robust and as a result more SEO friendly by using canonical URL's:

<configuration>
  <system.webServer>
    <defaultDocument>
      <files>
        <remove value="default.aspx" />
        <add value="default.aspx" />
      </files>
    </defaultDocument>
  </system.webServer>
</configuration>

Works OK for us.

Is there any option to limit mongodb memory usage?

This can be done with cgroups, by combining knowledge from these two articles: https://www.percona.com/blog/2015/07/01/using-cgroups-to-limit-mysql-and-mongodb-memory-usage/
http://frank2.net/cgroups-ubuntu-14-04/

You can find here a small shell script which will create config and init files for Ubuntu 14.04: http://brainsuckerna.blogspot.com.by/2016/05/limiting-mongodb-memory-usage-with.html

Just like that:

sudo bash -c 'curl -o- http://brains.by/misc/mongodb_memory_limit_ubuntu1404.sh | bash'

Enabling refreshing for specific html elements only

Try this:

_x000D_
_x000D_
function reload(){_x000D_
    var container = document.getElementById("yourDiv");_x000D_
    var content = container.innerHTML;_x000D_
    container.innerHTML= content; _x000D_
    _x000D_
   //this line is to watch the result in console , you can remove it later _x000D_
    console.log("Refreshed"); _x000D_
}
_x000D_
<a href="javascript: reload()">Click to Reload</a>_x000D_
    <div id="yourDiv">The content that you want to refresh/reload</div>
_x000D_
_x000D_
_x000D_

Hope it works. Let me know

Closing Excel Application using VBA

In my case, I needed to close just one excel window and not the entire application, so, I needed to tell which exact window to close, without saving it.

The following lines work just fine:

Sub test_t()
  Windows("yourfilename.xlsx").Activate
  ActiveWorkbook.Close SaveChanges:=False
End Sub

R numbers from 1 to 100

If you need the construct for a quick example to play with, use the : operator.

But if you are creating a vector/range of numbers dynamically, then use seq() instead.

Let's say you are creating the vector/range of numbers from a to b with a:b, and you expect it to be an increasing series. Then, if b is evaluated to be less than a, you will get a decreasing sequence but you will never be notified about it, and your program will continue to execute with the wrong kind of input.

In this case, if you use seq(), you can set the sign of the by argument to match the direction of your sequence, and an error will be raised if they do not match. For example,

seq(a, b, -1)

will raise an error for a=2, b=6, because the coder expected a decreasing sequence.

How to efficiently calculate a running standard deviation?

n=int(raw_input("Enter no. of terms:"))

L=[]

for i in range (1,n+1):

    x=float(raw_input("Enter term:"))

    L.append(x)

sum=0

for i in range(n):

    sum=sum+L[i]

avg=sum/n

sumdev=0

for j in range(n):

    sumdev=sumdev+(L[j]-avg)**2

dev=(sumdev/n)**0.5

print "Standard deviation is", dev

Check/Uncheck all the checkboxes in a table

All CheckBox Checked

$("input[type=checkbox]").prop('checked', true);

AngularJs: Reload page

window object is made available through $window service for easier testing and mocking, you can go with something like:

$scope.reloadPage = function(){$window.location.reload();}

And :

<a ng-click="reloadPage"  class="navbar-brand" title="home"  data-translate>PORTAL_NAME</a>

As a side note, i don't think $route.reload() actually reloads the page, but only the route.

angularjs: allows only numbers to be typed into a text box

This is the method that works for me. It's based in samnau anwser but allows to submit the form with ENTER, increase and decrease the number with UP and DOWN arrows, edition with DEL,BACKSPACE,LEFT and RIGHT, and navigate trough fields with TAB. Note that it works for positive integers such as an amount.

HTML:

<input ng-keypress="onlyNumbers($event)" min="0" type="number" step="1" ng-pattern="/^[0-9]{1,8}$/" ng-model="... >

ANGULARJS:

$scope.onlyNumbers = function(event){   
    var keys={
        'up': 38,'right':39,'down':40,'left':37,
        'escape':27,'backspace':8,'tab':9,'enter':13,'del':46,
        '0':48,'1':49,'2':50,'3':51,'4':52,'5':53,'6':54,'7':55,'8':56,'9':57
    };
    for(var index in keys) {
        if (!keys.hasOwnProperty(index)) continue;
        if (event.charCode==keys[index]||event.keyCode==keys[index]) {
            return; //default event
        }
    }   
    event.preventDefault();
};

Pass arguments to Constructor in VBA

When you export a class module and open the file in Notepad, you'll notice, near the top, a bunch of hidden attributes (the VBE doesn't display them, and doesn't expose functionality to tweak most of them either). One of them is VB_PredeclaredId:

Attribute VB_PredeclaredId = False

Set it to True, save, and re-import the module into your VBA project.

Classes with a PredeclaredId have a "global instance" that you get for free - exactly like UserForm modules (export a user form, you'll see its predeclaredId attribute is set to true).

A lot of people just happily use the predeclared instance to store state. That's wrong - it's like storing instance state in a static class!

Instead, you leverage that default instance to implement your factory method:

[Employee class]

'@PredeclaredId
Option Explicit

Private Type TEmployee
    Name As String
    Age As Integer
End Type

Private this As TEmployee

Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As Employee
    With New Employee
        .Name = emplName
        .Age = emplAge
        Set Create = .Self 'returns the newly created instance
    End With
End Function

Public Property Get Self() As Employee
    Set Self = Me
End Property

Public Property Get Name() As String
    Name = this.Name
End Property

Public Property Let Name(ByVal value As String)
    this.Name = value
End Property

Public Property Get Age() As String
    Age = this.Age
End Property

Public Property Let Age(ByVal value As String)
    this.Age = value
End Property

With that, you can do this:

Dim empl As Employee
Set empl = Employee.Create("Johnny", 69)

Employee.Create is working off the default instance, i.e. it's considered a member of the type, and invoked from the default instance only.

Problem is, this is also perfectly legal:

Dim emplFactory As New Employee
Dim empl As Employee
Set empl = emplFactory.Create("Johnny", 69)

And that sucks, because now you have a confusing API. You could use '@Description annotations / VB_Description attributes to document usage, but without Rubberduck there's nothing in the editor that shows you that information at the call sites.

Besides, the Property Let members are accessible, so your Employee instance is mutable:

empl.Name = "Jane" ' Johnny no more!

The trick is to make your class implement an interface that only exposes what needs to be exposed:

[IEmployee class]

Option Explicit

Public Property Get Name() As String : End Property
Public Property Get Age() As Integer : End Property

And now you make Employee implement IEmployee - the final class might look like this:

[Employee class]

'@PredeclaredId
Option Explicit
Implements IEmployee

Private Type TEmployee
    Name As String
    Age As Integer
End Type

Private this As TEmployee

Public Function Create(ByVal emplName As String, ByVal emplAge As Integer) As IEmployee
    With New Employee
        .Name = emplName
        .Age = emplAge
        Set Create = .Self 'returns the newly created instance
    End With
End Function

Public Property Get Self() As IEmployee
    Set Self = Me
End Property

Public Property Get Name() As String
    Name = this.Name
End Property

Public Property Let Name(ByVal value As String)
    this.Name = value
End Property

Public Property Get Age() As String
    Age = this.Age
End Property

Public Property Let Age(ByVal value As String)
    this.Age = value
End Property

Private Property Get IEmployee_Name() As String
    IEmployee_Name = Name
End Property

Private Property Get IEmployee_Age() As Integer
    IEmployee_Age = Age
End Property

Notice the Create method now returns the interface, and the interface doesn't expose the Property Let members? Now calling code can look like this:

Dim empl As IEmployee
Set empl = Employee.Create("Immutable", 42)

And since the client code is written against the interface, the only members empl exposes are the members defined by the IEmployee interface, which means it doesn't see the Create method, nor the Self getter, nor any of the Property Let mutators: so instead of working with the "concrete" Employee class, the rest of the code can work with the "abstract" IEmployee interface, and enjoy an immutable, polymorphic object.

Update my gradle dependencies in eclipse

I tried all above options but was still getting error, in my case issue was I have not setup gradle installation directory in eclipse, following worked:

eclipse -> Window -> Preferences -> Gradle -> "Select Local Installation Directory"

Click on Browse button and provide path.

Even though question is answered, thought to share in case somebody else is facing similar issue.

Cheers !

Node.js Error: connect ECONNREFUSED

You're trying to connect to localhost:8080 ... is any service running on your localhost and on this port? If not, the connection is refused which cause this error. I would suggest to check if there is anything running on localhost:8080 first.

How to launch an Activity from another Application in Android

Here is my example of launching bar/QR code scanner from my app if someone finds it useful

Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.setPackage("com.google.zxing.client.android");

try 
{
    startActivityForResult(intent, SCAN_REQUEST_CODE);
} 
catch (ActivityNotFoundException e) 
{
    //implement prompt dialog asking user to download the package
    AlertDialog.Builder downloadDialog = new AlertDialog.Builder(this);
    downloadDialog.setTitle(stringTitle);
    downloadDialog.setMessage(stringMessage);
    downloadDialog.setPositiveButton("yes",
            new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialogInterface, int i) 
                {
                    Uri uri = Uri.parse("market://search?q=pname:com.google.zxing.client.android");
                    Intent intent = new Intent(Intent.ACTION_VIEW, uri);
                    try
                    {
                        myActivity.this.startActivity(intent);
                    }
                    catch (ActivityNotFoundException e)
                    {
                        Dialogs.this.showAlert("ERROR", "Google Play Market not found!");
                    }
                }
            });
    downloadDialog.setNegativeButton("no",
            new DialogInterface.OnClickListener() 
            {
                public void onClick(DialogInterface dialog, int i) 
                {
                    dialog.dismiss();
                }
            });
    downloadDialog.show();
}

500 internal server error at GetResponse()

Finally I get rid of internal server error message with the following code. Not sure if there is another way to achieve it.


string uri = "Path.asmx";
string soap = "soap xml string";

HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uri);
request.Headers.Add("SOAPAction", "\"http://xxxxxx"");
request.ContentType = "text/xml;charset=\"utf-8\"";
request.Accept = "text/xml";
request.Method = "POST";

using (Stream stm = request.GetRequestStream())
{
    using (StreamWriter stmw = new StreamWriter(stm))
    {
        stmw.Write(soap);
    }
}

using (WebResponse webResponse = request.GetResponse())
{
}

Creating a JSON response using Django and Python

Most of these answers are out of date. JsonResponse is not recommended because it escapes the characters, which is usually undesired. Here's what I use:

views.py (returns HTML)

from django.shortcuts import render
from django.core import serializers

def your_view(request):
    data = serializers.serialize('json', YourModel.objects.all())
    context = {"data":data}
    return render(request, "your_view.html", context)

views.py (returns JSON)

from django.core import serializers
from django.http import HttpResponse

def your_view(request):
    data = serializers.serialize('json', YourModel.objects.all())
    return HttpResponse(data, content_type='application/json')

Bonus for Vue Users

If you want to bring your Django Queryset into Vue, you can do the following.

template.html

<div id="dataJson" style="display:none">
{{ data }}
</div>

<script>
let dataParsed = JSON.parse(document.getElementById('dataJson').textContent);
var app = new Vue({
  el: '#app',
  data: {
    yourVariable: dataParsed,
  },
})
</script>

jQuery validation plugin: accept only alphabetical characters?

If you include the additional methods file, here's the current file for 1.7: http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js

You can use the lettersonly rule :) The additional methods are part of the zip you download, you can always find the latest here.

Here's an example:

$("form").validate({
  rules: {
    myField: { lettersonly: true }
  }
});

It's worth noting, each additional method is independent, you can include that specific one, just place this before your .validate() call:

jQuery.validator.addMethod("lettersonly", function(value, element) {
  return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please"); 

Java image resize, maintain aspect ratio

try this

float rateX =  (float)jpDisplayImagen.getWidth()/(float)img.getWidth();
float rateY = (float)jpDisplayImagen.getHeight()/(float)img.getHeight();
if (rateX>rateY){
    int W=(int)(img.getWidth()*rateY);
    int H=(int)(img.getHeight()*rateY);
    jpDisplayImagen.getGraphics().drawImage(img, 0, 0,W,H, null);
}
else{
    int W=(int)(img.getWidth()*rateX);
    int H=(int)(img.getHeight()*rateX);
    jpDisplayImagen.getGraphics().drawImage(img, 0, 0,W,H, null);
}

How to check if a socket is connected/disconnected in C#?

I made an extension method based on this MSDN article. This is how you can determine whether a socket is still connected.

public static bool IsConnected(this Socket client)
{
    bool blockingState = client.Blocking;

    try
    {
        byte[] tmp = new byte[1];

        client.Blocking = false;
        client.Send(tmp, 0, 0);
        return true;
    }
    catch (SocketException e)
    {
        // 10035 == WSAEWOULDBLOCK
        if (e.NativeErrorCode.Equals(10035))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    finally
    {
        client.Blocking = blockingState;
    }
}

How do I delete everything below row X in VBA/Excel?

Any Reference to 'Row' should use 'long' not 'integer' else it will overflow if the spreadsheet has a lot of data.

How to extract one column of a csv file

I think the easiest is using csvkit:

Gets the 2nd column: csvcut -c 2 file.csv

However, there's also csvtool, and probably a number of other csv bash tools out there:

sudo apt-get install csvtool (for Debian-based systems)

This would return a column with the first row having 'ID' in it. csvtool namedcol ID csv_file.csv

This would return the fourth row: csvtool col 4 csv_file.csv

If you want to drop the header row:

csvtool col 4 csv_file.csv | sed '1d'

Bizarre Error in Chrome Developer Console - Failed to load resource: net::ERR_CACHE_MISS

Check for the presence of words like "ad", "banner" or "popup" within your file. I removed these and it worked. Based on this post here: Failed to load resource under Chrome it seems like Ad Block Plus was the culprit in my case.

Find if listA contains any elements not in listB

You can do it in a single line

var res = listA.Where(n => !listB.Contains(n));

This is not the fastest way to do it: in case listB is relatively long, this should be faster:

var setB = new HashSet(listB);
var res = listA.Where(n => !setB.Contains(n));

glob exclude pattern

If the position of the character isn't important, that is for example to exclude manifests files (wherever it is found _) with glob and re - regular expression operations, you can use:

import glob
import re
for file in glob.glob('*.txt'):
    if re.match(r'.*\_.*', file):
        continue
    else:
        print(file)

Or with in a more elegant way - list comprehension

filtered = [f for f in glob.glob('*.txt') if not re.match(r'.*\_.*', f)]

for mach in filtered:
    print(mach)

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Adding gem 'certified', '~> 1.0' to my Gemfile and running bundle solved this issue for me.

What is a Question Mark "?" and Colon ":" Operator Used for?

This is the ternary conditional operator, which can be used anywhere, not just the print statement. It's sometimes just called "the ternary operator", but it's not the only ternary operator, just the most common one.

Here's a good example from Wikipedia demonstrating how it works:

A traditional if-else construct in C, Java and JavaScript is written:

if (a > b) {
    result = x;
} else {
    result = y;
}

This can be rewritten as the following statement:

result = a > b ? x : y;

Basically it takes the form:

boolean statement ? true result : false result;

So if the boolean statement is true, you get the first part, and if it's false you get the second one.

Try these if that still doesn't make sense:

System.out.println(true ? "true!" : "false.");
System.out.println(false ? "true!" : "false.");

convert xml to java object using jaxb (unmarshal)

Tests

On the Tests class we will add an @XmlRootElement annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData property differs from the default mapping we will use the @XmlElement annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted

package forum11221136;

import javax.xml.bind.annotation.*;

@XmlRootElement
public class Tests {

    TestData testData;

    @XmlElement(name="test-data")
    public TestData getTestData() {
        return testData;
    }

    public void setTestData(TestData testData) {
        this.testData = testData;
    }

}

TestData

On this class I used the @XmlType annotation to specify the order in which the elements should be ordered in. I added a testData property that appeared to be missing. I also used an @XmlElement annotation for the same reason as in the Tests class.

package forum11221136;

import java.util.List;
import javax.xml.bind.annotation.*;

@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
    String title;
    String book;
    String count;
    List<TestData> testData;

    public String getTitle() {
        return title;
    }
    public void setTitle(String title) {
        this.title = title;
    }
    public String getBook() {
        return book;
    }
    public void setBook(String book) {
        this.book = book;
    }
    public String getCount() {
        return count;
    }
    public void setCount(String count) {
        this.count = count;
    }
    @XmlElement(name="test-data")
    public List<TestData> getTestData() {
        return testData;
    }
    public void setTestData(List<TestData> testData) {
        this.testData = testData;
    }
}

Demo

Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.

package forum11221136;

import java.io.File;
import javax.xml.bind.*;

public class Demo {

    public static void main(String[] args) throws Exception {
        JAXBContext jc = JAXBContext.newInstance(Tests.class);

        Unmarshaller unmarshaller = jc.createUnmarshaller();
        File xml = new File("src/forum11221136/input.xml");
        Tests tests = (Tests) unmarshaller.unmarshal(xml);

        Marshaller marshaller = jc.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(tests, System.out);
    }

}

TextView bold via xml file?

Example:

use: android:textStyle="bold"

 <TextView
    android:id="@+id/txtVelocidade"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/txtlatitude"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="34dp"
    android:textStyle="bold"
    android:text="Aguardando GPS"
    android:textAppearance="?android:attr/textAppearanceLarge" />

Set color of TextView span in Android

If you want more control, you might want to check the TextPaint class. Here is how to use it:

final ClickableSpan clickableSpan = new ClickableSpan() {
    @Override
    public void onClick(final View textView) {
        //Your onClick code here
    }

    @Override
    public void updateDrawState(final TextPaint textPaint) {
        textPaint.setColor(yourContext.getResources().getColor(R.color.orange));
        textPaint.setUnderlineText(true);
    }
};

How do you right-justify text in an HTML textbox?

Using inline styles:

<input type="text" style="text-align: right"/>

or, put it in a style sheet, like so:

<style>
   .rightJustified {
        text-align: right;
    }
</style>

and reference the class:

<input type="text" class="rightJustified"/>

Using Cygwin to Compile a C program; Execution error

You might be better off editing a file inside of cygwin shell. Normally it has default user directory when you start it up. You can edit a file from the shell doing something like "vi somefile.c" or "emacs somefile.c". That's assuming vi or emacs are installed in cygwin.

If you want to file on your desktop, you'll have to go to a path similar (on XP) to "/cygwindrive/c/Documents\ and\ Settings/Frank/Desktop" (If memory serves correctly). Just cd to that path, and run your command on the file.

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

With Python 3.8 this workes for me. For instance to execute a python script within the venv:

    import subprocess
    import sys
    res = subprocess.run([
              sys.executable,            # venv3.8/bin/python
              'main.py', '--help',], 
            stdout=PIPE, 
            text=True)
    print(res.stdout)

Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.

As an complement to Stefan Steiger answer: (as it doesn't look nice as a comment)

Extending String prototype:

String.prototype.b64encode = function() { 
    return btoa(unescape(encodeURIComponent(this))); 
};
String.prototype.b64decode = function() { 
    return decodeURIComponent(escape(atob(this))); 
};

Usage:

var str = "äöüÄÖÜçéèñ";
var encoded = str.b64encode();
console.log( encoded.b64decode() );

NOTE:

As stated in the comments, using unescape is not recommended as it may be removed in the future:

Warning: Although unescape() is not strictly deprecated (as in "removed from the Web standards"), it is defined in Annex B of the ECMA-262 standard, whose introduction states: … All of the language features and behaviours specified in this annex have one or more undesirable characteristics and in the absence of legacy usage would be removed from this specification.

Note: Do not use unescape to decode URIs, use decodeURI or decodeURIComponent instead.

nvarchar(max) still being truncated

Print truncates the varchar(MAX) to 8000, nvarchar(MAX) to 4000 chars.

But;

PRINT CAST(@query AS NTEXT)

will print the whole query.

How to find all positions of the maximum value in a list?

>>> m = max(a)
>>> [i for i, j in enumerate(a) if j == m]
[9, 12]

Get a list of all threads currently running in Java

In Groovy you can call private methods

// Get a snapshot of the list of all threads 
Thread[] threads = Thread.getThreads()

In Java, you can invoke that method using reflection provided that security manager allows it.

MySQL CONCAT returns NULL if any field contain NULL

you can use if statement like below

select CONCAT(if(affiliate_name is null ,'',affiliate_name),'- ',if(model is null ,'',affiliate_name)) as model from devices

javascript return true or return false when and how to use it?

returning true or false indicates that whether execution should continue or stop right there. So just an example

<input type="button" onclick="return func();" />

Now if func() is defined like this

function func()
{
 // do something
return false;
}

the click event will never get executed. On the contrary if return true is written then the click event will always be executed.

Sorting arrays in NumPy by column

Here is another solution considering all columns (more compact way of J.J's answer);

ar=np.array([[0, 0, 0, 1],
             [1, 0, 1, 0],
             [0, 1, 0, 0],
             [1, 0, 0, 1],
             [0, 0, 1, 0],
             [1, 1, 0, 0]])

Sort with lexsort,

ar[np.lexsort(([ar[:, i] for i in range(ar.shape[1]-1, -1, -1)]))]

Output:

array([[0, 0, 0, 1],
       [0, 0, 1, 0],
       [0, 1, 0, 0],
       [1, 0, 0, 1],
       [1, 0, 1, 0],
       [1, 1, 0, 0]])

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

How to determine if a string is a number with C++?

I'd suggest a regex approach. A full regex-match (for example, using boost::regex) with

-?[0-9]+([\.][0-9]+)?

would show whether the string is a number or not. This includes positive and negative numbers, integer as well as decimal.

Other variations:

[0-9]+([\.][0-9]+)?

(only positive)

-?[0-9]+

(only integer)

[0-9]+

(only positive integer)

EC2 instance has no public DNS

Go to VPC console, select your VPC, and click ACTIONS menu, select Edit DNS Hostnames - select Yes. That should fix it.

What's the difference between display:inline-flex and display:flex?

display: inline-flex does not make flex items display inline. It makes the flex container display inline. That is the only difference between display: inline-flex and display: flex. A similar comparison can be made between display: inline-block and display: block, and pretty much any other display type that has an inline counterpart.1

There is absolutely no difference in the effect on flex items; flex layout is identical whether the flex container is block-level or inline-level. In particular, the flex items themselves always behave like block-level boxes (although they do have some properties of inline-blocks). You cannot display flex items inline; otherwise you don't actually have a flex layout.

It is not clear what exactly you mean by "vertically align" or why exactly you want to display the contents inline, but I suspect that flexbox is not the right tool for whatever you are trying to accomplish. Chances are what you're looking for is just plain old inline layout (display: inline and/or display: inline-block), for which flexbox is not a replacement; flexbox is not the universal layout solution that everyone claims it is (I'm stating this because the misconception is probably why you're considering flexbox in the first place).


1 The differences between block layout and inline layout are outside the scope of this question, but the one that stands out the most is auto width: block-level boxes stretch horizontally to fill their containing block, whereas inline-level boxes shrink to fit their contents. In fact, it is for this reason alone you will almost never use display: inline-flex unless you have a very good reason to display your flex container inline.

eclipse won't start - no java virtual machine was found

My solution is Include JDK's "bin" Directory in the PATH

To edit the PATH environment variable in Windows 7/8/10:

  1. Launch "Control Panel" ? (Optional) System and Security ? System ? Click "Advanced system settings" on the left pane.
  2. Switch to "Advanced" tab ? Push "Environment Variables" button. Under "System Variables" (the bottom pane), scroll down to select "Path" ? Click "Edit...".
  3. Copy the JDK bin directory from JAVA folder and paste to "Edit..."

Getting "conflicting types for function" in C, why?

You have to declare the function before you use it. If the function name appears before its declaration, C compiler will follow certain rules and makes the declaration itself. If it is wrong, you will get that error.

You have two options: (1) define it before you use it, or (2) use forward declaration without implementation. For example:

char *do_something(char *dest, const char *src);

Note the semicolon at the end.

Use Awk to extract substring

You just want to set the field separator as . using the -F option and print the first field:

$ echo aaa0.bbb.ccc | awk -F'.' '{print $1}'
aaa0

Same thing but using cut:

$ echo aaa0.bbb.ccc | cut -d'.' -f1
aaa0

Or with sed:

$ echo aaa0.bbb.ccc | sed 's/[.].*//'
aaa0

Even grep:

$ echo aaa0.bbb.ccc | grep -o '^[^.]*'
aaa0

getCurrentPosition() and watchPosition() are deprecated on insecure origins

You could use the https://ipinfo.io API for this (it's my service). It's free for up to 1,000 req/day (with or without SSL support). It gives you coordinates, name and more. Here's an example:

curl ipinfo.io
{
  "ip": "172.56.39.47",
  "hostname": "No Hostname",
  "city": "Oakland",
  "region": "California",
  "country": "US",
  "loc": "37.7350,-122.2088",
  "org": "AS21928 T-Mobile USA, Inc.",
  "postal": "94621"
}

Here's an example which constructs a coords object with the API response that matches what you get from getCurrentPosition():

$.getJSON('https://ipinfo.io/geo', function(response) { 
    var loc = response.loc.split(',');
    var coords = {
        latitude: loc[0],
        longitude: loc[1]
    };
});

And here's a detailed example that shows how you can use it as a fallback for getCurrentPosition():

function do_something(coords) {
    // Do something with the coords here
}

navigator.geolocation.getCurrentPosition(function(position) { 
    do_something(position.coords);
    },
    function(failure) {
        $.getJSON('https://ipinfo.io/geo', function(response) { 
        var loc = response.loc.split(',');
        var coords = {
            latitude: loc[0],
            longitude: loc[1]
        };
        do_something(coords);
        });  
    };
});

See http://ipinfo.io/developers/replacing-navigator-geolocation-getcurrentposition for more details.

Eclipse can't find / load main class

I read so many blogs and tried so many tricks but my problem not resolved. I was able to run the code but not able to generate the jar file. :( Sad..

But I tried something which might be very silly but worked for me and bought eclipse on trace. What I did was.. Just deleted the main method from the class. Saved it. Did undo to bring the main class back. Tada... Issue resolved... Just one think would like to say, keep your eclipse in "Build Autometically" mode.

What is the best way to implement "remember me" for a website?

Store their UserId and a RememberMeToken. When they login with remember me checked generate a new RememberMeToken (which invalidate any other machines which are marked are remember me).

When they return look them up by the remember me token and make sure the UserId matches.

Pip error: Microsoft Visual C++ 14.0 is required

As an alternative to installing Visual C++, there is a way by installing an additional package in Conda (this option doesn't require admin rights). This worked for me:

conda install libpython m2w64-toolchain -c msys2

Which variable size to use (db, dw, dd) with x86 assembly?

Quick review,

  • DB - Define Byte. 8 bits
  • DW - Define Word. Generally 2 bytes on a typical x86 32-bit system
  • DD - Define double word. Generally 4 bytes on a typical x86 32-bit system

From x86 assembly tutorial,

The pop instruction removes the 4-byte data element from the top of the hardware-supported stack into the specified operand (i.e. register or memory location). It first moves the 4 bytes located at memory location [SP] into the specified register or memory location, and then increments SP by 4.

Your num is 1 byte. Try declaring it with DD so that it becomes 4 bytes and matches with pop semantics.

How to analyse the heap dump using jmap in java

If you use Eclipse as your IDE I would recommend the excellent eclipse plugin memory analyzer

Another option is to use JVisualVM, it can read (and create) heap dumps as well, and is shipped with every JDK. You can find it in the bin directory of your JDK.

Remove ListView items in Android

int count = adapter.getCount();
for (int i = 0; i < count; i++) {
 adapter.remove(adapter.getItem(i));
}

then call notifyDataSetChanged();

How to create folder with PHP code?

Purely basic folder creation

<?php mkdir("testing"); ?> <= this, actually creates a folder called "testing".



Basic file creation

<?php
$file = fopen("test.txt","w");
echo fwrite($file,"Hello World. Testing!");
fclose($file);
?>

Use the a or a+ switch to add/append to file.



EDIT:

This version will create a file and folder at the same time and show it on screen after.

<?php

// change the name below for the folder you want
$dir = "new_folder_name";

$file_to_write = 'test.txt';
$content_to_write = "The content";

if( is_dir($dir) === false )
{
    mkdir($dir);
}

$file = fopen($dir . '/' . $file_to_write,"w");

// a different way to write content into
// fwrite($file,"Hello World.");

fwrite($file, $content_to_write);

// closes the file
fclose($file);

// this will show the created file from the created folder on screen
include $dir . '/' . $file_to_write;

?>

How do I kill all the processes in Mysql "show processlist"?

login to Mysql as admin:

 mysql -uroot -ppassword;

And than run command:

mysql> show processlist;

You will get something like below :

+----+-------------+--------------------+----------+---------+------+-------+------------------+
| Id | User        | Host               | db       | Command | Time | State | Info             |
+----+-------------+--------------------+----------+---------+------+-------+------------------+
| 49 | application | 192.168.44.1:51718 | XXXXXXXX | Sleep   |  183 |       | NULL             ||
| 55 | application | 192.168.44.1:51769 | XXXXXXXX | Sleep   |  148 |       | NULL             |
| 56 | application | 192.168.44.1:51770 | XXXXXXXX | Sleep   |  148 |       | NULL             |
| 57 | application | 192.168.44.1:51771 | XXXXXXXX | Sleep   |  148 |       | NULL             |
| 58 | application | 192.168.44.1:51968 | XXXXXXXX | Sleep   |   11 |       | NULL             |
| 59 | root        | localhost          | NULL     | Query   |    0 | NULL  | show processlist |
+----+-------------+--------------------+----------+---------+------+-------+------------------+

You will see complete details of different connections. Now you can kill the sleeping connection as below:

mysql> kill 52;
Query OK, 0 rows affected (0.00 sec)

Get height of div with no height set in css

jQuery .height will return you the height of the element. It doesn't need CSS definition as it determines the computed height.

DEMO

You can use .height(), .innerHeight() or outerHeight() based on what you need.

enter image description here

.height() - returns the height of element excludes padding, border and margin.

.innerHeight() - returns the height of element includes padding but excludes border and margin.

.outerHeight() - returns the height of the div including border but excludes margin.

.outerHeight(true) - returns the height of the div including margin.

Check below code snippet for live demo. :)

_x000D_
_x000D_
$(function() {_x000D_
  var $heightTest = $('#heightTest');_x000D_
  $heightTest.html('Div style set as "height: 180px; padding: 10px; margin: 10px; border: 2px solid blue;"')_x000D_
    .append('<p>Height (.height() returns) : ' + $heightTest.height() + ' [Just Height]</p>')_x000D_
    .append('<p>Inner Height (.innerHeight() returns): ' + $heightTest.innerHeight() + ' [Height + Padding (without border)]</p>')_x000D_
    .append('<p>Outer Height (.outerHeight() returns): ' + $heightTest.outerHeight() + ' [Height + Padding + Border]</p>')_x000D_
    .append('<p>Outer Height (.outerHeight(true) returns): ' + $heightTest.outerHeight(true) + ' [Height + Padding + Border + Margin]</p>')_x000D_
});
_x000D_
div { font-size: 0.9em; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="heightTest" style="height: 150px; padding: 10px; margin: 10px; border: 2px solid blue; overflow: hidden; ">_x000D_
</div>
_x000D_
_x000D_
_x000D_

swift UITableView set rowHeight

Put the default rowHeight in viewDidLoad or awakeFromNib. As pointed out by Martin R., you cannot call cellForRowAtIndexPath from heightForRowAtIndexPath

self.tableView.rowHeight = 44.0

How to find out which JavaScript events fired?

You can use getEventListeners in your Google Chrome developer console.

getEventListeners(object) returns the event listeners registered on the specified object.

getEventListeners(document.querySelector('option[value=Closed]'));

JavaScript for detecting browser language preference

There is no decent way to get that setting, at least not something browser independent.

But the server has that info, because it is part of the HTTP request header (the Accept-Language field, see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4)

So the only reliable way is to get an answer back from the server. You will need something that runs on the server (like .asp, .jsp, .php, CGI) and that "thing" can return that info. Good examples here: http://www.developershome.com/wap/detection/detection.asp?page=readHeader

HTML Input="file" Accept Attribute File Type (CSV)

Well this is embarrassing... I found the solution I was looking for and it couldn't be simpler. I used the following code to get the desired result. Hope this helps someone in the future. Thanks everyone for your help.

<input id="fileSelect" type="file" accept=".csv, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" />  

Valid Accept Types:

For CSV files (.csv), use:

<input type="file" accept=".csv" />

For Excel Files 97-2003 (.xls), use:

<input type="file" accept="application/vnd.ms-excel" />

For Excel Files 2007+ (.xlsx), use:

<input type="file" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" />

For Text Files (.txt) use:

<input type="file" accept="text/plain" />

For Image Files (.png/.jpg/etc), use:

<input type="file" accept="image/*" />

For HTML Files (.htm,.html), use:

<input type="file" accept="text/html" />

For Video Files (.avi, .mpg, .mpeg, .mp4), use:

<input type="file" accept="video/*" />

For Audio Files (.mp3, .wav, etc), use:

<input type="file" accept="audio/*" />

For PDF Files, use:

<input type="file" accept=".pdf" /> 

DEMO:
http://jsfiddle.net/dirtyd77/LzLcZ/144/


NOTE:

If you are trying to display Excel CSV files (.csv), do NOT use:

  • text/csv
  • application/csv
  • text/comma-separated-values (works in Opera only).

If you are trying to display a particular file type (for example, a WAV or PDF), then this will almost always work...

 <input type="file" accept=".FILETYPE" />

How to allow only numeric (0-9) in HTML inputbox using jQuery?

Need to make sure you have the numeric keypad and the tab key working too

 // Allow only backspace and delete
            if (event.keyCode == 46 || event.keyCode == 8  || event.keyCode == 9) {
                // let it happen, don't do anything
            }
            else {
                // Ensure that it is a number and stop the keypress
                if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 96 && event.keyCode <= 105)) {

                }
                else {
                    event.preventDefault();
                }
            }

Escape quotes in JavaScript

Please find in the below code which escapes the single quotes as part of the entered string using a regular expression. It validates if the user-entered string is comma-separated and at the same time it even escapes any single quote(s) entered as part of the string.

In order to escape single quotes, just enter a backward slash followed by a single quote like: \’ as part of the string. I used jQuery validator for this example, and you can use as per your convenience.

Valid String Examples:

'Hello'

'Hello', 'World'

'Hello','World'

'Hello','World',' '

'It\'s my world', 'Can\'t enjoy this without me.', 'Welcome, Guest'

HTML:

<tr>
    <td>
        <label class="control-label">
            String Field:
        </label>
        <div class="inner-addon right-addon">
            <input type="text" id="stringField"
                   name="stringField"
                   class="form-control"
                   autocomplete="off"
                   data-rule-required="true"
                   data-msg-required="Cannot be blank."
                   data-rule-commaSeparatedText="true"
                   data-msg-commaSeparatedText="Invalid comma separated value(s).">
        </div>
    </td>

JavaScript:

     /**
 *
 * @param {type} param1
 * @param {type} param2
 * @param {type} param3
 */
jQuery.validator.addMethod('commaSeparatedText', function(value, element) {

    if (value.length === 0) {
        return true;
    }
    var expression = new RegExp("^((')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))(((,)|(,\\s))(')([^\'\\\\]*(?:\\\\.[^\'\\\\])*)[\\w\\s,\\.\\-_\\[\\]\\)\\(]+([^\'\\\\]*(?:\\\\.[^\'\\\\])*)('))*$");
    return expression.test(value);
}, 'Invalid comma separated string values.');

Ignoring a class property in Entity Framework 4.1 Code First

As of EF 5.0, you need to include the System.ComponentModel.DataAnnotations.Schema namespace.

jQuery - Get Width of Element when Not Visible (Display: None)

Thank you for posting the realWidth function above, it really helped me. Based on "realWidth" function above, I wrote, a CSS reset, (reason described below).

function getUnvisibleDimensions(obj) {
    if ($(obj).length == 0) {
        return false;
    }

    var clone = obj.clone();
    clone.css({
        visibility:'hidden',
        width : '',
        height: '',
        maxWidth : '',
        maxHeight: ''
    });
    $('body').append(clone);
    var width = clone.outerWidth(),
        height = clone.outerHeight();
    clone.remove();
    return {w:width, h:height};
}

"realWidth" gets the width of an existing tag. I tested this with some image tags. The problem was, when the image has given CSS dimension per width (or max-width), you will never get the real dimension of that image. Perhaps, the img has "max-width: 100%", the "realWidth" function clone it and append it to the body. If the original size of the image is bigger than the body, then you get the size of the body and not the real size of that image.

Find the number of columns in a table

Since all answers are using COUNT(), you can also use MAX() to get the number of columns in a specific table as

SELECT MAX(ORDINAL_POSITION) NumberOfColumnsInTable
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_CATALOG = 'YourDatabaseNameHere'
      AND 
      TABLE_SCHEMA = 'YourSchemaNameHere'
      AND
      TABLE_NAME = 'YourTableNameHere';

See The INFORMATION_SCHEMA COLUMNS Table

Codeigniter $this->db->order_by(' ','desc') result is not complete

$this->db1->where('tennant_id', $tennant_id);
$this->db1->order_by('id', 'DESC');
return $this->db1->get('courses')->result();

Convert float to std::string in C++

This tutorial gives a simple, yet elegant, solution, which i transcribe:

#include <sstream>
#include <string>
#include <stdexcept>

class BadConversion : public std::runtime_error {
public:
  BadConversion(std::string const& s)
    : std::runtime_error(s)
    { }
};

inline std::string stringify(double x)
{
  std::ostringstream o;
  if (!(o << x))
    throw BadConversion("stringify(double)");
  return o.str();
}
...
std::string my_val = stringify(val);

Android - drawable with rounded corners at the top only

Try giving these values:

 <corners android:topLeftRadius="6dp" android:topRightRadius="6dp"
         android:bottomLeftRadius="0.1dp" android:bottomRightRadius="0.1dp"/>

Note that I have changed 0dp to 0.1dp.

EDIT: See Aleks G comment below for a cleaner version

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

On the Developers bugs Facebook site, the last answer about that (parameters with sharer.php), makes me believe it was a bug that was going to be resolved. Am I right?

https://developers.facebook.com/x/bugs/357750474364812/

Ibrahim Faour · · Facebook Platform Team

Apologies for the inconvenience. We aim to update our external reports as soon as we get a resolution on issues. I do understand that sometimes the answer provided may not be satisfying, but we are eager to keep our platform as stable and efficient as possible. Thanks!

When to use 'raise NotImplementedError'?

As Uriel says, it is meant for a method in an abstract class that should be implemented in child class, but can be used to indicate a TODO as well.

There is an alternative for the first use case: Abstract Base Classes. Those help creating abstract classes.

Here's a Python 3 example:

class C(abc.ABC):
    @abc.abstractmethod
    def my_abstract_method(self, ...):
        ...

When instantiating C, you'll get an error because my_abstract_method is abstract. You need to implement it in a child class.

TypeError: Can't instantiate abstract class C with abstract methods my_abstract_method

Subclass C and implement my_abstract_method.

class D(C):
    def my_abstract_method(self, ...):
        ...

Now you can instantiate D.

C.my_abstract_method does not have to be empty. It can be called from D using super().

An advantage of this over NotImplementedError is that you get an explicit Exception at instantiation time, not at method call time.

Easiest way to mask characters in HTML(5) text input

  1. Basic validation can be performed by choosing the type attribute of input elements. For example: <input type="email" /> <input type="URL" /> <input type="number" />

  2. using pattern attribute like: <input type="text" pattern="[1-4]{5}" />

  3. required attribute <input type="text" required />

  4. maxlength: <input type="text" maxlength="20" />

  5. min & max: <input type="number" min="1" max="4" />

Auto reloading python Flask app upon code changes

To achieve this in PyCharm set 'Environment Variables' section to:

PYTHONUNBUFFERED=1;
FLASK_DEBUG=1

For Flask 'run / debug configurations'.

jQuery callback for multiple ajax calls

$.ajax({type:'POST', url:'www.naver.com', dataType:'text', async:false,
    complete:function(xhr, textStatus){},
    error:function(xhr, textStatus){},
    success:function( data ){
        $.ajax({type:'POST', 
            ....
            ....
            success:function(data){
                $.ajax({type:'POST',
                    ....
                    ....
            }
        }
    });

I'm sorry but I can't explain what I worte cuz I'm a Korean who can't speak even a word in english. but I think you can easily understand it.

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

Well, did you DO what the error says? You go to some length telling about installation, but what about the obvious?

  • Check the other server's network configuration in SQL Server.
  • Check the other machines FIREWALL. SQL Server does not open ports automatically, so the windows firewall normally blocks access..

How to Lock/Unlock screen programmatically?

Use Activity.getWindow() to get the window of your activity; use Window.addFlags() to add whichever of the following flags in WindowManager.LayoutParams that you desire:

ASP.NET Identity reset password

string message = null;
//reset the password
var result = await IdentityManager.Passwords.ResetPasswordAsync(model.Token, model.Password);
if (result.Success)
{
    message = "The password has been reset.";
    return RedirectToAction("PasswordResetCompleted", new { message = message });
}
else
{
    AddErrors(result);
}

This snippet of code is taken out of the AspNetIdentitySample project available on github

how to concatenate two dictionaries to create a new one in Python?

Here's a one-liner (imports don't count :) that can easily be generalized to concatenate N dictionaries:

Python 3

from itertools import chain
dict(chain.from_iterable(d.items() for d in (d1, d2, d3)))

and:

from itertools import chain
def dict_union(*args):
    return dict(chain.from_iterable(d.items() for d in args))

Python 2.6 & 2.7

from itertools import chain
dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3))

Output:

>>> from itertools import chain
>>> d1={1:2,3:4}
>>> d2={5:6,7:9}
>>> d3={10:8,13:22}
>>> dict(chain.from_iterable(d.iteritems() for d in (d1, d2, d3)))
{1: 2, 3: 4, 5: 6, 7: 9, 10: 8, 13: 22}

Generalized to concatenate N dicts:

from itertools import chain
def dict_union(*args):
    return dict(chain.from_iterable(d.iteritems() for d in args))

I'm a little late to this party, I know, but I hope this helps someone.

Choosing a jQuery datagrid plugin?

You should look here: https://stackoverflow.com/questions/159025/jquery-grid-recommendations

Update

The link above takes to a question that was closed and then deleted. Here are the original suggestions that were on the most voted answer:

Staging Deleted files

You can use this command

git add  `git ls-files --deleted`

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

What is Unicode, UTF-8, UTF-16?

Unicode is a fairly complex standard. Don’t be too afraid, but be prepared for some work! [2]

Because a credible resource is always needed, but the official report is massive, I suggest reading the following:

  1. The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!) An introduction by Joel Spolsky, Stack Exchange CEO.
  2. To the BMP and beyond! A tutorial by Eric Muller, Technical Director then, Vice President later, at The Unicode Consortium. (first 20 slides and you are done)

A brief explanation:

Computers read bytes and people read characters, so we use encoding standards to map characters to bytes. ASCII was the first widely used standard, but covers only Latin (7 bits/character can represent 128 different characters). Unicode is a standard with the goal to cover all possible characters in the world (can hold up to 1,114,112 characters, meaning 21 bits/character max. Current Unicode 8.0 specifies 120,737 characters in total, and that's all).

The main difference is that an ASCII character can fit to a byte (8 bits), but most Unicode characters cannot. So encoding forms/schemes (like UTF-8 and UTF-16) are used, and the character model goes like this:

Every character holds an enumerated position from 0 to 1,114,111 (hex: 0-10FFFF) called code point.
An encoding form maps a code point to a code unit sequence. A code unit is the way you want characters to be organized in memory, 8-bit units, 16-bit units and so on. UTF-8 uses 1 to 4 units of 8 bits, and UTF-16 uses 1 or 2 units of 16 bits, to cover the entire Unicode of 21 bits max. Units use prefixes so that character boundaries can be spotted, and more units mean more prefixes that occupy bits. So, although UTF-8 uses 1 byte for the Latin script it needs 3 bytes for later scripts inside Basic Multilingual Plane, while UTF-16 uses 2 bytes for all these. And that's their main difference.
Lastly, an encoding scheme (like UTF-16BE or UTF-16LE) maps (serializes) a code unit sequence to a byte sequence.

character: p
code point: U+03C0
encoding forms (code units):
      UTF-8: CF 80
      UTF-16: 03C0
encoding schemes (bytes):
      UTF-8: CF 80
      UTF-16BE: 03 C0
      UTF-16LE: C0 03

Tip: a hex digit represents 4 bits, so a two-digit hex number represents a byte
Also take a look at Plane maps in Wikipedia to get a feeling of the character set layout

how to open a page in new tab on button click in asp.net?

Just had the same problem. Client-side wasn't appropriate because the button was posting back information from a listview.

Saw same solution as Amaranth's on way2coding but this didn't work for me.

However, in the comments, someone posted a similar solution that does work

OnClientClick="document.getElementById('form1').target ='_blank';"

where form1 is the id of your asp.net form.

ssh_exchange_identification: Connection closed by remote host under Git bash

Hi I fix this on one vps service, restarting it, other way is if you have a console from your service o any other way to run a command in your remote machine the only command you must run is restart the ssh daemon and enjoy!! :P

/etc/init.d/ssh restart

JQUERY: Uncaught Error: Syntax error, unrecognized expression

If you're using jQuery 2.1.4 or above, try this:

$("#" + this.d);

Or, you can define var before using it. It makes your code simpler.

var d = this.d
$("#" + d);

What's the most appropriate HTTP status code for an "item not found" error page

That's depending if userid is a resource identifier or additional parameter. If it is then it's ok to return 404 if not you might return other code like

400 (bad request) - indicates a bad request
or
412 (Precondition Failed) e.g. conflict by performing conditional update

More info in free InfoQ Explores: REST book.

Javascript: set label text

For a dynamic approach, if your labels are always in front of your text areas:

$(object).prev("label").text(charsleft);

Annotation @Transactional. How to rollback?

or programatically

TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();

C - determine if a number is prime

After reading this question, I was intrigued by the fact that some answers offered optimization by running a loop with multiples of 2*3=6.

So I create a new function with the same idea, but with multiples of 2*3*5=30.

int check235(unsigned long n)
{
    unsigned long sq, i;

    if(n<=3||n==5)
        return n>1;

    if(n%2==0 || n%3==0 || n%5==0)
        return 0;

    if(n<=30)
        return checkprime(n); /* use another simplified function */

    sq=ceil(sqrt(n));
    for(i=7; i<=sq; i+=30)
        if (n%i==0 || n%(i+4)==0 || n%(i+6)==0 || n%(i+10)==0 || n%(i+12)==0 
           || n%(i+16)==0 || n%(i+22)==0 || n%(i+24)==0)
            return 0;

        return 1;
}

By running both functions and checking times I could state that this function is really faster. Lets see 2 tests with 2 different primes:

$ time ./testprimebool.x 18446744069414584321 0
f(2,3)
Yes, its prime.    
real    0m14.090s
user    0m14.096s
sys     0m0.000s

$ time ./testprimebool.x 18446744069414584321 1
f(2,3,5)
Yes, its prime.    
real    0m9.961s
user    0m9.964s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 0
f(2,3)
Yes, its prime.    
real    0m13.990s
user    0m13.996s
sys     0m0.004s

$ time ./testprimebool.x 18446744065119617029 1
f(2,3,5)
Yes, its prime.    
real    0m10.077s
user    0m10.068s
sys     0m0.004s

So I thought, would someone gain too much if generalized? I came up with a function that will do a siege first to clean a given list of primordial primes, and then use this list to calculate the bigger one.

int checkn(unsigned long n, unsigned long *p, unsigned long t)
{
    unsigned long sq, i, j, qt=1, rt=0;
    unsigned long *q, *r;

    if(n<2)
        return 0;

    for(i=0; i<t; i++)
    {
        if(n%p[i]==0)
            return 0;
        qt*=p[i];
    }
    qt--;

    if(n<=qt)
        return checkprime(n); /* use another simplified function */

    if((q=calloc(qt, sizeof(unsigned long)))==NULL)
    {
        perror("q=calloc()");
        exit(1);
    }
    for(i=0; i<t; i++)
        for(j=p[i]-2; j<qt; j+=p[i])
            q[j]=1;

    for(j=0; j<qt; j++)
        if(q[j])
            rt++;

    rt=qt-rt;
    if((r=malloc(sizeof(unsigned long)*rt))==NULL)
    {
        perror("r=malloc()");
        exit(1);
    }
    i=0;
    for(j=0; j<qt; j++)
        if(!q[j])
            r[i++]=j+1;

    free(q);

    sq=ceil(sqrt(n));
    for(i=1; i<=sq; i+=qt+1)
    {
        if(i!=1 && n%i==0)
            return 0;
        for(j=0; j<rt; j++)
            if(n%(i+r[j])==0)
                return 0;
    }
    return 1;
}

I assume I did not optimize the code, but it's fair. Now, the tests. Because so many dynamic memory, I expected the list 2 3 5 to be a little slower than the 2 3 5 hard-coded. But it was ok as you can see bellow. After that, time got smaller and smaller, culminating the best list to be:

2 3 5 7 11 13 17 19

With 8.6 seconds. So if someone would create a hardcoded program that makes use of such technique I would suggest use the list 2 3 and 5, because the gain is not that big. But also, if willing to code, this list is ok. Problem is you cannot state all cases without a loop, or your code would be very big (There would be 1658879 ORs, that is || in the respective internal if). The next list:

2 3 5 7 11 13 17 19 23

time started to get bigger, with 13 seconds. Here the whole test:

$ time ./testprimebool.x 18446744065119617029 2 3 5
f(2,3,5)
Yes, its prime.
real    0m12.668s
user    0m12.680s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7
f(2,3,5,7)
Yes, its prime.
real    0m10.889s
user    0m10.900s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11
f(2,3,5,7,11)
Yes, its prime.
real    0m10.021s
user    0m10.028s
sys     0m0.000s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13
f(2,3,5,7,11,13)
Yes, its prime.
real    0m9.351s
user    0m9.356s
sys     0m0.004s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17
f(2,3,5,7,11,13,17)
Yes, its prime.
real    0m8.802s
user    0m8.800s
sys     0m0.008s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17 19
f(2,3,5,7,11,13,17,19)
Yes, its prime.
real    0m8.614s
user    0m8.564s
sys     0m0.052s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17 19 23
f(2,3,5,7,11,13,17,19,23)
Yes, its prime.
real    0m13.013s
user    0m12.520s
sys     0m0.504s

$ time ./testprimebool.x 18446744065119617029 2 3 5 7 11 13 17 19 23 29
f(2,3,5,7,11,13,17,19,23,29)                                                                                                                         
q=calloc(): Cannot allocate memory

PS. I did not free(r) intentionally, giving this task to the OS, as the memory would be freed as soon as the program exited, to gain some time. But it would be wise to free it if you intend to keep running your code after the calculation.


BONUS

int check2357(unsigned long n)
{
    unsigned long sq, i;

    if(n<=3||n==5||n==7)
        return n>1;

    if(n%2==0 || n%3==0 || n%5==0 || n%7==0)
        return 0;

    if(n<=210)
        return checkprime(n); /* use another simplified function */

    sq=ceil(sqrt(n));
    for(i=11; i<=sq; i+=210)
    {    
        if(n%i==0 || n%(i+2)==0 || n%(i+6)==0 || n%(i+8)==0 || n%(i+12)==0 || 
   n%(i+18)==0 || n%(i+20)==0 || n%(i+26)==0 || n%(i+30)==0 || n%(i+32)==0 || 
   n%(i+36)==0 || n%(i+42)==0 || n%(i+48)==0 || n%(i+50)==0 || n%(i+56)==0 || 
   n%(i+60)==0 || n%(i+62)==0 || n%(i+68)==0 || n%(i+72)==0 || n%(i+78)==0 || 
   n%(i+86)==0 || n%(i+90)==0 || n%(i+92)==0 || n%(i+96)==0 || n%(i+98)==0 || 
   n%(i+102)==0 || n%(i+110)==0 || n%(i+116)==0 || n%(i+120)==0 || n%(i+126)==0 || 
   n%(i+128)==0 || n%(i+132)==0 || n%(i+138)==0 || n%(i+140)==0 || n%(i+146)==0 || 
   n%(i+152)==0 || n%(i+156)==0 || n%(i+158)==0 || n%(i+162)==0 || n%(i+168)==0 || 
   n%(i+170)==0 || n%(i+176)==0 || n%(i+180)==0 || n%(i+182)==0 || n%(i+186)==0 || 
   n%(i+188)==0 || n%(i+198)==0)
            return 0;
    }
    return 1;
}

Time:

$ time ./testprimebool.x 18446744065119617029 7
h(2,3,5,7)
Yes, its prime.
real    0m9.123s
user    0m9.132s
sys     0m0.000s

What does the error "JSX element type '...' does not have any construct or call signatures" mean?

In my case, I was using React.ReactNode as a type for a functional component instead of React.FC type.

In this component to be exact:

_x000D_
_x000D_
export const PropertiesList: React.FC = (props: any) => {_x000D_
  const list:string[] = [_x000D_
    ' Consequat Phasellus sollicitudin.',_x000D_
    ' Consequat Phasellus sollicitudin.',_x000D_
    '...'_x000D_
  ]_x000D_
_x000D_
  return (_x000D_
    <List_x000D_
      header={<ListHeader heading="Properties List" />}_x000D_
      dataSource={list}_x000D_
        renderItem={(listItem, index) =>_x000D_
          <List.Item key={index}> {listItem } </List.Item>_x000D_
      }_x000D_
    />_x000D_
  )_x000D_
}
_x000D_
_x000D_
_x000D_

How to save as a new file and keep working on the original one in Vim?

The following command will create a copy in a new window. So you can continue see both original file and the new file.

:w {newfilename} | sp #

How to sort an ArrayList in Java

Try BeanComparator from Apache Commons.

import org.apache.commons.beanutils.BeanComparator;


BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);

How can I rebuild indexes and update stats in MySQL innoDB?

For basic cleanup and re-analyzing you can run "OPTIMIZE TABLE ...", it will compact out the overhead in the indexes and run ANALYZE TABLE too, but it's not going to re-sort them and make them as small & efficient as they could be.

https://dev.mysql.com/doc/refman/8.0/en/optimize-table.html

However, if you want the indexes completely rebuilt for best performance, you can:

  1. drop / re-add indexes (obviously)
  2. dump / reload the table
  3. ALTER TABLE and "change" using the same storage engine
  4. REPAIR TABLE (only works for MyISAM, ARCHIVE, and CSV)

https://dev.mysql.com/doc/refman/8.0/en/rebuilding-tables.html

If you do an ALTER TABLE on a field (that is part of an index) and change its type, then it will also fully rebuild the related index(es).

How to create byte array from HttpPostedFile

in your question, both buffer and byteArray seem to be byte[]. So:

ImageElement image = ImageElement.FromBinary(buffer);

How to get single value from this multi-dimensional PHP array

I think you want this:

foreach ($myarray as $key => $value) {
    echo "$key = $value\n";
}

window.close() doesn't work - Scripts may close only the windows that were opened by it

The below code worked for me :)

window.open('your current page URL', '_self', '');
window.close();

How to create a DataTable in C# and how to add rows?

DataTable dt=new DataTable();
Datacolumn Name = new DataColumn("Name");
Name.DataType= typeoff(string);
Name.AllowDBNull=false; //set as null or not the default is true i.e null
Name.MaxLength=20; //sets the length the default is -1 which is max(no limit)
dt.Columns.Add(Name);
Datacolumn Age = new DataColumn("Age", typeoff(int));`

dt.Columns.Add(Age);

DataRow dr=dt.NewRow();

dr["Name"]="Mohammad Adem"; // or dr[0]="Mohammad Adem";
dr["Age"]=33; // or dr[1]=33;
dt.add.rows(dr);
dr=dt.NewRow();

dr["Name"]="Zahara"; // or dr[0]="Zahara";
dr["Age"]=22; // or dr[1]=22;
dt.rows.add(dr);
Gv.DataSource=dt;
Gv.DataBind();

case statement in SQL, how to return multiple variables?

The basic way, unfortunately, is to repeat yourself.

SELECT
  CASE WHEN <condition 1> THEN <a1> WHEN <condition 2> THEN <a2> ELSE <a3> END,
  CASE WHEN <condition 1> THEN <b1> WHEN <condition 2> THEN <b2> ELSE <b3> END
FROM 
  <table> 

Fortunately, most RDBMS are clever enough to NOT have to evaluate the conditions multiple times. It's just redundant typing.


In MS SQL Server (2005+) you could possible use CROSS APPLY as an alternative to this. Though I have no idea how performant it is...

SELECT
  *
FROM
  <table>
CROSS APPLY
  (
   SELECT a1, b1 WHERE <condition 1>
   UNION ALL
   SELECT a2, b2 WHERE <condition 2>
   UNION ALL
   SELECT a3, b3 WHERE <condition 3>
  )
  AS case_proxy

The noticable downside here is that there is no ELSE equivalent and as all the conditions could all return values, they need to be framed such that only one can ever be true at a time.


EDIT

If Yuck's answer is changed to a UNION rather than JOIN approach, it becomes very similar to this. The main difference, however, being that this only scans the input data set once, rather than once per condition (100 times in your case).


EDIT

I've also noticed that you may mean that the values returned by the CASE statements are fixed. All records that match the same condition get the exact sames values in value1 and value2. This could be formed like this...

WITH
  checked_data AS
(
  SELECT
    CASE WHEN <condition1> THEN 1
         WHEN <condition2> THEN 2
         WHEN <condition3> THEN 3
         ...
         ELSE                   100
    END AS condition_id,
    *
  FROM
    <table>
)
,
  results (condition_id, value1, value2) AS
(
   SELECT 1, a1, b1
   UNION ALL
   SELECT 2, a2, b2
   UNION ALL
   SELECT 3, a3, b3
   UNION ALL
   ...
   SELECT 100, a100, b100
)
SELECT
  *
FROM
  checked_data
INNER JOIN
  results
    ON results.condition_id = checked_data.condition_id

ActiveRecord OR query

Book.where.any_of(Book.where(:author => 'Poe'), Book.where(:author => 'Hemingway')

What is the correct way to check for string equality in JavaScript?

what led me to this question is the padding and white-spaces

check my case

 if (title === "LastName")
      doSomething();

and title was " LastName"

enter image description here

so maybe you have to use trim function like this

var title = $(this).text().trim();

Init array of structs in Go

You can have it this way:

It is important to mind the commas after each struct item or set of items.

earnings := []LineItemsType{

        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
    }

JPA CascadeType.ALL does not delete orphans

I was using one to one mapping , but child was not getting deleted JPA was giving foreign key violation

After using orphanRemoval = true , issue got resolved

How to POST form data with Spring RestTemplate?

The POST method should be sent along the HTTP request object. And the request may contain either of HTTP header or HTTP body or both.

Hence let's create an HTTP entity and send the headers and parameter in body.

HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

MultiValueMap<String, String> map= new LinkedMultiValueMap<String, String>();
map.add("email", "[email protected]");

HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<MultiValueMap<String, String>>(map, headers);

ResponseEntity<String> response = restTemplate.postForEntity( url, request , String.class );

http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/client/RestTemplate.html#postForObject-java.lang.String-java.lang.Object-java.lang.Class-java.lang.Object...-

Max retries exceeded with URL in requests

Specifying the proxy in a corporate environment solved it for me.

page = requests.get("http://www.google.com:80", proxies={"http": "http://111.233.225.166:1234"})

The full error is:

requests.exceptions.ConnectionError: HTTPSConnectionPool(host='www.google.com', port=80): Max retries exceeded with url: / (Caused by NewConnectionError(': Failed to establish a new connection: [WinError 10060] A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond'))

Can I change the fill color of an svg path with CSS?

you put this css for svg circle.

svg:hover circle{
    fill: #F6831D;
    stroke-dashoffset: 0;
    stroke-dasharray: 700;
    stroke-width: 2;
}

pip cannot install anything

This is the full text of the blog post linked below:

If you've tried installing a package with pip recently, you may have encountered this error:

Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Could not fetch URL https://pypi.python.org/simple/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL https://pypi.python.org/simple/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Cannot fetch index base URL https://pypi.python.org/simple/
  Could not fetch URL https://pypi.python.org/simple/Django/1.5.1: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL https://pypi.python.org/simple/Django/1.5.1 when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Could not fetch URL https://pypi.python.org/simple/Django/: There was a problem confirming the ssl certificate: <urlopen error [Errno 1] _ssl.c:504: error:0D0890A1:asn1 encoding routines:ASN1_verify:unknown message digest algorithm>
  Will skip URL https://pypi.python.org/simple/Django/ when looking for download links for Django==1.5.1 (from -r requirements.txt (line 1))
  Could not find any downloads that satisfy the requirement Django==1.5.1 (from -r requirements.txt (line 1))
No distributions at all found for Django==1.5.1 (from -r requirements.txt (line 1))
Storing complete log in /Users/paul/.pip/pip.log

This seems to be an issue with an old version of OpenSSL being incompatible with pip 1.3.1. If you're using a non-stock Python distribution (notably EPD 7.3), you're very likely to have a setup that isn't going to work with pip 1.3.1 without a shitload of work.

The easy workaround for now, is to install pip 1.2.1, which does not require SSL:

curl -O https://pypi.python.org/packages/source/p/pip/pip-1.2.1.tar.gz
tar xvfz pip-1.2.1.tar.gz
cd pip-1.2.1
python setup.py install

If you are using EPD, and you're not using it for a class where things might break, you may want to consider installing the new incarnation: Enthought Canopy. I know they were aware of the issues caused by the previous version of OpenSSL, and would imagine they are using a new version now that should play nicely with pip 1.3.1.

CSS Outside Border

Why not simply using background-clip?

-webkit-background-clip: padding;
   -moz-background-clip: padding;
        background-clip: padding-box;

See:
http://caniuse.com/#search=background-clip
https://developer.mozilla.org/en-US/docs/Web/CSS/background-clip
https://css-tricks.com/almanac/properties/b/background-clip

Get difference between two lists

In [5]: list(set(temp1) - set(temp2))
Out[5]: ['Four', 'Three']

Beware that

In [5]: set([1, 2]) - set([2, 3])
Out[5]: set([1]) 

where you might expect/want it to equal set([1, 3]). If you do want set([1, 3]) as your answer, you'll need to use set([1, 2]).symmetric_difference(set([2, 3])).

Return row of Data Frame based on value in a column - R

You could use dplyr:

df %>% group_by("Amount") %>% slice(which.min(x))

Using moment.js to convert date to string "MM/dd/yyyy"

I think you just have incorrect casing in the format string. According to the documentation this should work for you: MM/DD/YYYY

moment.js documentation

How to check the differences between local and github before the pull

git pull is really equivalent to running git fetch and then git merge. The git fetch updates your so-called "remote-tracking branches" - typically these are ones that look like origin/master, github/experiment, etc. that you see with git branch -r. These are like a cache of the state of branches in the remote repository that are updated when you do git fetch (or a successful git push).

So, suppose you've got a remote called origin that refers to your GitHub repository, you would do:

git fetch origin

... and then do:

git diff master origin/master

... in order to see the difference between your master, and the one on GitHub. If you're happy with those differences, you can merge them in with git merge origin/master, assuming master is your current branch.

Personally, I think that doing git fetch and git merge separately is generally a good idea.

Convert a SQL query result table to an HTML table for email

Here my common used script below. I use this for running scripts on two tables/views with SQL job and send results as two HTML tables via mail. Ofcourse you should create mail profile before run this.

DECLARE @mailfrom varchar(max)
DECLARE @subject varchar(100)
DECLARE @tableHTML NVARCHAR(MAX), @tableHTML1 NVARCHAR(MAX), @tableHTML2 NVARCHAR(MAX), @mailbody NVARCHAR(MAX)
DECLARE @Table1 NVARCHAR(MAX), @Table2 NVARCHAR(MAX)
DECLARE @jobName varchar(100)
SELECT @jobName = name from msdb..sysjobs where job_id = $(ESCAPE_NONE(JOBID))

-- If the result set is not empty then fill the Table1 HTML table
IF (SELECT COUNT(*) FROM [Database].[Schema].[Table1]) > 0
BEGIN
SET @Table1 = N''
SELECT @Table1 = @Table1 + '<tr style="font-size:13px;background-color:#FFFFFF">' + 
    '<td>' + ColumnText + '</td>' +
    '<td>' + CAST(ColumnNumber as nvarchar(30)) + '</td>' + '</tr>'  
FROM [Database].[Schema].[Table1]
ORDER BY ColumnText,ColumnNumber

SET @tableHTML1 = 
N'<table border="1" align="Left" cellpadding="2" cellspacing="0" style="color:black;font-family:arial,helvetica,sans-serif;text-align:left;" >' +
N'<tr style ="font-size:13px;font-weight: normal;background: #FFFFFF"> 
<th align=left>ColumnTextHeader1</th>
<th align=left>ColumnNumberHeader2</th> </tr>' + @Table1 + '</table>'
END
ELSE
BEGIN
SET @tableHTML1 = N''
SET @Table1 = N''
END


-- If the result set is not empty then fill the Table2 HTML table
IF (SELECT COUNT(*) FROM [Database].[Schema].[Table2]) > 0
BEGIN
SET @Table2 = N''
SELECT @Table2 = @Table2 + '<tr style="font-size:13px;background-color:#FFFFFF">' + 
    '<td>' + ColumnText + '</td>' +
    '<td>' + CAST(ColumnNumber as nvarchar(30)) + '</td>' + '</tr>'  
FROM [Database].[Schema].[Table2]
ORDER BY ColumnText,ColumnNumber

SET @tableHTML2 = 
N'<table border="1" align="Left" cellpadding="2" cellspacing="0" style="color:black;font-family:arial,helvetica,sans-serif;text-align:left;" >' +
N'<tr style ="font-size:13px;font-weight: normal;background: #FFFFFF"> 
<th align=left>ColumnTextHeader1</th>
<th align=left>ColumnNumberHeader2</th> </tr>' + @Table2 + '</table>'
END
ELSE
BEGIN
SET @tableHTML2 = N''
SET @Table2 = N''
END

SET @tableHTML = @tableHTML1 + @tableHTML2

-- If result sets from Table1 and Table2 are empty, then don't sent mail.
IF (SELECT @tableHTML) <> ''
BEGIN
SET @mailbody = N' Write mail text here<br><br>' + @tableHTML
SELECT @mailfrom = 'SQL Server <' + cast(SERVERPROPERTY('ComputerNamePhysicalNETBIOS') as varchar(50)) + '@domain.com>'
SELECT @subject = N'Mail Subject [Job: ' + @jobName + ']'
    EXEC msdb.dbo.sp_send_dbmail
    @profile_name= 'mailprofilename',
    @recipients= '<[email protected]>',
    @from_address = @mailfrom,
    @reply_to = '<[email protected]>',
    @subject = @subject,
    @body = @mailbody,
    @body_format = 'HTML'
--   ,@importance = 'HIGH'
END

Switching from zsh to bash on OSX, and back again?

zsh has a builtin command emulate which can emulate different shells by setting the appropriate options, although csh will never be fully emulated.

emulate bash
perform commands
emulate -R zsh

The -R flag restores all the options to their default values for that shell.

See: zsh manual

How do I set default values for functions parameters in Matlab?

There isn't a direct way to do this like you've attempted.

The usual approach is to use "varargs" and check against the number of arguments. Something like:

function f(arg1, arg2, arg3)

  if nargin < 3
    arg3 =   'some default'
  end

end

There are a few fancier things you can do with isempty, etc., and you might want to look at Matlab central for some packages that bundle these sorts of things.

You might have a look at varargin, nargchk, etc. They're useful functions for this sort of thing. varargs allow you to leave a variable number of final arguments, but this doesn't get you around the problem of default values for some/all of them.

How to convert a normal Git repository to a bare one?

Wow, it's simply amazing how many people chimed in on this, especially considering it doesn't seem that not a single on stopped to ask why this person is doing what he's doing.

The ONLY difference between a bare and non-bare git repository is that the non-bare version has a working copy. The main reason you would need a bare repo is if you wanted to make it available to a third party, you can't actually work on it directly so at some point you're going to have to clone it at which point you're right back to a regular working copy version.

That being said, to convert to a bare repo all you have to do is make sure you have no commits pending and then just :

rm -R * && mv .git/* . && rm -R .git

There ya go, bare repo.

Data binding in React

Define state attributes. Add universal handleChange event handler. Add name param to input tag for mapping.

this.state = { stateAttrName:"" }

handleChange=(event)=>{
    this.setState({[event.target.name]:event.target.value });
  } 

<input className="form-control" name="stateAttrName" value= 
{this.state.stateAttrName} onChange={this.handleChange}/>

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

Use

/js/bootstrap.bundle.min.js

instead of

/js/bootstrap.min.js

Change primary key column in SQL Server

Necromancing.
It looks you have just as good a schema to work with as me... Here is how to do it correctly:

In this example, the table name is dbo.T_SYS_Language_Forms, and the column name is LANG_UID

-- First, chech if the table exists...
IF 0 < (
    SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES 
    WHERE TABLE_TYPE = 'BASE TABLE'
    AND TABLE_SCHEMA = 'dbo'
    AND TABLE_NAME = 'T_SYS_Language_Forms'
)
BEGIN
    -- Check for NULL values in the primary-key column
    IF 0 = (SELECT COUNT(*) FROM T_SYS_Language_Forms WHERE LANG_UID IS NULL)
    BEGIN
        ALTER TABLE T_SYS_Language_Forms ALTER COLUMN LANG_UID uniqueidentifier NOT NULL 

        -- No, don't drop, FK references might already exist...
        -- Drop PK if exists 
        -- ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT pk_constraint_name 
        --DECLARE @pkDropCommand nvarchar(1000) 
        --SET @pkDropCommand = N'ALTER TABLE T_SYS_Language_Forms DROP CONSTRAINT ' + QUOTENAME((SELECT CONSTRAINT_NAME FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
        --WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
        --AND TABLE_SCHEMA = 'dbo' 
        --AND TABLE_NAME = 'T_SYS_Language_Forms' 
        ----AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
        --))
        ---- PRINT @pkDropCommand 
        --EXECUTE(@pkDropCommand) 

        -- Instead do
        -- EXEC sp_rename 'dbo.T_SYS_Language_Forms.PK_T_SYS_Language_Forms1234565', 'PK_T_SYS_Language_Forms';


        -- Check if they keys are unique (it is very possible they might not be) 
        IF 1 >= (SELECT TOP 1 COUNT(*) AS cnt FROM T_SYS_Language_Forms GROUP BY LANG_UID ORDER BY cnt DESC)
        BEGIN

            -- If no Primary key for this table
            IF 0 =  
            (
                SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS 
                WHERE CONSTRAINT_TYPE = 'PRIMARY KEY' 
                AND TABLE_SCHEMA = 'dbo' 
                AND TABLE_NAME = 'T_SYS_Language_Forms' 
                -- AND CONSTRAINT_NAME = 'PK_T_SYS_Language_Forms' 
            )
                ALTER TABLE T_SYS_Language_Forms ADD CONSTRAINT PK_T_SYS_Language_Forms PRIMARY KEY CLUSTERED (LANG_UID ASC)
            ;

            -- Adding foreign key
            IF 0 = (SELECT COUNT(*) FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS WHERE CONSTRAINT_NAME = 'FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms') 
                ALTER TABLE T_ZO_SYS_Language_Forms WITH NOCHECK ADD CONSTRAINT FK_T_ZO_SYS_Language_Forms_T_SYS_Language_Forms FOREIGN KEY(ZOLANG_LANG_UID) REFERENCES T_SYS_Language_Forms(LANG_UID); 
        END -- End uniqueness check
        ELSE
            PRINT 'FSCK, this column has duplicate keys, and can thus not be changed to primary key...' 
    END -- End NULL check
    ELSE
        PRINT 'FSCK, need to figure out how to update NULL value(s)...' 
END 

How can I declare and define multiple variables in one line using C++?

Possible approaches:

  • Initialize all local variables with zero.
  • Have an array, memset or {0} the array.
  • Make it global or static.
  • Put them in struct, and memset or have a constructor that would initialize them to zero.

How do I bind to list of checkbox values with AngularJS?

A simple HTML only way of doing it:

_x000D_
_x000D_
<input type="checkbox"_x000D_
       ng-checked="fruits.indexOf('apple') > -1"_x000D_
       ng-click="fruits.indexOf('apple') > -1 ? fruits.splice(fruits.indexOf('apple'), 1) : fruits.push('apple')">_x000D_
<input type="checkbox"_x000D_
       ng-checked="fruits.indexOf('orange') > -1"_x000D_
       ng-click="fruits.indexOf('orange') > -1 ? fruits.splice(fruits.indexOf('orange'), 1) : fruits.push('orange')">_x000D_
<input type="checkbox"_x000D_
       ng-checked="fruits.indexOf('pear') > -1"_x000D_
       ng-click="fruits.indexOf('pear') > -1 ? fruits.splice(fruits.indexOf('pear'), 1) : fruits.push('pear')">_x000D_
<input type="checkbox"_x000D_
       ng-checked="fruits.indexOf('naartjie') > -1"_x000D_
       ng-click="fruits.indexOf('apple') > -1 ? fruits.splice(fruits.indexOf('apple'), 1) : fruits.push('naartjie')">
_x000D_
_x000D_
_x000D_

Entity Framework: table without primary key

EF does not require a primary key on the database. If it did, you couldn't bind entities to views.

You can modify the SSDL (and the CSDL) to specify a unique field as your primary key. If you don't have a unique field, then I believe you are hosed. But you really should have a unique field (and a PK), otherwise you are going to run into problems later.

Erick

How would I check a string for a certain letter in Python?

If you want a version that raises an error:

"string to search".index("needle") 

If you want a version that returns -1:

"string to search".find("needle") 

This is more efficient than the 'in' syntax

bs4.FeatureNotFound: Couldn't find a tree builder with the features you requested: lxml. Do you need to install a parser library?

The error is coming because of the parser you are using. In general, if you have HTML file/code then you need to use html5lib(documentation can be found here) & in-case you have XML file/data then you need to use lxml(documentation can be found here). You can use lxml for HTML file/code also but sometimes it gives an error as above. So, better to choose the package wisely based on the type of data/file. You can also use html_parser which is built-in module. But, this also sometimes do not work.

For more details regarding when to use which package you can see the details here

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

SELECT CAST(Datetimefield AS DATE) as DateField, SUM(intfield) as SumField
FROM MyTable
GROUP BY CAST(Datetimefield AS DATE)

Python: most idiomatic way to convert None to empty string?

def xstr(s):
    return '' if s is None else str(s)

Set a path variable with spaces in the path in a Windows .cmd file or batch file

I always place the path in double quotes when I am creating a .bat file. (I just added the PAUSE so it wont close the screen.)

For example:

"C:\Program Files\PageTech\PCLReader64_131\PCLReader64.exe"
PAUSE

How to align linearlayout to vertical center?

use android:layout_gravity instead of android:gravity

android:gravity sets the gravity of the content of the View its used on. android:layout_gravity sets the gravity of the View or Layout in its parent.

import error: 'No module named' *does* exist

I've had this problem too, I had just forgotten to type workon myproject in the terminal before executing my program.

MySQL - Cannot add or update a child row: a foreign key constraint fails

I've faced this issue and the solution was making sure that all the data from the child field are matching the parent field

for example, you want to add foreign key inside (attendance) table to the column (employeeName)

where the parent is (employees) table, (employeeName) column

all the data in attendance.employeeName must be matching employee.employeeName

How to find out "The most popular repositories" on Github?

Ranking by stars or forks is not working. Each promoted or created by a famous company repository is popular at the beginning. Also it is possible to have a number of them which are in trend right now (publications, marketing, events). It doesn't mean that those repositories are useful/popular.

The gitmostwanted.com project (repo at github) analyses GH Archive data in order to highlight the most interesting repositories and exclude others. Just compare the results with mentioned resources.

VBA paste range

This is what I came up to when trying to copy-paste excel ranges with it's sizes and cell groups. It might be a little too specific for my problem but...:

'** 'Copies a table from one place to another 'TargetRange: where to put the new LayoutTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Sub CopyLayout(TargetRange As Range, typee As Integer)
    Application.ScreenUpdating = False
        Dim ncolumn As Integer
        Dim nrow As Integer

        SheetLayout.Activate
    If (typee = 1) Then 'is installation
        Range("installationlayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    ElseIf (typee = 2) Then 'is package
        Range("PackageLayout").Copy Destination:=TargetRange '@SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@
    End If

    Sheet2.Select 'SHEET2 TEM DE PASSAR A SER A SHEET DO PROJECT PLAN!@@@@@

    If typee = 1 Then
       nrow = SheetLayout.Range("installationlayout").Rows.Count
       ncolumn = SheetLayout.Range("installationlayout").Columns.Count

       Call RowHeightCorrector(SheetLayout.Range("installationlayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    ElseIf typee = 2 Then
       nrow = SheetLayout.Range("PackageLayout").Rows.Count
       ncolumn = SheetLayout.Range("PackageLayout").Columns.Count
       Call RowHeightCorrector(SheetLayout.Range("PackageLayout"), TargetRange.CurrentRegion, typee, nrow, ncolumn)
    End If
    Range("A1").Select 'Deselect the created table

    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub

'** 'Receives the Pasted Table Range and rearranjes it's properties 'accordingly to the original CopiedTable 'typee: If it is an Instalation Layout table(1) or Package Layout table(2) '**

Function RowHeightCorrector(CopiedTable As Range, PastedTable As Range, typee As Integer, RowCount As Integer, ColumnCount As Integer)
    Dim R As Long, C As Long

    For R = 1 To RowCount
        PastedTable.Rows(R).RowHeight = CopiedTable.CurrentRegion.Rows(R).RowHeight
        If R >= 2 And R < RowCount Then
            PastedTable.Rows(R).Group 'Main group of the table
        End If
        If R = 2 Then
            PastedTable.Rows(R).Group 'both type of tables have a grouped section at relative position "2" of Rows
        ElseIf (R = 4 And typee = 1) Then
            PastedTable.Rows(R).Group 'If it is an installation materials table, it has two grouped sections...
        End If
    Next R

    For C = 1 To ColumnCount
        PastedTable.Columns(C).ColumnWidth = CopiedTable.CurrentRegion.Columns(C).ColumnWidth
    Next C
End Function



Sub test ()
    Call CopyLayout(Sheet2.Range("A18"), 2)
end sub

jquery, selector for class within id

Just use the plain ol' class selector.

$('#my_id .my_class')

It doesn't matter if the element also has other classes. It has the .my_class class, and it's somewhere inside #my_id, so it will match that selector.

Regarding performance

According to the jQuery selector performance documentation, it's faster to use the two selectors separately, like this:

$('#my_id').find('.my_class')

Here's the relevant part of the documentation:

ID-Based Selectors

// Fast:
$( "#container div.robotarm" );

// Super-fast:
$( "#container" ).find( "div.robotarm" );

The .find() approach is faster because the first selection is handled without going through the Sizzle selector engine – ID-only selections are handled using document.getElementById(), which is extremely fast because it is native to the browser.

Selecting by ID or by class alone (among other things) invokes browser-supplied functions like document.getElementById() which are quite rapid, whereas using a descendent selector invokes the Sizzle engine as mentioned which, although fast, is slower than the suggested alternative.

git pull while not in a git directory

As some of my servers are on an old Ubuntu LTS versions, I can't easily upgrade git to the latest version (which supports the -C option as described in some answers).

This trick works well for me, especially because it does not have the side effect of some other answers that leave you in a different directory from where you started.

pushd /X/Y
git pull
popd

Or, doing it as a one-liner:

pushd /X/Y; git pull; popd

Both Linux and Windows have pushd and popd commands.

With CSS, use "..." for overflowed block of multi-lines

The link below provides a pure HTML / CSS solution to this problem.

Browser support - as stated in the article:

So far we have tested on Safari 5.0, IE 9 (must be in standards mode), Opera 12 and Firefox 15.

Older browsers will still work quite well, as the meat of the layout is in normal positioning, margin and padding properties. if your platform is older (e.g. Firefox 3.6, IE 8), you can use the method but redo the gradient as a standalone PNG image or DirectX filter.

http://www.mobify.com/dev/multiline-ellipsis-in-pure-css

the css:

p { margin: 0; padding: 0; font-family: sans-serif;}

.ellipsis {
    overflow: hidden;
    height: 200px;
    line-height: 25px;
    margin: 20px;
    border: 5px solid #AAA; }

.ellipsis:before {
    content:"";
    float: left;
    width: 5px; height: 200px; }

.ellipsis > *:first-child {
    float: right;
    width: 100%;
    margin-left: -5px; }        

.ellipsis:after {
    content: "\02026";  

    box-sizing: content-box;
    -webkit-box-sizing: content-box;
    -moz-box-sizing: content-box;

    float: right; position: relative;
    top: -25px; left: 100%; 
    width: 3em; margin-left: -3em;
    padding-right: 5px;

    text-align: right;

    background: -webkit-gradient(linear, left top, right top,
        from(rgba(255, 255, 255, 0)), to(white), color-stop(50%, white));
    background: -moz-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);           
    background: -o-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
    background: -ms-linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white);
    background: linear-gradient(to right, rgba(255, 255, 255, 0), white 50%, white); }

the html:

<div class="ellipsis">
    <div>
        <p>Call me Ishmael.  Some years ago &ndash; never mind how long precisely &ndash; having little or no money in my purse, and nothing particular to interest me on shore, I thought I would sail about a little and see the watery part of the world.  It is a way I have of driving off the spleen, and regulating the circulation.  Whenever I find myself growing grim about the mouth; whenever it is a damp, drizzly November in my soul; whenever I find myself involuntarily pausing before coffin warehouses, and bringing up the rear of every funeral I meet; and especially whenever my hypos get such an upper hand of me, that it requires a strong moral principle to prevent me from deliberately stepping into the street, and methodically knocking people's hats off &ndash; then, I account it high time to get to sea as soon as I can.</p>  
    </div>
</div>

the fiddle

(resize browser's window for testing)

Get value of c# dynamic property via string

Dynamitey is an open source .net std library, that let's you call it like the dynamic keyword, but using the a string for the property name rather than the compiler doing it for you, and it ends up being equal to reflection speedwise (which is not nearly as fast as using the dynamic keyword, but this is due to the extra overhead of caching dynamically, where the compiler caches statically).

Dynamic.InvokeGet(d,"value2");

Select columns from result set of stored procedure

Easiest way to do if you only need to this once:

Export to excel in Import and Export wizard and then import this excel into a table.