Programs & Examples On #Spoofing

In networking, the term 'spoofing' is used to describe a variety of ways in which hardware and software can be fooled. There are various kind of spoofing such as IP spoofing, MAC spoofing, E-mail address spoofing, Caller ID spoofing, GPS Spoofing etc.

Disable / Check for Mock Location (prevent gps spoofing)

It seems that the only way to do this is to prevent Location Spoofing preventing MockLocations. The down side is there are some users who use Bluetooth GPS devices to get a better signal, they won't be able to use the app as they are required to use the mock locations.

To do this, I did the following :

// returns true if mock location enabled, false if not enabled.
if (Settings.Secure.getString(getContentResolver(),
       Settings.Secure.ALLOW_MOCK_LOCATION).equals("0")) 
       return false; 
       else return true;

Why does sudo change the PATH?

the recommended solution in the comments on the OpenSUSE distro suggests to change:

Defaults env_reset

to:

Defaults !env_reset

and then presumably to comment out the following line which isn't needed:

Defaults env_keep = "LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION LC_MEASURE    MENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE LC_TIME LC_ALL L    ANGUAGE LINGUAS XDG_SESSION_COOKIE"

How to open the second form?

Respectively Form.Show() (or Form.ShowDialog() if you want the second form to be modal), and Form.Hide() (or Form.Close(), depending on what you mean by close it).

In Mongoose, how do I sort by date? (node.js)

Been dealing with this issue today using Mongoose 3.5(.2) and none of the answers quite helped me solve this issue. The following code snippet does the trick

Post.find().sort('-posted').find(function (err, posts) {
    // user posts array
});

You can send any standard parameters you need to find() (e.g. where clauses and return fields) but no callback. Without a callback it returns a Query object which you chain sort() on. You need to call find() again (with or without more parameters -- shouldn't need any for efficiency reasons) which will allow you to get the result set in your callback.

Fatal error: "No Target Architecture" in Visual Studio

I had a similar problem. In my case, I had accidentally included winuser.h before windows.h (actually, a buggy IDE extension had added it). Removing the winuser.h solved the problem.

Best Regular Expression for Email Validation in C#

Email address: RFC 2822 Format
Matches a normal email address. Does not check the top-level domain.
Requires the "case insensitive" option to be ON.

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

Usage :

bool isEmail = Regex.IsMatch(emailString, @"\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z", RegexOptions.IgnoreCase);

Differences between Emacs and Vim

Vim:

  • better as a simple editor (fewer keys required for simple tasks)
  • more active scripting community - internal language: vimscript
  • one central repository of scripts, plugins, color schemes, ...
  • also extensible in python, ruby
  • can be made portable (emacs has some problems with that)

Emacs:

  • non modal by default (most of today's editors have taken this approach). Though there is evil-mode which emulates vim behavior.
  • more powerful language for extending it (elisp is a full blown language, and in emacs you can practically redefine everything; while in vim you cannot redefine build in functions of the editor. On the downside, vimscript is relatively similar to today's dynamic languages while elisp doesn't resemble pretty much anything)
  • more extendible
  • excellent support for GNU tools (the bunch of them)

Personally, I prefer vim - it is small, does what it's supposed to do, and when I wish a full blown IDE I open VS. Emacs's approach of being an editor which wants to be an IDE (or should I say, an OS), but is not quite, is IMHO, outdated. In the old days having a email client, ftp client, tetris, ... whatnot in one package (emacs) made some sense ... nowadays, it doesn't anymore.

Both are however a topic of religious discussions among the programmer and superuser community users, and in that respect, both are excellent for starting flame wars if put in contact (in the same sentence / question).

What does "ulimit -s unlimited" do?

ulimit -s unlimited lets the stack grow unlimited.

This may prevent your program from crashing if you write programs by recursion, especially if your programs are not tail recursive (compilers can "optimize" those), and the depth of recursion is large.

byte array to pdf

You shouldn't be using the BinaryFormatter for this - that's for serializing .Net types to a binary file so they can be read back again as .Net types.

If it's stored in the database, hopefully, as a varbinary - then all you need to do is get the byte array from that (that will depend on your data access technology - EF and Linq to Sql, for example, will create a mapping that makes it trivial to get a byte array) and then write it to the file as you do in your last line of code.

With any luck - I'm hoping that fileContent here is the byte array? In which case you can just do

System.IO.File.WriteAllBytes("hello.pdf", fileContent);

Generating random whole numbers in JavaScript in a specific range?

If you need variable between 0 and max you can use:

Math.floor(Math.random() *  max);

Coerce multiple columns to factors at once

and, for completeness and with regards to this question asking about changing string columns only, there's mutate_if:

data <- cbind(stringVar = sample(c("foo","bar"),10,replace=TRUE),
              data.frame(matrix(sample(1:40), 10, 10, dimnames = list(1:10, LETTERS[1:10]))),stringsAsFactors=FALSE)     

factoredData = data %>% mutate_if(is.character,funs(factor(.)))

Bootstrap throws Uncaught Error: Bootstrap's JavaScript requires jQuery

If you are using require.js than need to add window.$ = window.jQuery = require('jquery') in app.js

OR you can make dependent file load after parent file loaded.. such as below concept

require.config({
    baseUrl: "scripts/appScript",
    paths: {
        'jquery':'jQuery/jquery.min',
        'bootstrap':'bootstrap/bootstrap.min' 
    },
   shim
    shim: {
        'bootstrap':['jquery'],
        },

    // kick start application
    deps: ['app']
});

Above code shown that bootstrap is dependent on Jquery so i have added in shim and make it dependent

How to set 'X-Frame-Options' on iframe?

You can't set X-Frame-Options on the iframe. That is a response header set by the domain from which you are requesting the resource (google.com.ua in your example). They have set the header to SAMEORIGIN in this case, which means that they have disallowed loading of the resource in an iframe outside of their domain. For more information see The X-Frame-Options response header on MDN.

A quick inspection of the headers (shown here in Chrome developer tools) reveals the X-Frame-Options value returned from the host.

enter image description here

Swift days between two NSDates

Nice handy one liner :

extension Date {
  var daysFromNow: Int {
    return Calendar.current.dateComponents([.day], from: Date(), to: self).day!
  }
}

Java Code for calculating Leap Year

import javax.swing.*;
public class LeapYear {
    public static void main(String[] args) {
    int year;
String yearStr = JOptionPane.showInputDialog(null, "Enter radius: " );

year = Integer.parseInt( yearStr );

boolean isLeapYear;
isLeapYear = (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0);  

 if(isLeapYear){ 
JOptionPane.showMessageDialog(null, "Leap Year!"); 
 }  
 else{
JOptionPane.showMessageDialog(null, "Not a Leap Year!"); 
    }
    }
    }

What's your most controversial programming opinion?

Never make up your mind on an issue before thoroughly considering said issue. No programming standard EVER justifies approaching an issue in a poor manner. If the standard demands a class to be written, but after careful thought, you deem a static method to be more appropriate, always go with the static method. Your own discretion is always better than even the best forward thinking of whoever wrote the standard. Standards are great if you're working in a team, but rules are meant to be broken (in good taste, of course).

How to map and remove nil values in Ruby

Try using reduce or inject.

[1, 2, 3].reduce([]) { |memo, i|
  if i % 2 == 0
    memo << i
  end

  memo
}

I agree with the accepted answer that we shouldn't map and compact, but not for the same reasons.

I feel deep inside that map then compact is equivalent to select then map. Consider: map is a one-to-one function. If you are mapping from some set of values, and you map, then you want one value in the output set for each value in the input set. If you are having to select before-hand, then you probably don't want a map on the set. If you are having to select afterwards (or compact) then you probably don't want a map on the set. In either case you are iterating twice over the entire set, when a reduce only needs to go once.

Also, in English, you are trying to "reduce a set of integers into a set of even integers".

How to check if an object is an array?

there is a difference between checkout it's prototype and Array.isArray:

function isArray(obj){
    return Object.getPrototypeOf(obj) === Array.prototype
}

this function will directly check if an obj is an array

but for this Proxy object:

var arr = [1,2,3]

var proxy = new Proxy(arr,{})

console.log(Array.isArray(proxy)) // true

Array.isArray will take it as Array.

How can I autoformat/indent C code in vim?

The plugin vim-autoformat lets you format your buffer (or buffer selections) with a single command: https://github.com/Chiel92/vim-autoformat. It uses external format programs for that, with a fallback to vim's indentation functionality.

Need to get current timestamp in Java

The threadunsafety of SimpleDateFormat should not be an issue if you just create it inside the very same method block as you use it. In other words, you are not assigning it as static or instance variable of a class and reusing it in one or more methods which can be invoked by multiple threads. Only this way the threadunsafety of SimpleDateFormat will be exposed. You can however safely reuse the same SimpleDateFormat instance within the very same method block as it would be accessed by the current thread only.

Also, the java.sql.Timestamp class which you're using there should not be abused as it's specific to the JDBC API in order to be able to store or retrieve a TIMESTAMP/DATETIME column type in a SQL database and convert it from/to java.util.Date.

So, this should do:

Date date = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy h:mm:ss a");
String formattedDate = sdf.format(date);
System.out.println(formattedDate); // 12/01/2011 4:48:16 PM

Migration: Cannot add foreign key constraint

I had the same error with Laravel 5 when making a pivot table, and the problem in my case was that I didn't have

->onDelete('cascade');

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Here is a more complete example using a fieldset for accessibility reasons and specifying the first button as the default. Without a fieldset, what the radio buttons are for as a whole can not be programmatically determined.

Model

public class MyModel
{
    public bool IsMarried { get; set; }
}

View

<fieldset>
    <legend>Married</legend>

    @Html.RadioButtonFor(e => e.IsMarried, true, new { id = "married-true" })
    @Html.Label("married-true", "Yes")

    @Html.RadioButtonFor(e => e.IsMarried, false, new { id = "married-false" })
    @Html.Label("married-false", "No")
</fieldset>

You can add a @checked argument to the anonymous object to set the radio button as the default:

new { id = "married-true", @checked = 'checked' }

Note that you can bind to a string by replacing true and false with the string values.

Assign a class name to <img> tag instead of write it in css file?

I think the Class on img tag is better when You use the same style in different structure on Your site. You have to decide when you write less line of CSS code and HTML is more readable.

How to style the <option> with only CSS?

EDIT 2015 May

Disclaimer: I've taken the snippet from the answer linked below:

Important Update!

In addition to WebKit, as of Firefox 35 we'll be able to use the appearance property:

Using -moz-appearance with the none value on a combobox now remove the dropdown button

So now in order to hide the default styling, it's as easy as adding the following rules on our select element:

select {
   -webkit-appearance: none;
   -moz-appearance: none;
   appearance: none;
}

For IE 11 support, you can use [::-ms-expand][15].

select::-ms-expand { /* for IE 11 */
    display: none;
}

Old Answer

Unfortunately what you ask is not possible by using pure CSS. However, here is something similar that you can choose as a work around. Check the live code below.

_x000D_
_x000D_
div { _x000D_
  margin: 10px;_x000D_
  padding: 10px; _x000D_
  border: 2px solid purple; _x000D_
  width: 200px;_x000D_
  -webkit-border-radius: 5px;_x000D_
  -moz-border-radius: 5px;_x000D_
  border-radius: 5px;_x000D_
}_x000D_
div > ul { display: none; }_x000D_
div:hover > ul {display: block; background: #f9f9f9; border-top: 1px solid purple;}_x000D_
div:hover > ul > li { padding: 5px; border-bottom: 1px solid #4f4f4f;}_x000D_
div:hover > ul > li:hover { background: white;}_x000D_
div:hover > ul > li:hover > a { color: red; }
_x000D_
<div>_x000D_
  Select_x000D_
  <ul>_x000D_
    <li><a href="#">Item 1</a></li>_x000D_
    <li><a href="#">Item 2</a></li>_x000D_
    <li><a href="#">Item 3</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

EDIT

Here is the question that you asked some time ago. How to style a <select> dropdown with CSS only without JavaScript? As it tells there, only in Chrome and to some extent in Firefox you can achieve what you want. Otherwise, unfortunately, there is no cross browser pure CSS solution for styling a select.

What causes signal 'SIGILL'?

It could be some un-initialized function pointer, in particular if you have corrupted memory (then the bogus vtable of C++ bad pointers to invalid objects might give that).

BTW gdb watchpoints & tracepoints, and also valgrind might be useful (if available) to debug such issues. Or some address sanitizer.

How to add trendline in python matplotlib dot (scatter) graphs?

as explained here

With help from numpy one can calculate for example a linear fitting.

# plot the data itself
pylab.plot(x,y,'o')

# calc the trendline
z = numpy.polyfit(x, y, 1)
p = numpy.poly1d(z)
pylab.plot(x,p(x),"r--")
# the line equation:
print "y=%.6fx+(%.6f)"%(z[0],z[1])

HTML form do some "action" when hit submit button

Ok, I'll take a stab at this. If you want to work with PHP, you will need to install and configure both PHP and a webserver on your machine. This article might get you started: PHP Manual: Installation on Windows systems

Once you have your environment setup, you can start working with webforms. Directly From the article: Processing form data with PHP:

For this example you will need to create two pages. On the first page we will create a simple HTML form to collect some data. Here is an example:

<html>   
<head>
 <title>Test Page</title>
</head>   
<body>   
    <h2>Data Collection</h2><p>
    <form action="process.php" method="post">  
        <table>
            <tr>
                <td>Name:</td>
                <td><input type="text" name="Name"/></td>
            </tr>   
            <tr>
                <td>Age:</td>
                <td><input type="text" name="Age"/></td>
            </tr>   
            <tr>
                <td colspan="2" align="center">
                <input type="submit"/>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

This page will send the Name and Age data to the page process.php. Now lets create process.php to use the data from the HTML form we made:

<?php   
    print "Your name is ". $Name;   
    print "<br />";   
    print "You are ". $Age . " years old";   
    print "<br />";   $old = 25 + $Age;
    print "In 25 years you will be " . $old . " years old";   
?>

As you may be aware, if you leave out the method="post" part of the form, the URL with show the data. For example if your name is Bill Jones and you are 35 years old, our process.php page will display as http://yoursite.com/process.php?Name=Bill+Jones&Age=35 If you want, you can manually change the URL in this way and the output will change accordingly.

Additional JavaScript Example

This single file example takes the html from your question and ties the onSubmit event of the form to a JavaScript function that pulls the values of the 2 textboxes and displays them in an alert box.

Note: document.getElementById("fname").value gets the object with the ID tag that equals fname and then pulls it's value - which in this case is the text in the First Name textbox.

 <html>
    <head>
     <script type="text/javascript">
     function ExampleJS(){
        var jFirst = document.getElementById("fname").value;
        var jLast = document.getElementById("lname").value;
        alert("Your name is: " + jFirst + " " + jLast);
     }
     </script>

    </head>
    <body>
        <FORM NAME="myform" onSubmit="JavaScript:ExampleJS()">

             First name: <input type="text" id="fname" name="firstname" /><br />
             Last name:  <input type="text" id="lname" name="lastname" /><br />
            <input name="Submit"  type="submit" value="Update" />
        </FORM>
    </body>
</html>

How can I check for existence of element in std::vector, in one line?

int elem = 42;
std::vector<int> v;
v.push_back(elem);
if(std::find(v.begin(), v.end(), elem) != v.end())
{
  //elem exists in the vector
} 

How can I disable selected attribute from select2() dropdown Jquery?

In selec2 site you can see options. There is "disabled" option for api. You can use like :

$('#foo').select2({
    disabled: true
});

How can I change all input values to uppercase using Jquery?

Use css text-transform to display text in all input type text. In Jquery you can then transform the value to uppercase on blur event.

Css:

input[type=text] {
    text-transform: uppercase;
}

Jquery:

$(document).on('blur', "input[type=text]", function () {
    $(this).val(function (_, val) {
        return val.toUpperCase();
    });
});

How to sum up an array of integers in C#

If you don't prefer LINQ, it is better to use foreach loop to avoid out of index.

int[] arr = new int[] { 1, 2, 3 };
int sum = 0;
foreach (var item in arr)
{
   sum += item;
}

SQL server stored procedure return a table

The Status Value being returned by a Stored Procedure can only be an INT datatype. You cannot return other datatypes in the RETURN statement.

From Lesson 2: Designing Stored Procedures:

Every stored procedure can return an integer value known as the execution status value or return code.

If you still want a table returned from the SP, you'll either have to work the record set returned from a SELECT within the SP or tie into an OUTPUT variable that passes an XML datatype.

HTH,

John

How to divide two columns?

Presumably, those columns are integer columns - which will be the reason as the result of the calculation will be of the same type.

e.g. if you do this:

SELECT 1 / 2

you will get 0, which is obviously not the real answer. So, convert the values to e.g. decimal and do the calculation based on that datatype instead.

e.g.

SELECT CAST(1 AS DECIMAL) / 2

gives 0.500000

How do I make a C++ console program exit?

There are several ways to cause your program to terminate. Which one is appropriate depends on why you want your program to terminate. The vast majority of the time it should be by executing a return statement in your main function. As in the following.

int main()
{
     f();
     return 0;
}

As others have identified this allows all your stack variables to be properly destructed so as to clean up properly. This is very important.

If you have detected an error somewhere deep in your code and you need to exit out you should throw an exception to return to the main function. As in the following.

struct stop_now_t { };
void f()
{
      // ...
      if (some_condition())
           throw stop_now_t();
      // ...
}

int main()
{
     try {
          f();
     } catch (stop_now_t& stop) {
          return 1;
     }
     return 0;
 }

This causes the stack to be unwound an all your stack variables to be destructed. Still very important. Note that it is appropriate to indicate failure with a non-zero return value.

If in the unlikely case that your program detects a condition that indicates it is no longer safe to execute any more statements then you should use std::abort(). This will bring your program to a sudden stop with no further processing. std::exit() is similar but may call atexit handlers which could be bad if your program is sufficiently borked.

Getting a count of objects in a queryset in django

To get the number of votes for a specific item, you would use:

vote_count = Item.objects.filter(votes__contest=contestA).count()

If you wanted a break down of the distribution of votes in a particular contest, I would do something like the following:

contest = Contest.objects.get(pk=contest_id)
votes   = contest.votes_set.select_related()

vote_counts = {}

for vote in votes:
  if not vote_counts.has_key(vote.item.id):
    vote_counts[vote.item.id] = {
      'item': vote.item,
      'count': 0
    }

  vote_counts[vote.item.id]['count'] += 1

This will create dictionary that maps items to number of votes. Not the only way to do this, but it's pretty light on database hits, so will run pretty quickly.

JQUERY: Uncaught Error: Syntax error, unrecognized expression

I had to look a little more to solve my problem but what solved it was finding where the error was. Here It shows how to do that in Jquery's error dump.

In my case id was empty and $("#" + id);; produces the error.

It was where I wasn't looking so that helped pinpoint where it was so I could troubleshoot and fix it.

How to insert a line break <br> in markdown

Just adding a new line worked for me if you're to store the markdown in a JavaScript variable. like so

let markdown = `
    1. Apple
    2. Mango
     this is juicy
    3. Orange
`

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

CSS two divs next to each other

This won't be the answer for everyone, since it is not supported in IE7-, but you could use it and then use an alternate answer for IE7-. It is display: table, display: table-row and display: table-cell. Note that this is not using tables for layout, but styling divs so that things line up nicely with out all the hassle from above. Mine is an html5 app, so it works great.

This article shows an example: http://www.sitepoint.com/table-based-layout-is-the-next-big-thing/

Here is what your stylesheet will look like:

 .container {
    display: table;
    width:100%;
 }

 .left-column {
    display: table-cell;
 }

 .right-column {
    display: table-cell;
    width: 200px;
 }

Display the binary representation of a number in C?

You have to write your own transformation. Only decimal, hex and octal numbers are supported with format specifiers.

Where can I find the default timeout settings for all browsers?

For Google Chrome (Tested on ver. 62)

I was trying to keep a socket connection alive from the google chrome's fetch API to a remote express server and found the request headers have to match Node.JS's native <net.socket> connection settings.

I set the headers object on my client-side script with the following options:

/* ----- */
head = new headers();
head.append("Connnection", "keep-alive")
head.append("Keep-Alive", `timeout=${1*60*5}`) //in seconds, not milliseconds
/* apply more definitions to the header */
fetch(url, {
    method: 'OPTIONS',
    credentials: "include",
    body: JSON.stringify(data),
    cors: 'cors',
    headers: head, //could be object literal too
    cache: 'default'
 })
 .then(response=>{
    ....
  }).catch(err=>{...});

And on my express server I setup my router as follows:

 router.head('absolute or regex', (request, response, next)=>{
  req.setTimeout(1000*60*5, ()=>{
     console.info("socket timed out");
   });
  console.info("Proceeding down the middleware chain link...\n\n");
  next();
 });

 /*Keep the socket alive by enabling it on the server, with an optional 
  delay on the last packet sent 
 */
server.on('connection', (socket)=>socket.setKeepAlive(true, 10))

WARNING

Please use common sense and make sure the users you're keeping the socket connection open to is validated and serialized. It works for Firefox as well, but it's really vulnerable if you keep the TCP connection open for longer than 5 minutes.

I'm not sure how some of the lesser known browsers operate, but I'll append to this answer with the Microsoft browser details as well.

Reading file from Workspace in Jenkins with Groovy script

As mentioned in a different post Read .txt file from workspace groovy script in Jenkins I was struggling to make it work for the pom modules for a file in the workspace, in the Extended Choice Parameter. Here is my solution with the printlns:

import groovy.util.XmlSlurper
import java.util.Map
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*    

try{
//get Jenkins instance
    def jenkins = Jenkins.instance
//get job Item
    def item = jenkins.getItemByFullName("The_JOB_NAME")
    println item
// get workspacePath for the job Item
    def workspacePath = jenkins.getWorkspaceFor (item)
    println workspacePath

    def file = new File(workspacePath.toString()+"\\pom.xml")
    def pomFile = new XmlSlurper().parse(file)
    def pomModules = pomFile.modules.children().join(",")
    return pomModules
} catch (Exception ex){
    println ex.message
}

What is an unsigned char?

An unsigned char is an unsigned byte value (0 to 255). You may be thinking of char in terms of being a "character" but it is really a numerical value. The regular char is signed, so you have 128 values, and these values map to characters using ASCII encoding. But in either case, what you are storing in memory is a byte value.

jQuery - Appending a div to body, the body is the object?

    $('body').append($('<div/>', {
        id: 'holdy' 
    }));

lvalue required as left operand of assignment

Change = to == i.e if (strcmp("hello", "hello") == 0)

You want to compare the result of strcmp() to 0. So you need ==. Assigning it to 0 won't work because rvalues cannot be assigned to.

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

How do I add an active class to a Link from React Router?

To set class on the active navigation element

import { NavLink } from 'react-router-dom';

&

<NavLink to="/Home" activeClassName="active">Home</NavLink>

Ruby on Rails: Clear a cached page

If you're doing fragment caching, you can manually break the cache by updating your cache key, like so:

Version #1

<% cache ['cool_name_for_cache_key', 'v1'] do %>

Version #2

<% cache ['cool_name_for_cache_key', 'v2'] do %>

Or you can have the cache automatically reset based on the state of a non-static object, such as an ActiveRecord object, like so:

<% cache @user_object do %>

With this ^ method, any time the user object is updated, the cache will automatically be reset.

MySQL: Curdate() vs Now()

For questions like this, it is always worth taking a look in the manual first. Date and time functions in the mySQL manual

CURDATE() returns the DATE part of the current time. Manual on CURDATE()

NOW() returns the date and time portions as a timestamp in various formats, depending on how it was requested. Manual on NOW().

How to get the background color of an HTML element?

Simple solution

myDivObj = document.getElementById("myDivID")
let myDivObjBgColor = window.getComputedStyle(myDivObj).backgroundColor;

Now the background color is stored in the new variable.

https://jsfiddle.net/7q1dpeo9/1/

python numpy machine epsilon

An easier way to get the machine epsilon for a given float type is to use np.finfo():

print(np.finfo(float).eps)
# 2.22044604925e-16

print(np.finfo(np.float32).eps)
# 1.19209e-07

Programmatically Add CenterX/CenterY Constraints

The ObjectiveC equivalent is:

    myView.translatesAutoresizingMaskIntoConstraints = NO;

    [[myView.centerXAnchor constraintEqualToAnchor:self.view.centerXAnchor] setActive:YES];

    [[myView.centerYAnchor constraintEqualToAnchor:self.view.centerYAnchor] setActive:YES];

Easy way to prevent Heroku idling?

Tested and working on my own Heroku app using Node.js 0.10.x on 6/28/2013

var http = require('http'); //importing http

function startKeepAlive() {
    setInterval(function() {
        var options = {
            host: 'your_app_name.herokuapp.com',
            port: 80,
            path: '/'
        };
        http.get(options, function(res) {
            res.on('data', function(chunk) {
                try {
                    // optional logging... disable after it's working
                    console.log("HEROKU RESPONSE: " + chunk);
                } catch (err) {
                    console.log(err.message);
                }
            });
        }).on('error', function(err) {
            console.log("Error: " + err.message);
        });
    }, 20 * 60 * 1000); // load every 20 minutes
}

startKeepAlive();

How to use Simple Ajax Beginform in Asp.net MVC 4?

Besides the previous post instructions, I had to install the package Microsoft.jQuery.Unobtrusive.Ajax and add to the view the following line

<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.js")" type="text/javascript"></script>

'foo' was not declared in this scope c++

In C++ you are supposed to declare functions before you can use them. In your code integrate is not declared before the point of the first call to integrate. The same applies to sum. Hence the error. Either reorder your definitions so that function definition precedes the first call to that function, or introduce a [forward] non-defining declaration for each function.

Additionally, defining external non-inline functions in header files in a no-no in C++. Your definitions of SkewNormalEvalutatable::SkewNormalEvalutatable, getSkewNormal, integrate etc. have no business being in header file.

Also SkewNormalEvalutatable e(); declaration in C++ declares a function e, not an object e as you seem to assume. The simple SkewNormalEvalutatable e; will declare an object initialized by default constructor.

Also, you receive the last parameter of integrate (and of sum) by value as an object of Evaluatable type. That means that attempting to pass SkewNormalEvalutatable as last argument of integrate will result in SkewNormalEvalutatable getting sliced to Evaluatable. Polymorphism won't work because of that. If you want polymorphic behavior, you have to receive this parameter by reference or by pointer, but not by value.

A python class that acts like dict

Don’t inherit from Python built-in dict, ever! for example update method woldn't use __setitem__, they do a lot for optimization. Use UserDict.

from collections import UserDict

class MyDict(UserDict):
    def __delitem__(self, key):
        pass
    def __setitem__(self, key, value):
        pass

How to group by month from Date field using sql

SQL Server 2012 version above,

SELECT  format(Closing_Date,'yyyy-MM') as ClosingMonth,
        Category,  
        COUNT(Status) TotalCount 
FROM    MyTable
WHERE   Closing_Date >= '2012-02-01' 
AND     Closing_Date <= '2012-12-31'
AND     Defect_Status1 IS NOT NULL
GROUP BY format(Closing_Date,'yyyy-MM'), Category;

Detect if a page has a vertical scrollbar?

I wrote an updated version of Kees C. Bakker's answer:

const hasVerticalScroll = (node) => {
  if (!node) {
    if (window.innerHeight) {
      return document.body.offsetHeight > window.innerHeight
    }
    return (document.documentElement.scrollHeight > document.documentElement.offsetHeight)
      || (document.body.scrollHeight > document.body.offsetHeight)
  }
  return node.scrollHeight > node.offsetHeight
}

if (hasVerticalScroll(document.querySelector('body'))) {
  this.props.handleDisableDownScrollerButton()
}

The function returns true or false depending whether the page has a vertical scrollbar or not.

For example:

const hasVScroll = hasVerticalScroll(document.querySelector('body'))

if (hasVScroll) {
  console.log('HAS SCROLL', hasVScroll)
}

Difference between nVidia Quadro and Geforce cards?

The difference is in view-port wire-frame rendering and double-sided polygon rendering, which is very common in professional CAD/3D software but not in games.

The difference is almost 10x-13x faster in single-fixed rendering pipeline (now very obsolete but some CAD software using it) rendering double sided polygons and wireframes:

enter image description here

Thats how entry level Quadro beats high-end GeForce. At least in the single-fixed pipeline using legacy calls like glLightModel(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE). The trick is done with driver optimization (does not matter if its single-fixed pipeline Direct3D or OpenGL). And its true that on some GeForce cards some firmware/hardware hacking can unlock the features.

If double sided is implemented using shader code, the GeForce has to render the polygon twice giving the Quadro only 2x the speed difference (it's less in real-world). The wireframe rendering remains much much slower on GeForce even if implemented in a modern way.

Todays GeForce cards can render millions of polygons per second, drawing lines with faded polygons can result in 100x speed difference eliminating the Quadro benefit.

Quadro equivalent GTX cards have usually better clock speeds giving 2%-10% better performance in games.


So to sum up:

The Quadro rules the single-fixed legacy now obsolete rendering pipeline (which CAD uses), but by implementing modern rendering methods this can be significantly reduced (virtually no speed gain in Maya's Viewport 2.0, it uses GLSL effects - very similar to game engine).

Other reasons to get Quadro are double precision float computations for science, better warranty and display's support for professionals.

That's about it, price-vise the Quadros or FirePros are artificially overpriced.

How can I make the contents of a fixed element scrollable only when it exceeds the height of the viewport?

I'm presenting this as a workaround rather than a solution. This may not work all the time. I did it this way as I'm doing a very basic HTML page, for internal use, in a very bizarre environment. I know there are libraries like MaterializeCSS that can do really nice nav bars. (I was going to use them, but it didn't work with my environment.)

<div id="nav" style="position:fixed;float:left;overflow-y:hidden;width:10%;"></div>
<div style="margin-left:10%;float:left;overflow-y:auto;width:60%;word-break:break-all;word-wrap:break-word;" id="content"></div>

Open an image using URI in Android's default gallery image viewer

Accepted answer was not working for me,

What had worked:

Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + "/sdcard/test.jpg"), "image/*");
startActivity(intent);

Set line height in Html <p> to make the html looks like a office word when <p> has different font sizes

I found that in my code when I used a ration or percentage for line-height line-height;1.5;

My page would scale in such a way that lower case font and upper case font would take up different page heights (I.E. All caps took more room than all lower). Normally I think this looks better, but I had to go to a fixed height line-height:24px; so that I could predict exactly how many pixels each page would take with a given number of lines.

How to write to a file without overwriting current contents?

Instead of "w" use "a" (append) mode with open function:

with open("games.txt", "a") as text_file:

How can I tell if a DOM element is visible in the current viewport?

I had the same question and figured it out by using getBoundingClientRect().

This code is completely 'generic' and only has to be written once for it to work (you don't have to write it out for each element that you want to know is in the viewport).

This code only checks to see if it is vertically in the viewport, not horizontally. In this case, the variable (array) 'elements' holds all the elements that you are checking to be vertically in the viewport, so grab any elements you want anywhere and store them there.

The 'for loop', loops through each element and checks to see if it is vertically in the viewport. This code executes every time the user scrolls! If the getBoudingClientRect().top is less than 3/4 the viewport (the element is one quarter in the viewport), it registers as 'in the viewport'.

Since the code is generic, you will want to know 'which' element is in the viewport. To find that out, you can determine it by custom attribute, node name, id, class name, and more.

Here is my code (tell me if it doesn't work; it has been tested in Internet Explorer 11, Firefox 40.0.3, Chrome Version 45.0.2454.85 m, Opera 31.0.1889.174, and Edge with Windows 10, [not Safari yet])...

// Scrolling handlers...
window.onscroll = function(){
  var elements = document.getElementById('whatever').getElementsByClassName('whatever');
  for(var i = 0; i != elements.length; i++)
  {
   if(elements[i].getBoundingClientRect().top <= window.innerHeight*0.75 &&
      elements[i].getBoundingClientRect().top > 0)
   {
      console.log(elements[i].nodeName + ' ' +
                  elements[i].className + ' ' +
                  elements[i].id +
                  ' is in the viewport; proceed with whatever code you want to do here.');
   }
};

Assembly code vs Machine code vs Object code?

Assembly is short descriptive terms humans can understand that can be directly translated into the machine code that a CPU actually uses.

While somewhat understandable by humans, Assembler is still low level. It takes a lot of code to do anything useful.

So instead we use higher level languages such as C, BASIC, FORTAN (OK I know I've dated myself). When compiled these produce object code. Early languages had machine language as their object code.

Many languages today such a JAVA and C# usually compile into a bytecode that is not machine code, but one that easily be interpreted at run time to produce machine code.

Create a root password for PHPMyAdmin

Here the simple step that you can easily set phpMyAdmin Password.

  1. Goto C:\xampp\phpMyAdmin and find config.inc.php file
  2. Open config.inc.php file in Text editor like Notepad++.
  3. Find the line $cfg['Servers'][$a]['auth_type'] = 'config'; in config.inc.php file.
  4. Change the word $cfg['Servers'][$a]['auth_type'] = 'config'; to $cfg['Servers'][$a]['auth_type'] = 'cookie'; in config.inc.php file and Save the changes.
  5. Now open browser and type localhost/phpmyadmin. Enter username is root. password is null means empty. you don't type anything leave blank and press GO button.
  6. Now you can see change password link. please click that link.
  7. Set your phpMyAdmin password and retype again and press GO button.

How to set minDate to current date in jQuery UI Datepicker?

You can specify minDate as today by adding minDate: 0 to the options.

$("input.DateFrom").datepicker({
    minDate: 0,
    ...
});

Demo: http://jsfiddle.net/2CZtV/

Docs: http://jqueryui.com/datepicker/#min-max

Error: No default engine was specified and no extension was provided

You can use express-error-handler to use static html pages for error handling and to avoid defining a view handler.

The error was probably caused by a 404, maybe a missing favicon (apparent if you had included the previous console message). The 'view handler' of 'html' doesn't seem to be valid in 4.x express.

Regardless of the cause, you can avoid defining a (valid) view handler as long as you modify additional elements of your configuration.

Your options are to fix this problem are:

  • Define a valid view handler as in other answers
  • Use send() instead of render to return the content directly

http://expressjs.com/en/api.html#res.render

Using render without a filepath automatically invokes a view handler as with the following two lines from your configuration:

res.render('404', { url: req.url });

and:

res.render('500);

Make sure you install express-error-handler with:

npm install --save express-error-handler

Then import it in your app.js

var ErrorHandler = require('express-error-handler');

Then change your error handling to use:

// define below all other routes
var errorHandler = ErrorHandler({
  static: {
    '404': 'error.html' // put this file in your Public folder
    '500': 'error.html' // ditto
});

// any unresolved requests will 404
app.use(function(req,res,next) {
  var err = new Error('Not Found');
  err.status(404);
  next(err);
}

app.use(errorHandler);

How can I display a messagebox in ASP.NET?

you can use clientscript. MSDN : Clientscript

String scriptText = 
        "alert('sdsd');";
    ClientScript.RegisterOnSubmitStatement(this.GetType(), 
        "ConfirmSubmit", scriptText);

try this

ClientScript.RegisterStartupScript(this.GetType(), "JSScript", scriptText); 



ClientScript.RegisterClientScriptBlock(this.GetType(), "alert", scriptText); //use this 

Nth word in a string variable

Using awk

echo $STRING | awk -v N=$N '{print $N}'

Test

% N=3
% STRING="one two three four"
% echo $STRING | awk -v N=$N '{print $N}'
three

Create a file if it doesn't exist

If you don't need atomicity you can use os module:

import os

if not os.path.exists('/tmp/test'):
    os.mknod('/tmp/test')

UPDATE:

As Cory Klein mentioned, on Mac OS for using os.mknod() you need a root permissions, so if you are Mac OS user, you may use open() instead of os.mknod()

import os

if not os.path.exists('/tmp/test'):
    with open('/tmp/test', 'w'): pass

JVM option -Xss - What does it do exactly?

It indeed sets the stack size on a JVM.

You should touch it in either of these two situations:

  • StackOverflowError (the stack size is greater than the limit), increase the value
  • OutOfMemoryError: unable to create new native thread (too many threads, each thread has a large stack), decrease it.

The latter usually comes when your Xss is set too large - then you need to balance it (testing!)

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

I have this problem when update android studio from 3.2 to 3.3 and test every answers that i none of them was working. at the end i enabled Maven repository and its work.

enter image description here

hide div tag on mobile view only?

Set the display property to none as the default, then use a media query to apply the desired styles to the div when the browser reaches a certain width. Replace 768px in the media query with whatever the minimum px value is where your div should be visible.

#title_message {
    display: none;
}

@media screen and (min-width: 768px) {
    #title_message {
        clear: both;
        display: block;
        float: left;
        margin: 10px auto 5px 20px;
        width: 28%;
    }
}

android set button background programmatically

Further from @finnmglas, the Java answer as of 2021 is:

    if (Build.VERSION.SDK_INT >= 29)
        btn.getBackground().setColorFilter(new BlendModeColorFilter(color, BlendMode.MULTIPLY));
    else
        btn.getBackground().setColorFilter(color, PorterDuff.Mode.MULTIPLY);

Max or Default?

One interesting difference that seems worth noting is that while FirstOrDefault and Take(1) generate the same SQL (according to LINQPad, anyway), FirstOrDefault returns a value--the default--when there are no matching rows and Take(1) returns no results... at least in LINQPad.

Convert string to hex-string in C#

For Unicode support:

public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}

How do I print a double value without scientific notation using Java?

Java prevent E notation in a double:

Five different ways to convert a double to a normal number:

import java.math.BigDecimal;
import java.text.DecimalFormat;

public class Runner {
    public static void main(String[] args) {
        double myvalue = 0.00000021d;

        //Option 1 Print bare double.
        System.out.println(myvalue);

        //Option2, use decimalFormat.
        DecimalFormat df = new DecimalFormat("#");
        df.setMaximumFractionDigits(8);
        System.out.println(df.format(myvalue));

        //Option 3, use printf.
        System.out.printf("%.9f", myvalue);
        System.out.println();

        //Option 4, convert toBigDecimal and ask for toPlainString().
        System.out.print(new BigDecimal(myvalue).toPlainString());
        System.out.println();

        //Option 5, String.format 
        System.out.println(String.format("%.12f", myvalue));
    }
}

This program prints:

2.1E-7
.00000021
0.000000210
0.000000210000000000000001085015324114868562332958390470594167709350585
0.000000210000

Which are all the same value.

Protip: If you are confused as to why those random digits appear beyond a certain threshold in the double value, this video explains: computerphile why does 0.1+0.2 equal 0.30000000000001?

http://youtube.com/watch?v=PZRI1IfStY0

Fastest method of screen capturing on Windows

In my Impression, the GDI approach and the DX approach are different in its nature. painting using GDI applies the FLUSH method, the FLUSH approach draws the frame then clear it and redraw another frame in the same buffer, this will result in flickering in games require high frame rate.

  1. WHY DX quicker? in DX (or graphics world), a more mature method called double buffer rendering is applied, where two buffers are present, when present the front buffer to the hardware, you can render to the other buffer as well, then after the frame 1 is finished rendering, the system swap to the other buffer( locking it for presenting to hardware , and release the previous buffer ), in this way the rendering inefficiency is greatly improved.
  2. WHY turning down hardware acceleration quicker? although with double buffer rendering, the FPS is improved, but the time for rendering is still limited. modern graphic hardware usually involves a lot of optimization during rendering typically like anti-aliasing, this is very computation intensive, if you don't require that high quality graphics, of course you can just disable this option. and this will save you some time.

I think what you really need is a replay system, which I totally agree with what people discussed.

Posting array from form

Give each input a name in array format:

<input type="hidden" name="data[EstPriceInput]" value="" />

Then the in PHP $_POST['data']; will be an array:

  print_r($_POST);         // print out the whole post
  print_r($_POST['data']); // print out only the data array

Expected response code 220 but got code "", with message "" in Laravel

This problem can generally occur when you do not enable two step verification for the gmail account (which can be done here) you are using to send an email. So first, enable two step verification, you can find plenty of resources for enabling two step verification. After you enable it, then you have to create an app password. And use the app password in your .env file. When you are done with it, your .env file will look something like.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<<your email address>>
MAIL_PASSWORD=<<app password>>
MAIL_ENCRYPTION=tls

and your mail.php

<?php

return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.gmail.com'),
    'port' => env('MAIL_PORT', 587),
    'from' => ['address' => '<<your email>>', 'name' => '<<any name>>'],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => false,

];

After doing so, run php artisan config:cache and php artisan config:clear, then check, email should work.

Rotate an image in image source in html

This CSS seems to work in Safari and Chrome:

div#div2
{
-webkit-transform:rotate(90deg); /* Chrome, Safari, Opera */
transform:rotate(90deg); /* Standard syntax */
}

and in the body:

<div id="div2"><img src="image.jpg"  ></div>

But this (and the .rotate90 example above) pushes the rotated image higher up on the page than if it were un-rotated. Not sure how to control placement of the image relative to text or other rotated images.

TCPDF Save file to folder?

$pdf->Output( "myfile.pdf", "F");

TCPDF ERROR: Unable to create output file: myfile.pdf

In the include/tcpdf_static.php file about 2435 line in the static function fopenLocal if I delete the complete 'if statement' it works fine.

public static function fopenLocal($filename, $mode) {
    /*if (strpos($filename, '://') === false) {
        $filename = 'file://'.$filename;
    } elseif (strpos($filename, 'file://') !== 0) {
        return false;
    }*/
    return fopen($filename, $mode);
}

Remove title in Toolbar in appcompat-v7

 Toolbar actionBar = (Toolbar)findViewById(R.id.toolbar);
    actionBar.addView(view);
    setSupportActionBar(actionBar);
    getSupportActionBar().setDisplayShowTitleEnabled(false);

take note of this line getSupportActionBar().setDisplayShowTitleEnabled(false);

Crop image in android

Can you use default android Crop functionality?

Here is my code

private void performCrop(Uri picUri) {
    try {
        Intent cropIntent = new Intent("com.android.camera.action.CROP");
        // indicate image type and Uri
        cropIntent.setDataAndType(picUri, "image/*");
        // set crop properties here
        cropIntent.putExtra("crop", true);
        // indicate aspect of desired crop
        cropIntent.putExtra("aspectX", 1);
        cropIntent.putExtra("aspectY", 1);
        // indicate output X and Y
        cropIntent.putExtra("outputX", 128);
        cropIntent.putExtra("outputY", 128);
        // retrieve data on return
        cropIntent.putExtra("return-data", true);
        // start the activity - we handle returning in onActivityResult
        startActivityForResult(cropIntent, PIC_CROP);
    }
    // respond to users whose devices do not support the crop action
    catch (ActivityNotFoundException anfe) {
        // display an error message
        String errorMessage = "Whoops - your device doesn't support the crop action!";
        Toast toast = Toast.makeText(this, errorMessage, Toast.LENGTH_SHORT);
        toast.show();
    }
}

declare:

final int PIC_CROP = 1;

at top.

In onActivity result method, writ following code:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == PIC_CROP) {
        if (data != null) {
            // get the returned data
            Bundle extras = data.getExtras();
            // get the cropped bitmap
            Bitmap selectedBitmap = extras.getParcelable("data");

            imgView.setImageBitmap(selectedBitmap);
        }
    }
}

It is pretty easy for me to implement and also shows darken areas.

Virtual Memory Usage from Java under Linux, too much memory used

There is a known problem with Java and glibc >= 2.10 (includes Ubuntu >= 10.04, RHEL >= 6).

The cure is to set this env. variable:

export MALLOC_ARENA_MAX=4

If you are running Tomcat, you can add this to TOMCAT_HOME/bin/setenv.sh file.

For Docker, add this to Dockerfile

ENV MALLOC_ARENA_MAX=4

There is an IBM article about setting MALLOC_ARENA_MAX https://www.ibm.com/developerworks/community/blogs/kevgrig/entry/linux_glibc_2_10_rhel_6_malloc_may_show_excessive_virtual_memory_usage?lang=en

This blog post says

resident memory has been known to creep in a manner similar to a memory leak or memory fragmentation.

There is also an open JDK bug JDK-8193521 "glibc wastes memory with default configuration"

search for MALLOC_ARENA_MAX on Google or SO for more references.

You might want to tune also other malloc options to optimize for low fragmentation of allocated memory:

# tune glibc memory allocation, optimize for low fragmentation
# limit the number of arenas
export MALLOC_ARENA_MAX=2
# disable dynamic mmap threshold, see M_MMAP_THRESHOLD in "man mallopt"
export MALLOC_MMAP_THRESHOLD_=131072
export MALLOC_TRIM_THRESHOLD_=131072
export MALLOC_TOP_PAD_=131072
export MALLOC_MMAP_MAX_=65536

jQuery if Element has an ID?

You can using the following code:

   if($(".parent a").attr('id')){

      //do something
   }


   $(".parent a").each(function(i,e){
       if($(e).attr('id')){
          //do something and check
          //if you want to break the each
          //return false;
       }
   });

The same question is you can find here: how to check if div has id or not?

Page scroll when soft keyboard popped up

Also if you want to do that programmatically just add the below line to the onCreate of the activity.

getWindow().setSoftInputMode(
            WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE | 
            WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE );

How do I free memory in C?

You actually can't manually "free" memory in C, in the sense that the memory is released from the process back to the OS ... when you call malloc(), the underlying libc-runtime will request from the OS a memory region. On Linux, this may be done though a relatively "heavy" call like mmap(). Once this memory region is mapped to your program, there is a linked-list setup called the "free store" that manages this allocated memory region. When you call malloc(), it quickly looks though the free-store for a free block of memory at the size requested. It then adjusts the linked list to reflect that there has been a chunk of memory taken out of the originally allocated memory pool. When you call free() the memory block is placed back in the free-store as a linked-list node that indicates its an available chunk of memory.

If you request more memory than what is located in the free-store, the libc-runtime will again request more memory from the OS up to the limit of the OS's ability to allocate memory for running processes. When you free memory though, it's not returned back to the OS ... it's typically recycled back into the free-store where it can be used again by another call to malloc(). Thus, if you make a lot of calls to malloc() and free() with varying memory size requests, it could, in theory, cause a condition called "memory fragmentation", where there is enough space in the free-store to allocate your requested memory block, but not enough contiguous space for the size of the block you've requested. Thus the call to malloc() fails, and you're effectively "out-of-memory" even though there may be plenty of memory available as a total amount of bytes in the free-store.

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

Well.. for me it was Telerik JustMock Q3 2013 (13.3.1015.0) that caused the problem. Uninstalled it from VS 2013 and the problem has gone..

see also ASP.NET-MVC4 Code Not Running and http://feedback.telerik.com/Project/105/Feedback/Details/63749-unable-to-debug-asp-net-projects-with-q3-2013

One lost day and many new white hairs... Curse on you Telerik guys! ;)

Nested JSON objects - do I have to use arrays for everything?

You don't need to use arrays.

JSON values can be arrays, objects, or primitives (numbers or strings).

You can write JSON like this:

{ 
    "stuff": {
        "onetype": [
            {"id":1,"name":"John Doe"},
            {"id":2,"name":"Don Joeh"}
        ],
        "othertype": {"id":2,"company":"ACME"}
    }, 
    "otherstuff": {
        "thing": [[1,42],[2,2]]
     }
}

You can use it like this:

obj.stuff.onetype[0].id
obj.stuff.othertype.id
obj.otherstuff.thing[0][1]  //thing is a nested array or a 2-by-2 matrix.
                            //I'm not sure whether you intended to do that.

Converting java date to Sql timestamp

I suggest using DateUtils from apache.commons library.

long millis = DateUtils.truncate(utilDate, Calendar.MILLISECOND).getTime();
java.sql.Timestamp sq = new java.sql.Timestamp(millis );

Edit: Fixed Calendar.MILISECOND to Calendar.MILLISECOND

How to set the From email address for mailx command?

You can use the "-r" option to set the sender address:

mailx -r [email protected] -s ...

Basic text editor in command prompt?

MS-DOS Editor (or just edit) is a 16-bit text editor that is still included with 32-bit versions of Windows XP, Vista, 7, 8 and 8.1. It can edit files upto 65,279 lines long and has mouse support. Being an 16-bit DOS editor, it cannot run directly on 64-bit versions of Windows. It can be launched by typing edit at the command prompt.

Android Recyclerview vs ListView with Viewholder

The other plus of using RecycleView is animation, it can be done in two lines of code

RecyclerView.ItemAnimator itemAnimator = new DefaultItemAnimator();
        recyclerView.setItemAnimator(itemAnimator);

But the widget is still raw, e.g you can't create header and footer.

Restore the mysql database from .frm files

I just copy pasted the database folders to data folder in MySQL, i.e. If you have a database called alto then find the folder alto in your MySQL -> Data folder in your backup and copy the entire alto folder and past it to newly installed MySQL -> data folder, restart the MySQL and this works perfect.

jQuery: get parent, parent id?

 $(this).closest('ul').attr('id');

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

YES!....always style textarea using CSS and avoid the attributes, unless you need to support some very old agent that does not support style sheets. Otherwise, you have full power to use CSS. Below is my default CSS formatting for textarea that looks beautiful in any website. Customize it as you like. Comments are included below so you can see why I chose those CSS properties and values:

textarea {
    display: inline-block;
    margin: 0;
    padding: .2em;
    width: auto;
    min-width: 30em;
    /* The max-width "100%" value fixes a weird issue where width is too wide by default and extends beyond 100% of the parent in some agents. */
    max-width: 100%;
    /* Height "auto" will allow the text area to expand vertically in size with a horizontal scrollbar if pre-existing content is added to the box before rendering. Remove this if you want a pre-set height. Use "em" to match the font size set in the website. */
    height: auto;
    /* Use "em" to define the height based on the text size set in your website and the text rows in the box, not a static pixel value. */
    min-height: 10em;
    /* Do not use "border" in textareas unless you want to remove the 3D box most browsers assign and flatten the box design. */
    /*border: 1px solid black;*/
    cursor: text;
    /* Some textareas have a light gray background by default anyway. */
    background-color: #eee;
    /* Overflow "auto" allows the box to start with no scrollbars but add them as content fills the box. */
    overflow: auto;
    /* Resize creates a tab in the lower right corner of textarea for most modern browsers and allows users to resize the box manually. Note: Resize isn't supported by most older agents and IE. */
    resize: both;
}

In my "reset" element style sheet I set these values as defaults for "textarea" by default, which give all your textareas a nice look and feel with scrolling when detected, a resizing tab (non-IE browsers), and fixes for dimensions, including a height that allows the box to size itself based on existing content you put in it for the user and a width that does not break out beyond its parent containers limitations.

Calculate logarithm in python

math.log10(1.5)

Use the log10 function in the math module.

Why is setTimeout(fn, 0) sometimes useful?

setTimout on 0 is also very useful in the pattern of setting up a deferred promise, which you want to return right away:

myObject.prototype.myMethodDeferred = function() {
    var deferredObject = $.Deferred();
    var that = this;  // Because setTimeout won't work right with this
    setTimeout(function() { 
        return myMethodActualWork.call(that, deferredObject);
    }, 0);
    return deferredObject.promise();
}

SQL QUERY replace NULL value in a row with a value from the previous known value

If you are using Sql Server this should work

DECLARE @Table TABLE(
        ID INT,
        Val INT
)

INSERT INTO @Table (ID,Val) SELECT 1, 3
INSERT INTO @Table (ID,Val) SELECT 2, NULL
INSERT INTO @Table (ID,Val) SELECT 3, 5
INSERT INTO @Table (ID,Val) SELECT 4, NULL
INSERT INTO @Table (ID,Val) SELECT 5, NULL
INSERT INTO @Table (ID,Val) SELECT 6, 2


SELECT  *,
        ISNULL(Val, (SELECT TOP 1 Val FROM @Table WHERE ID < t.ID AND Val IS NOT NULL ORDER BY ID DESC))
FROM    @Table t

git add, commit and push commands in one?

define function in .bashrc

function gitall() {
    file=${1:-.}
    comment=${2:-update}
    echo $file
    echo $comment
    git add $file && git commit -m '$comment' && git push origin master
}

in your terminal

gitall

default gitall will add all in current git repo

gitall some-file-to-add 'update file'

will add certain file to change, and use custom commit message

How do I format a number with commas in T-SQL?

While I agree with everyone, including the OP, who says that formatting should be done in the presentation layer, this formatting can be accomplished in T-SQL by casting to money and then converting to varchar. This does include trailing decimals, though, that could be looped off with SUBSTRING.

SELECT CONVERT(varchar, CAST(987654321 AS money), 1)

How can I git stash a specific file?

I usually add to index changes I don't want to stash and then stash with --keep-index option.

git add app/controllers/cart_controller.php
git stash --keep-index
git reset

Last step is optional, but usually you want it. It removes changes from index.


Warning As noted in the comments, this puts everything into the stash, both staged and unstaged. The --keep-index just leaves the index alone after the stash is done. This can cause merge conflicts when you later pop the stash.

How do I integrate Ajax with Django applications?

AJAX is the best way to do asynchronous tasks. Making asynchronous calls is something common in use in any website building. We will take a short example to learn how we can implement AJAX in Django. We need to use jQuery so as to write less javascript.

This is Contact example, which is the simplest example, I am using to explain the basics of AJAX and its implementation in Django. We will be making POST request in this example. I am following one of the example of this post: https://djangopy.org/learn/step-up-guide-to-implement-ajax-in-django

models.py

Let's first create the model of Contact, having basic details.

from django.db import models

class Contact(models.Model):
    name = models.CharField(max_length = 100)
    email = models.EmailField()
    message = models.TextField()
    timestamp = models.DateTimeField(auto_now_add = True)

    def __str__(self):
        return self.name

forms.py

Create the form for the above model.

from django import forms
from .models import Contact

class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact
        exclude = ["timestamp", ]

views.py

The views look similar to the basic function-based create view, but instead of returning with render, we are using JsonResponse response.

from django.http import JsonResponse
from .forms import ContactForm

def postContact(request):
    if request.method == "POST" and request.is_ajax():
        form = ContactForm(request.POST)
        form.save()
        return JsonResponse({"success":True}, status=200)
    return JsonResponse({"success":False}, status=400)

urls.py

Let's create the route of the above view.

from django.contrib import admin
from django.urls import path
from app_1 import views as app1

urlpatterns = [
    path('ajax/contact', app1.postContact, name ='contact_submit'),
]

template

Moving to frontend section, render the form which was created above enclosing form tag along with csrf_token and submit button. Note that we have included the jquery library.

<form id = "contactForm" method= "POST">{% csrf_token %}
   {{ contactForm.as_p }}
  <input type="submit" name="contact-submit" class="btn btn-primary" />
</form>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Javascript

Let's now talk about javascript part, on the form submit we are making ajax request of type POST, taking the form data and sending to the server side.

$("#contactForm").submit(function(e){
    // prevent from normal form behaviour
        e.preventDefault();
        // serialize the form data  
        var serializedData = $(this).serialize();
        $.ajax({
            type : 'POST',
            url :  "{% url 'contact_submit' %}",
            data : serializedData,
            success : function(response){
            //reset the form after successful submit
                $("#contactForm")[0].reset(); 
            },
            error : function(response){
                console.log(response)
            }
        });
   });

This is just a basic example to get started with AJAX with django, if you want to get dive with several more examples, you can go through this article: https://djangopy.org/learn/step-up-guide-to-implement-ajax-in-django

How to send an email with Gmail as provider using Python?

I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:

https://support.google.com/accounts/answer/6010255

In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as "less secure", so what you have to do is go to this link while you're logged in to your google account, and allow the access:

https://www.google.com/settings/security/lesssecureapps

Once that is set (see my screenshot below), it should work.

enter image description here

Login now works:

smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('[email protected]', 'me_pass')

Response after change:

(235, '2.7.0 Accepted')

Response prior:

smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')

Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:

https://accounts.google.com/DisplayUnlockCaptcha

Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.

UPDATE: This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:

235 == 'Authentication successful'
503 == 'Error: already authenticated'

The message says to use the browser to sign in:

SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')

After enabling 'lesssecureapps', go for a coffee, come back, and try the 'DisplayUnlockCaptcha' link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.

Storyboard - refer to ViewController in AppDelegate

Generally, the system should be handling view controller instantiation with a storyboard. What you want is to traverse the viewController hierarchy by grabbing a reference to the self.window.rootViewController as opposed to initializing view controllers, which should already be initialized correctly if you've setup your storyboard properly.

So, let's say your rootViewController is a UINavigationController and then you want to send something to its top view controller, you would do it like this in your AppDelegate's didFinishLaunchingWithOptions:

UINavigationController *nav = (UINavigationController *) self.window.rootViewController;
MyViewController *myVC = (MyViewController *)nav.topViewController;
myVC.data = self.data;

In Swift if would be very similar:

let nav = self.window.rootViewController as! UINavigationController;
let myVC = nav.topViewController as! MyViewController
myVc.data = self.data

You really shouldn't be initializing view controllers using storyboard id's from the app delegate unless you want to bypass the normal way storyboard is loaded and load the whole storyboard yourself. If you're having to initialize scenes from the AppDelegate you're most likely doing something wrong. I mean imagine you, for some reason, want to send data to a view controller way down the stack, the AppDelegate shouldn't be reaching way into the view controller stack to set data. That's not its business. It's business is the rootViewController. Let the rootViewController handle its own children! So, if I were bypassing the normal storyboard loading process by the system by removing references to it in the info.plist file, I would at most instantiate the rootViewController using instantiateViewControllerWithIdentifier:, and possibly its root if it is a container, like a UINavigationController. What you want to avoid is instantiating view controllers that have already been instantiated by the storyboard. This is a problem I see a lot. In short, I disagree with the accepted answer. It is incorrect unless the posters means to remove loading of the storyboard from the info.plist since you will have loaded 2 storyboards otherwise, which makes no sense. It's probably not a memory leak because the system initialized the root scene and assigned it to the window, but then you came along and instantiated it again and assigned it again. Your app is off to a pretty bad start!

How do I add target="_blank" to a link within a specified div?

Bear in mind that doing this is considered bad practice in general by web developers and usability experts. Jakob Nielson has this to say about removing control of the users browsing experience:

Avoid spawning multiple browser windows if at all possible — taking the "Back" button away from users can make their experience so painful that it usually far outweighs whatever benefit you're trying to provide. One common theory in favor of spawning the second window is that it keeps users from leaving your site, but ironically it may have just the opposite effect by preventing them from returning when they want to.

I believe this is the rationale for the target attribute being removed by the W3C from the XHTML 1.1 spec.

If you're dead set on taking this approach, Pim Jager's solution is good.

A nicer, more user friendly idea, would be to append a graphic to all of your external links, indicating to the user that following the link will take them externally.

You could do this with jquery:

$('a[href^="http://"]').each(function() {
    $('<img width="10px" height="10px" src="/images/skin/external.png" alt="External Link" />').appendTo(this)

});

Defining a variable with or without export

Just to show the difference between an exported variable being in the environment (env) and a non-exported variable not being in the environment:

If I do this:

$ MYNAME=Fred
$ export OURNAME=Jim

then only $OURNAME appears in the env. The variable $MYNAME is not in the env.

$ env | grep NAME
OURNAME=Jim

but the variable $MYNAME does exist in the shell

$ echo $MYNAME
Fred

How to send authorization header with axios

res.setHeader('Access-Control-Allow-Headers',
            'Access-Control-Allow-Headers, Origin,OPTIONS,Accept,Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');

Blockquote : you have to add OPTIONS & Authorization to the setHeader()

this change has fixed my problem, just give a try!

javascript toISOString() ignores timezone offset

My solution without using moment is to convert it to a timestamp, add the timezone offset, then convert back to a date object, and then run the toISOString()

var date = new Date(); // Or the date you'd like converted.
var isoDateTime = new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();

Angular2 material dialog has issues - Did you add it to @NgModule.entryComponents?

If someone needs to call Dialog from services here is how to solve the issue. I agree with some of above answer, my answer is for calling dialog in services if someone may face issues on.

Create a service for example DialogService then move your dialog function inside the services and add your dialogservice in the component you call like below code:

 @Component({
  selector: "app-newsfeed",
  templateUrl: "./abc.component.html",
  styleUrls: ["./abc.component.css",],
  providers:[DialogService]
})

otherwise you get error

VBA: Convert Text to Number

For large datasets a faster solution is required.

Making use of 'Text to Columns' functionality provides a fast solution.

Example based on column F, starting range at 25 to LastRow

Sub ConvTxt2Nr()

Dim SelectR As Range
Dim sht As Worksheet
Dim LastRow As Long

Set sht = ThisWorkbook.Sheets("DumpDB")

LastRow = sht.Cells(sht.Rows.Count, "F").End(xlUp).Row

Set SelectR = ThisWorkbook.Sheets("DumpDB").Range("F25:F" & LastRow)

SelectR.TextToColumns Destination:=Range("F25"), DataType:=xlDelimited, _
    TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=False, Tab:=True, _
    Semicolon:=False, Comma:=False, Space:=False, Other:=False, FieldInfo _
    :=Array(1, 1), TrailingMinusNumbers:=True

End Sub

Configure active profile in SpringBoot via Maven

You can run using the following command. Here I want to run using spring profile local:

spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=local"

Count number of lines in a git repository

If you want to get the number of lines from a certain author, try the following code:

git ls-files "*.java" | xargs -I{} git blame {} | grep ${your_name} | wc -l

QLabel: set color of text and background

The best and recommended way is to use Qt Style Sheet.

To change the text color and background color of a QLabel, here is what I would do :

QLabel* pLabel = new QLabel;
pLabel->setStyleSheet("QLabel { background-color : red; color : blue; }");

You could also avoid using Qt Style Sheets and change the QPalette colors of your QLabel, but you might get different results on different platforms and/or styles.

As Qt documentation states :

Using a QPalette isn't guaranteed to work for all styles, because style authors are restricted by the different platforms' guidelines and by the native theme engine.

But you could do something like this :

 QPalette palette = ui->pLabel->palette();
 palette.setColor(ui->pLabel->backgroundRole(), Qt::yellow);
 palette.setColor(ui->pLabel->foregroundRole(), Qt::yellow);
 ui->pLabel->setPalette(palette);

But as I said, I strongly suggest not to use the palette and go for Qt Style Sheet.

How to capture the screenshot of a specific element rather than entire page using Selenium Webdriver?

Here is a Python 3 version using Selenium webdriver and Pillow. This program captures the screenshot of the whole page and crop the element based on its location. The element image will be available as image.png. Firefox supports saving element image directly using element.screenshot_as_png('image_name').

from selenium import webdriver
from PIL import Image

driver = webdriver.Chrome()
driver.get('https://www.google.co.in')

element = driver.find_element_by_id("lst-ib")

location = element.location
size = element.size

driver.save_screenshot("shot.png")

x = location['x']
y = location['y']
w = size['width']
h = size['height']
width = x + w
height = y + h

im = Image.open('shot.png')
im = im.crop((int(x), int(y), int(width), int(height)))
im.save('image.png')

Update

Now chrome also supports individual element screenshots. So you may directly capture the screenshot of the web element as given below.

from selenium import webdriver

driver = webdriver.Chrome()
driver.get('https://www.google.co.in')
image = driver.find_element_by_id("lst-ib").screenshot_as_png 
# or
# element = driver.find_element_by_id("lst-ib")
# element.screenshot_as_png("image.png")

Java verify void method calls n times with Mockito

The necessary method is Mockito#verify:

public static <T> T verify(T mock,
                           VerificationMode mode)

mock is your mocked object and mode is the VerificationMode that describes how the mock should be verified. Possible modes are:

verify(mock, times(5)).someMethod("was called five times");
verify(mock, never()).someMethod("was never called");
verify(mock, atLeastOnce()).someMethod("was called at least once");
verify(mock, atLeast(2)).someMethod("was called at least twice");
verify(mock, atMost(3)).someMethod("was called at most 3 times");
verify(mock, atLeast(0)).someMethod("was called any number of times"); // useful with captors
verify(mock, only()).someMethod("no other method has been called on the mock");

You'll need these static imports from the Mockito class in order to use the verify method and these verification modes:

import static org.mockito.Mockito.atLeast;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.atMost;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.only;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

So in your case the correct syntax will be:

Mockito.verify(mock, times(4)).send()

This verifies that the method send was called 4 times on the mocked object. It will fail if it was called less or more than 4 times.


If you just want to check, if the method has been called once, then you don't need to pass a VerificationMode. A simple

verify(mock).someMethod("was called once");

would be enough. It internally uses verify(mock, times(1)).someMethod("was called once");.


It is possible to have multiple verification calls on the same mock to achieve a "between" verification. Mockito doesn't support something like this verify(mock, between(4,6)).someMethod("was called between 4 and 6 times");, but we can write

verify(mock, atLeast(4)).someMethod("was called at least four times ...");
verify(mock, atMost(6)).someMethod("... and not more than six times");

instead, to get the same behaviour. The bounds are included, so the test case is green when the method was called 4, 5 or 6 times.

How to use ADB to send touch events to device using sendevent command?

You don't need to use

adb shell getevent -l

command, you just need to enable in Developer Options on the device [Show Touch data] to get X and Y.

Some more information can be found in my article here: https://mobileqablog.wordpress.com/2016/08/20/android-automatic-touchscreen-taps-adb-shell-input-touchscreen-tap/

How can I use a DLL file from Python?

If the DLL is of type COM library, then you can use pythonnet.

pip install pythonnet

Then in your python code, try the following

import clr
clr.AddReference('path_to_your_dll')

then instantiate an object as per the class in the DLL, and access the methods within it.

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

Here's a general example with obvious delimiters (X and Y):

(?<=X)(.*?)(?=Y)

Here it's used to find the string between X and Y. Rubular example here, or see image:

enter image description here

How to configure heroku application DNS to Godaddy Domain?

There are 2 steps you need to perform,

  1. Add the custom domains addon and add the domain your going to use, eg www.mywebsite.com to your application
  2. Go to your domain registrar control panel and set www.mywebsite.com to be a CNAME entry to yourapp.herokuapp.com assuming you are using the CEDAR stack.
  3. There is a third step if you want to use a naked domain, eg mywebsite.com when you would have to add the IP addresses of the Heroku load balancers to your DNS for mywebsite.com

You can read more about this at http://devcenter.heroku.com/articles/custom-domains

At a guess you've missed out the first step perhaps?

UPDATE: Following the announcement of Bamboo's EOL proxy.heroku.com being retired (September 2014) for Bamboo applications so these should also now use the yourapp.herokuapp.com mapping now as well.

how to get the child node in div using javascript

var tds = document.getElementById("ctl00_ContentPlaceHolder1_Jobs_dlItems_ctl01_a").getElementsByTagName("td");
time = tds[0].firstChild.value;
address = tds[3].firstChild.value;

Calculate a MD5 hash from a string

Depends entirely on what you are trying to achieve. Technically, you could just take the first 12 characters from the result of the MD5 hash, but the specification of MD5 is to generate a 32 char one.

Reducing the size of the hash reduces the security, and increases the chance of collisions and the system being broken.

Perhaps if you let us know more about what you are trying to achieve we may be able to assist more.

How can I use break or continue within for loop in Twig template?

This can be nearly done by setting a new variable as a flag to break iterating:

{% set break = false %}
{% for post in posts if not break %}
    <h2>{{ post.heading }}</h2>
    {% if post.id == 10 %}
        {% set break = true %}
    {% endif %}
{% endfor %}

An uglier, but working example for continue:

{% set continue = false %}
{% for post in posts %}
    {% if post.id == 10 %}
        {% set continue = true %}
    {% endif %}
    {% if not continue %}
        <h2>{{ post.heading }}</h2>
    {% endif %}
    {% if continue %}
        {% set continue = false %}
    {% endif %}
{% endfor %}

But there is no performance profit, only similar behaviour to the built-in break and continue statements like in flat PHP.

Place input box at the center of div

#input_box {
    margin: 0 auto;
    text-align: left;
}
#div {
    text-align: center;
}

<div id="div">
    <label for="input_box">Input: </label><input type="text" id="input_box" name="input_box" />
</div>

or you could do it using padding, but this is not that great of an idea.

add new element in laravel collection object

As mentioned above if you wish to as a new element your queried collection you can use:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
        $product = DB::select(DB::raw(' select * from product
               where product_id = '. $id.';' ));

        $items->push($product);
        // or 
        // $items->put('products', $product);
    }

but if you wish to add new element to each queried element you need to do like:

    $items = DB::select(DB::raw('SELECT * FROM items WHERE items.id = '.$id.'  ;'));
    foreach($items as $item){
           $product = DB::select(DB::raw(' select * from product
                 where product_id = '. $id.';' ));

          $item->add_whatever_element_you_want = $product;
    }

add_whatever_element_you_want can be whatever you wish that your element is named (like product for example).

Line continue character in C#

C# will allow you to have a string split over multiple lines, the term is called verbatim literal:

string myString = @"this is a
                    test
                   to see how long my string
                   can be



                    and it can be quite long";

If you are looking for the alternative to & _ from VB, use the + to join your lines.

How can I make a horizontal ListView in Android?

Have you looked into using a HorizontalScrollView to wrap your list items? That will allow each of your list items to be horizontally scrollable (what you put in there is up to you, and can make them dynamic items similar to ListView). This will work well if you are only after a single row of items.

Including a .js file within a .js file

A popular method to tackle the problem of reducing JavaScript references from HTML files is by using a concatenation tool like Sprockets, which preprocesses and concatenates JavaScript source files together.

Apart from reducing the number of references from the HTML files, this will also reduce the number of hits to the server.

You may then want to run the resulting concatenation through a minification tool like jsmin to have it minified.

A select query selecting a select statement

I was over-complicating myself. After taking a long break and coming back, the desired output could be accomplished by this simple query:

SELECT Sandwiches.[Sandwich Type], Sandwich.Bread, Count(Sandwiches.[SandwichID]) AS [Total Sandwiches]
FROM Sandwiches
GROUP BY Sandwiches.[Sandwiches Type], Sandwiches.Bread;

Thanks for answering, it helped my train of thought.

How to create a MySQL hierarchical recursive query?

Did the same thing for another quetion here

Mysql select recursive get all child with multiple level

The query will be :

SELECT GROUP_CONCAT(lv SEPARATOR ',') FROM (
  SELECT @pv:=(
    SELECT GROUP_CONCAT(id SEPARATOR ',')
    FROM table WHERE parent_id IN (@pv)
  ) AS lv FROM table 
  JOIN
  (SELECT @pv:=1)tmp
  WHERE parent_id IN (@pv)
) a;

How do I display a MySQL error in PHP for a long query that depends on the user input?

One useful line of code for you would be:

$sql = "Your SQL statement here";
$result = mysqli_query($this->db_link, $sql) or trigger_error("Query Failed! SQL: $sql - Error: ".mysqli_error($this->db_link), E_USER_ERROR);

This method is better than die, because you can use it for development AND production. It's the permanent solution.

wildcard * in CSS for classes

If you don't need the unique identifier for further styling of the divs and are using HTML5 you could try and go with custom Data Attributes. Read on here or try a google search for HTML5 Custom Data Attributes

MySQL: Error Code: 1118 Row size too large (> 8126). Changing some columns to TEXT or BLOB

I have changed the length of value from varchar(255) to varchar(25) to all varchar columns and i get the solution.

How can I do width = 100% - 100px in CSS?

<div style="width: 200px; border: 1px solid red;">
    <br>
    <div style="margin: 0px 50px 0px 50px; border: 1px solid blue;">
        <br>
    </div>
    <br>
</div>

JQuery/Javascript: check if var exists

For your case, and 99.9% of all others elclanrs answer is correct.

But because undefined is a valid value, if someone were to test for an uninitialized variable

var pagetype; //== undefined
if (typeof pagetype === 'undefined') //true

the only 100% reliable way to determine if a var exists is to catch the exception;

var exists = false;
try { pagetype; exists = true;} catch(e) {}
if (exists && ...) {}

But I would never write it this way

Eclipse jump to closing brace

With Ctrl + Shift + L you can open the "key assist", where you can find all the shortcuts.

How to set multiple commands in one yaml file with Kubernetes?

Here is how you can pass, multiple commands & arguments in one YAML file with kubernetes:

# Write your commands here
command: ["/bin/sh", "-c"]
# Write your multiple arguments in args
args: ["/usr/local/bin/php /var/www/test.php & /usr/local/bin/php /var/www/vendor/api.php"]

Full containers block from yaml file:

    containers:
      - name: widc-cron # container name
        image: widc-cron # custom docker image
        imagePullPolicy: IfNotPresent # advisable to keep
        # write your command here
        command: ["/bin/sh", "-c"]
        # You can declare multiple arguments here, like this example
        args: ["/usr/local/bin/php /var/www/tools/test.php & /usr/local/bin/php /var/www/vendor/api.php"]
        volumeMounts: # to mount files from config-map generator
          - mountPath: /var/www/session/constants.inc.php
            subPath: constants.inc.php
            name: widc-constants

"for" vs "each" in Ruby

As far as I know, using blocks instead of in-language control structures is more idiomatic.

How do I return multiple values from a function in C?

Since one of your result types is a string (and you're using C, not C++), I recommend passing pointers as output parameters. Use:

void foo(int *a, char *s, int size);

and call it like this:

int a;
char *s = (char *)malloc(100); /* I never know how much to allocate :) */
foo(&a, s, 100);

In general, prefer to do the allocation in the calling function, not inside the function itself, so that you can be as open as possible for different allocation strategies.

How do I concatenate strings with variables in PowerShell?

Try this

Get-ChildItem  | % { Write-Host "$($_.FullName)\$buildConfig\$($_.Name).dll" }

In your code,

  1. $build-Config is not a valid variable name.
  2. $.FullName should be $_.FullName
  3. $ should be $_.Name

Why should I use IHttpActionResult instead of HttpResponseMessage?

// this will return HttpResponseMessage as IHttpActionResult
return ResponseMessage(httpResponseMessage); 

How to detect a USB drive has been plugged in?

It is easy to check for removable devices. However, there's no guarantee that it is a USB device:

var drives = DriveInfo.GetDrives()
    .Where(drive => drive.IsReady && drive.DriveType == DriveType.Removable);

This will return a list of all removable devices that are currently accessible. More information:

Why use @PostConstruct?

Consider the following scenario:

public class Car {
  @Inject
  private Engine engine;  

  public Car() {
    engine.initialize();  
  }
  ...
}

Since Car has to be instantiated prior to field injection, the injection point engine is still null during the execution of the constructor, resulting in a NullPointerException.

This problem can be solved either by JSR-330 Dependency Injection for Java constructor injection or JSR 250 Common Annotations for the Java @PostConstruct method annotation.

@PostConstruct

JSR-250 defines a common set of annotations which has been included in Java SE 6.

The PostConstruct annotation is used on a method that needs to be executed after dependency injection is done to perform any initialization. This method MUST be invoked before the class is put into service. This annotation MUST be supported on all classes that support dependency injection.

JSR-250 Chap. 2.5 javax.annotation.PostConstruct

The @PostConstruct annotation allows for the definition of methods to be executed after the instance has been instantiated and all injects have been performed.

public class Car {
  @Inject
  private Engine engine;  

  @PostConstruct
  public void postConstruct() {
    engine.initialize();  
  }
  ...
} 

Instead of performing the initialization in the constructor, the code is moved to a method annotated with @PostConstruct.

The processing of post-construct methods is a simple matter of finding all methods annotated with @PostConstruct and invoking them in turn.

private  void processPostConstruct(Class type, T targetInstance) {
  Method[] declaredMethods = type.getDeclaredMethods();

  Arrays.stream(declaredMethods)
      .filter(method -> method.getAnnotation(PostConstruct.class) != null) 
      .forEach(postConstructMethod -> {
         try {
           postConstructMethod.setAccessible(true);
           postConstructMethod.invoke(targetInstance, new Object[]{});
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {      
          throw new RuntimeException(ex);
        }
      });
}

The processing of post-construct methods has to be performed after instantiation and injection have been completed.

In Java, what is the best way to determine the size of an object?

You have to walk the objects using reflection. Be careful as you do:

  • Just allocating an object has some overhead in the JVM. The amount varies by JVM so you might make this value a parameter. At least make it a constant (8 bytes?) and apply to anything allocated.
  • Just because byte is theoretically 1 byte doesn't mean it takes just one in memory.
  • There will be loops in object references, so you'll need to keep a HashMap or somesuch using object-equals as the comparator to eliminate infinite loops.

@jodonnell: I like the simplicity of your solution, but many objects aren't Serializable (so this would throw an exception), fields can be transient, and objects can override the standard methods.

jQuery - Fancybox: But I don't want scrollbars!

Sounds a bit wierd. an ugly solution is to use css, overflow:hidden;

Whenever I use fancybox, the scrollbars work correctly. sure that the content oc the fancybox is not setting another height?

Edit: Viewed your example-site. Seems like there is some width beeing set in the content that is larger than the fancybox itself.

What is a "bundle" in an Android application

Bundle is not only to transfer data between two different components but more importantly it is used to restore the values stored before activity is destroyed into new activity.

such as the text in an EditText widget or the scroll position of a ListView.

In Spring MVC, how can I set the mime type header when using @ResponseBody

My version of reality. Loading a HTML file and streaming to the browser.

@Controller
@RequestMapping("/")
public class UIController {

    @RequestMapping(value="index", method=RequestMethod.GET, produces = "text/html")
    public @ResponseBody String GetBootupFile() throws IOException  {
        Resource resource = new ClassPathResource("MainPage.html");
        String fileContents = FileUtils.readFileToString(resource.getFile());
        return fileContents;
    }
}

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

I've found this easy solution

To convert from bitmap to Base64 use this method.

private String convertBitmapToBase64(Bitmap bitmap) {
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
    byte[] byteArray = byteArrayOutputStream .toByteArray();
    return Base64.encodeToString(byteArray, Base64.DEFAULT);
}

To convert from Base64 to bitmap OR revert.

private Bitmap convertBase64ToBitmap(String b64) {
    byte[] imageAsBytes = Base64.decode(b64.getBytes(), Base64.DEFAULT);
    return BitmapFactory.decodeByteArray(imageAsBytes, 0, imageAsBytes.length);
}

Append key/value pair to hash with << in Ruby

No, I don't think you can append key/value pairs. The only thing closest that I am aware of is using the store method:

h = {}
h.store("key", "value")

Is there a list of Pytz Timezones?

Available from Python3.9:

zoneinfo,new module in Python3.9 which works against the database of IANA. In order to grab all the available timezones, first:

pip install tzdata

And then:

import zoneinfo

print(zoneinfo.available_timezones())

Joining three tables using MySQL

SELECT 
employees.id, 
CONCAT(employees.f_name," ",employees.l_name) AS   'Full Name', genders.gender_name AS 'Sex', 
depts.dept_name AS 'Team Name', 
pay_grades.pay_grade_name AS 'Band', 
designations.designation_name AS 'Role' 
FROM employees 
LEFT JOIN genders ON employees.gender_id = genders.id 
LEFT JOIN depts ON employees.dept_id = depts.id 
LEFT JOIN pay_grades ON employees.pay_grade_id = pay_grades.id 
LEFT JOIN designations ON employees.designation_id = designations.id 
ORDER BY employees.id;

You can JOIN multiple TABLES like this example above.

WITH (NOLOCK) vs SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

  • NOLOCK is local to the table (or views etc)
  • READ UNCOMMITTED is per session/connection

As for guidelines... a random search from StackOverflow and the electric interweb...

T-SQL query to show table definition?

I know it's an old question, but exactly what I was looking for. Because I want to batch script some tables, I rewrote the C# code from Anthony Faull for PowerShell.

This one is uses Integrated Security:

Import-Module sqlps

$serverInstance = "<server>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"

$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true

$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
    -ArgumentList $serverInstance
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
    -ArgumentList $connection

$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
    | ForEach-Object -Process { $_ + "`nGO"}

And here with username and password:

Import-Module sqlps

$serverInstance = "<server>"
$user = "<user>"
$password = "<pasword>"
$database = "<database>"
$table = "<table>"
$schema = "<schema>"

$options = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$options.DriAll = $true
$options.SchemaQualify = $true

$connection = New-Object -TypeName Microsoft.SqlServer.Management.Common.ServerConnection `
    -ArgumentList $serverInstance
$connection.LoginSecure = $false
$connection.Login = $user
$connection.Password = $password
$server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server `
    -ArgumentList $connection

$server.Databases.Item($database).Tables.Item($table, $schema).Script($options) `
    | ForEach-Object -Process { $_ + "`nGO"}

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

If you want to generate a file in the Windows, then, please follow the below steps:

  1. Go to a directory where you want to save the generated file
  2. Open the command prompt on that directory
  3. Run this fsutil file createnew [filename].[extension] [# of bytes] command. For example fsutil file createnew test.pdf 999999999
  4. 95.3 MB File will be generated

Update: The generated file will not be a valid pdf file. It just holds the given size.

AngularJS : The correct way of binding to a service properties

The Most Elegant Solutions...

app.service('svc', function(){ this.attr = []; return this; });
app.controller('ctrl', function($scope, svc){
    $scope.attr = svc.attr || [];
    $scope.$watch('attr', function(neo, old){ /* if necessary */ });
});
app.run(function($rootScope, svc){
    $rootScope.svc = svc;
    $rootScope.$watch('svc', function(neo, old){ /* change the world */ });
});

Also, I write EDAs (Event-Driven Architectures) so I tend to do something like the following [oversimplified version]:

var Service = function Service($rootScope) {
    var $scope = $rootScope.$new(this);
    $scope.that = [];
    $scope.$watch('that', thatObserver, true);
    function thatObserver(what) {
        $scope.$broadcast('that:changed', what);
    }
};

Then, I put a listener in my controller on the desired channel and just keep my local scope up to date this way.

In conclusion, there's not much of a "Best Practice" -- rather, its mostly preference -- as long as you're keeping things SOLID and employing weak coupling. The reason I would advocate the latter code is because EDAs have the lowest coupling feasible by nature. And if you aren't too concerned about this fact, let us avoid working on the same project together.

Hope this helps...

Docker: How to delete all local Docker images

Easy and handy commands

To delete all images

docker rmi $(docker images -a)

To delete containers which are in exited state

docker rm $(docker ps -a -f status=exited -q)

To delete containers which are in created state

docker rm $(docker ps -a -f status=created -q)

NOTE: Remove all the containers then remove the images

Carriage return and Line feed... Are both required in C#?

A carriage return \r moves the cursor to the beginning of the current line. A newline \n causes a drop to the next line and possibly the beginning of the next line; That's the platform dependent part that Alexei notes above (on a *nix system \n gives you both a carriage return and a newline, in windows it doesn't)

What you use depends on what you're trying to do. If I wanted to make a little spinning thing on a console I would do str = "|\r/\r-\r\\\r"; for example.

How can I remove non-ASCII characters but leave periods and spaces using Python?

Your question is ambiguous; the first two sentences taken together imply that you believe that space and "period" are non-ASCII characters. This is incorrect. All chars such that ord(char) <= 127 are ASCII characters. For example, your function excludes these characters !"#$%&\'()*+,-./ but includes several others e.g. []{}.

Please step back, think a bit, and edit your question to tell us what you are trying to do, without mentioning the word ASCII, and why you think that chars such that ord(char) >= 128 are ignorable. Also: which version of Python? What is the encoding of your input data?

Please note that your code reads the whole input file as a single string, and your comment ("great solution") to another answer implies that you don't care about newlines in your data. If your file contains two lines like this:

this is line 1
this is line 2

the result would be 'this is line 1this is line 2' ... is that what you really want?

A greater solution would include:

  1. a better name for the filter function than onlyascii
  2. recognition that a filter function merely needs to return a truthy value if the argument is to be retained:

    def filter_func(char):
        return char == '\n' or 32 <= ord(char) <= 126
    # and later:
    filtered_data = filter(filter_func, data).lower()
    

javascript: pause setTimeout();

If you're using jquery anyhow, check out the $.doTimeout plugin. This thing is a huge improvement over setTimeout, including letting you keep track of your time-outs with a single string id that you specify and that doesn't change every time you set it, and implement easy canceling, polling loops & debouncing, and more. One of my most-used jquery plugins.

Unfortunately, it doesn't support pause/resume out of the box. For this, you would need to wrap or extend $.doTimeout, presumably similarly to the accepted answer.

How to import functions from different js file in a Vue+webpack+vue-loader project

I like the answer of Anacrust, though, by the fact "console.log" is executed twice, I would like to do a small update for src/mylib.js:

let test = {
  foo () { return 'foo' },
  bar () { return 'bar' },
  baz () { return 'baz' }
}

export default test

All other code remains the same...

Remove #N/A in vlookup result

if you are looking to change the colour of the cell in case of vlookup error then go for conditional formatting . To do this go the "CONDITIONAL FORMATTING" > "NEW RULE". In this choose the "Select the rule type" = "Format only cells that contains" . After this the window below changes , in which choose "Error" in the first drop-down .After this proceed accordingly.

Using only CSS, show div on hover over <a>

I'm by know means an expert, but I'm incredibly proud of myself for having worked something out about this code. If you do:

div {
    display: none;
}

a:hover > div {
    display: block;
} 

(Note the '>') You can contain the whole thing in an a tag, then, as long as your trigger (which can be in it's own div, or straight up in the a tag, or anything you want) is physically touching the revealed div, you can move your mouse from one to the other.

Maybe this isn't useful for a great deal, but I had to set my revealed div to overflow: auto, so sometimes it had scroll bars, which couldn't be used as soon as you move away from the div.

In fact, after finally working out how to make the revealed div, (although it is now a child of the trigger, not a sibling), sit behind the trigger, in terms of z-index, (with a little help from this page: How to get a parent element to appear above child) you don't even have to roll over the revealed div to scroll it, just stay hovering over the trigger and use your wheel, or whatever.

My revealed div covers most of the page, so this technique makes it a lot more permanent, rather than the screen flashing from one state to another with every move of the mouse. It's really intuitive actually, hence why I'm really quite proud of myself.

The only downside is that you can't put links within the whole thing, but you can use the whole thing as one big link.

Create file path from variables

You want the path.join() function from os.path.

>>> from os import path
>>> path.join('foo', 'bar')
'foo/bar'

This builds your path with os.sep (instead of the less portable '/') and does it more efficiently (in general) than using +.

However, this won't actually create the path. For that, you have to do something like what you do in your question. You could write something like:

start_path = '/my/root/directory'
final_path = os.join(start_path, *list_of_vars)
if not os.path.isdir(final_path):
    os.makedirs (final_path)

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

Is there a wrapper module on top of the http to more easily handle processing http responses from a node application?

request

Redirection logic in request

jQuery AJAX cross domain

This is possible, but you need to use JSONP, not JSON. Stefan's link pointed you in the right direction. The jQuery AJAX page has more information on JSONP.

Remy Sharp has a detailed example using PHP.

How do I pass multiple parameter in URL?

I do not know much about Java but URL query arguments should be separated by "&", not "?"

http://tools.ietf.org/html/rfc3986 is good place for reference using "sub-delim" as keyword. http://en.wikipedia.org/wiki/Query_string is another good source.

How to create a folder with name as current date in batch (.bat) files

https://stackoverflow.com/a/31789045/1010918 foxidrive's answer helped me get the folder with the date and time I wanted. I would like to share this method here since it worked great for me and I think it could help other people too, regardless of their locale.

rem The four lines below will give you reliable YY DD MM YYYY HH Min Sec MS variables in XP Pro and higher.

for /f "tokens=2 delims==" %%a in ('wmic OS Get localdatetime /value') do set "dt=%%a"
set "YY=%dt:~2,2%" & set "YYYY=%dt:~0,4%" & set "MM=%dt:~4,2%" & set "DD=%dt:~6,2%"
set "HH=%dt:~8,2%" & set "Min=%dt:~10,2%" & set "Sec=%dt:~12,2%" & set "MS=%dt:~15,3%"

 set "dirname=%YYYY%-%MM%-%DD% %HH%-%Min%-%Sec%"

 :: remove echo here if you like
 echo "dirName"="%dirName%"

How to convert std::string to LPCWSTR in C++ (Unicode)

If you are in an ATL/MFC environment, You can use the ATL conversion macro:

#include <atlbase.h>
#include <atlconv.h>

. . .

string myStr("My string");
CA2W unicodeStr(myStr);

You can then use unicodeStr as an LPCWSTR. The memory for the unicode string is created on the stack and released then the destructor for unicodeStr executes.

How to download/upload files from/to SharePoint 2013 using CSOM?

This article describes various options for accessing SharePoint content. You have a choice between REST and CSOM. I'd try CSOM if possible. File upload / download specifically is nicely described in this article.

Overall notes:

    //First construct client context, the object which will be responsible for
    //communication with SharePoint:
    var context = new ClientContext(@"http://site.absolute.url")

    //then get a hold of the list item you want to download, for example
    var list = context.Web.Lists.GetByTitle("Pipeline");
    var query = CamlQuery.CreateAllItemsQuery(10000);
    var result = list.GetItems(query);

    //note that data has not been loaded yet. In order to load the data
    //you need to tell SharePoint client what you want to download:

    context.Load(result, items=>items.Include(
        item => item["Title"],
        item => item["FileRef"]
    ));

    //now you get the data
    context.ExecuteQuery();

    //here you have list items, but not their content (files). To download file
    //you'll have to do something like this:

    var item = items.First();

    //get the URL of the file you want:
    var fileRef = item["FileRef"];

    //get the file contents:
    FileInformation fileInfo = File.OpenBinaryDirect(context, fileRef.ToString());

    using (var memory = new MemoryStream())
    {
          byte[] buffer = new byte[1024 * 64];
          int nread = 0;
          while ((nread = fileInfo.Stream.Read(buffer, 0, buffer.Length)) > 0)
          {
              memory.Write(buffer, 0, nread);
          }
          memory.Seek(0, SeekOrigin.Begin);
          // ... here you have the contents of your file in memory, 
          // do whatever you want
    }

Avoid working with the stream directly, read it into the memory first. Network-bound streams are not necessarily supporting stream operations, not to mention performance. So, if you are reading a pic from that stream or parsing a document, you may end up with some unexpected behavior.

On a side note, I have a related question re: performance of this code above, as you are taking some penalty with every file request. See here. And yes, you need 4.5 full .NET profile for this.

Convert columns to string in Pandas

If you need to convert ALL columns to strings, you can simply use:

df = df.astype(str)

This is useful if you need everything except a few columns to be strings/objects, then go back and convert the other ones to whatever you need (integer in this case):

 df[["D", "E"]] = df[["D", "E"]].astype(int) 

The Definitive C Book Guide and List

Warning!

This is a list of random books of diverse quality. In the view of some people (with some justification), it is no longer a list of recommended books. Some of the listed books contain blatantly incorrect statements or teach wrong/harmful practices. People who are aware of such books can edit this answer to help improve it. See The C book list has gone haywire. What to do with it?, and also Deleted question audit 2018.

Reference (All Levels)

  • The C Programming Language (2nd Edition) - Brian W. Kernighan and Dennis M. Ritchie (1988). Still a good, short but complete introduction to C (C90, not C99 or later versions), written by the inventor of C. However, the language has changed and good C style has developed in the last 25 years, and there are parts of the book that show its age.

  • C: A Reference Manual (5th Edition) - Samuel P. Harbison and Guy R. Steele (2002). An excellent reference book on C, up to and including C99. It is not a tutorial, and probably unfit for beginners. It's great if you need to write a compiler for C, as the authors had to do when they started.

  • C Pocket Reference (O'Reilly) - Peter Prinz and Ulla Kirch-Prinz (2002).

  • The comp.lang.c FAQ - Steve Summit. Web site with answers to many questions about C.

  • Various versions of the C language standards can be found here. There is an online version of the draft C11 standard.

  • The new C standard - an annotated reference (Free PDF) - Derek M. Jones (2009). The "new standard" referred to is the old C99 standard rather than C11.

  • Rationale for C99 Standard.


Beginner

  • C In Easy Steps (5th Edition) - Mike McGrath (2018). It is a good book for learning and referencing C.

  • Effective C - Robert C Seacord (2020). A good introduction to modern C, including chapters on dynamic memory allocation, on program structure, and on debugging, testing and analysis. It has some pointers toward probable C2x features.

Intermediate

  • Modern C — Jens Gustedt (2017 1st Edn; 2020 2nd Edn). Covers C in 5 levels (encounter, acquaintance, cognition, experience, ambition) from beginning C to advanced C. It covers C11 and C17, including threads and atomic access, which few other books do. Not all compilers recognize these features in all environments.

  • C Interfaces and Implementations - David R. Hanson (1997). Provides information on how to define a boundary between an interface and implementation in C in a generic and reusable fashion. It also demonstrates this principle by applying it to the implementation of common mechanisms and data structures in C, such as lists, sets, exceptions, string manipulation, memory allocators, and more. Basically, Hanson took all the code he'd written as part of building Icon and lcc and pulled out the best bits in a form that other people could reuse for their own projects. It's a model of good C programming using modern design techniques (including Liskov's data abstraction), showing how to organize a big C project as a bunch of useful libraries.

  • The C Puzzle Book - Alan R. Feuer (1998)

  • The Standard C Library - P.J. Plauger (1992). It contains the complete source code to an implementation of the C89 standard library, along with extensive discussions about the design and why the code is designed as shown.

  • 21st Century C: C Tips from the New School - Ben Klemens (2012). In addition to the C language, the book explains gdb, valgrind, autotools, and git. The comments on style are found in the last part (Chapter 6 and beyond).

  • Algorithms in C - Robert Sedgewick (1997). Gives you a real grasp of implementing algorithms in C. Very lucid and clear; will probably make you want to throw away all of your other algorithms books and keep this one.

  • Extreme C: Push the limits of what C and you can do - Kamran Amini (2019). This book builds on your existing C knowledge to help you become a more expert C programmer. You will gain insights into algorithm design, functions, and structures, and understand both multi-threading and multi-processing in a POSIX environment.

Expert


Uncategorized

  • Essential C (Free PDF) - Nick Parlante (2003). Note that this describes the C90 language at several points (e.g., in discussing // comments and placement of variable declarations at arbitrary points in the code), so it should be treated with some caution.

  • C Programming FAQs: Frequently Asked Questions - Steve Summit (1995). This is the book of the web site listed earlier. It doesn't cover C99 or the later standards.

  • C in a Nutshell - Peter Prinz and Tony Crawford (2005). Excellent book if you need a reference for C99.

  • Functional C - Pieter Hartel and Henk Muller (1997). Teaches modern practices that are invaluable for low-level programming, with concurrency and modularity in mind.

  • The Practice of Programming - Brian W. Kernighan and Rob Pike (1999). A very good book to accompany K&R. It uses C++ and Java too.

  • C Traps and Pitfalls by A. Koenig (1989). Very good, but the C style pre-dates standard C, which makes it less recommendable these days.

    Some have argued for the removal of 'Traps and Pitfalls' from this list because it has trapped some people into making mistakes; others continue to argue for its inclusion. Perhaps it should be regarded as an 'expert' book because it requires a moderately extensive knowledge of C to understand what's changed since it was published.

  • MISRA-C - industry standard published and maintained by the Motor Industry Software Reliability Association. Covers C89 and C99.

    Although this isn't a book as such, many programmers recommend reading and implementing as much of it as possible. MISRA-C was originally intended as guidelines for safety-critical applications in particular, but it applies to any area of application where stable, bug-free C code is desired (who doesn't want fewer bugs?). MISRA-C is becoming the de facto standard in the whole embedded industry and is getting increasingly popular even in other programming branches. There are (at least) three publications of the standard (1998, 2004, and the current version from 2012). There is also a MISRA Compliance Guidelines document from 2016, and MISRA C:2012 Amendment 1 — Additional Security Guidelines for MISRA C:2012 (published in April 2016).

    Note that some of the strictures in the MISRA rules are not appropriate to every context. For example, directive 4.12 states "Dynamic memory allocation shall not be used". This is appropriate in the embedded systems for which the MISRA rules are designed; it is not appropriate everywhere. (Compilers, for instance, generally use dynamic memory allocation for things like symbol tables, and to do without dynamic memory allocation would be difficult, if not preposterous.)

  • Archived lists of ACCU-reviewed books on Beginner's C (116 titles) from 2007 and Advanced C (76 titles) from 2008. Most of these don't look to be on the main site anymore, and you can't browse that by subject anyway.


Warnings

There is a list of books and tutorials to be cautious about at the ISO 9899 Wiki, which is not itself formally associated with ISO or the C standard, but contains information about the C standard (though it hails the release of ISO 9899:2011 and does not mention the release of ISO 9899:2018).

Be wary of books written by Herbert Schildt. In particular, you should stay away from C: The Complete Reference (4th Edition, 2000), known in some circles as C: The Complete Nonsense.

Also do not use the book Let Us C (16th Edition, 2017) by Yashwant Kanetkar. Many people view it as an outdated book that teaches Turbo C and has lots of obsolete, misleading and incorrect material. For example, page 137 discusses the expected output from printf("%d %d %d\n", a, ++a, a++) and does not categorize it as undefined behaviour as it should. It also consistently promotes unportable and buggy coding practices, such as using gets, %[\n]s in scanf, storing return value of getchar in a variable of type char or using fflush on stdin.

Learn C The Hard Way (2015) by Zed Shaw. A book with mixed reviews. A critique of this book by Tim Hentenaar:

To summarize my views, which are laid out below, the author presents the material in a greatly oversimplified and misleading way, the whole corpus is a bundled mess, and some of the opinions and analyses he offers are just plain wrong. I've tried to view this book through the eyes of a novice, but unfortunately I am biased by years of experience writing code in C. It's obvious to me that either the author has a flawed understanding of C, or he's deliberately oversimplifying to the point where he's actually misleading the reader (intentionally or otherwise).

"Learn C The Hard Way" is not a book that I could recommend to someone who is both learning to program and learning C. If you're already a competent programmer in some other related language, then it represents an interesting and unusual exposition on C, though I have reservations about parts of the book. Jonathan Leffler


Outdated


Other contributors, not necessarily credited in the revision history, include:
Alex Lockwood, Ben Jackson, Bubbles, claws, coledot, Dana Robinson, Daniel Holden, desbest, Dervin Thunk, dwc, Erci Hou, Garen, haziz, Johan Bezem, Jonathan Leffler, Joshua Partogi, Lucas, Lundin, Matt K., mossplix, Matthieu M., midor, Nietzche-jou, Norman Ramsey, r3st0r3, ridthyself, Robert S. Barnes, Steve Summit, Tim Ring, Tony Bai, VMAtm

How to show another window from mainwindow in QT

  1. Implement a slot in your QMainWindow where you will open your new Window,
  2. Place a widget on your QMainWindow,
  3. Connect a signal from this widget to a slot from the QMainWindow (for example: if the widget is a QPushButton connect the signal click() to the QMainWindow custom slot you have created).

Code example:

MainWindow.h

// ...
include "newwindow.h"
// ...
public slots:
   void openNewWindow();
// ...
private:
   NewWindow *mMyNewWindow;
// ...
}

MainWindow.cpp

// ...
   MainWindow::MainWindow()
   {
      // ...
      connect(mMyButton, SIGNAL(click()), this, SLOT(openNewWindow()));
      // ...
   }
// ...
void MainWindow::openNewWindow()
{
   mMyNewWindow = new NewWindow(); // Be sure to destroy your window somewhere
   mMyNewWindow->show();
   // ...
}

This is an example on how display a custom new window. There are a lot of ways to do this.

jQuery Combobox/select autocomplete?

Have a look at the following example of the jQueryUI Autocomplete, as it is keeping a select around and I think that is what you are looking for. Hope this helps.

http://jqueryui.com/demos/autocomplete/#combobox

Linux Command History with date and time

Regarding this link you can make the first solution provided by krzyk permanent by executing:

echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bash_profile
source ~/.bash_profile

SQL Order By Count

Q. List the name of each show, and the number of different times it has been held. List the show which has been held most often first.

event_id show_id event_name judge_id
0101    01  Dressage        01
0102    01  Jumping         02
0103    01  Led in          01
0201    02  Led in          02
0301    03  Led in          01
0401    04  Dressage        04
0501    05  Dressage        01
0502    05  Flag and Pole   02

Ans:

select event_name, count(show_id) as held_times from event 
group by event_name 
order by count(show_id) desc

What are "named tuples" in Python?

Everyone else has already answered it, but I think I still have something else to add.

Namedtuple could be intuitively deemed as a shortcut to define a class.

See a cumbersome and conventional way to define a class .

class Duck:
    def __init__(self, color, weight):
        self.color = color
        self.weight = weight
red_duck = Duck('red', '10')

    In [50]: red_duck
    Out[50]: <__main__.Duck at 0x1068e4e10>
    In [51]: red_duck.color
    Out[51]: 'red'

As for namedtuple

from collections import namedtuple
Duck = namedtuple('Duck', ['color', 'weight'])
red_duck = Duck('red', '10')

In [54]: red_duck
Out[54]: Duck(color='red', weight='10')
In [55]: red_duck.color
Out[55]: 'red'

Can my enums have friendly names?

You can use the Description attribute to get that friendly name. You can use the code below:

public static string ToStringEnums(Enum en)
{
    Type type = en.GetType();

    MemberInfo[] memInfo = type.GetMember(en.ToString());
    if (memInfo != null && memInfo.Length > 0)
    {
        object[] attrs = memInfo[0].GetCustomAttributes(typeof(DescriptionAttribute), false);
        if (attrs != null && attrs.Length > 0)
            return ((DescriptionAttribute)attrs[0]).Description;
    }
    return en.ToString();
}

An example of when you would want to use this method: When your enum value is EncryptionProviderType and you want enumVar.Tostring() to return "Encryption Provider Type".

Prerequisite: All enum members should be applied with the attribute [Description("String to be returned by Tostring()")].

Example enum:

enum ExampleEnum
{
    [Description("One is one")]
    ValueOne = 1,
    [Description("Two is two")]
    ValueTow = 2
}

And in your class, you would use it like this:

ExampleEnum enumVar = ExampleEnum.ValueOne;
Console.WriteLine(ToStringEnums(enumVar));

Python/BeautifulSoup - how to remove all tags from an element?

Here is the source code: you can get the text which is exactly in the URL

URL = ''
page = requests.get(URL)
soup = bs4.BeautifulSoup(page.content,'html.parser').get_text()
print(soup)

Best tool for inspecting PDF files?

I've used PDFBox with good success. Here's a sample of what the code looks like (back from version 0.7.2), that likely came from one of the provided examples:

// load the document
System.out.println("Reading document: " + filename);
PDDocument doc = null;                                                                                                                                                                                                          
doc = PDDocument.load(filename);

// look at all the document information
PDDocumentInformation info = doc.getDocumentInformation();
COSDictionary dict = info.getDictionary();
List l = dict.keyList();
for (Object o : l) {
    //System.out.println(o.toString() + " " + dict.getString(o));
    System.out.println(o.toString());
}

// look at the document catalog
PDDocumentCatalog cat = doc.getDocumentCatalog();
System.out.println("Catalog:" + cat);

List<PDPage> lp = cat.getAllPages();
System.out.println("# Pages: " + lp.size());
PDPage page = lp.get(4);
System.out.println("Page: " + page);
System.out.println("\tCropBox: " + page.getCropBox());
System.out.println("\tMediaBox: " + page.getMediaBox());
System.out.println("\tResources: " + page.getResources());
System.out.println("\tRotation: " + page.getRotation());
System.out.println("\tArtBox: " + page.getArtBox());
System.out.println("\tBleedBox: " + page.getBleedBox());
System.out.println("\tContents: " + page.getContents());
System.out.println("\tTrimBox: " + page.getTrimBox());
List<PDAnnotation> la = page.getAnnotations();
System.out.println("\t# Annotations: " + la.size());

ALTER TABLE DROP COLUMN failed because one or more objects access this column

The @SqlZim's answer is correct but just to explain why this possibly have happened. I've had similar issue and this was caused by very innocent thing: adding default value to a column

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int DEFAULT NULL;

But in the realm of MS SQL Server a default value on a colum is a CONSTRAINT. And like every constraint it has an identifier. And you cannot drop a column if it is used in a CONSTRAINT.

So what you can actually do avoid this kind of problems is always give your default constraints a explicit name, for example:

ALTER TABLE MySchema.MyTable ADD 
  MyColumn int NULL,
  CONSTRAINT DF_MyTable_MyColumn DEFAULT NULL FOR MyColumn;

You'll still have to drop the constraint before dropping the column, but you will at least know its name up front.

Counting the number of files in a directory using Java

Since you don't really need the total number, and in fact want to perform an action after a certain number (in your case 5000), you can use java.nio.file.Files.newDirectoryStream. The benefit is that you can exit early instead having to go through the entire directory just to get a count.

public boolean isOverMax(){
    Path dir = Paths.get("C:/foo/bar");
    int i = 1;

    try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
        for (Path p : stream) {
            //larger than max files, exit
            if (++i > MAX_FILES) {
                return true;
            }
        }
    } catch (IOException ex) {
        ex.printStackTrace();
    }

    return false;
}

The interface doc for DirectoryStream also has some good examples.

Error:Execution failed for task ':ProjectName:mergeDebugResources'. > Crunching Cruncher *some file* failed, see logs

As stated here this can happen when using the Gradle Tools v1.1.0. After updating to v1.1.3, this has not happened anymore.

How can I change the default Django date template format?

Just use this:

{{you_date_field|date:'Y-m-d'}}

This will show something like 2016-10-16. You can use the format as you want.

Difference between save and saveAndFlush in Spring data jpa

On saveAndFlush, changes will be flushed to DB immediately in this command. With save, this is not necessarily true, and might stay just in memory, until flush or commit commands are issued.

But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.

In your case, you probably use some sort of transactions mechanism, which issues commit command for you if everything works out fine.

Android studio Gradle icon error, Manifest Merger

For me, this issue occurred after updating Google Play Services. One of the libraries I was using incorporated this library using the "+" in its gradel reference, like

compile 'com.google.android.gms:play-services:+'

This created an issue because the min version targeted by that library was less than what was targeted by the current version of Google Play Services. I found this by simply looking in the logs.

What is the point of the diamond operator (<>) in Java 7?

Your understanding is slightly flawed. The diamond operator is a nice feature as you don't have to repeat yourself. It makes sense to define the type once when you declare the type but just doesn't make sense to define it again on the right side. The DRY principle.

Now to explain all the fuzz about defining types. You are right that the type is removed at runtime but once you want to retrieve something out of a List with type definition you get it back as the type you've defined when declaring the list otherwise it would lose all specific features and have only the Object features except when you'd cast the retrieved object to it's original type which can sometimes be very tricky and result in a ClassCastException.

Using List<String> list = new LinkedList() will get you rawtype warnings.

How to use: while not in

Using sets will be screaming fast if you have any volume of data

If you are willing to use sets, you have the isdisjoint() method which will check to see if the intersection between your operator list and your other list is empty.

MyOper = set(['AND', 'OR', 'NOT'])
MyList = set(['c1', 'c2', 'NOT', 'c3'])

while not MyList.isdisjoint(MyOper):
    print "No boolean Operator"

http://docs.python.org/library/stdtypes.html#set.isdisjoint

Android SDK manager won't open

Google removed the GUI for SDK starting from version 26. If you're using version 26, try downgrading to version 25. You can still open the SDK from Android Studio.

Source: Is GUI for Android SDK manager gone?

path.join vs path.resolve with __dirname

const absolutePath = path.join(__dirname, some, dir);

vs.

const absolutePath = path.resolve(__dirname, some, dir);

path.join will concatenate __dirname which is the directory name of the current file concatenated with values of some and dir with platform-specific separator.

Whereas

path.resolve will process __dirname, some and dir i.e. from right to left prepending it by processing it.

If any of the values of some or dir corresponds to a root path then the previous path will be omitted and process rest by considering it as root

In order to better understand the concept let me explain both a little bit more detail as follows:-

The path.join and path.resolve are two different methods or functions of the path module provided by nodejs.

Where both accept a list of paths but the difference comes in the result i.e. how they process these paths.

path.join concatenates all given path segments together using the platform-specific separator as a delimiter, then normalizes the resulting path. While the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

When no arguments supplied

The following example will help you to clearly understand both concepts:-

My filename is index.js and the current working directory is E:\MyFolder\Pjtz\node

const path = require('path');

console.log("path.join() : ", path.join());
// outputs .
console.log("path.resolve() : ", path.resolve());
// outputs current directory or equivalent to __dirname

Result

? node index.js
path.join() :  .
path.resolve() :  E:\MyFolder\Pjtz\node

path.resolve() method will output the absolute path whereas the path.join() returns . representing the current working directory if nothing is provided

When some root path is passed as arguments

const path=require('path');

console.log("path.join() : " ,path.join('abc','/bcd'));
console.log("path.resolve() : ",path.resolve('abc','/bcd'));

Result i

? node index.js
path.join() :  abc\bcd
path.resolve() :  E:\bcd

path.join() only concatenates the input list with platform-specific separator while the path.resolve() process the sequence of paths from right to left, with each subsequent path prepended until an absolute path is constructed.

"implements Runnable" vs "extends Thread" in Java

Runnable is an interface, while Thread is a class which implements this interface. From a design point of view, there should be a clean separation between how a task is defined and between how it is executed. The former is the responsibility of a Runnalbe implementation, and the latter is job of the Thread class. In most of the cases implementing Runnable is the right way to follow.

Refresh DataGridView when updating data source

Alexander Abakumov's answer is the correct one. It solved every binding issue I had updating the underlying data and having the grid update.

Its easy to implement and modify any existing source code you have.

grdDetails.DataSource = new System.Windows.Forms.BindingSource { DataSource = OrderDetails };

Android: Pass data(extras) to a fragment

great answer by @Rarw. Try using a bundle to pass information from one fragment to another

Difference between window.location.href=window.location.href and window.location.reload()

The difference is that

window.location = document.URL;

will not reload the page if there is a hash (#) in the URL (with or without something after it), whereas

window.location.reload();

will reload the page.

How do I declare a two dimensional array?

For a simple, "fill as you go" kind of solution:

$foo = array(array());

This will get you a flexible pseudo two dimensional array that can hold $foo[n][n] where n <= 8 (of course your limited by the usual constraints of memory size, but you get the idea I hope). This could, in theory, be extended to create as many sub arrays as you need.

How to get name of the computer in VBA?

A shell method to read the environmental variable for this courtesy of devhut

Debug.Print CreateObject("WScript.Shell").ExpandEnvironmentStrings("%COMPUTERNAME%")

Same source gives an API method:

Option Explicit

#If VBA7 And Win64 Then
    'x64 Declarations
    Declare PtrSafe Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#Else
    'x32 Declaration
    Declare Function GetComputerName Lib "kernel32" Alias "GetComputerNameA" (ByVal lpBuffer As String, nSize As Long) As Long
#End If

Public Sub test()

    Debug.Print ComputerName
    
End Sub

Public Function ComputerName() As String
    Dim sBuff                 As String * 255
    Dim lBuffLen              As Long
    Dim lResult               As Long
 
    lBuffLen = 255
    lResult = GetComputerName(sBuff, lBuffLen)
    If lBuffLen > 0 Then
        ComputerName = Left(sBuff, lBuffLen)
    End If
End Function

ValueError: Wrong number of items passed - Meaning and suggestions?

Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.

Using braces with dynamic variable names in PHP

I do this quite often on results returned from a query..

e.g.

// $MyQueryResult is an array of results from a query

foreach ($MyQueryResult as $key=>$value)
{
   ${$key}=$value;
}

Now I can just use $MyFieldname (which is easier in echo statements etc) rather than $MyQueryResult['MyFieldname']

Yep, it's probably lazy, but I've never had any problems.

How to change the Push and Pop animations in a navigation based app

@Luca Davanzo's answer in Swift 4.2

public extension UINavigationController {

    /**
     Pop current view controller to previous view controller.

     - parameter type:     transition animation type.
     - parameter duration: transition animation duration.
     */
    func pop(transitionType type: CATransitionType = .fade, duration: CFTimeInterval = 0.3) {
        self.addTransition(transitionType: type, duration: duration)
        self.popViewController(animated: false)
    }

    /**
     Push a new view controller on the view controllers's stack.

     - parameter vc:       view controller to push.
     - parameter type:     transition animation type.
     - parameter duration: transition animation duration.
     */
    func push(viewController vc: UIViewController, transitionType type: CATransitionType = .fade, duration: CFTimeInterval = 0.3) {
        self.addTransition(transitionType: type, duration: duration)
        self.pushViewController(vc, animated: false)
    }

    private func addTransition(transitionType type: CATransitionType = .fade, duration: CFTimeInterval = 0.3) {
        let transition = CATransition()
        transition.duration = duration
        transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
        transition.type = type
        self.view.layer.add(transition, forKey: nil)
    }

}