Programs & Examples On #Visual c++ 2005

The November 2005 release of Microsoft Visual C++, a C and C++ compiler for Windows, also known as the VC8 compiler.

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

LTrim function and RTrim function :

  • The LTrim function to remove leading spaces and the RTrim function to remove trailing spaces from a string variable.
  • It uses the Trim function to remove both types of spaces.

                  select LTRIM(RTRIM(' SQL Server '))
    

    output:

                             SQL Server
    

SVG gradient using CSS

2019 Answer

With brand new css properties you can have even more flexibility with variables aka custom properties

_x000D_
_x000D_
.shape {
  width:500px;
  height:200px;
}

.shape .gradient-bg {
  fill: url(#header-shape-gradient) #fff;
}

#header-shape-gradient {
  --color-stop: #f12c06;
  --color-bot: #faed34;
}
_x000D_
<svg viewBox="0 0 100 100" xmlns="http://www.w3.org/2000/svg" preserveAspectRatio="none" class="shape">
  <defs>
    <linearGradient id="header-shape-gradient" x2="0.35" y2="1">
        <stop offset="0%" stop-color="var(--color-stop)" />
        <stop offset="30%" stop-color="var(--color-stop)" />
        <stop offset="100%" stop-color="var(--color-bot)" />
      </linearGradient>
  </defs>
  <g>
    <polygon class="gradient-bg" points="0,0 100,0 0,66" />
  </g>
</svg>
_x000D_
_x000D_
_x000D_

Just set a named variable for each stop in gradient and then customize as you like in css. You can even change their values dynamically with javascript, like:

document.querySelector('#header-shape-gradient').style.setProperty('--color-stop', "#f5f7f9");

Argparse optional positional arguments?

As an extension to @VinaySajip answer. There are additional nargs worth mentioning.

  1. parser.add_argument('dir', nargs=1, default=os.getcwd())

N (an integer). N arguments from the command line will be gathered together into a list

  1. parser.add_argument('dir', nargs='*', default=os.getcwd())

'*'. All command-line arguments present are gathered into a list. Note that it generally doesn't make much sense to have more than one positional argument with nargs='*', but multiple optional arguments with nargs='*' is possible.

  1. parser.add_argument('dir', nargs='+', default=os.getcwd())

'+'. Just like '*', all command-line args present are gathered into a list. Additionally, an error message will be generated if there wasn’t at least one command-line argument present.

  1. parser.add_argument('dir', nargs=argparse.REMAINDER, default=os.getcwd())

argparse.REMAINDER. All the remaining command-line arguments are gathered into a list. This is commonly useful for command line utilities that dispatch to other command line utilities

If the nargs keyword argument is not provided, the number of arguments consumed is determined by the action. Generally this means a single command-line argument will be consumed and a single item (not a list) will be produced.

Edit (copied from a comment by @Acumenus) nargs='?' The docs say: '?'. One argument will be consumed from the command line if possible and produced as a single item. If no command-line argument is present, the value from default will be produced.

Spring configure @ResponseBody JSON format

For the folks who are using Java based Spring configuration:

@Configuration
@ComponentScan(basePackages = "com.domain.sample")
@EnableWebMvc
public class SpringConfig extends WebMvcConfigurerAdapter {
....

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        converter.setObjectMapper(objectMapper);
        converters.add(converter);
        super.configureMessageConverters(converters);
    }

....

}

I'm using MappingJackson2HttpMessageConverter - which is from fasterxml.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.3.1</version>
</dependency>

If you want to use codehaus-jackson mapper, instead use this one MappingJacksonHttpMessageConverter

 <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>${codehaus.jackson.version}</version>
 </dependency>

How do I remove duplicates from a C# array?

Here is a O(n*n) approach that uses O(1) space.

void removeDuplicates(char* strIn)
{
    int numDups = 0, prevIndex = 0;
    if(NULL != strIn && *strIn != '\0')
    {
        int len = strlen(strIn);
        for(int i = 0; i < len; i++)
        {
            bool foundDup = false;
            for(int j = 0; j < i; j++)
            {
                if(strIn[j] == strIn[i])
                {
                    foundDup = true;
                    numDups++;
                    break;
                }
            }

            if(foundDup == false)
            {
                strIn[prevIndex] = strIn[i];
                prevIndex++;
            }
        }

        strIn[len-numDups] = '\0';
    }
}

The hash/linq approaches above are what you would generally use in real life. However in interviews they usually want to put some constraints e.g. constant space which rules out hash or no internal api - which rules out using LINQ.

How to get a file or blob from an object URL?

Maybe someone finds this useful when working with React/Node/Axios. I used this for my Cloudinary image upload feature with react-dropzone on the UI.

    axios({
        method: 'get',
        url: file[0].preview, // blob url eg. blob:http://127.0.0.1:8000/e89c5d87-a634-4540-974c-30dc476825cc
        responseType: 'blob'
    }).then(function(response){
         var reader = new FileReader();
         reader.readAsDataURL(response.data); 
         reader.onloadend = function() {
             var base64data = reader.result;
             self.props.onMainImageDrop(base64data)
         }

    })

Python webbrowser.open() to open Chrome browser

In Selenium to get the URL of the active tab try,

from selenium import webdriver

driver = webdriver.Firefox()
print driver.current_url # This will print the URL of the Active link

Sending a signal to change the tab

driver.find_element_by_tag_name('body').send_keys(Keys.CONTROL + Keys.TAB)

and again use

print driver.current_url

I am here just providing a pseudo code for you.

You can put this in a loop and create your own flow.

I new to Stackoverflow so still learning how to write proper answers.

compare differences between two tables in mysql

I found another solution in this link

SELECT MIN (tbl_name) AS tbl_name, PK, column_list
FROM
 (
  SELECT ' source_table ' as tbl_name, S.PK, S.column_list
  FROM source_table AS S
  UNION ALL
  SELECT 'destination_table' as tbl_name, D.PK, D.column_list
  FROM destination_table AS D 
)  AS alias_table
GROUP BY PK, column_list
HAVING COUNT(*) = 1
ORDER BY PK

How to delete all files and folders in a folder by cmd call

One easy one-line option is to create an empty directory somewhere on your file system, and then use ROBOCOPY (http://technet.microsoft.com/en-us/library/cc733145.aspx) with the /MIR switch to remove all files and subfolders. By default, robocopy does not copy security, so the ACLs in your root folder should remain intact.

Also probably want to set a value for the retry switch, /r, because the default number of retries is 1 million.

robocopy "C:\DoNotDelete_UsedByScripts\EmptyFolder" "c:\temp\MyDirectoryToEmpty" /MIR /r:3

How to get values and keys from HashMap?

With java8 streaming API:

List values = map.entrySet().stream().map(Map.Entry::getValue).collect(Collectors.toList());

How do I convert a long to a string in C++?

int main()
{
    long mylong = 123456789;
    string mystring;
    stringstream mystream;
    mystream << mylong;
    mystring = mystream.str();
    cout << mystring << "\n";
    return 0;
}

Change image in HTML page every few seconds

Best way to swap images with javascript with left vertical clickable thumbnails

SCRIPT FILE: function swapImages() {

    window.onload = function () {
        var img = document.getElementById("img_wrap");
        var imgall = img.getElementsByTagName("img");
        var firstimg = imgall[0]; //first image
        for (var a = 0; a <= imgall.length; a++) {
            setInterval(function () {
                var rand = Math.floor(Math.random() * imgall.length);
                firstimg.src = imgall[rand].src;
            }, 3000);



            imgall[1].onmouseover = function () {
                 //alert("what");
                clearInterval();
                firstimg.src = imgall[1].src;


            }
            imgall[2].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[2].src;
            }
            imgall[3].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[3].src;
            }
            imgall[4].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[4].src;
            }
            imgall[5].onmouseover = function () {
                clearInterval();
                firstimg.src = imgall[5].src;
            }
        }

    }


}

Vim for Windows - What do I type to save and exit from a file?

Use:

:wq!

The exclamation mark is used for overriding read-only mode.

Override body style for content in an iframe

Override another domain iframe CSS

By using part of SimpleSam5's answer, I achieved this with a few of Tawk's chat iframes (their customization interface is fine but I needed further customizations).

In this particular iframe that shows up on mobile devices, I needed to hide the default icon and place one of my background images. I did the following:

Tawk_API.onLoad = function() {
// without a specific API, you may try a similar load function
// perhaps with a setTimeout to ensure the iframe's content is fully loaded
  $('#mtawkchat-minified-iframe-element').
    contents().find("head").append(
     $("<style type='text/css'>"+
       "#tawkchat-status-text-container {"+
         "background: url(https://example.net/img/my_mobile_bg.png) no-repeat center center blue;"+
         "background-size: 100%;"+
       "} "+
       "#tawkchat-status-icon {display:none} </style>")
   );
};

I do not own any Tawk's domain and this worked for me, thus you may do this even if it's not from the same parent domain (despite Jeremy Becker's comment on Sam's answer).

Trust Store vs Key Store - creating with keytool

To explain in common usecase/purpose or layman way:

TrustStore : As the name indicates, its normally used to store the certificates of trusted entities. A process can maintain a store of certificates of all its trusted parties which it trusts.

keyStore : Used to store the server keys (both public and private) along with signed cert.

During the SSL handshake,

  1. A client tries to access https://

  2. And thus, Server responds by providing a SSL certificate (which is stored in its keyStore)

  3. Now, the client receives the SSL certificate and verifies it via trustStore (i.e the client's trustStore already has pre-defined set of certificates which it trusts.). Its like : Can I trust this server ? Is this the same server whom I am trying to talk to ? No middle man attacks ?

  4. Once, the client verifies that it is talking to server which it trusts, then SSL communication can happen over a shared secret key.

Note : I am not talking here anything about client authentication on server side. If a server wants to do a client authentication too, then the server also maintains a trustStore to verify client. Then it becomes mutual TLS

Can I recover a branch after its deletion in Git?

For recovering a deleted branch, First go through the reflog history,

git reflog -n 60

Where n refers to the last n commits. Then find the proper head and create a branch with that head.

git branch testbranch HEAD@{30}

Regex to get string between curly braces

Try this:

/[^{\}]+(?=})/g

For example

Welcome to RegExr v2.1 by #{gskinner.com},  #{ssd.sd} hosted by Media Temple!

will return gskinner.com, ssd.sd.

How to get IntPtr from byte[] in C#

IntPtr GetIntPtr(Byte[] byteBuf)
{
    IntPtr ptr = Marshal.AllocHGlobal(byteBuf.Length);
    for (int i = 0; i < byteBuf.Length; i++)
    {
       Marshal.WriteByte(ptr, i, byteBuf[i]);
    }
    return ptr;
}

Cannot deserialize the current JSON array (e.g. [1,2,3])


To read more than one json tip (array, attribute) I did the following.


var jVariable = JsonConvert.DeserializeObject<YourCommentaryClass>(jsonVariableContent);

change to

var jVariable = JsonConvert.DeserializeObject <List<YourCommentaryClass>>(jsonVariableContent);

Because you cannot see all the bits in the method used in the foreach loop. Example foreach loop

foreach (jsonDonanimSimple Variable in jVariable)
                {    
                    debugOutput(jVariable.Id.ToString());
                    debugOutput(jVariable.Header.ToString());
                    debugOutput(jVariable.Content.ToString());
                }

I also received an error in this loop and changed it as follows.

foreach (jsonDonanimSimple Variable in jVariable)
                    {    
                        debugOutput(Variable.Id.ToString());
                        debugOutput(Variable.Header.ToString());
                        debugOutput(Variable.Content.ToString());
                    }

How to find substring from string?

Use strstr(const char *s , const char *t) and include<string.h>

You can write your own function which behaves same as strstr and you can modify according to your requirement also

char * str_str(const char *s, const char *t)
{
int i, j, k;
for (i = 0; s[i] != '\0'; i++) 
{
for (j=i, k=0; t[k]!='\0' && s[j]==t[k]; j++, k++);
if (k > 0 && t[k] == '\0')
return (&s[i]);
}
return NULL;
}

Calculating distance between two points, using latitude longitude?

Future readers who stumble upon this SOF article.

Obviously, the question was asked in 2010 and its now 2019. But it comes up early in an internet search. The original question does not discount use of third-party-library (when I wrote this answer).

public double calculateDistanceInMeters(double lat1, double long1, double lat2,
                                     double long2) {


    double dist = org.apache.lucene.util.SloppyMath.haversinMeters(lat1, long1, lat2, long2);
    return dist;
}

and

<dependency>
  <groupId>org.apache.lucene</groupId>
  <artifactId>lucene-spatial</artifactId>
  <version>8.2.0</version>
</dependency>

https://mvnrepository.com/artifact/org.apache.lucene/lucene-spatial/8.2.0

Please read documentation about "SloppyMath" before diving in!

https://lucene.apache.org/core/8_2_0/core/org/apache/lucene/util/SloppyMath.html

Select 2 columns in one and combine them

Yes,

SELECT CONCAT(field1, field2) AS WHOLENAME FROM TABLE
WHERE ...

will result in data set like:

WHOLENAME
field1field2

What are alternatives to ExtJS?

Nothing compares to in terms of community size and presence on StackOverflow. Despite previous controversy, Ext JS now has a GPLv3 open source license. Its learning curve is long, but it can be quite rewarding once learned. Ext JS lacks a Material Design theme, and the team has repeatedly refused to release the source code on GitHub. For mobile, one must use the separate Sencha Touch library.

Have in mind also that,

large JavaScript libraries, such as YUI, have been receiving less attention from the community. Many developers today look at large JavaScript libraries as walled gardens they don’t want to be locked into.

-- Announcement of YUI development being ceased

That said, below are a number of Ext JS alternatives currently available.

Leading client widget libraries

  1. Blueprint is a React-based UI toolkit developed by big data analytics company Palantir in TypeScript, and "optimized for building complex data-dense interfaces for desktop applications". Actively developed on GitHub as of May 2019, with comprehensive documentation. Components range from simple (chips, toast, icons) to complex (tree, data table, tag input with autocomplete, date range picker. No accordion or resizer.

    Blueprint targets modern browsers (Chrome, Firefox, Safari, IE 11, and Microsoft Edge) and is licensed under a modified Apache license.

    Sandbox / demoGitHubDocs

  2. Webix - an advanced, easy to learn, mobile-friendly, responsive and rich free&open source JavaScript UI components library. Webix spun off from DHTMLX Touch (a project with 8 years of development behind it - see below) and went on to become a standalone UI components framework. The GPL3 edition allows commercial use and lets non-GPL applications using Webix keep their license, e.g. MIT, via a license exemption for FLOSS. Webix has 55 UI widgets, including trees, grids, treegrids and charts. Funding comes from a commercial edition with some advanced widgets (Pivot, Scheduler, Kanban, org chart etc.). Webix has an extensive list of free and commercial widgets, and integrates with most popular frameworks (React, Vue, Meteor, etc) and UI components.

    Webix

    Skins look modern, and include a Material Design theme. The Touch theme also looks quite Material Design-ish. See also the Skin Builder.

    Minimal GitHub presence, but includes the library code, and the documentation (which still needs major improvements). Webix suffers from a having a small team and a lack of marketing. However, they have been responsive to user feedback, both on GitHub and on their forum.

    The library was lean (128Kb gzip+minified for all 55 widgets as of ~2015), faster than ExtJS, dojo and others, and the design is pleasant-looking. The current version of Webix (v6, as of Nov 2018) got heavier (400 - 676kB minified but NOT gzipped).

    The demos on Webix.com look and function great. The developer, XB Software, uses Webix in solutions they build for paying customers, so there's likely a good, funded future ahead of it.

    Webix aims for backwards compatibility down to IE8, and as a result carries some technical debt.

    WikipediaGitHubPlayground/sandboxAdmin dashboard demoDemosWidget samples

  3. react-md - MIT-licensed Material Design UI components library for React. Responsive, accessible. Implements components from simple (buttons, cards) to complex (sortable tables, autocomplete, tags input, calendars). One lead author, ~1900 GitHub stars.

  4. - jQuery-based UI toolkit with 40+ basic open-source widgets, plus commercial professional widgets (grids, trees, charts etc.). Responsive&mobile support. Works with Bootstrap and AngularJS. Modern, with Material Design themes. The documentation is available on GitHub, which has enabled numerous contributions from users (4500+ commits, 500+ PRs as of Jan 2015).

    enter image description here

    Well-supported commercially, claiming millions of developers, and part of a large family of developer tools. Telerik has received many accolades, is a multi-national company (Bulgaria, US), was acquired by Progress Software, and is a thought leader.

    A Kendo UI Professional developer license costs $700 and posting access to most forums is conditioned upon having a license or being in the trial period.

    [Wikipedia] • GitHub/TelerikDemosPlaygroundTools

  5. OpenUI5 - jQuery-based UI framework with 180 widgets, Apache 2.0-licensed and fully-open sourced and funded by German software giant SAP SE.

    OpenUI5

    The community is much larger than that of Webix, SAP is hiring developers to grow OpenUI5, and they presented OpenUI5 at OSCON 2014.

    The desktop themes are rather lackluster, but the Fiori design for web and mobile looks clean and neat.

    WikipediaGitHubMobile-first controls demosDesktop controls demosSO

  6. DHTMLX - JavaScript library for building rich Web and Mobile apps. Looks most like ExtJS - check the demos. Has been developed since 2005 but still looks modern. All components except TreeGrid are available under GPLv2 but advanced features for many components are only available in the commercial PRO edition - see for example the tree. Claims to be used by many Fortune 500 companies.

    DHTMLX

    Minimal presence on GitHub (the main library code is missing) and StackOverflow but active forum. The documentation is not available on GitHub, which makes it difficult to improve by the community.

  7. Polymer, a Web Components polyfill, plus Polymer Paper, Google's implementation of the Material design. Aimed at web and mobile apps. Doesn't have advanced widgets like trees or even grids but the controls it provides are mobile-first and responsive. Used by many big players, e.g. IBM or USA Today.

    Polymer Paper Elements

  8. Ant Design claims it is "a design language for background applications", influenced by "nature" and helping designers "create low-entropy atmosphere for developer team". That's probably a poor translation from Chinese for "UI components for enterprise web applications". It's a React UI library written in TypeScript, with many components, from simple (buttons, cards) to advanced (autocomplete, calendar, tag input, table).

    The project was born in China, is popular with Chinese companies, and parts of the documentation are available only in Chinese. Quite popular on GitHub, yet it makes the mistake of splitting the community into Chinese and English chat rooms. The design looks Material-ish, but fonts are small and the information looks lost in a see of whitespace.

  9. PrimeUI - collection of 45+ rich widgets based on jQuery UI. Apache 2.0 license. Small GitHub community. 35 premium themes available.

  10. qooxdoo - "a universal JavaScript framework with a coherent set of individual components", developed and funded by German hosting provider 1&1 (see the contributors, one of the world's largest hosting companies. GPL/EPL (a business-friendly license).

    Mobile themes look modern but desktop themes look old (gradients).

    Qooxdoo

    WikipediaGitHubWeb/Mobile/Desktop demosWidgets Demo browserWidget browserSOPlaygroundCommunity

  11. jQuery UI - easy to pick up; looks a bit dated; lacks advanced widgets. Of course, you can combine it with independent widgets for particular needs, e.g. trees or other UI components, but the same can be said for any other framework.

  12. + Angular UI. While Angular is backed by Google, it's being radically revamped in the upcoming 2.0 version, and "users will need to get to grips with a new kind of architecture. It's also been confirmed that there will be no migration path from Angular 1.X to 2.0". Moreover, the consensus seems to be that Angular 2 won't really be ready for use until a year or two from now. Angular UI has relatively few widgets (no trees, for example).

  13. DojoToolkit and their powerful Dijit set of widgets. Completely open-sourced and actively developed on GitHub, but development is now (Nov 2018) focused on the new dojo.io framework, which has very few basic widgets. BSD/AFL license. Development started in 2004 and the Dojo Foundation is being sponsored by IBM, Google, and others - see Wikipedia. 7500 questions here on SO.

    Dojo Dijit

    Themes look desktop-oriented and dated - see the theme tester in dijit. The official theme previewer is broken and only shows "Claro". A Bootstrap theme exists, which looks a lot like Bootstrap, but doesn't use Bootstrap classes. In Jan 2015, I started a thread on building a Material Design theme for Dojo, which got quite popular within the first hours. However, there are questions regarding building that theme for the current Dojo 1.10 vs. the next Dojo 2.0. The response to that thread shows an active and wide community, covering many time zones.

    Unfortunately, Dojo has fallen out of popularity and fewer companies appear to use it, despite having (had?) a strong foothold in the enterprise world. In 2009-2012, its learning curve was steep and the documentation needed improvements; while the documentation has substantially improved, it's unclear how easy it is to pick up Dojo nowadays.

    With a Material Design theme, Dojo (2.0?) might be the killer UI components framework.

    WikipediaGitHubThemesDemosDesktop widgetsSO

  14. Enyo - front-end library aimed at mobile and TV apps (e.g. large touch-friendly controls). Developed by LG Electronix and Apache-licensed on GitHub.

  15. The radical Cappuccino - Objective-J (a superset of JavaScript) instead of HTML+CSS+DOM

  16. Mochaui, MooTools UI Library User Interface Library. <300 GitHub stars.

  17. CrossUI - cross-browser JS framework to develop and package the exactly same code and UI into Web Apps, Native Desktop Apps (Windows, OS X, Linux) and Mobile Apps (iOS, Android, Windows Phone, BlackBerry). Open sourced LGPL3. Featured RAD tool (form builder etc.). The UI looks desktop-, not web-oriented. Actively developed, small community. No presence on GitHub.

  18. ZinoUI - simple widgets. The DataTable, for instance, doesn't even support sorting.

  19. Wijmo - good-looking commercial widgets, with old (jQuery UI) widgets open-sourced on GitHub (their development stopped in 2013). Developed by ComponentOne, a division of GrapeCity. See Wijmo Complete vs. Open.

  20. CxJS - commercial JS framework based on React, Babel and webpack offering form elements, form validation, advanced grid control, navigational elements, tooltips, overlays, charts, routing, layout support, themes, culture dependent formatting and more.

CxJS

Widgets - Demo Apps - Examples - GitHub

Full-stack frameworks

  1. SproutCore - developed by Apple for web applications with native performance, handling large data sets on the client. Powers iCloud.com. Not intended for widgets.

  2. Wakanda: aimed at business/enterprise web apps - see What is Wakanda?. Architecture:

  3. Servoy - "a cross platform frontend development and deployment environment for SQL databases". Boasts a "full WYSIWIG (What You See Is What You Get) UI designer for HTML5 with built-in data-binding to back-end services", responsive design, support for HTML6 Web Components, Websockets and mobile platforms. Written in Java and generates JavaScript code using various JavaBeans.

  4. SmartClient/SmartGWT - mobile and cross-browser HTML5 UI components combined with a Java server. Aimed at building powerful business apps - see demos.

  5. Vaadin - full-stack Java/GWT + JavaScript/HTML3 web app framework

  6. Backbase - portal software

  7. Shiny - front-end library on top R, with visualization, layout and control widgets

  8. ZKOSS: Java+jQuery+Bootstrap framework for building enterprise web and mobile apps.

CSS libraries + minimal widgets

These libraries don't implement complex widgets such as tables with sorting/filtering, autocompletes, or trees.

  1. Bootstrap

  2. Foundation for Apps - responsive front-end framework on top of AngularJS; more of a grid/layout/navigation library

  3. UI Kit - similar to Bootstrap, with fewer widgets, but with official off-canvas.

Libraries using HTML Canvas

Using the canvas elements allows for complete control over the UI, and great cross-browser compatibility, but comes at the cost of missing native browser functionality, e.g. page search via Ctrl/Cmd+F.

  1. Zebra - demos

No longer developed as of Dec 2014

  1. Yahoo! User Interface - YUI, launched in 2005, but no longer maintained by the core contributors - see the announcement, which highlights reasons why large UI widget libraries are perceived as walled gardens that developers don't want to be locked into.
  2. echo3, GitHub. Supports writing either server-side Java applications that don't require developer knowledge of HTML, HTTP, or JavaScript, or client-side JavaScript-based applications do not require a server, but can communicate with one via AJAX. Last update: July 2013.
  3. ampleSDK
  4. Simpler widgets livepipe.net
  5. JxLib
  6. rialto
  7. Simple UI kit
  8. Prototype-ui

Other lists

Redis - Connect to Remote Server

  • if you downloaded redis yourself (not apt-get install redis-server) and then edited the redis.conf with the above suggestions, make sure your start redis with the config like so: ./src/redis-server redis.conf

    • also side note i am including a screenshot of virtual box setting to connect to redis, if you are on windows and connecting to a virtualbox vm.

enter image description here

Deserialize a JSON array in C#

This code is working fine for me,

var a = serializer.Deserialize<List<Entity>>(json);

Javascript Uncaught Reference error Function is not defined

In JSFiddle, when you set the wrapping to "onLoad" or "onDomready", the functions you define are only defined inside that block, and cannot be accessed by outside event handlers.

Easiest fix is to change:

function something(...)

To:

window.something = function(...)

How to import JsonConvert in C# application?

If you are developing a .Net Core WebApi or WebSite you dont not need to install newtownsoft.json to perform json serialization/deserealization

Just make sure that your controller method returns a JsonResult and call return Json(<objectoToSerialize>); like this example

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            return Json(lstAccounts);
        }
    }
}

If you are developing a .Net Framework WebApi or WebSite you need to use NuGet to download and install the newtonsoft json package

"Project" -> "Manage NuGet packages" -> "Search for "newtonsoft json". -> click "install".

namespace WebApi.Controllers
{
    [Produces("application/json")]
    [Route("api/Accounts")]
    public class AccountsController : Controller
    {
        // GET: api/Transaction
        [HttpGet]
        public JsonResult Get()
        {
            List<Account> lstAccounts;

            lstAccounts = AccountsFacade.GetAll();

            //This line is different !! 
            return new JsonConvert.SerializeObject(lstAccounts);
        }
    }
}

More details can be found here - https://docs.microsoft.com/en-us/aspnet/core/web-api/advanced/formatting?view=aspnetcore-2.1

Set Background cell color in PHPExcel

$objPHPExcel
->getActiveSheet()
->getStyle('A1')
->getFill()
->setFillType(PHPExcel_Style_Fill::FILL_SOLID)
->getStartColor()
->setRGB('colorcode'); //i.e,colorcode=D3D3D3

How to put multiple statements in one line?

You are mixing a lot of things, which makes it hard to answer your question. The short answer is: As far as I know, what you want to do is just not possible in Python - for good reason!

The longer answer is that you should make yourself more comfortable with Python, if you want to develop in Python. Comprehensions are not hard to read. You might not be used to reading them, but you have to get used to it if you want to be a Python developer. If there is a language that fits your needs better, choose that one. If you choose Python, be prepared to solve problems in a pythonic way. Of course you are free to fight against Python, But it will not be fun! ;-)

And if you would tell us what your real problem is, you might even get a pythonic answer. "Getting something in one line" us usually not a programming problem.

How to send an object from one Android Activity to another using Intents?

you can use putExtra(Serializable..) and getSerializableExtra() methods to pass and retrieve objects of your class type; you will have to mark your class Serializable and make sure that all your member variables are serializable too...

UnicodeEncodeError: 'latin-1' codec can't encode character

Latin-1 (aka ISO 8859-1) is a single octet character encoding scheme, and you can't fit \u201c () into a byte.

Did you mean to use UTF-8 encoding?

How do I handle ImeOptions' done button click?

Thanks to chikka.anddev and Alex Cohn in Kotlin it is:

text.setOnEditorActionListener { v, actionId, event ->
    if (actionId == EditorInfo.IME_ACTION_DONE ||
        event?.action == KeyEvent.ACTION_DOWN && event.keyCode == KeyEvent.KEYCODE_ENTER) {
        doSomething()
        true
    } else {
        false
    }
}

Here I check for Enter key, because it returns EditorInfo.IME_NULL instead of IME_ACTION_DONE.

See also Android imeOptions="actionDone" not working. Add android:singleLine="true" in the EditText.

Converting HTML to XML

I was successful using tidy command line utility. On linux I installed it quickly with apt-get install tidy. Then the command:

tidy -q -asxml --numeric-entities yes source.html >file.xml

gave an xml file, which I was able to process with xslt processor. However I needed to set up xhtml1 dtds correctly.

This is their homepage: html-tidy.org (and the legacy one: HTML Tidy)

Keyboard shortcuts in WPF

Special case: your shortcut doesn't trigger if the focus is on an element that "isn't native". In my case for example, a focus on a WpfCurrencyTextbox won't trigger shortcuts defined in your XAML (defined like in oliwa's answer).

I fixed this issue by making my shortcut global with the NHotkey package.

In short, for XAML, all you need to do is to replace

<KeyBinding Gesture="Ctrl+Alt+Add" Command="{Binding IncrementCommand}" />

by

<KeyBinding Gesture="Ctrl+Alt+Add" Command="{Binding IncrementCommand}"
            HotkeyManager.RegisterGlobalHotkey="True" />

Answer has also been posted to: How can I register a global hot key to say CTRL+SHIFT+(LETTER) using WPF and .NET 3.5?

How to get last key in an array?

Try using array_pop and array_keys function as follows:

<?php

$array = array(
    'one' => 1,
    'two' => 2,
    'three' => 3
);

echo array_pop(array_keys($array)); // prints three

?>

See :hover state in Chrome Developer Tools

Changing to hover status in Chrome is pretty easy, just follow these steps below:

1) Right click in your page and select inspect

enter image description here

2) Select the element you like to have inspect in the DOM

enter image description here

3) Select the pin icon enter image description here (Toggle Element State)

4) Then tick the hover

Now you can see the hover state of the selected DOM in the browser!

Command CompileSwift failed with a nonzero exit code in Xcode 10

For me, the error message said I had too many simulator files open to build Swift. When I quit the simulator and built again, everything worked.

Cannot construct instance of - Jackson

Your @JsonSubTypes declaration does not make sense: it needs to list implementation (sub-) classes, NOT the class itself (which would be pointless). So you need to modify that entry to list sub-class(es) there are; or use some other mechanism to register sub-classes (SimpleModule has something like addAbstractTypeMapping).

How to configure the web.config to allow requests of any length

If your website is using authentication, but you don't have the correct authentication method set up in IIS (e.g. Basic, Forms etc..) then the browser will be getting stuck in a redirect loop. This causes the redirect url to get longer and longer until it explodes.

Bash mkdir and subfolders

FWIW,

Poor mans security folder (to protect a public shared folder from little prying eyes ;) )

mkdir -p {0..9}/{0..9}/{0..9}/{0..9}

Now you can put your files in a pin numbered folder. Not exactly waterproof, but it's a barrier for the youngest.

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

How to read an external properties file in Maven

Using the suggested Maven properties plugin I was able to read in a buildNumber.properties file that I use to version my builds.

  <build>    
    <plugins>
      <plugin>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>properties-maven-plugin</artifactId>
        <version>1.0-alpha-1</version>
        <executions>
          <execution>
            <phase>initialize</phase>
            <goals>
              <goal>read-project-properties</goal>
            </goals>
            <configuration>
              <files>
                <file>${basedir}/../project-parent/buildNumber.properties</file>
              </files>
            </configuration>
          </execution>
        </executions>
      </plugin>
   </plugins>

CMake link to external library

Set libraries search path first:

LINK_DIRECTORIES(${CMAKE_BINARY_DIR}/res)

And then just do

TARGET_LINK_LIBRARIES(GLBall mylib)

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

It is a RAM related issue. The documentation is self explanatory:

You are trying to allocate >3GB of RAM to the VM. This requires: (a) a 64 bit host system; and (b) true hardware pass-through ie VT-x.

Fast solution

Allocate less than 3GB for the virtual machine.

Complete solution

  1. Make sure your system is 64 bit.
  2. Enable virtualisation in your host machine. You can find how to do it here or there are many other resources available on Google.

How to validate phone numbers using regex

Although the answer to strip all whitespace is neat, it doesn't really solve the problem that's posed, which is to find a regex. Take, for instance, my test script that downloads a web page and extracts all phone numbers using the regex. Since you'd need a regex anyway, you might as well have the regex do all the work. I came up with this:

1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?

Here's a perl script to test it. When you match, $1 contains the area code, $2 and $3 contain the phone number, and $5 contains the extension. My test script downloads a file from the internet and prints all the phone numbers in it.

#!/usr/bin/perl

my $us_phone_regex =
        '1?\W*([2-9][0-8][0-9])\W*([2-9][0-9]{2})\W*([0-9]{4})(\se?x?t?(\d*))?';


my @tests =
(
"1-234-567-8901",
"1-234-567-8901 x1234",
"1-234-567-8901 ext1234",
"1 (234) 567-8901",
"1.234.567.8901",
"1/234/567/8901",
"12345678901",
"not a phone number"
);

foreach my $num (@tests)
{
        if( $num =~ m/$us_phone_regex/ )
        {
                print "match [$1-$2-$3]\n" if not defined $4;
                print "match [$1-$2-$3 $5]\n" if defined $4;
        }
        else
        {
                print "no match [$num]\n";
        }
}

#
# Extract all phone numbers from an arbitrary file.
#
my $external_filename =
        'http://web.textfiles.com/ezines/PHREAKSANDGEEKS/PnG-spring05.txt';
my @external_file = `curl $external_filename`;
foreach my $line (@external_file)
{
        if( $line =~ m/$us_phone_regex/ )
        {
                print "match $1 $2 $3\n";
        }
}

Edit:

You can change \W* to \s*\W?\s* in the regex to tighten it up a bit. I wasn't thinking of the regex in terms of, say, validating user input on a form when I wrote it, but this change makes it possible to use the regex for that purpose.

'1?\s*\W?\s*([2-9][0-8][0-9])\s*\W?\s*([2-9][0-9]{2})\s*\W?\s*([0-9]{4})(\se?x?t?(\d*))?';

How to get number of rows using SqlDataReader in C#

Per above, a dataset or typed dataset might be a good temorary structure which you could use to do your filtering. A SqlDataReader is meant to read the data very quickly. While you are in the while() loop you are still connected to the DB and it is waiting for you to do whatever you are doing in order to read/process the next result before it moves on. In this case you might get better performance if you pull in all of the data, close the connection to the DB and process the results "offline".

People seem to hate datasets, so the above could be done wiht a collection of strongly typed objects as well.

Send HTTP GET request with header

Here's a code excerpt we're using in our app to set request headers. You'll note we set the CONTENT_TYPE header only on a POST or PUT, but the general method of adding headers (via a request interceptor) is used for GET as well.

/**
 * HTTP request types
 */
public static final int POST_TYPE   = 1;
public static final int GET_TYPE    = 2;
public static final int PUT_TYPE    = 3;
public static final int DELETE_TYPE = 4;

/**
 * HTTP request header constants
 */
public static final String CONTENT_TYPE         = "Content-Type";
public static final String ACCEPT_ENCODING      = "Accept-Encoding";
public static final String CONTENT_ENCODING     = "Content-Encoding";
public static final String ENCODING_GZIP        = "gzip";
public static final String MIME_FORM_ENCODED    = "application/x-www-form-urlencoded";
public static final String MIME_TEXT_PLAIN      = "text/plain";

private InputStream performRequest(final String contentType, final String url, final String user, final String pass,
    final Map<String, String> headers, final Map<String, String> params, final int requestType) 
            throws IOException {

    DefaultHttpClient client = HTTPClientFactory.newClient();

    client.getParams().setParameter(HttpProtocolParams.USER_AGENT, mUserAgent);

    // add user and pass to client credentials if present
    if ((user != null) && (pass != null)) {
        client.getCredentialsProvider().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
    }

    // process headers using request interceptor
    final Map<String, String> sendHeaders = new HashMap<String, String>();
    if ((headers != null) && (headers.size() > 0)) {
        sendHeaders.putAll(headers);
    }
    if (requestType == HTTPRequestHelper.POST_TYPE || requestType == HTTPRequestHelper.PUT_TYPE ) {
        sendHeaders.put(HTTPRequestHelper.CONTENT_TYPE, contentType);
    }
    // request gzip encoding for response
    sendHeaders.put(HTTPRequestHelper.ACCEPT_ENCODING, HTTPRequestHelper.ENCODING_GZIP);

    if (sendHeaders.size() > 0) {
        client.addRequestInterceptor(new HttpRequestInterceptor() {

            public void process(final HttpRequest request, final HttpContext context) throws HttpException,
                IOException {
                for (String key : sendHeaders.keySet()) {
                    if (!request.containsHeader(key)) {
                        request.addHeader(key, sendHeaders.get(key));
                    }
                }
            }
        });
    }

    //.... code omitted ....//

}

recursively use scp but excluding some folders

Assuming the simplest option (installing rsync on the remote host) isn't feasible, you can use sshfs to mount the remote locally, and rsync from the mount directory. That way you can use all the options rsync offers, for example --exclude.

Something like this should do:

sshfs user@server: sshfsdir
rsync --recursive --exclude=whatever sshfsdir/path/on/server /where/to/store

Note that the effectiveness of rsync (only transferring changes, not everything) doesn't apply here. This is because for that to work, rsync must read every file's contents to see what has changed. However, as rsync runs only on one host, the whole file must be transferred there (by sshfs). Excluded files should not be transferred, however.

How do I delete rows in a data frame?

Create id column in your data frame or use any column name to identify the row. Using index is not fair to delete.

Use subset function to create new frame.

updated_myData <- subset(myData, id!= 6)
print (updated_myData)

updated_myData <- subset(myData, id %in% c(1, 3, 5, 7))
print (updated_myData)

How to create SPF record for multiple IPs?

Yes the second syntax is fine.

Have you tried using the SPF wizard? https://www.spfwizard.net/

It can quickly generate basic and complex SPF records.

What are the safe characters for making URLs?

Always Safe

In theory and by the specification, these are safe basically anywhere, except the domain name. Percent-encode anything not listed, and you're good to go.

    A-Z a-z 0-9 - . _ ~ ( ) ' ! * : @ , ;

Sometimes Safe

Only safe when used within specific URL components; use with care.

    Paths:     + & =
    Queries:   ? /
    Fragments: ? / # + & =
    

Never Safe

According to the URI specification (RFC 3986), all other characters must be percent-encoded. This includes:

    <space> <control-characters> <extended-ascii> <unicode>
    % < > [ ] { } | \ ^
    

If maximum compatibility is a concern, limit the character set to A-Z a-z 0-9 - _ . (with periods only for filename extensions).

Keep Context in Mind

Even if valid per the specification, a URL can still be "unsafe", depending on context. Such as a file:/// URL containing invalid filename characters, or a query component containing "?", "=", and "&" when not used as delimiters. Correct handling of these cases are generally up to your scripts and can be worked around, but it's something to keep in mind.

How to make a phone call using intent in Android?

Every thing is fine.

i just placed call permissions tag before application tag in manifest file

and now every thing is working fine.

Android Respond To URL in Intent

You might need to allow different combinations of data in your intent filter to get it to work in different cases (http/ vs https/, www. vs no www., etc).

For example, I had to do the following for an app which would open when the user opened a link to Google Drive forms (www.docs.google.com/forms)

Note that path prefix is optional.

        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />

            <data android:scheme="http" />
            <data android:scheme="https" />

            <data android:host="www.docs.google.com" />
            <data android:host="docs.google.com" />

            <data android:pathPrefix="/forms" />
        </intent-filter>

How to convert hashmap to JSON object in Java

You can convert Map to JSON using Jackson as follows:

Map<String,Object> map = new HashMap<>();
//You can convert any Object.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);
map.put("key3","string1");
map.put("key4","string2");

String json = new ObjectMapper().writeValueAsString(map);
System.out.println(json);

Maven Dependencies for Jackson :

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
    <scope>compile</scope>
</dependency>

If you are using JSONObject library, you can convert map to JSON as follows:

Map<String, Object> map = new HashMap<>();
// Convert a map having list of values.
String[] value1 = new String[] { "value11", "value12", "value13" };
String[] value2 = new String[] { "value21", "value22", "value23" };
map.put("key1", value1);
map.put("key2", value2);

JSONObject json = new JSONObject(map);
System.out.println(json);

Maven Dependencies for JSONObject :

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20140107</version>
</dependency>

Hope this will help. Happy coding.

How to check if a string is null in python

In python, bool(sequence) is False if the sequence is empty. Since strings are sequences, this will work:

cookie = ''
if cookie:
    print "Don't see this"
else:
    print "You'll see this"

git still shows files as modified after adding to .gitignore

To the people who might be searching for this issue still, are looking at this page only.

This will help you remove cached index files, and then only add the ones you need, including changes to your .gitignore file.

1. git rm -r --cached .  
2. git add .
3. git commit -m 'Removing ignored files'

Here is a little bit more info.

  1. This command will remove all cached files from index.
  2. This command will add all files except those which are mentioned in gitignore.
  3. This command will commit your files again and remove the files you want git to ignore, but keep them in your local directory.

What's the difference between window.location and document.location in JavaScript?

Well yea, they are the same, but....!

window.location is not working on some Internet Explorer browsers.

Steps to upload an iPhone application to the AppStore

This arstechnica article describes the basic steps:

Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?

Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.

Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.

You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.

The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.

If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.

If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.

What is the error "Every derived table must have its own alias" in MySQL?

I arrived here because I thought I should check in SO if there are adequate answers, after a syntax error that gave me this error, or if I could possibly post an answer myself.

OK, the answers here explain what this error is, so not much more to say, but nevertheless I will give my 2 cents using my words:

This error is caused by the fact that you basically generate a new table with your subquery for the FROM command.

That's what a derived table is, and as such, it needs to have an alias (actually a name reference to it).

So given the following hypothetical query:

SELECT id, key1
FROM (
    SELECT t1.ID id, t2.key1 key1, t2.key2 key2, t2.key3 key3
    FROM table1 t1 
    LEFT JOIN table2 t2 ON t1.id = t2.id
    WHERE t2.key3 = 'some-value'
) AS tt

So, at the end, the whole subquery inside the FROM command will produce the table that is aliased as tt and it will have the following columns id, key1, key2, key3.

So, then with the initial SELECT from that table we finally select the id and key1 from the tt.

Bootstrap 3.0: How to have text and input on same line?

Straight from documentation http://getbootstrap.com/css/#forms-horizontal.

Use Bootstrap's predefined grid classes to align labels and groups of form controls in a horizontal layout by adding .form-horizontal to the form (which doesn't have to be a <form>). Doing so changes .form-groups to behave as grid rows, so no need for .row.

Sample:

<form class="form-horizontal">
  <div class="form-group">
    <label for="inputEmail3" class="col-sm-2 control-label">Email</label>
    <div class="col-sm-10">
      <input type="email" class="form-control" id="inputEmail3" placeholder="Email">
    </div>
  </div>
  <div class="form-group">
    <label for="inputPassword3" class="col-sm-2 control-label">Password</label>
    <div class="col-sm-10">
      <input type="password" class="form-control" id="inputPassword3" placeholder="Password">
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <div class="checkbox">
        <label>
          <input type="checkbox"> Remember me
        </label>
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="col-sm-offset-2 col-sm-10">
      <button type="submit" class="btn btn-default">Sign in</button>
    </div>
  </div>
</form>

Why is a ConcurrentModificationException thrown and how to debug it

Try either CopyOnWriteArrayList or CopyOnWriteArraySet depending on what you are trying to do.

Broken references in Virtualenvs

I had a broken virtual env due to a Homebrew reinstall of python (thereby broken symlinks) and also a few "sudo pip install"s I had done earlier. Weizhong's tips were very helpful in fixing the issues without having to reinstall packages. I also had to do the following for the mixed permissions problem.

sudo chown -R my_username lib/python2.7/site-packages

Pandas: Appending a row to a dataframe and specify its index label

There is another solution. The next code is bad (although I think pandas needs this feature):

import pandas as pd

# empty dataframe
a = pd.DataFrame()
a.loc[0] = {'first': 111, 'second': 222}

But the next code runs fine:

import pandas as pd

# empty dataframe
a = pd.DataFrame()
a = a.append(pd.Series({'first': 111, 'second': 222}, name=0))

How can I make a horizontal ListView in Android?

You know, it might be possible to use an existing ListView with some judicious overriding of dispatchDraw() (to rotate the Canvas by 90 degrees), onTouch() (to swap the X and Y of the MotionEvent coords) and maybe onMeasure() or whatever to fool it into thinking it's y by x rather than x by y...

I have no idea if this would actually work but it'd be fun to find out. :)

How to use onClick event on react Link component?

You are passing hello() as a string, also hello() means execute hello immediately.

try

onClick={hello}

How to execute a JavaScript function when I have its name as a string

all you have to do is use a context or define a new context where you function(s) reside. you are not limited to window["f"]();

here is an example of how I use some dynamic invocation for some REST services.

/* 
Author: Hugo Reyes
@ www.teamsrunner.com

*/

    (function ( W, D) { // enclose it as self invoking function to avoid name collisions.


    // to call function1 as string
    // initialize your FunctionHUB as your namespace - context
    // you can use W["functionX"](), if you want to call a function at the window scope.
    var container = new FunctionHUB();


    // call a function1 by name with one parameter.

    container["function1"](' Hugo ');


    // call a function2 by name.
    container["function2"](' Hugo Leon');


    // OO style class
    function FunctionHUB() {

        this.function1 = function (name) {

            console.log('Hi ' + name + ' inside function 1')
        }

        this.function2 = function (name) {

            console.log('Hi' + name + ' inside function 2 ')
        }
    }

})(window, document); // in case you need window context inside your namespace.

If you want to generate the entire function from a string, that's a different answer. also please notice that you are not limited to a single name space, if you name space exists as my.name.space.for.functions.etc.etc.etc the last branch of your name space contains the function as my.name.space.for.functions.etc.etc["function"]();

Hope it helps. H.

Get selected element's outer HTML

node.cloneNode() hardly seems like a hack. You can clone the node and append it to any desired parent element, and also manipulate it by manipulating individual properties, rather than having to e.g. run regular expressions on it, or add it in to the DOM, then manipulate it afterwords.

That said, you could also iterate over the attributes of the element to construct an HTML string representation of it. It seems likely this is how any outerHTML function would be implemented were jQuery to add one.

How to print a stack trace in Node.js?

@isaacs answer is correct, but if you need more specific or cleaner error stack, you can use this function:

function getCleanerStack() {
   var err = new Error();
   Error.captureStackTrace(err, getStack);

   return err.stack;
}

This function is inspired directly from the console.trace function in NodeJS.

Source code: Recent version or Old version.

How to run a function when the page is loaded?

Rather than using jQuery or window.onload, native JavaScript has adopted some great functions since the release of jQuery. All modern browsers now have their own DOM ready function without the use of a jQuery library.

I'd recommend this if you use native Javascript.

document.addEventListener('DOMContentLoaded', function() {
    alert("Ready!");
}, false);

How to get the CPU Usage in C#?

It's OK, I got it! Thanks for your help!

Here is the code to do it:

private void button1_Click(object sender, EventArgs e)
{
    selectedServer = "JS000943";
    listBox1.Items.Add(GetProcessorIdleTime(selectedServer).ToString());
}

private static int GetProcessorIdleTime(string selectedServer)
{
    try
    {
        var searcher = new
           ManagementObjectSearcher
             (@"\\"+ selectedServer +@"\root\CIMV2",
              "SELECT * FROM Win32_PerfFormattedData_PerfOS_Processor WHERE Name=\"_Total\"");

        ManagementObjectCollection collection = searcher.Get();
        ManagementObject queryObj = collection.Cast<ManagementObject>().First();

        return Convert.ToInt32(queryObj["PercentIdleTime"]);
    }
    catch (ManagementException e)
    {
        MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
    }
    return -1;
}

Jackson JSON: get node name from json-tree

JsonNode root = mapper.readTree(json);
root.at("/some-node").fields().forEachRemaining(e -> {
                              System.out.println(e.getKey()+"---"+ e.getValue());

        });

In one line Jackson 2+

What does $_ mean in PowerShell?

$_ is a variable created by the system usually inside block expressions that are referenced by cmdlets that are used with pipe such as Where-Object and ForEach-Object.

But it can be used also in other types of expressions, for example with Select-Object combined with expression properties. Get-ChildItem | Select-Object @{Name="Name";Expression={$_.Name}}. In this case the $_ represents the item being piped but multiple expressions can exist.

It can also be referenced by custom parameter validation, where a script block is used to validate a value. In this case the $_ represents the parameter value as received from the invocation.

The closest analogy to c# and java is the lamda expression. If you break down powershell to basics then everything is a script block including a script file a, functions and cmdlets. You can define your own parameters but in some occasions one is created by the system for you that represents the input item to process/evaluate. In those situations the automatic variable is $_.

Reading Data From Database and storing in Array List object

Also If you want you result set data in list .please use below LOC:

public List<String> dbselect(String query)
  {
      List<String> dbdata=new ArrayList<String>();
      try {
        dbResult=statement.executeQuery(query);
        ResultSetMetaData metadata=dbResult.getMetaData();
        for(int i=0;i>=metadata.getColumnCount();i++)
        {
            dbdata.add(dbResult.getString(i));
        }
        return dbdata;
    } catch (SQLException e) {
        return null;
    }
      
      
  }

How to iterate through SparseArray?

Seems I found the solution. I hadn't properly noticed the keyAt(index) function.

So I'll go with something like this:

for(int i = 0; i < sparseArray.size(); i++) {
   int key = sparseArray.keyAt(i);
   // get the object by the key.
   Object obj = sparseArray.get(key);
}

Can we import XML file into another XML file?

The other answers cover the 2 most common approaches, Xinclude and XML external entities. Microsoft has a really great writeup on why one should prefer Xinclude, as well as several example implementations. I've quoted the comparison below:

Per http://msdn.microsoft.com/en-us/library/aa302291.aspx

Why XInclude?

The first question one may ask is "Why use XInclude instead of XML external entities?" The answer is that XML external entities have a number of well-known limitations and inconvenient implications, which effectively prevent them from being a general-purpose inclusion facility. Specifically:

  • An XML external entity cannot be a full-blown independent XML document—neither standalone XML declaration nor Doctype declaration is allowed. That effectively means an XML external entity itself cannot include other external entities.
  • An XML external entity must be well formed XML (not so bad at first glance, but imagine you want to include sample C# code into your XML document).
  • Failure to load an external entity is a fatal error; any recovery is strictly forbidden.
  • Only the whole external entity may be included, there is no way to include only a portion of a document. -External entities must be declared in a DTD or an internal subset. This opens a Pandora's Box full of implications, such as the fact that the document element must be named in Doctype declaration and that validating readers may require that the full content model of the document be defined in DTD among others.

The deficiencies of using XML external entities as an inclusion mechanism have been known for some time and in fact spawned the submission of the XML Inclusion Proposal to the W3C in 1999 by Microsoft and IBM. The proposal defined a processing model and syntax for a general-purpose XML inclusion facility.

Four years later, version 1.0 of the XML Inclusions, also known as Xinclude, is a Candidate Recommendation, which means that the W3C believes that it has been widely reviewed and satisfies the basic technical problems it set out to solve, but is not yet a full recommendation.

Another good site which provides a variety of example implementations is https://www.xml.com/pub/a/2002/07/31/xinclude.html. Below is a common use case example from their site:

<book xmlns:xi="http://www.w3.org/2001/XInclude">

  <title>The Wit and Wisdom of George W. Bush</title>

  <xi:include href="malapropisms.xml"/>

  <xi:include href="mispronunciations.xml"/>

  <xi:include href="madeupwords.xml"/>

</book>

C - gettimeofday for computing time?

The answer offered by @Daniel Kamil Kozar is the correct answer - gettimeofday actually should not be used to measure the elapsed time. Use clock_gettime(CLOCK_MONOTONIC) instead.


Man Pages say - The time returned by gettimeofday() is affected by discontinuous jumps in the system time (e.g., if the system administrator manually changes the system time). If you need a monotonically increasing clock, see clock_gettime(2).

The Opengroup says - Applications should use the clock_gettime() function instead of the obsolescent gettimeofday() function.

Everyone seems to love gettimeofday until they run into a case where it does not work or is not there (VxWorks) ... clock_gettime is fantastically awesome and portable.

<<

Validate decimal numbers in JavaScript - IsNumeric()

This should work. Some of the functions provided here are flawed, also should be faster than any other function here.

        function isNumeric(n)
        {
            var n2 = n;
            n = parseFloat(n);
            return (n!='NaN' && n2==n);
        }

Explained:

Create a copy of itself, then converts the number into float, then compares itself with the original number, if it is still a number, (whether integer or float) , and matches the original number, that means, it is indeed a number.

It works with numeric strings as well as plain numbers. Does not work with hexadecimal numbers.

Warning: use at your own risk, no guarantees.

Check if boolean is true?

Almost everyone I've seen expressing an opinion prefers

if (foo)
{
}

Indeed, I've seen many people criticize the explicit comparison, and I may even have done so myself before now. I'd say the "short" style is idiomatic.

EDIT:

Note that this doesn't mean that line of code is always incorrect. Consider:

bool? maybeFoo = GetSomeNullableBooleanValue();
if (maybeFoo == true)
{
    ...
}

That will compile, but without the "== true" it won't, as there's no implicit conversion from bool? to bool.

unix sort descending order

If you only want to sort only on the 5th field then use -k5,5.

Also, use the -t command line switch to specify the delimiter to tab. Try this:

sort  -k5,5 -r -n -t \t filename

or if the above doesn't work (with the tab) this:

sort  -k5,5 -r -n -t $'\t' filename

The man page for sort states:

-t, --field-separator=SEP use SEP instead of non-blank to blank transition

Finally, this SO question Unix Sort with Tab Delimiter might be helpful.

How can I use if/else in a dictionary comprehension?

You've already got it: A if test else B is a valid Python expression. The only problem with your dict comprehension as shown is that the place for an expression in a dict comprehension must have two expressions, separated by a colon:

{ (some_key if condition else default_key):(something_if_true if condition
          else something_if_false) for key, value in dict_.items() }

The final if clause acts as a filter, which is different from having the conditional expression.


Worth mentioning that you don't need to have an if-else condition for both the key and the value. For example, {(a if condition else b): value for key, value in dict.items()} will work.

How to jump to a particular line in a huge text file?

If you don't want to read the entire file in memory .. you may need to come up with some format other than plain text.

of course it all depends on what you're trying to do, and how often you will jump across the file.

For instance, if you're gonna be jumping to lines many times in the same file, and you know that the file does not change while working with it, you can do this:
First, pass through the whole file, and record the "seek-location" of some key-line-numbers (such as, ever 1000 lines),
Then if you want line 12005, jump to the position of 12000 (which you've recorded) then read 5 lines and you'll know you're in line 12005 and so on

How do I set GIT_SSL_NO_VERIFY for specific repos only?

You can do as follows

For a single repo

git config http.sslVerify false

For all repo

git config --global http.sslVerify false

Spring MVC: difference between <context:component-scan> and <annotation-driven /> tags?

Annotation-driven indicates to Spring that it should scan for annotated beans, and to not just rely on XML bean configuration. Component-scan indicates where to look for those beans.

Here's some doc: http://static.springsource.org/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-config-enable

Overlay a background-image with an rgba background-color

Yes, there is a way to do this. You could use a pseudo-element after to position a block on top of your background image. Something like this: http://jsfiddle.net/Pevara/N2U6B/

The css for the :after looks like this:

#the-div:hover:after {
    content: ' ';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0,0,0,.5);
}

edit:
When you want to apply this to a non-empty element, and just get the overlay on the background, you can do so by applying a positive z-index to the element, and a negative one to the :after. Something like this:

#the-div {
    ...
    z-index: 1;
}
#the-div:hover:after {
    ...
    z-index: -1;
}

And the updated fiddle: http://jsfiddle.net/N2U6B/255/

Sqlite or MySql? How to decide?

SQLite out-of-the-box is not really feature-full regarding concurrency. You will get into trouble if you have hundreds of web requests hitting the same SQLite database.

You should definitely go with MySQL or PostgreSQL.

If it is for a single-person project, SQLite will be easier to setup though.

EOFError: end of file reached issue with Net::HTTP

I find that I run into Net::HTTP and Net::FTP problems like this periodically, and when I do, surrounding the call with a timeout() makes all of those issues vanish. So where this will occasionally hang for 3 minutes or so and then raise an EOFError:

res = Net::HTTP.post_form(uri, args)

This always fixes it for me:

res = timeout(120) { Net::HTTP.post_form(uri, args) }

Resize font-size according to div size

The answer that i am presenting is very simple, instead of using "px","em" or "%", i'll use "vw". In short it might look like this:- h1 {font-size: 5.9vw;} when used for heading purposes.

See this:Demo

For more details:Main tutorial

How to make borders collapse (on a div)?

Example of using border-collapse: separate; as

  • container displayed as table:

    ol[type="I"]>li{
      display: table;
      border-collapse: separate;
      border-spacing: 1rem;
    }
    
  • Download a specific tag with Git

    try:

    git clone -b <name_of_the_tag> <repository_url> <destination>
    

    Check whether IIS is installed or not?

    go to Start->Run type inetmgr and press OK. If you get an IIS configuration screen. It is installed, otherwise it isn't.

    You can also check ControlPanel->Add Remove Programs, Click Add Remove Windows Components and look for IIS in the list of installed components.

    EDIT


    To Reinstall IIS.

    Control Panel -> Add Remove Programs -> Click Add Remove Windows Components
    Uncheck IIS box
    

    Click next and follow prompts to UnInstall IIS. Insert your windows disc into the appropriate drive.

    Control Panel -> Add Remove Programs -> Click Add Remove Windows Components
    Check IIS box
    

    Click next and follow prompts to Install IIS.

    Django - limiting query results

    Looks like the solution in the question doesn't work with Django 1.7 anymore and raises an error: "Cannot reorder a query once a slice has been taken"

    According to the documentation https://docs.djangoproject.com/en/dev/topics/db/queries/#limiting-querysets forcing the “step” parameter of Python slice syntax evaluates the Query. It works this way:

    Model.objects.all().order_by('-id')[:10:1]
    

    Still I wonder if the limit is executed in SQL or Python slices the whole result array returned. There is no good to retrieve huge lists to application memory.

    div hover background-color change?

    div hover background color change

    Try like this:

    .class_name:hover{
        background-color:#FF0000;
    }
    

    Regex replace uppercase with lowercase letters

    Try this

    • Find: ([A-Z])([A-Z]+)\b
    • Replace: $1\L$2

    Make sure case sensitivity is on (Alt + C)

    Android: How do I prevent the soft keyboard from pushing my view up?

    None of them worked for me, try this one

     private void scrollingWhileKeyboard() {
        drawerlayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
    
                Rect r = new Rect();
                try {
                    drawerlayout.getWindowVisibleDisplayFrame(r);
                    int screenHeight = drawerlayout.getRootView().getHeight();
                    int keypadHeight = screenHeight - r.bottom;
                    if (keypadHeight > screenHeight * 0.15) {
                        tabLayout.setVisibility(View.GONE);
                    } else {
                        tabLayout.setVisibility(View.VISIBLE);
                    }
                } catch (NullPointerException e) {
    
                }
            }
        });
    
    }
    

    ORA-00907: missing right parenthesis

    Firstly, in histories_T, you are referencing table T_customer (should be T_customers) and secondly, you are missing the FOREIGN KEY clause that REFERENCES orders; which is not being created (or dropped) with the code you provided.

    There may be additional errors as well, and I admit Oracle has never been very good at describing the cause of errors - "Mutating Tables" is a case in point.

    Let me know if there additional problems you are missing.

    Using AES encryption in C#

    //Code to encrypt Data :   
     public byte[] encryptdata(byte[] bytearraytoencrypt, string key, string iv)  
             {  
               AesCryptoServiceProvider dataencrypt = new AesCryptoServiceProvider();  
               //Block size : Gets or sets the block size, in bits, of the cryptographic operation.  
               dataencrypt.BlockSize = 128;  
               //KeySize: Gets or sets the size, in bits, of the secret key  
               dataencrypt.KeySize = 128;  
               //Key: Gets or sets the symmetric key that is used for encryption and decryption.  
               dataencrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);  
               //IV : Gets or sets the initialization vector (IV) for the symmetric algorithm  
               dataencrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);  
               //Padding: Gets or sets the padding mode used in the symmetric algorithm  
               dataencrypt.Padding = PaddingMode.PKCS7;  
               //Mode: Gets or sets the mode for operation of the symmetric algorithm  
               dataencrypt.Mode = CipherMode.CBC;  
               //Creates a symmetric AES encryptor object using the current key and initialization vector (IV).  
               ICryptoTransform crypto1 = dataencrypt.CreateEncryptor(dataencrypt.Key, dataencrypt.IV);  
               //TransformFinalBlock is a special function for transforming the last block or a partial block in the stream.   
               //It returns a new array that contains the remaining transformed bytes. A new array is returned, because the amount of   
               //information returned at the end might be larger than a single block when padding is added.  
               byte[] encrypteddata = crypto1.TransformFinalBlock(bytearraytoencrypt, 0, bytearraytoencrypt.Length);  
               crypto1.Dispose();  
               //return the encrypted data  
               return encrypteddata;  
             }  
    
    //code to decrypt data
        private byte[] decryptdata(byte[] bytearraytodecrypt, string key, string iv)  
         {  
    
           AesCryptoServiceProvider keydecrypt = new AesCryptoServiceProvider();  
           keydecrypt.BlockSize = 128;  
           keydecrypt.KeySize = 128;  
           keydecrypt.Key = System.Text.Encoding.UTF8.GetBytes(key);  
           keydecrypt.IV = System.Text.Encoding.UTF8.GetBytes(iv);  
           keydecrypt.Padding = PaddingMode.PKCS7;  
           keydecrypt.Mode = CipherMode.CBC;  
           ICryptoTransform crypto1 = keydecrypt.CreateDecryptor(keydecrypt.Key, keydecrypt.IV);  
    
           byte[] returnbytearray = crypto1.TransformFinalBlock(bytearraytodecrypt, 0, bytearraytodecrypt.Length);  
           crypto1.Dispose();  
           return returnbytearray;  
         }
    

    How to implement a binary tree?

    #!/usr/bin/python
    
    class BinaryTree:
        def __init__(self, left, right, data):
            self.left = left
            self.right = right
            self.data = data
    
    
        def pre_order_traversal(root):
            print(root.data, end=' ')
    
            if root.left != None:
                pre_order_traversal(root.left)
    
            if root.right != None:
                pre_order_traversal(root.right)
    
        def in_order_traversal(root):
            if root.left != None:
                in_order_traversal(root.left)
            print(root.data, end=' ')
            if root.right != None:
                in_order_traversal(root.right)
    
        def post_order_traversal(root):
            if root.left != None:
                post_order_traversal(root.left)
            if root.right != None:
                post_order_traversal(root.right)
            print(root.data, end=' ')
    

    jquery (or pure js) simulate enter key pressed for testing

    For those who want to do this in pure javascript, look at:

    Using standard KeyboardEvent

    As Joe comment it, KeyboardEvent is now the standard.

    Same example to fire an enter (keyCode 13):

    const ke = new KeyboardEvent('keydown', {
        bubbles: true, cancelable: true, keyCode: 13
    });
    document.body.dispatchEvent(ke);
    

    You can use this page help you to find the right keyboard event.


    Outdated answer:

    You can do something like (here for Firefox)

    var ev = document.createEvent('KeyboardEvent');
    // Send key '13' (= enter)
    ev.initKeyEvent(
        'keydown', true, true, window, false, false, false, false, 13, 0);
    document.body.dispatchEvent(ev);
    

    Change output format for MySQL command line results to CSV

    I wound up writing my own command-line tool to take care of this. It's similar to cut, except it knows what to do with quoted fields, etc. This tool, paired with @Jimothy's answer, allows me to get a headerless CSV from a remote MySQL server I have no filesystem access to onto my local machine with this command:

    $ mysql -N -e "select people, places from things" | csvm -i '\t' -o ','
    Bill,"Raleigh, NC"
    

    csvmaster on github

    How do I expire a PHP session after 30 minutes?

    How PHP handles sessions is quite confusing for beginners to understand. This might help them by giving an overview of how sessions work: how sessions work(custom-session-handlers)

    How to enable or disable an anchor using jQuery?

    I think a nicer solution is to set disabled data attribute on and anchor an check for it on click. This way we can disable temporarily an anchor until e.g. the javascript is finished with ajax call or some calculations. If we do not disable it, then we can quickly click it a few times, which is undesirable...

    $('a').live('click', function () {
        var anchor = $(this);
    
        if (anchor.data("disabled")) {
            return false;
        }
    
        anchor.data("disabled", "disabled");
    
        $.ajax({
            url: url,
            data: data,
            cache: false,
            success: function (json) {
                // when it's done, we enable the anchor again
                anchor.removeData("disabled");
            },
            error: function () {
                 // there was an error, enable the anchor
                anchor.removeData("disabled");
            }
        });
    
        return false;
    });
    

    I made a jsfiddle example: http://jsfiddle.net/wgZ59/76/

    Ifelse statement in R with multiple conditions

    There is a simpler solution to this. What you describe is the natural behavior of the & operator and can thus be done primatively:

    > c(1,1,NA) & c(1,0,NA) & c(1,NA,NA)
    [1]  TRUE FALSE    NA
    

    If all are 1, then 1 is returned. If any are 0, then 0. If all are NA, then NA.

    In your case, the code would be:

    DF$Den<-DF$Denial1 & DF$Denial2 & DF$Denial3
    

    In order for this to work, you will need to stop working in character and use numeric or logical types.

    Subtract days from a DateTime

    The dateTime.AddDays(-1) does not subtract that one day from the dateTime reference. It will return a new instance, with that one day subtracted from the original reference.

    DateTime dateTime = DateTime.Now;
    DateTime otherDateTime = dateTime.AddDays(-1);
    

    How do I get the list of keys in a Dictionary?

    I often used this to get the key and value inside a dictionary: (VB.Net)

     For Each kv As KeyValuePair(Of String, Integer) In layerList
    
     Next
    

    (layerList is of type Dictionary(Of String, Integer))

    How to prevent favicon.ico requests?

    You could use

    <link rel="shortcut icon" href="http://localhost/" />
    

    That way it won't actually be requested from the server.

    How to force child div to be 100% of parent div's height without specifying parent's height?

    #main {
       display: table;
    } 
    #navigation, #content {
       display: table-cell;
    }
    

    Look at this example.

    How to get logged-in user's name in Access vba?

    Public Declare Function GetUserName Lib "advapi32.dll" 
        Alias "GetUserNameA" (ByVal lpBuffer As String, nSize As Long) As Long
    

    ....

    Dim strLen As Long
    Dim strtmp As String * 256
    Dim strUserName As String
    
    strLen = 255
    GetUserName strtmp, strLen
    strUserName = Trim$(TrimNull(strtmp))
    

    Turns out question has been asked before: How can I get the currently logged-in windows user in Access VBA?

    What's a good (free) visual merge tool for Git? (on windows)

    Another free option is jmeld: http://keeskuip.home.xs4all.nl/jmeld/

    It's a java tool and could therefore be used on several platforms.

    But (as Preet mentioned in his answer), free is not always the best option. The best diff/merge tool I ever came across is Araxis Merge. Standard edition is available for 99 EUR which is not that much.

    They also provide a documentation for how to integrate Araxis with msysGit.

    If you want to stick to a free tool, JMeld comes pretty close to Araxis.

    Caused by: java.security.UnrecoverableKeyException: Cannot recover key

    In order to not have the Cannot recover key exception, I had to apply the Java Cryptography Extension (JCE) Unlimited Strength Jurisdiction Policy Files to the installation of Java that was running my application. Version 8 of those files can be found here or the latest version should be listed on this page. The download includes a file that explains how to apply the policy files.


    Since JDK 8u151 it isn't necessary to add policy files. Instead the JCE jurisdiction policy files are controlled by a Security property called crypto.policy. Setting that to unlimited with allow unlimited cryptography to be used by the JDK. As the release notes linked to above state, it can be set by Security.setProperty() or via the java.security file. The java.security file could also be appended to by adding -Djava.security.properties=my_security.properties to the command to start the program as detailed here.


    Since JDK 8u161 unlimited cryptography is enabled by default.

    Bootstrap 3 Collapse show state with Chevron icon

    I'm using font awesome! and wanted a panel to be collapsible

            <div class="panel panel-default">
                    <div class="panel-heading" data-toggle="collapse" data-target="#collapseOrderItems"><i class="fa fa-chevron fa-fw" ></i> products</div>
    
                    <div class="collapse in" id="collapseOrderItems">
                                ....
                    </div>
            </div>
    

    and the css

    .panel-heading .fa-chevron:after {
        content: "\f078";   
    }
    .panel-heading.collapsed .fa-chevron:after {
        content: "\f054";   
    }
    

    enter image description here

    enter image description here

    How do I make a checkbox required on an ASP.NET form?

    Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.

    The .ascx:

    <script type="text/javascript">
    
        function checkAgreement(source, args)
        {                
            var elem = document.getElementById('<%= chkAgree.ClientID %>');
            if (elem.checked)
            {
                args.IsValid = true;
            }
            else
            {        
                args.IsValid = false;
            }
        }
    
        function checkAge(source, args)
        {
            var elem = document.getElementById('<%= chkAge.ClientID %>');
            if (elem.checked)
            {
                args.IsValid = true;
            }
            else
            {
                args.IsValid = false;
            }    
        }
    
    </script>
    
    <asp:CheckBox ID="chkAgree" runat="server" />
    <asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
    <asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
    <asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
    <br />
    
    <asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
        ClientValidationFunction="checkAgreement">
        You must agree to the terms and conditions.
        </asp:CustomValidator>
    
    <asp:CheckBox ID="chkAge" runat="server" />
    <asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>        
    <asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
        ClientValidationFunction="checkAge">
        You must be 18 years or older to continue.
        </asp:CustomValidator>
    

    And the codebehind:

    Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
    Handles chkAgreeValidator.ServerValidate
        e.IsValid = chkAgree.Checked
    End Sub
    
    Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
    Handles chkAgeValidator.ServerValidate
        e.IsValid = chkAge.Checked
    End Sub
    

    Add horizontal scrollbar to html table

    With bootstrap

     <div class="table-responsive">
       <table class="table">
         ...
       </table>
     </div>
    

    What is setBounds and how do I use it?

    setBounds is used to define the bounding rectangle of a component. This includes it's position and size.

    The is used in a number of places within the framework.

    • It is used by the layout manager's to define the position and size of a component within it's parent container.
    • It is used by the paint sub system to define clipping bounds when painting the component.

    For the most part, you should never call it. Instead, you should use appropriate layout managers and let them determine the best way to provide information to this method.

    Make a div fill the height of the remaining screen space

    Vincent, I'll answer again using your new requirements. Since you don't care about the content being hidden if it's too long, you don't need to float the header. Just put overflow hidden on the html and body tags, and set #content height to 100%. The content will always be longer than the viewport by the height of the header, but it'll be hidden and won't cause scrollbars.

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"     "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
        <title>Test</title>
        <style type="text/css">
        body, html {
          height: 100%;
          margin: 0;
          padding: 0;
          overflow: hidden;
          color: #FFF;
        }
        p {
          margin: 0;
        }
    
        #header {
          background: red;
        }
    
        #content {
          position: relative;
          height: 100%;
          background: blue;
        }
    
        #content #positioned {
          position: absolute;
          top: 0;
          right: 0;
        }
      </style>
    </head>
    
    <body>
      <div id="header">
        Header
        <p>Header stuff</p>
      </div>
    
      <div id="content">
        Content
        <p>Content stuff</p>
        <div id="positioned">Positioned Content</div>
      </div>
    
    </body>
    </html>
    

    How to create a HashMap with two keys (Key-Pair, Value)?

    Two possibilities. Either use a combined key:

    class MyKey {
        int firstIndex;
        int secondIndex;
        // important: override hashCode() and equals()
    }
    

    Or a Map of Map:

    Map<Integer, Map<Integer, Integer>> myMap;
    

    How to delete an SVN project from SVN repository

    Go to Eclipse, Click on Window from Menu bar then "Open Perspective -> other -> SVN Repository Exploring -> Click OK"

    Now, after performing "Click OK" you need to go to truck (or place where your project is saved in SVN) then select project(which you want to Delete) then right click -> Delete.

    This Will Delete project from subversion.

    Fastest way to tell if two files have the same contents in Unix/Linux?

    To quickly and safely compare any two files:

    if cmp --silent -- "$FILE1" "$FILE2"; then
      echo "files contents are identical"
    else
      echo "files differ"
    fi
    

    It's readable, efficient, and works for any file names including "` $()

    How to convert a string of bytes into an int?

    import array
    integerValue = array.array("I", 'y\xcc\xa6\xbb')[0]
    

    Warning: the above is strongly platform-specific. Both the "I" specifier and the endianness of the string->int conversion are dependent on your particular Python implementation. But if you want to convert many integers/strings at once, then the array module does it quickly.

    react-router (v4) how to go back?

    this.props.history.goBack();
    

    This is the correct solution for react-router v4

    But one thing you should keep in mind is that you need to make sure this.props.history is existed.

    That means you need to call this function this.props.history.goBack(); inside the component that is wrapped by < Route/>

    If you call this function in a component that deeper in the component tree, it will not work.

    EDIT:

    If you want to have history object in the component that is deeper in the component tree (which is not wrapped by < Route>), you can do something like this:

    ...
    import {withRouter} from 'react-router-dom';
    
    class Demo extends Component {
        ...
        // Inside this you can use this.props.history.goBack();
    }
    
    export default withRouter(Demo);
    

    How to reference a method in javadoc?

    The general format, from the @link section of the javadoc documentation, is:

    {@link package.class#member label}

    Examples

    Method in the same class:

    /** See also {@link #myMethod(String)}. */
    void foo() { ... }
    

    Method in a different class, either in the same package or imported:

    /** See also {@link MyOtherClass#myMethod(String)}. */
    void foo() { ... }
    

    Method in a different package and not imported:

    /** See also {@link com.mypackage.YetAnotherClass#myMethod(String)}. */
    void foo() { ... }
    

    Label linked to method, in plain text rather than code font:

    /** See also this {@linkplain #myMethod(String) implementation}. */
    void foo() { ... }
    

    A chain of method calls, as in your question. We have to specify labels for the links to methods outside this class, or we get getFoo().Foo.getBar().Bar.getBaz(). But these labels can be fragile during refactoring -- see "Labels" below.

    /**
     * A convenience method, equivalent to 
     * {@link #getFoo()}.{@link Foo#getBar() getBar()}.{@link Bar#getBaz() getBaz()}.
     * @return baz
     */
    public Baz fooBarBaz()
    

    Labels

    Automated refactoring may not affect labels. This includes renaming the method, class or package; and changing the method signature.

    Therefore, provide a label only if you want different text than the default.

    For example, you might link from human language to code:

    /** You can also {@linkplain #getFoo() get the current foo}. */
    void setFoo( Foo foo ) { ... }
    

    Or you might link from a code sample with text different than the default, as shown above under "A chain of method calls." However, this can be fragile while APIs are evolving.

    Type erasure and #member

    If the method signature includes parameterized types, use the erasure of those types in the javadoc @link. For example:

    int bar( Collection<Integer> receiver ) { ... }
    
    /** See also {@link #bar(Collection)}. */
    void foo() { ... }
    

    What does '?' do in C++?

    This is commonly referred to as the conditional operator, and when used like this:

    condition ? result_if_true : result_if_false
    

    ... if the condition evaluates to true, the expression evaluates to result_if_true, otherwise it evaluates to result_if_false.

    It is syntactic sugar, and in this case, it can be replaced with

    int qempty()
    { 
      if(f == r)
      {
          return 1;
      } 
      else 
      {
          return 0;
      }
    }
    

    Note: Some people refer to ?: it as "the ternary operator", because it is the only ternary operator (i.e. operator that takes three arguments) in the language they are using.

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

    select[value="value"]{
       background-color: red;
       padding: 3px;
       font-weight:bold;
    }
    

    javascript node.js next()

    It is naming convention used when passing callbacks in situations that require serial execution of actions, e.g. scan directory -> read file data -> do something with data. This is in preference to deeply nesting the callbacks. The first three sections of the following article on Tim Caswell's HowToNode blog give a good overview of this:

    http://howtonode.org/control-flow

    Also see the Sequential Actions section of the second part of that posting:

    http://howtonode.org/control-flow-part-ii

    Newtonsoft JSON Deserialize

    As per the Newtonsoft Documentation you can also deserialize to an anonymous object like this:

    var definition = new { Name = "" };
    
    string json1 = @"{'Name':'James'}";
    var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition);
    
    Console.WriteLine(customer1.Name);
    // James
    

    The shortest possible output from git log containing author and date

    Run this in project folder:

    $ git log --pretty=format:"%C(yellow)%h %ar %C(auto)%d %Creset %s , %Cblue%cn" --graph --all
    

    And if you like, add this line to your ~/.gitconfig:

    [alias]
        ...
        list = log --pretty=format:\"%C(yellow)%h %ar %C(auto)%d %Creset %s, %Cblue%cn\" --graph --all
    

    What is the difference between gravity and layout_gravity in Android?

    The difference

    android:layout_gravity is the Outside gravity of the View. Specifies the direction in which the View should touch its parent's border.

    android:gravity is the Inside gravity of that View. Specifies in which direction its contents should align.

    HTML/CSS Equivalents

    (if you are coming from a web development background)

    Android                 | CSS
    ————————————————————————+————————————
    android:layout_gravity  | float
    android:gravity         | text-align
    

    Easy trick to help you remember

    Take layout-gravity as "Lay-outside-gravity".

    Add vertical scroll bar to panel

    AutoScroll is really the solution! You just have to set AutoScrollMargin to 0, 1000 or something like this, then use it to scroll down and add buttons and items there!

    Shortcut for changing font size

    In visual studio code if your front is too small or too big, then you just need to zoom out or zoom in. To do that you just have to do:

    • For zoom in : ctrl + = (ctrl and equal both)
    • For zoom out: ctrl + - (ctrl and - both)

    Check if a specific tab page is selected (active)

    To check if a specific tab page is the currently selected page of a tab control is easy; just use the SelectedTab property of the tab control:

    if (tabControl1.SelectedTab == someTabPage)
    {
    // Do stuff here...
    }
    

    This is more useful if the code is executed based on some event other than the tab page being selected (in which case SelectedIndexChanged would be a better choice).

    For example I have an application that uses a timer to regularly poll stuff over TCP/IP connection, but to avoid unnecessary TCP/IP traffic I only poll things that update GUI controls in the currently selected tab page.

    Hibernate Criteria Restrictions AND / OR combination

    think works

    Criteria criteria = getSession().createCriteria(clazz); 
    Criterion rest1= Restrictions.and(Restrictions.eq(A, "X"), 
               Restrictions.in("B", Arrays.asList("X",Y)));
    Criterion rest2= Restrictions.and(Restrictions.eq(A, "Y"), 
               Restrictions.eq(B, "Z"));
    criteria.add(Restrictions.or(rest1, rest2));
    

    Excel VBA: Copying multiple sheets into new workbook

    Try do something like this (the problem was that you trying to use MyBook.Worksheets, but MyBook is not a Workbook object, but string, containing workbook name. I've added new varible Set WB = ActiveWorkbook, so you can use WB.Worksheets instead MyBook.Worksheets):

    Sub NewWBandPasteSpecialALLSheets()
       MyBook = ActiveWorkbook.Name ' Get name of this book
       Workbooks.Add ' Open a new workbook
       NewBook = ActiveWorkbook.Name ' Save name of new book
    
       Workbooks(MyBook).Activate ' Back to original book
    
       Set WB = ActiveWorkbook
    
       Dim SH As Worksheet
    
       For Each SH In WB.Worksheets
    
           SH.Range("WholePrintArea").Copy
    
           Workbooks(NewBook).Activate
    
           With SH.Range("A1")
            .PasteSpecial (xlPasteColumnWidths)
            .PasteSpecial (xlFormats)
            .PasteSpecial (xlValues)
    
           End With
    
         Next
    
    End Sub
    

    But your code doesn't do what you want: it doesen't copy something to a new WB. So, the code below do it for you:

    Sub NewWBandPasteSpecialALLSheets()
       Dim wb As Workbook
       Dim wbNew As Workbook
       Dim sh As Worksheet
       Dim shNew As Worksheet
    
       Set wb = ThisWorkbook
       Workbooks.Add ' Open a new workbook
       Set wbNew = ActiveWorkbook
    
       On Error Resume Next
    
       For Each sh In wb.Worksheets
          sh.Range("WholePrintArea").Copy
    
          'add new sheet into new workbook with the same name
          With wbNew.Worksheets
    
              Set shNew = Nothing
              Set shNew = .Item(sh.Name)
    
              If shNew Is Nothing Then
                  .Add After:=.Item(.Count)
                  .Item(.Count).Name = sh.Name
                  Set shNew = .Item(.Count)
              End If
          End With
    
          With shNew.Range("A1")
              .PasteSpecial (xlPasteColumnWidths)
              .PasteSpecial (xlFormats)
              .PasteSpecial (xlValues)
          End With
       Next
    End Sub
    

    Datagrid binding in WPF

    Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

    <DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
        <DataGrid.Columns>                
            <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
            <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
       </DataGrid.Columns>
    </DataGrid>
    

    (This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

    3 column layout HTML/CSS

    This is less for @easwee and more for others that might have the same question:

    If you do not require support for IE < 10, you can use Flexbox. It's an exciting CSS3 property that unfortunately was implemented in several different versions,; add in vendor prefixes, and getting good cross-browser support suddenly requires quite a few more properties than it should.

    With the current, final standard, you would be done with

    .container {
        display: flex;
    }
    
    .container div {
        flex: 1;
    }
    
    .column_center {
        order: 2;
    }
    

    That's it. If you want to support older implementations like iOS 6, Safari < 6, Firefox 19 or IE10, this blossoms into

    .container {
        display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
        display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
        display: -ms-flexbox;      /* TWEENER - IE 10 */
        display: -webkit-flex;     /* NEW - Chrome */
        display: flex;             /* NEW, Spec - Opera 12.1, Firefox 20+ */
    }
    
    .container div {
        -webkit-box-flex: 1;      /* OLD - iOS 6-, Safari 3.1-6 */
        -moz-box-flex: 1;         /* OLD - Firefox 19- */
        -webkit-flex: 1;          /* Chrome */
        -ms-flex: 1;              /* IE 10 */
        flex: 1;                  /* NEW, Spec - Opera 12.1, Firefox 20+ */
    }
    
    .column_center {
        -webkit-box-ordinal-group: 2;   /* OLD - iOS 6-, Safari 3.1-6 */
        -moz-box-ordinal-group: 2;      /* OLD - Firefox 19- */
        -ms-flex-order: 2;              /* TWEENER - IE 10 */
        -webkit-order: 2;               /* NEW - Chrome */
        order: 2;                       /* NEW, Spec - Opera 12.1, Firefox 20+ */
    }
    

    jsFiddle demo

    Here is an excellent article about Flexbox cross-browser support: Using Flexbox: Mixing Old And New

    cd into directory without having permission

    @user812954's answer was quite helpful, except I had to do this this in two steps:

    sudo su
    cd directory
    

    Then, to exit out of "super user" mode, just type exit.

    What does 'foo' really mean?

    As definition of "Foo" has lot's of meanings:

    • bar, and baz are often compounded together to make such words as foobar, barbaz, and foobaz. www.nationmaster.com/encyclopedia/Metasyntactic-variable

    • Major concepts in CML, usually mapped directly onto XMLElements (to be discussed later). wwmm.ch.cam.ac.uk/blogs/cml/

    • Measurement of the total quantity of pasture in a paddock, expressed in kilograms of pasture dry matter per hectare (kg DM/ha) www.lifetimewool.com.au/glossary.aspx

    • Forward Observation Officer. An artillery officer who remained with infantry and tank battalions to set up observation posts in the front lines from which to observe enemy positions and radio the coordinates of targets to the guns further in the rear. members.fortunecity.com/lniven/definition.htm

    • is the first metasyntactic variable commonly used. It is sometimes combined with bar to make foobar. This suggests that foo may have originated with the World War II slang term fubar, as an acronym for fucked/fouled up beyond all recognition, although the Jargon File makes a pretty good case ... explanation-guide.info/meaning/Metasyntactic-variable.html

    • Foo is a metasyntactic variable used heavily in computer science to represent concepts abstractly and can be used to represent any part of a ... en.wikipedia.org/wiki/FOo

    • Foo is the world of dreams (no its not) in Obert Skye's Leven Thumps series. Although it has many original inhabitants, most of its current dwellers are from Reality, and are known as nits. ... en.wikipedia.org/wiki/Foo (place)

    • Also foo’. Representation of fool (foolish person), in a Mr. T accent en.wiktionary.org/wiki/foo

    Resource: google

    Using generic std::function objects with member functions in one class

    Either you need

    std::function<void(Foo*)> f = &Foo::doSomething;
    

    so that you can call it on any instance, or you need to bind a specific instance, for example this

    std::function<void(void)> f = std::bind(&Foo::doSomething, this);
    

    How to find the largest file in a directory and its subdirectories?

    That is quite simpler way to do it:

    ls -l | tr -s " " " " | cut -d " " -f 5,9 | sort -n -r | head -n 1***
    

    And you'll get this: 8445 examples.desktop

    How do I start an activity from within a Fragment?

    I do it like this, to launch the SendFreeTextActivity from a (custom) menu fragment that appears in multiple activities:

    In the MenuFragment class:

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_menu, container, false);
    
        final Button sendFreeTextButton = (Button) view.findViewById(R.id.sendFreeTextButton);
        sendFreeTextButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Log.d(TAG, "sendFreeTextButton clicked");
                Intent intent = new Intent(getActivity(), SendFreeTextActivity.class);
                MenuFragment.this.startActivity(intent);
            }
        });
        ...
    

    Hiding a form and showing another when a button is clicked in a Windows Forms application

    Anything after Application.Run( ) will only be executed when the main form closes.

    What you could do is handle the VisibleChanged event as follows:

    static Form1 form1;
    static Form2 form2;
    
    static void Main()
    {
    
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        form2 = new Form2();
        form1 = new Form1();
        form2.Hide();
        form1.VisibleChanged += OnForm1Changed;
        Application.Run(form1);
    
    }
    
    static void OnForm1Changed( object sender, EventArgs args )
    {
        if ( !form1.Visible )
        {
            form2.Show( );
        }
    }
    

    Is it possible to serialize and deserialize a class in C++?

    As far as "built-in" libraries go, the << and >> have been reserved specifically for serialization.

    You should override << to output your object to some serialization context (usually an iostream) and >> to read data back from that context. Each object is responsible for outputting its aggregated child objects.

    This method works fine so long as your object graph contains no cycles.

    If it does, then you will have to use a library to deal with those cycles.

    This app won't run unless you update Google Play Services (via Bazaar)

    I spent about one day to configure the new gmaps API (Google Maps Android API v2) on the Android emulator. None of the methods of those I found on the Internet was working correctly for me. But still I did it. Here is how:

    1. Create a new emulator with the following configuration:

    Enter image description here

    On the other versions I could not configure because of various errors when I installed the necessary applications.

    2) Start the emulator and install the following applications:

    • GoogleLoginService.apk
    • GoogleServicesFramework.apk
    • Phonesky.apk

    You can do this with following commands:

    2.1) adb shell mount -o remount,rw -t yaffs2 /dev/block/mtdblock0 /system
    2.2) adb shell chmod 777 /system/app
    2.3-2.5) adb push Each_of_the_3_apk_files.apk /system/app/

    Links to download APK files. I have copied them from my rooted Android device.

    3) Install Google Play Services and Google Maps on the emulator. I have an error 491, if I install them from Google Play store. I uploaded the apps to the emulator and run the installation locally. (You can use adb to install this). Links to the apps:

    4) I successfully run a demo sample on the emulator after these steps. Here is a screenshot:

    Google Maps

    Spaces in URLs?

    The information there is I think partially correct:

    That's not true. An URL can use spaces. Nothing defines that a space is replaced with a + sign.

    As you noted, an URL can NOT use spaces. The HTTP request would get screwed over. I'm not sure where the + is defined, though %20 is standard.

    Dialog to pick image from gallery or from camera

    The code below can be used for taking a photo and for picking a photo. Just show a dialog with two options and upon selection, use the appropriate code.

    To take picture from camera:

    Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
    startActivityForResult(takePicture, 0);//zero can be replaced with any action code (called requestCode)
    

    To pick photo from gallery:

    Intent pickPhoto = new Intent(Intent.ACTION_PICK,
               android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
    startActivityForResult(pickPhoto , 1);//one can be replaced with any action code
    

    onActivityResult code:

    protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) { 
        super.onActivityResult(requestCode, resultCode, imageReturnedIntent); 
        switch(requestCode) {
        case 0:
            if(resultCode == RESULT_OK){  
                Uri selectedImage = imageReturnedIntent.getData();
                imageview.setImageURI(selectedImage);
            }
    
        break; 
        case 1:
            if(resultCode == RESULT_OK){  
                Uri selectedImage = imageReturnedIntent.getData();
                imageview.setImageURI(selectedImage);
            }
        break;
        }
    }
    

    Finally add this permission in the manifest file:

     <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
    

    This could be due to the service endpoint binding not using the HTTP protocol

    I was facing the same issue and solved with below code. (if any TLS connectivity issue)

    System.Net.ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;
    

    Please paste this line before open the client channel.

    android asynctask sending callbacks to ui

    IN completion to above answers, you can also customize your fallbacks for each async call you do, so that each call to the generic ASYNC method will populate different data, depending on the onTaskDone stuff you put there.

      Main.FragmentCallback FC= new  Main.FragmentCallback(){
                @Override
                public void onTaskDone(String results) {
    
                    localText.setText(results); //example TextView
                }
            };
    
    new API_CALL(this.getApplicationContext(), "GET",FC).execute("&Books=" + Main.Books + "&args=" + profile_id);
    

    Remind: I used interface on the main activity thats where "Main" comes, like this:

    public interface FragmentCallback {
        public void onTaskDone(String results);
    
    
    }
    

    My API post execute looks like this:

      @Override
        protected void onPostExecute(String results) {
    
            Log.i("TASK Result", results);
            mFragmentCallback.onTaskDone(results);
    
        }
    

    The API constructor looks like this:

     class  API_CALL extends AsyncTask<String,Void,String>  {
    
        private Main.FragmentCallback mFragmentCallback;
        private Context act;
        private String method;
    
    
        public API_CALL(Context ctx, String api_method,Main.FragmentCallback fragmentCallback) {
            act=ctx;
            method=api_method;
            mFragmentCallback = fragmentCallback;
    
    
        }
    

    Update R using RStudio

    I would recommend using the Windows package installr to accomplish this. Not only will the package update your R version, but it will also copy and update all of your packages. There is a blog on the subject here. Simply run the following commands in R Studio and follow the prompts:

    # installing/loading the package:
    if(!require(installr)) {
    install.packages("installr"); require(installr)} #load / install+load installr
    
    # using the package:
    updateR() # this will start the updating process of your R installation.  It will check for newer versions, and if one is available, will guide you through the decisions you'd need to make.
    

    Where IN clause in LINQ

    public List<Requirement> listInquiryLogged()
    {
        using (DataClassesDataContext dt = new DataClassesDataContext(System.Configuration.ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString))
        {
            var inq = new int[] {1683,1684,1685,1686,1687,1688,1688,1689,1690,1691,1692,1693};
            var result = from Q in dt.Requirements
                         where inq.Contains(Q.ID)
                         orderby Q.Description
                         select Q;
    
            return result.ToList<Requirement>();
        }
    }
    

    How to convert list to string

    By using ''.join

    list1 = ['1', '2', '3']
    str1 = ''.join(list1)
    

    Or if the list is of integers, convert the elements before joining them.

    list1 = [1, 2, 3]
    str1 = ''.join(str(e) for e in list1)
    

    Simple pagination in javascript

    enter image description here file:icons.svg

    <svg aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <defs>
    <symbol id="icon-triangle-left" viewBox="0 0 20 20">
    <title>triangle-left</title>
    <path d="M14 5v10l-9-5 9-5z"></path>
    </symbol>
    <symbol id="icon-triangle-right" viewBox="0 0 20 20">
    <title>triangle-right</title>
    <path d="M15 10l-9 5v-10l9 5z"></path>
    </symbol>
    </defs>
    </svg>
    

    file: style.css

     .results__btn--prev{
        float: left;
        flex-direction: row-reverse; }
      .results__btn--next{
        float: right; }
    

    file index.html:

    <body>
    <form class="search">
                    <input type="text" class="search__field" placeholder="Search over 1,000,000 recipes...">
                    <button class="btn search__btn">
                        <svg class="search__icon">
                            <use href="img/icons.svg#icon-magnifying-glass"></use>
                        </svg>
                        <span>Search</span>
                    </button>
                </form>
         <div class="results">
             <ul class="results__list">
             </ul>
             <div class="results__pages">
             </div>
         </div>
    </body>
    

    file: searchView.js

    export const element = {
        searchForm:document.querySelector('.search'),
        searchInput: document.querySelector('.search__field'),
        searchResultList: document.querySelector('.results__list'),
        searchRes:document.querySelector('.results'),
        searchResPages:document.querySelector('.results__pages')
    
    }
    export const getInput = () => element.searchInput.value;
    export const clearResults = () =>{
        element.searchResultList.innerHTML=``;
        element.searchResPages.innerHTML=``;
    }
    export const clearInput = ()=> element.searchInput.value = "";
    
    const limitRecipeTitle = (title, limit=17)=>{
        const newTitle = [];
        if(title.length>limit){
            title.split(' ').reduce((acc, cur)=>{
                if(acc+cur.length <= limit){
                    newTitle.push(cur);
                }
                return acc+cur.length;
            },0);
        }
    
        return `${newTitle.join(' ')} ...`
    }
    const renderRecipe = recipe =>{
        const markup = `
            <li>
                <a class="results__link" href="#${recipe.recipe_id}">
                    <figure class="results__fig">
                        <img src="${recipe.image_url}" alt="${limitRecipeTitle(recipe.title)}">
                    </figure>
                    <div class="results__data">
                        <h4 class="results__name">${recipe.title}</h4>
                        <p class="results__author">${recipe.publisher}</p>
                    </div>
                </a>
            </li>
        `;
        var htmlObject = document.createElement('div');
        htmlObject.innerHTML = markup;
        element.searchResultList.insertAdjacentElement('beforeend',htmlObject);
    }
    
    const createButton = (page, type)=>`
    
        <button class="btn-inline results__btn--${type}" data-goto=${type === 'prev'? page-1 : page+1}>
        <svg class="search__icon">
            <use href="img/icons.svg#icon-triangle-${type === 'prev'? 'left' : 'right'}}"></use>
        </svg>
        <span>Page ${type === 'prev'? page-1 : page+1}</span>
        </button>
    `
    const renderButtons = (page, numResults, resultPerPage)=>{
        const pages = Math.ceil(numResults/resultPerPage);
        let button;
        if(page == 1 && pages >1){
            //button to go to next page
            button = createButton(page, 'next');
        }else if(page<pages){
          //both buttons  
          button = `
          ${createButton(page, 'prev')}
          ${createButton(page, 'next')}`;
    
    
        }
        else if (page === pages && pages > 1){
            //Only button to go to prev page
            button = createButton(page, 'prev');
        }
    
        element.searchResPages.insertAdjacentHTML('afterbegin', button);
    }
    export const renderResults = (recipes, page=1, resultPerPage=10) =>{
        /*//recipes.foreach(el=>renderRecipe(el))
        //or foreach will automatically call the render recipes
        //recipes.forEach(renderRecipe)*/
        const start = (page-1)*resultPerPage;
        const end = page * resultPerPage;
        recipes.slice(start, end).forEach(renderRecipe);
        renderButtons(page, recipes.length, resultPerPage);
    }
    
    

    file: Search.js

    export default class Search{
        constructor(query){
            this.query = query;
        }
        async getResults(){
            try{
                const res = await axios(`https://api.com/api/search?&q=${this.query}`);
                this.result = res.data.recipes;
                //console.log(this.result);
            }catch(error){
                alert(error);
            }
        }
    }
    

    file: Index.js

    onst state = {};
    const controlSearch = async()=>{
      const query = searchView.getInput();
      if (query){
        state.search = new Search(query); 
        searchView.clearResults();
        searchView.clearInput();
        await state.search.getResults();
        searchView.renderResults(state.search.result);
      }
    }
    //event listner to the parent object to delegate the event
    element.searchForm.addEventListener('submit', event=>{
      console.log("submit search");
      event.preventDefault();
      controlSearch();
    });
    
    element.searchResPages.addEventListener('click', e=>{
      const btn = e.target.closest('.btn-inline');
      if(btn){
        const goToPage = parseInt(btn.dataset.goto, 10);//base 10
        searchView.clearResults();
        searchView.renderResults(state.search.result, goToPage);
      }
    });
    
    

    From ND to 1D arrays

    I wanted to see a benchmark result of functions mentioned in answers including unutbu's.

    Also want to point out that numpy doc recommend to use arr.reshape(-1) in case view is preferable. (even though ravel is tad faster in the following result)


    TL;DR: np.ravel is the most performant (by very small amount).

    Benchmark

    Functions:

    numpy version: '1.18.0'

    Execution times on different ndarray sizes

    +-------------+----------+-----------+-----------+-------------+
    |  function   |   10x10  |  100x100  | 1000x1000 | 10000x10000 |
    +-------------+----------+-----------+-----------+-------------+
    | ravel       | 0.002073 |  0.002123 |  0.002153 |    0.002077 |
    | reshape(-1) | 0.002612 |  0.002635 |  0.002674 |    0.002701 |
    | flatten     | 0.000810 |  0.007467 |  0.587538 |  107.321913 |
    | flat        | 0.000337 |  0.000255 |  0.000227 |    0.000216 |
    +-------------+----------+-----------+-----------+-------------+
    

    Conclusion

    ravel and reshape(-1)'s execution time was consistent and independent from ndarray size. However, ravel is tad faster, but reshape provides flexibility in reshaping size. (maybe that's why numpy doc recommend to use it instead. Or there could be some cases where reshape returns view and ravel doesn't).
    If you are dealing with large size ndarray, using flatten can cause a performance issue. Recommend not to use it. Unless you need a copy of the data to do something else.

    Used code

    import timeit
    setup = '''
    import numpy as np
    nd = np.random.randint(10, size=(10, 10))
    '''
    
    timeit.timeit('nd = np.reshape(nd, -1)', setup=setup, number=1000)
    timeit.timeit('nd = np.ravel(nd)', setup=setup, number=1000)
    timeit.timeit('nd = nd.flatten()', setup=setup, number=1000)
    timeit.timeit('nd.flat', setup=setup, number=1000)
    

    pip install mysql-python fails with EnvironmentError: mysql_config not found

    There maybe various answers for the above issue, below is a aggregated solution.

    For Ubuntu:

    $ sudo apt update
    $ sudo apt install python-dev
    $ sudo apt install python-MySQLdb
    

    For CentOS:

    $ yum install python-devel mysql-devel
    

    Set the Value of a Hidden field using JQuery

    Drop the hash - that's for identifying the id attribute.

    Creating a div element inside a div element in javascript

    Your code works well you just mistyped this line of code:

    document.getElementbyId('lc').appendChild(element);

    change it with this: (The "B" should be capitalized.)

    document.getElementById('lc').appendChild(element);  
    

    HERE IS MY EXAMPLE:

    _x000D_
    _x000D_
    <html>_x000D_
    <head>_x000D_
    _x000D_
    <script>_x000D_
    _x000D_
    function test() {_x000D_
    _x000D_
        var element = document.createElement("div");_x000D_
        element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
        document.getElementById('lc').appendChild(element);_x000D_
    _x000D_
    }_x000D_
    _x000D_
    </script>_x000D_
    _x000D_
    </head>_x000D_
    <body>_x000D_
    <input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
    _x000D_
    <div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
    }" onclick="test();">  _x000D_
    </div>_x000D_
    </body>_x000D_
    _x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    rm: cannot remove: Permission denied

    The code says everything:

    max@serv$ chmod 777 .
    

    Okay, it doesn't say everything.

    In UNIX and Linux, the ability to remove a file is not determined by the access bits of that file. It is determined by the access bits of the directory which contains the file.

    Think of it this way -- deleting a file doesn't modify that file. You aren't writing to the file, so why should "w" on the file matter? Deleting a file requires editing the directory that points to the file, so you need "w" on the that directory.

    How to auto-format code in Eclipse?

    This can also be done at the Project Level: In the Package Explorer, right-click on the project > Properties > Java Editor > Save Actions

    This might be preferable when working as a team so that everyone's code is saved with the same format settings.

    Changing a specific column name in pandas DataFrame

    A one liner does exist:

    In [27]: df=df.rename(columns = {'two':'new_name'})
    
    In [28]: df
    Out[28]: 
      one three  new_name
    0    1     a         9
    1    2     b         8
    2    3     c         7
    3    4     d         6
    4    5     e         5
    

    Following is the docstring for the rename method.

    Definition: df.rename(self, index=None, columns=None, copy=True, inplace=False)
    Docstring:
    Alter index and / or columns using input function or
    functions. Function / dict values must be unique (1-to-1). Labels not
    contained in a dict / Series will be left as-is.
    
    Parameters
    ----------
    index : dict-like or function, optional
        Transformation to apply to index values
    columns : dict-like or function, optional
        Transformation to apply to column values
    copy : boolean, default True
        Also copy underlying data
    inplace : boolean, default False
        Whether to return a new DataFrame. If True then value of copy is
        ignored.
    
    See also
    --------
    Series.rename
    
    Returns
    -------
    renamed : DataFrame (new object)
    

    Clear and refresh jQuery Chosen dropdown list

    Using .trigger("chosen:updated"); you can update the options list after appending.

    Updating Chosen Dynamically: If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.

    Your code:

    $("#refreshgallery").click(function(){
            $('#picturegallery').empty(); //remove all child nodes
            var newOption = $('<option value="1">test</option>');
            $('#picturegallery').append(newOption);
            $('#picturegallery').trigger("chosen:updated");
        });
    

    How to Query an NTP Server using C#?

    Since the old accepted answer got deleted (It was a link to a Google code search results that no longer exist), I figured I could answer this question for future reference :

    public static DateTime GetNetworkTime()
    {
        //default Windows time server
        const string ntpServer = "time.windows.com";
    
        // NTP message size - 16 bytes of the digest (RFC 2030)
        var ntpData = new byte[48];
    
        //Setting the Leap Indicator, Version Number and Mode values
        ntpData[0] = 0x1B; //LI = 0 (no warning), VN = 3 (IPv4 only), Mode = 3 (Client Mode)
    
        var addresses = Dns.GetHostEntry(ntpServer).AddressList;
    
        //The UDP port number assigned to NTP is 123
        var ipEndPoint = new IPEndPoint(addresses[0], 123);
        //NTP uses UDP
    
        using(var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp))
        {
            socket.Connect(ipEndPoint);
    
            //Stops code hang if NTP is blocked
            socket.ReceiveTimeout = 3000;     
    
            socket.Send(ntpData);
            socket.Receive(ntpData);
            socket.Close();
        }
    
        //Offset to get to the "Transmit Timestamp" field (time at which the reply 
        //departed the server for the client, in 64-bit timestamp format."
        const byte serverReplyTime = 40;
    
        //Get the seconds part
        ulong intPart = BitConverter.ToUInt32(ntpData, serverReplyTime);
    
        //Get the seconds fraction
        ulong fractPart = BitConverter.ToUInt32(ntpData, serverReplyTime + 4);
    
        //Convert From big-endian to little-endian
        intPart = SwapEndianness(intPart);
        fractPart = SwapEndianness(fractPart);
    
        var milliseconds = (intPart * 1000) + ((fractPart * 1000) / 0x100000000L);
    
        //**UTC** time
        var networkDateTime = (new DateTime(1900, 1, 1, 0, 0, 0, DateTimeKind.Utc)).AddMilliseconds((long)milliseconds);
    
        return networkDateTime.ToLocalTime();
    }
    
    // stackoverflow.com/a/3294698/162671
    static uint SwapEndianness(ulong x)
    {
        return (uint) (((x & 0x000000ff) << 24) +
                       ((x & 0x0000ff00) << 8) +
                       ((x & 0x00ff0000) >> 8) +
                       ((x & 0xff000000) >> 24));
    }
    

    Note: You will have to add the following namespaces

    using System.Net;
    using System.Net.Sockets;
    

    How to interpolate variables in strings in JavaScript, without concatenation?

    String.prototype.interpole = function () {
        var c=0, txt=this;
        while (txt.search(/{var}/g) > 0){
            txt = txt.replace(/{var}/, arguments[c]);
            c++;
        }
        return txt;
    }
    

    Uso:

    var hello = "foo";
    var my_string = "I pity the {var}".interpole(hello);
    //resultado "I pity the foo"
    

    Prevent PDF file from downloading and printing

    if you want to provide a solution, well, there just isn't one. You would have to be able stop the user running a program that can access the buffers in the GPU to prevent them grabbing a screen shot. Anything displayed on the screen can be captured.

    If you decide to send a file where the contents are not accessible online, then you need to rely on the security that the end product/application uses. This will also be completely breakable for an extremely determined pserson.

    The last option is to send printed documents in the post. The old fashioned way using a good courier service. Costs go up, time delays are inevitble - but you get exactly what you are after. A solution is not without its costs.

    Always happy to point out the obvious :)

    Not equal to != and !== in PHP

    !== should match the value and data type

    != just match the value ignoring the data type

    $num = '1';
    $num2 = 1;
    
    $num == $num2; // returns true    
    $num === $num2; // returns false because $num is a string and $num2 is an integer
    

    How to list npm user-installed packages?

    For project dependencies use:

    npm list --depth=0
    

    For global dependencies use:

    npm list -g --depth=0
    

    How to open a different activity on recyclerView item onclick

    _x000D_
    _x000D_
    public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {_x000D_
        private LayoutInflater inflater;_x000D_
        private Context context;_x000D_
    List<Information>data= Collections.emptyList();_x000D_
        public AdapterClass(Context context,List<Information>data){_x000D_
            this.context=context;_x000D_
    _x000D_
            inflater= LayoutInflater.from(context);_x000D_
            this.data=data;_x000D_
        }_x000D_
        @Override_x000D_
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {_x000D_
           View view= inflater.inflate(R.layout.custom_row,parent,false);_x000D_
            MyViewHolder holder=new MyViewHolder(view);_x000D_
            return holder;_x000D_
        }_x000D_
    _x000D_
        @Override_x000D_
        public void onBindViewHolder(MyViewHolder holder, int position) {_x000D_
            Information current=data.get(position);_x000D_
            holder.title.setText(current.title);_x000D_
            holder.icon.setImageResource(current.iconId);_x000D_
    _x000D_
        }_x000D_
    _x000D_
        @Override_x000D_
        public int getItemCount() {_x000D_
            return data.size();_x000D_
        }_x000D_
        class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{_x000D_
            TextView title;_x000D_
            ImageView icon;_x000D_
    _x000D_
            public MyViewHolder(View itemView) {_x000D_
                super(itemView);_x000D_
                title=(TextView)itemView.findViewById(R.id.listText);_x000D_
               icon=(ImageView)itemView.findViewById(R.id.listIcon);_x000D_
                itemView.setClickable(true);_x000D_
                itemView.setOnClickListener(this);_x000D_
            }_x000D_
    _x000D_
            @Override_x000D_
            public void onClick(View v) {_x000D_
    _x000D_
                Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();_x000D_
            }_x000D_
        };_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    _x000D_
    _x000D_
    public class AdapterClass extends RecyclerView.Adapter<AdapterClass.MyViewHolder> {_x000D_
        private LayoutInflater inflater;_x000D_
        private Context context;_x000D_
    List<Information>data= Collections.emptyList();_x000D_
        public AdapterClass(Context context,List<Information>data){_x000D_
            this.context=context;_x000D_
    _x000D_
            inflater= LayoutInflater.from(context);_x000D_
            this.data=data;_x000D_
        }_x000D_
        @Override_x000D_
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {_x000D_
           View view= inflater.inflate(R.layout.custom_row,parent,false);_x000D_
            MyViewHolder holder=new MyViewHolder(view);_x000D_
            return holder;_x000D_
        }_x000D_
    _x000D_
        @Override_x000D_
        public void onBindViewHolder(MyViewHolder holder, int position) {_x000D_
            Information current=data.get(position);_x000D_
            holder.title.setText(current.title);_x000D_
            holder.icon.setImageResource(current.iconId);_x000D_
    _x000D_
        }_x000D_
    _x000D_
        @Override_x000D_
        public int getItemCount() {_x000D_
            return data.size();_x000D_
        }_x000D_
        class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener{_x000D_
            TextView title;_x000D_
            ImageView icon;_x000D_
    _x000D_
            public MyViewHolder(View itemView) {_x000D_
                super(itemView);_x000D_
                title=(TextView)itemView.findViewById(R.id.listText);_x000D_
               icon=(ImageView)itemView.findViewById(R.id.listIcon);_x000D_
                itemView.setClickable(true);_x000D_
                itemView.setOnClickListener(this);_x000D_
            }_x000D_
    _x000D_
            @Override_x000D_
            public void onClick(View v) {_x000D_
    _x000D_
                Toast.makeText(context,"The Item Clicked is: "+getPosition(),Toast.LENGTH_SHORT).show();_x000D_
            }_x000D_
        };_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    Swift: Reload a View Controller

    If you are using a navigation controller you can segue again to the current UIViewController and it will be refreshed. Here I use a UIButton for refreshing

    Angular2: Cannot read property 'name' of undefined

    You were getting this error because you followed the poorly-written directions on the Heroes tutorial. I ran into the same thing.

    Specifically, under the heading Display hero names in a template, it states:

    To display the hero names in an unordered list, insert the following chunk of HTML below the title and above the hero details.

    followed by this code block:

    <h2>My Heroes</h2>
    <ul class="heroes">
      <li>
        <!-- each hero goes here -->
      </li>
    </ul>
    

    It does not instruct you to replace the previous detail code, and it should. This is why we are left with:

    <h2>{{hero.name}} details!</h2>
    

    outside of our *ngFor.

    However, if you scroll further down the page, you will encounter the following:

    The template for displaying heroes should look like this:

    <h2>My Heroes</h2>
    <ul class="heroes">
      <li *ngFor="let hero of heroes">
        <span class="badge">{{hero.id}}</span> {{hero.name}}
      </li>
    </ul>
    

    Note the absence of the detail elements from previous efforts.

    An error like this by the author can result in quite a wild goose-chase. Hopefully, this post helps others avoid that.

    How to modify JsonNode in Java?

    You need to get ObjectNode type object in order to set values. Take a look at this

    Attach IntelliJ IDEA debugger to a running Java process

    Also, don't forget you need to add "-Xdebug" flag in app JAVA_OPTS if you want connect in debug mode.

    IN vs OR in the SQL WHERE Clause

    I think oracle is smart enough to convert the less efficient one (whichever that is) into the other. So I think the answer should rather depend on the readability of each (where I think that IN clearly wins)

    How can I declare optional function parameters in JavaScript?

    Update

    With ES6, this is possible in exactly the manner you have described; a detailed description can be found in the documentation.

    Old answer

    Default parameters in JavaScript can be implemented in mainly two ways:

    function myfunc(a, b)
    {
        // use this if you specifically want to know if b was passed
        if (b === undefined) {
            // b was not passed
        }
        // use this if you know that a truthy value comparison will be enough
        if (b) {
            // b was passed and has truthy value
        } else {
            // b was not passed or has falsy value
        }
        // use this to set b to a default value (using truthy comparison)
        b = b || "default value";
    }
    

    The expression b || "default value" evaluates the value AND existence of b and returns the value of "default value" if b either doesn't exist or is falsy.

    Alternative declaration:

    function myfunc(a)
    {
        var b;
    
        // use this to determine whether b was passed or not
        if (arguments.length == 1) {
            // b was not passed
        } else {
            b = arguments[1]; // take second argument
        }
    }
    

    The special "array" arguments is available inside the function; it contains all the arguments, starting from index 0 to N - 1 (where N is the number of arguments passed).

    This is typically used to support an unknown number of optional parameters (of the same type); however, stating the expected arguments is preferred!

    Further considerations

    Although undefined is not writable since ES5, some browsers are known to not enforce this. There are two alternatives you could use if you're worried about this:

    b === void 0;
    typeof b === 'undefined'; // also works for undeclared variables
    

    Easy way to turn JavaScript array into comma-separated list?

    Actually, the toString() implementation does a join with commas by default:

    var arr = [ 42, 55 ];
    var str1 = arr.toString(); // Gives you "42,55"
    var str2 = String(arr); // Ditto
    

    I don't know if this is mandated by the JS spec but this is what most pretty much all browsers seem to be doing.

    LAST_INSERT_ID() MySQL

    It would be possible to save the last_id_in_table1 variable into a php variable to use it later?

    With this last_id I need to attach some records in another table with this last_id, so I need:

    1) Do an INSERT and get the last_id_in_table1

    INSERT into Table1(name) values ("AAA"); 
    SET @last_id_in_table1 = LAST_INSERT_ID();
    

    2) For any indeterminated rows in another table, UPDATING these rows with the last_id_insert generated in the insert.

    $element = array(some ids)    
    foreach ($element as $e){ 
             UPDATE Table2 SET column1 = @last_id_in_table1 WHERE id = $e 
        }
    

    Is string in array?

    Linq (for s&g's):

    var test = "This is the string I'm looking for";
    var found = strArray.Any(x=>x == test);
    

    or, depending on requirements

    var found = strArray.Any(
        x=>x.Equals(test, StringComparison.OrdinalIgnoreCase));
    

    get current url in twig template?

    {{ path(app.request.attributes.get('_route'),
         app.request.attributes.get('_route_params')) }}
    

    If you want to read it into a view variable:

    {% set currentPath = path(app.request.attributes.get('_route'),
                           app.request.attributes.get('_route_params')) %}
    

    The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

    How to copy a java.util.List into another java.util.List

    re: indexOutOfBoundsException, your sublist args are the problem; you need to end the sublist at size-1. Being zero-based, the last element of a list is always size-1, there is no element in the size position, hence the error.

    "Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

    For me the following approach solved the issue (Python 3.5.2; mysqlclient 1.3.9):

    1. Dowload latest MySQL C Connector http://dev.mysql.com/downloads/connector/c/ (for me was Windows (x86, 64-bit), MSI Installer)
    2. Copy c:\Program Files\MySQL\MySQL Connector C 6.0.2\ directory to c:\Program Files (x86)\MySQL\MySQL Connector C 6.1\
    3. Run pip install mysqlclient
    4. [optional] delete c:\Program Files (x86)\MySQL\MySQL Connector C 6.1\

    The issue here is only for x64 bit installation owners, since build script is trying to locate C connector includes in x86 program files directory.

    Is either GET or POST more secure than the other?

    Consider this situation: A sloppy API accepts GET requests like:

    http://www.example.com/api?apikey=abcdef123456&action=deleteCategory&id=1
    

    In some settings, when you request this URL and if there is an error/warning regarding the request, this whole line gets logged in the log file. Worse yet: if you forget to disable error messages in the production server, this information is just displayed in plain in the browser! Now you've just given your API key away to everyone.

    Unfortunately, there are real API's working this way.

    I wouldn't like the idea of having some sensitive info in the logs or displaying them in the browser. POST and GET is not the same. Use each where appropriate.

    Android Studio Emulator and "Process finished with exit code 0"

    Android Studio Emulator: Process finished with exit code 1. Maybe disk drive is FULL. You can delete some virtual devices unused. It works for me. it's next to the edit in your virtual manager devices menu (the arrow down)

    disabling spring security in spring boot app

    You could just comment the maven dependency for a while:

    <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-actuator</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-data-mongodb</artifactId>
            </dependency>
    <!--        <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-security</artifactId>
            </dependency>-->
    </dependencies>
    

    It worked fine for me

    Disabling it from application.properties is deprecated for Spring Boot 2.0

    Getting the Facebook like/share count for a given URL

    Your question is quite old and Facebook has depreciated FQL now but what you want can still be done using this utility: Facebook Analytics. However you will find that if you want details about who is liking or commenting it will take a long time to get. This is because Facebook only gives a very small chunk of data at a time and a lot of paging is required in order to get everything.

    Using ffmpeg to change framerate

    You can use this command and the video duration is still unaltered.

    ffmpeg -i input.mp4 -r 24 output.mp4
    

    What is the difference between the HashMap and Map objects in Java?

    Map is interface and Hashmap is a class that implements Map Interface

    Git asks for username every time I push

    To avoid entering username, but still be prompted to enter a password, then you can simply clone your repository including the username:

    git clone [email protected]/my_repo.git
    

    jquery live hover

    $('.hoverme').live('mouseover mouseout', function(event) {
      if (event.type == 'mouseover') {
        // do something on mouseover
      } else {
        // do something on mouseout
      }
    });
    

    http://api.jquery.com/live/

    How Do I Take a Screen Shot of a UIView?

    You need to capture the key window for a screenshot or a UIView. You can do it in Retina Resolution using UIGraphicsBeginImageContextWithOptions and set its scale parameter 0.0f. It always captures in native resolution (retina for iPhone 4 and later).

    This one does a full screen screenshot (key window)

    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    CGRect rect = [keyWindow bounds];
    UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [keyWindow.layer renderInContext:context];   
    UIImage *capturedScreen = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    This code capture a UIView in native resolution

    CGRect rect = [captureView bounds];
    UIGraphicsBeginImageContextWithOptions(rect.size,YES,0.0f);
    CGContextRef context = UIGraphicsGetCurrentContext();
    [captureView.layer renderInContext:context];   
    UIImage *capturedImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    

    This saves the UIImage in jpg format with 95% quality in the app's document folder if you need to do that.

    NSString  *imagePath = [NSHomeDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"Documents/capturedImage.jpg"]];    
    [UIImageJPEGRepresentation(capturedImage, 0.95) writeToFile:imagePath atomically:YES];
    

    jquery clone div and append it after specific div

    You can do it using clone() function of jQuery, Accepted answer is ok but i am providing alternative to it, you can use append(), but it works only if you can change html slightly as below:

    _x000D_
    _x000D_
    $(document).ready(function(){_x000D_
        $('#clone_btn').click(function(){_x000D_
          $("#car_parent").append($("#car2").clone());_x000D_
        });_x000D_
    });
    _x000D_
    .car-well{_x000D_
      border:1px solid #ccc;_x000D_
      text-align: center;_x000D_
      margin: 5px;_x000D_
      padding:3px;_x000D_
      font-weight:bold;_x000D_
    }
    _x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    <head>_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
    </head>_x000D_
    <body>_x000D_
    <div id="car_parent">_x000D_
      <div id="car1" class="car-well">Normal div</div>_x000D_
      <div id="car2" class="car-well" style="background-color:lightpink;color:blue">Clone div</div>_x000D_
      <div id="car3" class="car-well">Normal div</div>_x000D_
      <div id="car4" class="car-well">Normal div</div>_x000D_
      <div id="car5" class="car-well">Normal div</div>_x000D_
    </div>_x000D_
    <button type="button" id="clone_btn" class="btn btn-primary">Clone</button>_x000D_
    _x000D_
    </body>_x000D_
    </html>
    _x000D_
    _x000D_
    _x000D_

    What is a callback in java

    Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

    Paul Jakubik, Callback Implementations in C++.

    Tab separated values in awk

    You can set the Field Separator:

    ... | awk 'BEGIN {FS="\t"}; {print $1}'
    

    Excellent read:

    https://docs.freebsd.org/info/gawk/gawk.info.Field_Separators.html

    How to make space between LinearLayout children?

    You can get the LayoutParams of parent LinearLayout and apply to the individual views this way:

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    lp.setMargins(8,8,8,8);
    
    • Take care that setMargins() take pixels as int data type.So, convert to dp before adding values
    • Above code will set height and width to wrap_content. you can customise it.

    java.util.NoSuchElementException - Scanner reading user input

    The problem is

    When a Scanner is closed, it will close its input source if the source implements the Closeable interface.

    http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Scanner.html

    Thus scan.close() closes System.in.

    To fix it you can make

    Scanner scan static and do not close it in PromptCustomerQty. Code below works.

    public static void main (String[] args) {   
    
    // Create a customer
    // Future proofing the possabiltiies of multiple customers
    Customer customer = new Customer("Will");
    
    // Create object for each Product
    // (Name,Code,Description,Price)
    // Initalize Qty at 0
    Product Computer = new Product("Computer","PC1003","Basic Computer",399.99); 
    Product Monitor = new Product("Monitor","MN1003","LCD Monitor",99.99);
    Product Printer = new Product("Printer","PR1003x","Inkjet Printer",54.23);
    
    // Define internal variables 
    // ## DONT CHANGE 
    ArrayList<Product> ProductList = new ArrayList<Product>(); // List to store Products
    String formatString = "%-15s %-10s %-20s %-10s %-10s %n"; // Default format for output
    
    // Add objects to list
    ProductList.add(Computer);
    ProductList.add(Monitor);
    ProductList.add(Printer);
    
    // Ask users for quantities 
    PromptCustomerQty(customer, ProductList);
    
    // Ask user for payment method
    PromptCustomerPayment(customer);
    
    // Create the header
    PrintHeader(customer, formatString);
    
    // Create Body
    PrintBody(ProductList, formatString);   
    }
    
    static Scanner scan;
    
    public static void PromptCustomerQty(Customer customer, ArrayList<Product> ProductList)               {
    // Initiate a Scanner
    scan = new Scanner(System.in);
    
    // **** VARIABLES ****
    int qty = 0;
    
    // Greet Customer
    System.out.println("Hello " + customer.getName());
    
    // Loop through each item and ask for qty desired
    for (Product p : ProductList) {
    
        do {
        // Ask user for qty
        System.out.println("How many would you like for product: " + p.name);
        System.out.print("> ");
    
        // Get input and set qty for the object
        qty = scan.nextInt();
    
        }
        while (qty < 0); // Validation
    
        p.setQty(qty); // Set qty for object
        qty = 0; // Reset count
    }
    
    // Cleanup
    
    }
    
    public static void PromptCustomerPayment (Customer customer) {
    // Variables
    String payment = "";
    
    // Prompt User
    do {
    System.out.println("Would you like to pay in full? [Yes/No]");
    System.out.print("> ");
    
    payment = scan.next();
    
    } while ((!payment.toLowerCase().equals("yes")) && (!payment.toLowerCase().equals("no")));
    
    // Check/set result
    if (payment.toLowerCase() == "yes") {
        customer.setPaidInFull(true);
    }
    else {
        customer.setPaidInFull(false);
    }
    }
    

    On a side note, you shouldn't use == for String comparision, use .equals instead.

    How can I get the domain name of my site within a Django template?

    I use a custom template tag. Add to e.g. <your_app>/templatetags/site.py:

    # -*- coding: utf-8 -*-
    from django import template
    from django.contrib.sites.models import Site
    
    register = template.Library()
    
    @register.simple_tag
    def current_domain():
        return 'http://%s' % Site.objects.get_current().domain
    

    Use it in a template like this:

    {% load site %}
    {% current_domain %}
    

    CodeIgniter: "Unable to load the requested class"

    I had a similar issue when deploying from OSx on my local to my Linux live site.

    It ran fine on OSx, but on Linux I was getting:

    An Error Was Encountered
    
    Unable to load the requested class: Ckeditor
    

    The problem was that Linux paths are apparently case-sensitive so I had to rename my library files from "ckeditor.php" to "CKEditor.php".

    I also changed my load call to match the capitalization:

    $this->load->library('CKEditor');
    

    How to store array or multiple values in one column

    Well, there is an array type in recent Postgres versions (not 100% about PG 7.4). You can even index them, using a GIN or GIST index. The syntaxes are:

    create table foo (
      bar  int[] default '{}'
    );
    
    select * from foo where bar && array[1] -- equivalent to bar && '{1}'::int[]
    
    create index on foo using gin (bar); -- allows to use an index in the above query
    

    But as the prior answer suggests, it will be better to normalize properly.

    Find UNC path of a network drive?

    The answer is a simple PowerShell one-liner:

    Get-WmiObject Win32_NetworkConnection | ft "RemoteName","LocalName" -A
    

    If you only want to pull the UNC for one particular drive, add a where statement:

    Get-WmiObject Win32_NetworkConnection | where -Property 'LocalName' -eq 'Z:'  | ft "RemoteName","LocalName" -A
    

    Page loaded over HTTPS but requested an insecure XMLHttpRequest endpoint

    Try to add a s after http

    Like this:

    http://integration.jsite.com/data/vis => https://integration.jsite.com/data/vis

    It works for me

    How to get the full URL of a Drupal page?

    drupal_get_destination() has some internal code that points at the correct place to getthe current internal path. To translate that path into an absolute URL, the url() function should do the trick. If the 'absolute' option is passed in it will generate the full URL, not just the internal path. It will also swap in any path aliases for the current path as well.

    $path = isset($_GET['q']) ? $_GET['q'] : '<front>';
    $link = url($path, array('absolute' => TRUE));
    

    TypeError: 'dict_keys' object does not support indexing

    Convert an iterable to a list may have a cost. Instead, to get the the first item, you can use:

    next(iter(keys))
    

    Or, if you want to iterate over all items, you can use:

    items = iter(keys)
    while True:
        try:
            item = next(items)
        except StopIteration as e:
            pass # finish
    

    How to flip background image using CSS?

    According to w3schools: http://www.w3schools.com/cssref/css3_pr_transform.asp

    The transform property is supported in Internet Explorer 10, Firefox, and Opera. Internet Explorer 9 supports an alternative, the -ms-transform property (2D transforms only). Safari and Chrome support an alternative, the -webkit-transform property (3D and 2D transforms). Opera supports 2D transforms only.

    This is a 2D transform, so it should work, with the vendor prefixes, on Chrome, Firefox, Opera, Safari, and IE9+.

    Other answers used :before to stop it from flipping the inner content. I used this on my footer (to vertically-mirror the image from my header):

    HTML:

    <footer>
    <p><a href="page">Footer Link</a></p>
    <p>&copy; 2014 Company</p>
    </footer>
    

    CSS:

    footer {
    background:url(/img/headerbg.png) repeat-x 0 0;
    
    /* flip background vertically */
    -webkit-transform:scaleY(-1);
    -moz-transform:scaleY(-1);
    -ms-transform:scaleY(-1);
    -o-transform:scaleY(-1);
    transform:scaleY(-1);
    }
    
    /* undo the vertical flip for all child elements */
    footer * {
    -webkit-transform:scaleY(-1);
    -moz-transform:scaleY(-1);
    -ms-transform:scaleY(-1);
    -o-transform:scaleY(-1);
    transform:scaleY(-1);
    }
    

    So you end up flipping the element and then re-flipping all its children. Works with nested elements, too.

    Installing Java 7 (Oracle) in Debian via apt-get

    Managed to get answer after do some google..

    echo "deb http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
    echo "deb-src http://ppa.launchpad.net/webupd8team/java/ubuntu precise main" | tee -a /etc/apt/sources.list
    apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys EEA14886
    apt-get update
    # Java 7
    apt-get install oracle-java7-installer
    # For Java 8 command is:
    apt-get install oracle-java8-installer
    

    Delete empty lines using sed

    I am missing the awk solution:

    awk 'NF' file
    

    Which would return:

    xxxxxx
    yyyyyy
    zzzzzz
    

    How does this work? Since NF stands for "number of fields", those lines being empty have 0 fiedls, so that awk evaluates 0 to False and no line is printed; however, if there is at least one field, the evaluation is True and makes awk perform its default action: print the current line.