Programs & Examples On #Xquery

XQuery is a functional language designed to query and manipulate XML data. It is a superset of XPath, to which it adds features such as the creation of new nodes and more powerful FLWOR expressions. Although it shares its data model with XSLT, XQuery is optimized for querying rather than transforming data, and as such it has a different design inspired by SQL.

How can I query a value in SQL Server XML column

I came up with a simple work around below which is easy to remember too :-)

select * from  
(select cast (xmlCol as varchar(max)) texty
 from myTable (NOLOCK) 
) a 
where texty like '%MySearchText%'

Is there a JSON equivalent of XQuery/XPath?

Other alternatives I am aware of are

  1. JSONiq specification, which specifies two subtypes of languages: one that hides XML details and provides JS-like syntax, and one that enriches XQuery syntax with JSON constructors and such. Zorba implements JSONiq.
  2. Corona, which builds on top of MarkLogic provides a REST interface for storing, managing, and searching XML, JSON, Text and Binary content.
  3. MarkLogic 6 and later provide a similar REST interface as Corona out of the box.
  4. MarkLogic 8 and later support JSON natively in both their XQuery and Server-side JavaScript environment. You can apply XPath on it.

HTH.

Concatenate multiple node values in xpath

for $d in $doc/element2/element3 return fn:string-join(fn:data($d/element()), ".").
$doc stores the Xml.

How can I change the width and height of slides on Slick Carousel?

You could also use this:

$('.slider').slick({
   //other settings ................
   respondTo: 'slider', //makes the slider to change width depending on the container it is in
   adaptiveHeight: true //makes the height change depending on the height of the element inside
})

Jquery DatePicker Set default date

For today's Date

$(document).ready(function() {
$('#textboxname').datepicker();
$('#textboxname').datepicker('setDate', 'today');});

Download an SVN repository?

For me DownloadSVN is the best SVN client no install no explore shell integration so no need to worry about system instability small and very light weight and it does a great job just recently i had a very bad experience with TortoiseSVN on my WindowsXP_x86:) luckily i found this great SVN client

How to write :hover condition for a:before and a:after?

You can also restrict your action to just one class using the right pointed bracket (">"), as I have done in this code:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Document</title>
  <style type="text/css">
    span {
    font-size:12px;
    }
    a {
        color:green;
    }
    .test1>a:hover span {
        display:none;
    }
    .test1>a:hover:before {
        color:red;
        content:"Apple";
    }
  </style>
</head>

<body>
  <div class="test1">
    <a href="#"><span>Google</span></a>
  </div>
  <div class="test2">
    <a href="#"><span>Apple</span></a>
  </div>
</body>

</html>

Note: The hover:before switch works only on the .test1 class

comma separated string of selected values in mysql

Just so for people doing it in SQL server: use STRING_AGG to get similar results.

Nested select statement in SQL Server

The answer provided by Joe Stefanelli is already correct.

SELECT name FROM (SELECT name FROM agentinformation) as a  

We need to make an alias of the subquery because a query needs a table object which we will get from making an alias for the subquery. Conceptually, the subquery results are substituted into the outer query. As we need a table object in the outer query, we need to make an alias of the inner query.

Statements that include a subquery usually take one of these forms:

  • WHERE expression [NOT] IN (subquery)
  • WHERE expression comparison_operator [ANY | ALL] (subquery)
  • WHERE [NOT] EXISTS (subquery)

Check for more subquery rules and subquery types.

More examples of Nested Subqueries.

  1. IN / NOT IN – This operator takes the output of the inner query after the inner query gets executed which can be zero or more values and sends it to the outer query. The outer query then fetches all the matching [IN operator] or non matching [NOT IN operator] rows.

  2. ANY – [>ANY or ANY operator takes the list of values produced by the inner query and fetches all the values which are greater than the minimum value of the list. The

e.g. >ANY(100,200,300), the ANY operator will fetch all the values greater than 100.

  1. ALL – [>ALL or ALL operator takes the list of values produced by the inner query and fetches all the values which are greater than the maximum of the list. The

e.g. >ALL(100,200,300), the ALL operator will fetch all the values greater than 300.

  1. EXISTS – The EXISTS keyword produces a Boolean value [TRUE/FALSE]. This EXISTS checks the existence of the rows returned by the sub query.

How to get the CUDA version?

i get /usr/local - no such file or directory. Though nvcc -V gives

nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2016 NVIDIA Corporation
Built on Sun_Sep__4_22:14:01_CDT_2016
Cuda compilation tools, release 8.0, V8.0.44

What is the difference between Python's list methods append and extend?

Append and extend are one of the extensibility mechanisms in python.

Append: Adds an element to the end of the list.

my_list = [1,2,3,4]

To add a new element to the list, we can use append method in the following way.

my_list.append(5)

The default location that the new element will be added is always in the (length+1) position.

Insert: The insert method was used to overcome the limitations of append. With insert, we can explicitly define the exact position we want our new element to be inserted at.

Method descriptor of insert(index, object). It takes two arguments, first being the index we want to insert our element and second the element itself.

Example: my_list = [1,2,3,4]
my_list[4, 'a']
my_list
[1,2,3,4,'a']

Extend: This is very useful when we want to join two or more lists into a single list. Without extend, if we want to join two lists, the resulting object will contain a list of lists.

a = [1,2]
b = [3]
a.append(b)
print (a)
[1,2,[3]]

If we try to access the element at pos 2, we get a list ([3]), instead of the element. To join two lists, we'll have to use append.

a = [1,2]
b = [3]
a.extend(b)
print (a)
[1,2,3]

To join multiple lists

a = [1]
b = [2]
c = [3]
a.extend(b+c)
print (a)
[1,2,3]

Android Studio 3.0 Flavor Dimension Issue

If you want not to use dimensions you should use this line

android { 
compileSdkVersion 24

...
flavorDimensions "default"
...
}

but if you want ti use dimensions you should declare your dimension name first and then use this name after THIS example is from the documentations:

android {
...
buildTypes {
debug {...}
release {...}
}

  // Specifies the flavor dimensions you want to use. The order in which you
  // list each dimension determines its priority, from highest to lowest,
  // when Gradle merges variant sources and configurations. You must assign
  // each product flavor you configure to one of the flavor dimensions.
  flavorDimensions "api", "mode"

  productFlavors {
    demo {
  // Assigns this product flavor to the "mode" flavor dimension.
  dimension "mode"
  ...
}

full {
  dimension "mode"
  ...
}

// Configurations in the "api" product flavors override those in "mode"
// flavors and the defaultConfig block. Gradle determines the priority
// between flavor dimensions based on the order in which they appear next
// to the flavorDimensions property above--the first dimension has a higher
// priority than the second, and so on.
minApi24 {
  dimension "api"
  minSdkVersion 24
  // To ensure the target device receives the version of the app with
  // the highest compatible API level, assign version codes in increasing
  // value with API level. To learn more about assigning version codes to
  // support app updates and uploading to Google Play, read Multiple APK Support
  versionCode 30000 + android.defaultConfig.versionCode
  versionNameSuffix "-minApi24"
  ...
}

minApi23 {
  dimension "api"
  minSdkVersion 23
  versionCode 20000  + android.defaultConfig.versionCode
  versionNameSuffix "-minApi23"
  ...
}

minApi21 {
  dimension "api"
  minSdkVersion 21
  versionCode 10000  + android.defaultConfig.versionCode
  versionNameSuffix "-minApi21"
  ...
    }
  }
}
...

How can I parse JSON with C#?

         string json = @"{
            'Name': 'Wide Web',
            'Url': 'www.wideweb.com.br'}";

        JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
        dynamic j = jsonSerializer.Deserialize<dynamic>(json);
        string name = j["Name"].ToString();
        string url = j["Url"].ToString();

Removing items from a ListBox in VB.net

I think your ListBox already clear with ListBox2.Items.Clear(). The problem is that you also need to clear your dataset from previous results with ds6.Tables.Clear().

Add this in your code:

da6 = New SqlDataAdapter("select distinct(component_type) from component where   component_name='" & ListBox1.SelectedItem() & "'", con)
    ListBox1.Items.Clear()    ' clears ListBox1
    ListBox2.Items.Clear()    ' clears ListBox2
    ds6.Tables.Clear()        ' clears DataSet  <======= DON'T FORGET TO DO THIS
da6.Fill(ds6, "component")
For Each row As DataRow In ds6.Tables(0).Rows
    ListBox2.Items.Add(row.Field(Of String)("component_type"))
Next

SVN icon overlays not showing properly

They showed up after installing Ankh SVN

NameError: name 'self' is not defined

If you have arrived here via google, please make sure to check that you have given self as the first parameter to a class function. Especially if you try to reference values for that object instance inside the class function.

def foo():
    print(self.bar)

>NameError: name 'self' is not defined

def foo(self):
    print(self.bar)

Replace all whitespace characters

\s is a meta character that covers all white space. You don't need to make it case-insensitive — white space doesn't have case.

str.replace(/\s/g, "X")

Cannot create PoolableConnectionFactory (Io exception: The Network Adapter could not establish the connection)

Just check tsnnames.ora and listener.ora files. It should not have localhost as a server. change it to hostname.

Like in tnsnames.ora

LISTENER_ORCL =
(ADDRESS = (PROTOCOL = TCP)(HOST = localhost)(PORT = 1521))

Replace localhost by hostname.

How to check if any flags of a flag combination are set?

If it really annoys you, you can write a function like that:

public bool IsSet(Letters value, Letters flag)
{
    return (value & flag) == flag;
}

if (IsSet(letter, Letters.A))
{
   // ...
}

// If you want to check if BOTH Letters.A and Letters.B are set:
if (IsSet(letter, Letters.A & Letters.B))
{
   // ...
}

// If you want an OR, I'm afraid you will have to be more verbose:
if (IsSet(letter, Letters.A) || IsSet(letter, Letters.B))
{
   // ...
}

multiple packages in context:component-scan, spring config

You can add multiple base packages (see axtavt's answer), but you can also filter what's scanned inside the base package:

<context:component-scan base-package="x.y.z">
   <context:include-filter type="regex" expression="(service|controller)\..*"/>
</context:component-scan>

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

It turns out Java does not accept a bare Date value as DateTime. Using LocalDate instead of LocalDateTime solves the issue:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
LocalDate dt = LocalDate.parse("20140218", formatter);

Turning off eslint rule for a specific line

To disable a single rule for the rest of the file below:

/* eslint no-undef: "off"*/
const uploadData = new FormData();

Remove all spaces from a string in SQL Server

I had this issue today and replace / trim did the trick..see below.

update table_foo 
set column_bar  = REPLACE(LTRIM(RTRIM(column_bar)), '  ', '')

before and after :

old-bad:  column_bar    |   New-fixed:   column_bar
       '  xyz  '        |                'xyz'   
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 
       '  xyz  '        |                'xyz' 

DataColumn Name from DataRow (not DataTable)

You need something like this:

foreach(DataColumn c in dr.Table.Columns)
{
  MessageBox.Show(c.ColumnName);
}

What is the proper way to URL encode Unicode characters?

IRI (RFC 3987) is the latest standard that replaces the URI/URL (RFC 3986 and older) standards. URI/URL do not natively support Unicode (well, RFC 3986 adds provisions for future URI/URL-based protocols to support it, but does not update past RFCs). The "%uXXXX" scheme is a non-standard extension to allow Unicode in some situations, but is not universally implemented by everyone. IRI, on the other hand, fully supports Unicode, and requires that text be encoded as UTF-8 before then being percent-encoded.

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Is there a way to automatically generate getters and setters in Eclipse?

  1. Open the class file in Eclipse
  2. Double click on the class name or highlight it
  3. Then navigate to Source -> Insert Code
  4. Click on Getter and Setter

It opens a popup to select the fields for which getter/setter methods to be generated. Select the fields and click on "Generate" button. enter image description hereenter image description here

Can you do greater than comparison on a date in a Rails 3 search?

If you aren't a fan of passing in a string, I prefer how @sesperanto has done it, except to make it even more concise, you could drop Float::INFINITY in the date range and instead simply use created_at: p[:date]..

Note.where(
    user_id: current_user.id,
    notetype: p[:note_type],
    created_at: p[:date]..
).order(:date, :created_at)

Take note that this will change the query to be >= instead of >. If that's a concern, you could always add a unit of time to the date by running something like p[:date] + 1.day..

Error : ORA-01704: string literal too long

INSERT INTO table(clob_column) SELECT TO_CLOB(q'[chunk1]') || TO_CLOB(q'[chunk2]') ||
            TO_CLOB(q'[chunk3]') || TO_CLOB(q'[chunk4]') FROM DUAL;

Executing Javascript code "on the spot" in Chrome?

Have you tried something like this? Put it in the head for it to work properly.

<script type="text/javascript">
    document.addEventListener("DOMContentLoaded", function(){
         //using DOMContentLoaded is good as it relies on the DOM being ready for
         //manipulation, rather than the windows being fully loaded. Just like
         //how jQuery's $(document).ready() does it.

         //loop through your inputs and set their values here
    }, false);
</script>

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

How to display a gif fullscreen for a webpage background?

IMG Method

If you want the image to be a stand alone element, use this CSS:

#selector {
    width:100%;
    height:100%;
}

With this HTML:

<img src='folder/image.gif' id='selector'/>

Fiddle

Please note that the img tag would have to be inside the body tag ONLY. If it were inside anything else, it may not fill the entire screen based on the other elements properties. This method will also not work if the page is taller than the image. It will leave white space. This is where the background method comes in

Background Image Method

If you want it to be the background image of you page, you can use this CSS:

body {
    background-image:url('folder/image.gif');
    background-size:100%;
    background-repeat: repeat-y;
    background-attachment: fixed;
    height:100%;
    width:100%;
}

Fiddle

Or the shorthand version:

body {
    background:url('folder/image.gif') repeat-y 100% 100% fixed;
    height:100%;
    width:100%;
}

Fiddle

JFrame.dispose() vs System.exit()

System.exit(); causes the Java VM to terminate completely.

JFrame.dispose(); causes the JFrame window to be destroyed and cleaned up by the operating system. According to the documentation, this can cause the Java VM to terminate if there are no other Windows available, but this should really just be seen as a side effect rather than the norm.

The one you choose really depends on your situation. If you want to terminate everything in the current Java VM, you should use System.exit() and everything will be cleaned up. If you only want to destroy the current window, with the side effect that it will close the Java VM if this is the only window, then use JFrame.dispose().

SQL JOIN, GROUP BY on three tables to get totals

Thank you very much for the replies!

Saggi Malachi, that query unfortunately sums the invoice amount in cases where there is more than one payment. Say there are two payments to a $39 invoice of $18 and $12. So rather than ending up with a result that looks like:

1   39.00   9.00

You'll end up with:

1   78.00   48.00

Charles Bretana, in the course of trimming my query down to the simplest possible query I (stupidly) omitted an additional table, customerinvoices, which provides a link between customers and invoices. This can be used to see invoices for which payments haven't made.

After much struggling, I think that the following query returns what I need it to:

SELECT DISTINCT i.invoiceid, i.amount, ISNULL(i.amount - p.amount, i.amount) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN customerinvoices ci ON i.invoiceid = ci.invoiceid
LEFT JOIN (
  SELECT invoiceid, SUM(p.amount) amount
  FROM invoicepayments ip 
  LEFT JOIN payments p ON ip.paymentid = p.paymentid
  GROUP BY ip.invoiceid
) p
ON p.invoiceid = ip.invoiceid
LEFT JOIN payments p2 ON ip.paymentid = p2.paymentid
LEFT JOIN customers c ON ci.customerid = c.customerid
WHERE c.customernumber='100'

Would you guys concur?

Can I use Objective-C blocks as properties?

Here's an example of how you would accomplish such a task:

#import <Foundation/Foundation.h>
typedef int (^IntBlock)();

@interface myobj : NSObject
{
    IntBlock compare;
}

@property(readwrite, copy) IntBlock compare;

@end

@implementation myobj

@synthesize compare;

- (void)dealloc 
{
   // need to release the block since the property was declared copy. (for heap
   // allocated blocks this prevents a potential leak, for compiler-optimized 
   // stack blocks it is a no-op)
   // Note that for ARC, this is unnecessary, as with all properties, the memory management is handled for you.
   [compare release];
   [super dealloc];
}
@end

int main () {
    @autoreleasepool {
        myobj *ob = [[myobj alloc] init];
        ob.compare = ^
        {
            return rand();
        };
        NSLog(@"%i", ob.compare());
        // if not ARC
        [ob release];
    }

    return 0;
}

Now, the only thing that would need to change if you needed to change the type of compare would be the typedef int (^IntBlock)(). If you need to pass two objects to it, change it to this: typedef int (^IntBlock)(id, id), and change your block to:

^ (id obj1, id obj2)
{
    return rand();
};

I hope this helps.

EDIT March 12, 2012:

For ARC, there are no specific changes required, as ARC will manage the blocks for you as long as they are defined as copy. You do not need to set the property to nil in your destructor, either.

For more reading, please check out this document: http://clang.llvm.org/docs/AutomaticReferenceCounting.html

Bash: Syntax error: redirection unexpected

You can get the output of that command and put it in a variable. then use heredoc. for example:

nc -l -p 80 <<< "tested like a charm";

can be written like:

nc -l -p 80 <<EOF
tested like a charm
EOF

and like this (this is what you want):

text="tested like a charm"
nc -l -p 80 <<EOF
$text
EOF

Practical example in busybox under docker container:

kasra@ubuntu:~$ docker run --rm -it busybox
/ # nc -l -p 80 <<< "tested like a charm";
sh: syntax error: unexpected redirection


/ # nc -l -p 80 <<EOL
> tested like a charm
> EOL
^Cpunt!       => socket listening, no errors. ^Cpunt! is result of CTRL+C signal.


/ # text="tested like a charm"
/ # nc -l -p 80 <<EOF
> $text
> EOF
^Cpunt!

How to get screen width and height

DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);

int height = metrics.heightPixels;
int width = metrics.widthPixels;

i guess the code which you wrote is deprecated.

Binding IIS Express to an IP Address

In order for IIS Express answer on any IP address, just leave the address blank, i.e:

bindingInformation=":8080:"

Don't forget to restart the IIS express before the changes can take place.

How to generate random float number in C

If you want to generate a random float in a range, try a next solution.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>


float
random_float(const float min, const float max)
{
    if (max == min) return min;
    else if (min < max) return (max - min) * ((float)rand() / RAND_MAX) + min;

    // return 0 if min > max
    return 0;
}


int
main (const int argc, const char *argv[])
{
    srand(time(NULL));

    char line[] = "-------------------------------------------";

    float data[10][2] = {
        {-10, 10},
        {-5., 5},
        {-1, 1},
        {-0.25, -0.15},
        {1.5, 1.52},
        {-1700, 8000},
        {-0.1, 0.1},
        {-1, 0},
        {-1, -2},
        {1.2, 1.1}
    };

    puts(line);
    puts("     From    |    Result    |      To");
    puts(line);


    int i;
    for (i = 0; i < 10; ++i) {
        printf("%12f | %12f | %12f\n", data[i][0], random_float(data[i][0], data[i][1]), data[i][1]);
    }

    puts(line);

    return 0;
}

A result (values is fickle)

-------------------------------------------
     From    |    Result    |      To
-------------------------------------------
  -10.000000 |     2.330828 |    10.000000
   -5.000000 |    -4.945523 |     5.000000
   -1.000000 |     0.004242 |     1.000000
   -0.250000 |    -0.203197 |    -0.150000
    1.500000 |     1.513431 |     1.520000
-1700.000000 |  3292.941895 |  8000.000000
   -0.100000 |    -0.021541 |     0.100000
   -1.000000 |    -0.148299 |     0.000000
   -1.000000 |     0.000000 |    -2.000000
    1.200000 |     0.000000 |     1.100000
-------------------------------------------

Auto-click button element on page load using jQuery

I tried the following ways in first jQuery, then JavaScript:

jQuery:

 window.location.href = $(".contact").attr('href');
 $('.contactformone').trigger('click');  

This is the best way in JavaScript:

 document.getElementById("id").click();

npm - how to show the latest version of a package

The npm view <pkg> version prints the last version by release date. That might very well be an hotfix release for a older stable branch at times.

The solution is to list all versions and fetch the last one by version number

$ npm view <pkg> versions --json | jq -r '.[-1]'

Or with awk instead of jq:

$ npm view <pkg> --json  | awk '/"$/{print gensub("[ \"]", "", "G")}'

Find the files that have been changed in last 24 hours

For others who land here in the future (including myself), add a -name option to find specific file types, for instance: find /var -name "*.php" -mtime -1 -ls

Want to make Font Awesome icons clickable

Using bootstrap with font awesome.

<a class="btn btn-large btn-primary logout" href="#">
        <i class="fa fa-sign-out" aria-hidden="true">Logout</i>
</a>

Remove special symbols and extra spaces and replace with underscore using the replace method

var str = "hello world & hello universe"

In order to replace both Spaces and Symbols in one shot, we can use the below regex code.

str.replaceAll("\\W+","")

Note: \W -> represents Not Words (includes spaces/special characters) | + -> one or many matches

Try it!

C# "as" cast vs classic cast

There's nothing deep happening here.. Basically, it's handy to test something to see if it's of a certain type (i.e. use 'as'). You would want to check the result of the 'as' call to see if the result is null.

When you expect a cast to work and you want the exception to be thrown, use the 'classic' method.

Sort divs in jQuery based on attribute 'data-sort'?

Use this function

   var result = $('div').sort(function (a, b) {

      var contentA =parseInt( $(a).data('sort'));
      var contentB =parseInt( $(b).data('sort'));
      return (contentA < contentB) ? -1 : (contentA > contentB) ? 1 : 0;
   });

   $('#mylist').html(result);

You can call this function just after adding new divs.

If you want to preserve javascript events within the divs, DO NOT USE html replace as in the above example. Instead use:

$(targetSelector).sort(function (a, b) {
    // ...
}).appendTo($container);

What is the fastest way to compare two sets in Java?

There's an O(N) solution for very specific cases where:

  • the sets are both sorted
  • both sorted in the same order

The following code assumes that both sets are based on the records comparable. A similar method could be based on on a Comparator.

    public class SortedSetComparitor <Foo extends Comparable<Foo>> 
            implements Comparator<SortedSet<Foo>> {

        @Override
        public int compare( SortedSet<Foo> arg0, SortedSet<Foo> arg1 ) {
            Iterator<Foo> otherRecords = arg1.iterator();
            for (Foo thisRecord : arg0) {
                // Shorter sets sort first.
                if (!otherRecords.hasNext()) return 1;
                int comparison = thisRecord.compareTo(otherRecords.next());
                if (comparison != 0) return comparison;
            }
            // Shorter sets sort first
            if (otherRecords.hasNext()) return -1;
            else return 0;
        }
    }

Pass path with spaces as parameter to bat file

Interesting one. I love collecting quotes about quotes handling in cmd/command.

Your particular scripts gets fixed by using %1 instead of "%1" !!!

By adding an 'echo on' ( or getting rid of an echo off ), you could have easily found that out.

Iterate over elements of List and Map using JSTL <c:forEach> tag

try this

<c:forEach items="${list}" var="map">
    <tr>
        <c:forEach items="${map}" var="entry">

            <td>${entry.value}</td>

        </c:forEach>
    </tr>
</c:forEach>

CSS display:inline property with list-style-image: property on <li> tags

Try using float: left (or right) instead of display: inline. Inline display replaces list-item display, which is what adds the bullet points.

How do I get the current date in JavaScript?

Date.prototype.toLocalFullDateStringYYYYMMDDHHMMSS = function () {
if (this != null && this != undefined) {
    let str = this.getFullYear();
    str += "-" + round(this.getMonth() + 1);
    str += "-" + round(this.getDate());
    str += "T";
    str += round(this.getHours());
    str += ":" + round(this.getMinutes());
    str += ":" + round(this.getSeconds());
    return str;
} else {
    return this;
}

function round(n){
    if(n < 10){
        return "0" + n;
    }
    else return n;
}};

Check if string is neither empty nor space in shell script

[ $(echo $variable_to_test | sed s/\n// | sed s/\ //) == "" ] && echo "String is empty"

Stripping all newlines and spaces from the string will cause a blank one to be reduced to nothing which can be tested and acted upon

Simulate delayed and dropped packets on Linux

An easy to use network fault injection tool is Saboteur. It can simulate:

  • Total network partition
  • Remote service dead (not listening on the expected port)
  • Delays
  • Packet loss -TCP connection timeout (as often happens when two systems are separated by a stateful firewall)

What are the uses of the exec command in shell scripts?

The exec built-in command mirrors functions in the kernel, there are a family of them based on execve, which is usually called from C.

exec replaces the current program in the current process, without forking a new process. It is not something you would use in every script you write, but it comes in handy on occasion. Here are some scenarios I have used it;

  1. We want the user to run a specific application program without access to the shell. We could change the sign-in program in /etc/passwd, but maybe we want environment setting to be used from start-up files. So, in (say) .profile, the last statement says something like:

     exec appln-program
    

    so now there is no shell to go back to. Even if appln-program crashes, the end-user cannot get to a shell, because it is not there - the exec replaced it.

  2. We want to use a different shell to the one in /etc/passwd. Stupid as it may seem, some sites do not allow users to alter their sign-in shell. One site I know had everyone start with csh, and everyone just put into their .login (csh start-up file) a call to ksh. While that worked, it left a stray csh process running, and the logout was two stage which could get confusing. So we changed it to exec ksh which just replaced the c-shell program with the korn shell, and made everything simpler (there are other issues with this, such as the fact that the ksh is not a login-shell).

  3. Just to save processes. If we call prog1 -> prog2 -> prog3 -> prog4 etc. and never go back, then make each call an exec. It saves resources (not much, admittedly, unless repeated) and makes shutdown simplier.

You have obviously seen exec used somewhere, perhaps if you showed the code that's bugging you we could justify its use.

Edit: I realised that my answer above is incomplete. There are two uses of exec in shells like ksh and bash - used for opening file descriptors. Here are some examples:

exec 3< thisfile          # open "thisfile" for reading on file descriptor 3
exec 4> thatfile          # open "thatfile" for writing on file descriptor 4
exec 8<> tother           # open "tother" for reading and writing on fd 8
exec 6>> other            # open "other" for appending on file descriptor 6
exec 5<&0                 # copy read file descriptor 0 onto file descriptor 5
exec 7>&4                 # copy write file descriptor 4 onto 7
exec 3<&-                 # close the read file descriptor 3
exec 6>&-                 # close the write file descriptor 6

Note that spacing is very important here. If you place a space between the fd number and the redirection symbol then exec reverts to the original meaning:

  exec 3 < thisfile       # oops, overwrite the current program with command "3"

There are several ways you can use these, on ksh use read -u or print -u, on bash, for example:

read <&3
echo stuff >&4

Select rows having 2 columns equal value

SELECT *
FROM my_table
WHERE column_a <=> column_b AND column_a <=> column_c

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

I could solve the issue simply by replacing the JPA api jar file which is located jboss7/modules/javax/persistence/api/main with 'hibernate-jpa-2.1-api'. also with updating module.xml in the directory.

Age from birthdate in python

Extend to Danny W. Adair Answer, to get month also

def calculate_age(b):
    t = date.today()
    c = ((t.month, t.day) < (b.month, b.day))
    c2 = (t.day< b.day)
    return t.year - b.year - c,c*12+t.month-b.month-c2

Auto select file in Solution Explorer from its open tab

The Tab Studio plugin adds "select in solution explorer" to the right click menu on tabs.

Random / noise functions for GLSL

For very simple pseudorandom-looking stuff, I use this oneliner that I found on the internet somewhere:

float rand(vec2 co){
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

You can also generate a noise texture using whatever PRNG you like, then upload this in the normal fashion and sample the values in your shader; I can dig up a code sample later if you'd like.

Also, check out this file for GLSL implementations of Perlin and Simplex noise, by Stefan Gustavson.

Resizing an image in an HTML5 canvas

The problem with some of this solutions is that they access directly the pixel data and loop through it to perform the downsampling. Depending on the size of the image this can be very resource intensive, and it would be better to use the browser's internal algorithms.

The drawImage() function is using a linear-interpolation, nearest-neighbor resampling method. That works well when you are not resizing down more than half the original size.

If you loop to only resize max one half at a time, the results would be quite good, and much faster than accessing pixel data.

This function downsample to half at a time until reaching the desired size:

  function resize_image( src, dst, type, quality ) {
     var tmp = new Image(),
         canvas, context, cW, cH;

     type = type || 'image/jpeg';
     quality = quality || 0.92;

     cW = src.naturalWidth;
     cH = src.naturalHeight;

     tmp.src = src.src;
     tmp.onload = function() {

        canvas = document.createElement( 'canvas' );

        cW /= 2;
        cH /= 2;

        if ( cW < src.width ) cW = src.width;
        if ( cH < src.height ) cH = src.height;

        canvas.width = cW;
        canvas.height = cH;
        context = canvas.getContext( '2d' );
        context.drawImage( tmp, 0, 0, cW, cH );

        dst.src = canvas.toDataURL( type, quality );

        if ( cW <= src.width || cH <= src.height )
           return;

        tmp.src = dst.src;
     }

  }
  // The images sent as parameters can be in the DOM or be image objects
  resize_image( $( '#original' )[0], $( '#smaller' )[0] );

Credits to this post

Generate a random number in a certain range in MATLAB

ocw.mit.edu is a great resource that has helped me a bunch. randi is the best option, but if your into number fun try using the floor function with rand to get what you want.

I drew a number line and came up with

floor(rand*8) + 13

How to normalize a 2-dimensional numpy array in python less verbose?

I think you can normalize the row elements sum to 1 by this: new_matrix = a / a.sum(axis=1, keepdims=1). And the column normalization can be done with new_matrix = a / a.sum(axis=0, keepdims=1). Hope this can hep.

String to object in JS

if you're using JQuery:

var obj = jQuery.parseJSON('{"path":"/img/filename.jpg"}');
console.log(obj.path); // will print /img/filename.jpg

REMEMBER: eval is evil! :D

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

Oracle "SQL Error: Missing IN or OUT parameter at index:: 1"

Based on the comments left above I ran this under sqlplus instead of SQL Developer and the UPDATE statement ran perfectly, leaving me to believe this is an issue in SQL Developer particularly as there was no ORA error number being returned. Thank you for leading me in the right direction.

Netbeans - Error: Could not find or load main class

I had the same problem, I had the package and class named the same. I renamed the class, then clean and build. Then I set the main class in the "run" under the properties of the project. I works now.

python global name 'self' is not defined

self is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main(), you first have to instantiate an object of your class and call the function on the object.

Further, your function setavalue should be in __init___, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name class ;)

class Name:
    def __init__(self):
        self.myname = "harry"

    def printaname(self):
        print "Name", self.myname     

    def main(self):
        self.printaname()

if __name__ == "__main__":
    objName = Name()
    objName.main() 

Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.

Copying data from one SQLite database to another

You'll have to attach Database X with Database Y using the ATTACH command, then run the appropriate Insert Into commands for the tables you want to transfer.

INSERT INTO X.TABLE SELECT * FROM Y.TABLE;

Or, if the columns are not matched up in order:

INSERT INTO X.TABLE(fieldname1, fieldname2) SELECT fieldname1, fieldname2 FROM Y.TABLE;

Cannot start GlassFish 4.1 from within Netbeans 8.0.1 Service area

You will get like this error

error ss

Try the following steps

1. Open Command Prompt (Press Windows key and type "cmd" and hit Enter) Then type this command as show in picture

netstat -aon | find ":8080" | find "LISTENING" cmd command

  1. Now open Task Manager (Press Windows key and type "Task Manager" and hit Enter) In that, go to Details Tab and under PID Column, search for the number you found in cmd

task manager

  1. Right Click on that program and select end process

Excel - Using COUNTIF/COUNTIFS across multiple sheets/same column

I was looking to do the same thing, and I have a work around that seems to be less complicated using the Frequency and Index functions. I use this part of the function from averaging over multiple sheets while excluding the all the 0's.

=(FREQUENCY(Start:End!B1,-0.000001)+INDEX(FREQUENCY(Start:End!B1,0),2))

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

Creating a button in Android Toolbar

I was able to achieve that by wrapping Button with ConstraintLayout:

<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.material.appbar.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:elevation="0dp">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/top_toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/white_color">

            <androidx.constraintlayout.widget.ConstraintLayout
                android:layout_width="match_parent"
                android:layout_marginTop="10dp"
                android:layout_height="wrap_content">

                <TextView
                    android:id="@+id/cancel"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/cancel"
                    android:layout_marginStart="5dp"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintLeft_toLeftOf="parent"
                    app:layout_constraintTop_toTopOf="parent" />

                <Button
                    android:id="@+id/btn_publish"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:text="@string/publish"
                    android:background="@drawable/button_publish_rounded"
                    app:layout_constraintTop_toTopOf="parent"
                    app:layout_constraintBottom_toBottomOf="parent"
                    app:layout_constraintEnd_toEndOf="parent"
                    android:layout_marginEnd="10dp"
                    app:layout_constraintLeft_toRightOf="@id/cancel"
                    tools:layout_editor_absoluteY="0dp" />

            </androidx.constraintlayout.widget.ConstraintLayout>

        </androidx.appcompat.widget.Toolbar>

    </com.google.android.material.appbar.AppBarLayout>

</androidx.coordinatorlayout.widget.CoordinatorLayout>

You may create a drawable resourcebutton_publish_rounded, define the button properties and assign this file to button's android:background property:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <solid android:color="@color/green" />
    <corners android:radius="100dp" />
</shape>

ASP.NET Core 1.0 on IIS error 502.5

I got the same problem and the reason in my case was that the EF core was trying to read connection string from appsettings.development.json file. I opened it and found the connection string was commented.

//{
//  "ConnectionStrings": {
//    "DefaultConnection": "Server=vaio;Database=Goldentaurus;Trusted_Connection=True;",
//    "IdentityConnection": "Server=vaio;Database=GTIdentity;Trusted_Connection=True;"
//  }
//}

I then uncommitted them like below and the problem solved:

{
  "ConnectionStrings": {
    "DefaultConnection": "Server=vaio;Database=Goldentaurus;Trusted_Connection=True;",
    "IdentityConnection": "Server=vaio;Database=GTIdentity;Trusted_Connection=True;"
  }
}

How to open a workbook specifying its path

You can also open a required file through a prompt, This helps when you want to select file from different path and different file.

Sub openwb()
Dim wkbk As Workbook
Dim NewFile As Variant

NewFile = Application.GetOpenFilename("microsoft excel files (*.xlsm*), *.xlsm*")

If NewFile <> False Then
Set wkbk = Workbooks.Open(NewFile)
End If
End Sub

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

display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical; 

see more click here

HTML5 video won't play in Chrome only

Have you tried by setting the MIME type of your .m4v to "video/m4v" or "video/x-m4v" ?

Browsers might use the canPlayType method internally to check if a <source> is candidate to playback.

In Chrome, I have these results:

document.createElement("video").canPlayType("video/mp4"); // "maybe"
document.createElement("video").canPlayType("video/m4v"); // ""
document.createElement("video").canPlayType("video/x-m4v"); // "maybe"

How to convert CSV to JSON in Node.js

Node.js csvtojson module is a comprehensive nodejs csv parser. It can be used as node.js app library / a command line tool / or browser with help of browserify or webpack.

the source code can be found at: https://github.com/Keyang/node-csvtojson

It is fast with low memory consumption yet powerful to support any of parsing needs with abundant API and easy to read documentation.

The detailed documentation can be found here

Here are some code examples:

Use it as a library in your Node.js application ([email protected] +):

  1. Install it through npm

npm install --save csvtojson@latest

  1. Use it in your node.js app:
// require csvtojson
var csv = require("csvtojson");

// Convert a csv file with csvtojson
csv()
  .fromFile(csvFilePath)
  .then(function(jsonArrayObj){ //when parse finished, result will be emitted here.
     console.log(jsonArrayObj); 
   })

// Parse large csv with stream / pipe (low mem consumption)
csv()
  .fromStream(readableStream)
  .subscribe(function(jsonObj){ //single json object will be emitted for each csv line
     // parse each json asynchronousely
     return new Promise(function(resolve,reject){
         asyncStoreToDb(json,function(){resolve()})
     })
  }) 

//Use async / await
const jsonArray=await csv().fromFile(filePath);

Use it as a command-line tool:

sh# npm install csvtojson
sh# ./node_modules/csvtojson/bin/csvtojson ./youCsvFile.csv

-or-

sh# npm install -g csvtojson
sh# csvtojson ./yourCsvFile.csv

For advanced usage:

sh# csvtojson --help

You can find more details from the github page above.

What is the use of ByteBuffer in Java?

In Android you can create shared buffer between C++ and Java (with directAlloc method) and manipulate it in both sides.

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

Laravel where on relationship object

The correct syntax to do this on your relations is:

Event::whereHas('participants', function ($query) {
    return $query->where('IDUser', '=', 1);
})->get();

Read more at https://laravel.com/docs/5.8/eloquent-relationships#eager-loading

How to know whether refresh button or browser back button is clicked in Firefox

Use for on refresh event

window.onbeforeunload = function(e) {
  return 'Dialog text here.';
};

https://developer.mozilla.org/en-US/docs/Web/API/window.onbeforeunload?redirectlocale=en-US&redirectslug=DOM%2Fwindow.onbeforeunload

And

$(window).unload(function() {
      alert('Handler for .unload() called.');
});

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Bug? #1146 - Table 'xxx.xxxxx' doesn't exist

In my case I ran this command even if the table wasn't visible in PhpMyAdmin :

DROP TABLE mytable

then

CREATE TABLE....

Worked for me !

How do I specify unique constraint for multiple columns in MySQL?

If You are creating table in mysql then use following :

create table package_template_mapping (
mapping_id  int(10) not null auto_increment  ,
template_id int(10) NOT NULL ,
package_id  int(10) NOT NULL ,
remark      varchar(100),
primary key (mapping_id) ,
UNIQUE KEY template_fun_id (template_id , package_id)
);

How to get a matplotlib Axes instance to plot to?

Use the gca ("get current axes") helper function:

ax = plt.gca()

Example:

import matplotlib.pyplot as plt
import matplotlib.finance
quotes = [(1, 5, 6, 7, 4), (2, 6, 9, 9, 6), (3, 9, 8, 10, 8), (4, 8, 8, 9, 8), (5, 8, 11, 13, 7)]
ax = plt.gca()
h = matplotlib.finance.candlestick(ax, quotes)
plt.show()

enter image description here

How can I see CakePHP's SQL dump in the controller?

If you're using CakePHP 1.3, you can put this in your views to output the SQL:

<?php echo $this->element('sql_dump'); ?>

So you could create a view called 'sql', containing only the line above, and then call this in your controller whenever you want to see it:

$this->render('sql');

(Also remember to set your debug level to at least 2 in app/config/core.php)

Source

creating json object with variables

Try this to see how you can create a object from strings.

var firstName = "xx";
var lastName  = "xy";
var phone     = "xz";
var adress    = "x1";
var obj = {"firstName":firstName, "lastName":lastName, "phone":phone, "address":adress};
console.log(obj);

What does random.sample() method in python do?

According to documentation:

random.sample(population, k)

Return a k length list of unique elements chosen from the population sequence. Used for random sampling without replacement.

Basically, it picks k unique random elements, a sample, from a sequence:

>>> import random
>>> c = list(range(0, 15))
>>> c
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> random.sample(c, 5)
[9, 2, 3, 14, 11]

random.sample works also directly from a range:

>>> c = range(0, 15)
>>> c
range(0, 15)
>>> random.sample(c, 5)
[12, 3, 6, 14, 10]

In addition to sequences, random.sample works with sets too:

>>> c = {1, 2, 4}
>>> random.sample(c, 2)
[4, 1]

However, random.sample doesn't work with arbitrary iterators:

>>> c = [1, 3]
>>> random.sample(iter(c), 5)
TypeError: Population must be a sequence or set.  For dicts, use list(d).

Encoding conversion in java

You don't need a library beyond the standard one - just use Charset. (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.)

EDIT: As pointed out in comments, you can still use Charset instances but have the ease of use of the String methods: new String(bytes, charset) and String.getBytes(charset).

See "URL Encoding (or: 'What are those "%20" codes in URLs?')".

Convert to binary and keep leading zeros in Python

Sometimes you just want a simple one liner:

binary = ''.join(['{0:08b}'.format(ord(x)) for x in input])

Python 3

What does LayoutInflater in Android do?

What inflater does

It takes a xml layout as input (say) and converts it to View object.

Why needed

Let us think a scenario where we need to create a custom listview. Now each row should be custom. But how can we do it. Its not possible to assign a xml layout to a row of listview. So, we create a View object. Thus we can access the elements in it (textview,imageview etc) and also assign the object as row of listview

So, whenever we need to assign view type object somewhere and we have our custom xml design we just convert it to object by inflater and use it.

How to refresh a Page using react-route Link

You can use this

<a onClick={() => {window.location.href="/something"}}>Something</a>

Read text file into string array (and write)

Note: ioutil is deprecated as of Go 1.16.

If the file isn't too large, this can be done with the ioutil.ReadFile and strings.Split functions like so:

content, err := ioutil.ReadFile(filename)
if err != nil {
    //Do something
}
lines := strings.Split(string(content), "\n")

You can read the documentation on ioutil and strings packages.

Proxy with urllib2

To use the default system proxies (e.g. from the http_support environment variable), the following works for the current request (without installing it into urllib2 globally):

url = 'http://www.example.com/'
proxy = urllib2.ProxyHandler()
opener = urllib2.build_opener(proxy)
in_ = opener.open(url)
in_.read()

Update multiple rows with different values in a single SQL query

Something like this might work for you:

"UPDATE myTable SET ... ;
 UPDATE myTable SET ... ;
 UPDATE myTable SET ... ;
 UPDATE myTable SET ... ;"

If any of the posX or posY values are the same, then they could be combined into one query

UPDATE myTable SET posX='39' WHERE id IN('2','3','40');

Check if string begins with something?

String.prototype.startsWith = function(needle)
{
    return this.indexOf(needle) === 0;
};

How to write unit testing for Angular / TypeScript for private methods with Jasmine

I agree with @toskv: I wouldn't recommend to do that:-)

But if you really want to test your private method, you can be aware that the corresponding code for the TypeScript correspond to a method of the constructor function prototype. This means that it can be used at runtime (whereas you will probably have some compilation errors).

For example:

export class FooBar {
  private _status: number;

  constructor( private foo : Bar ) {
    this.initFooBar({});
  }

  private initFooBar(data){
    this.foo.bar( data );
    this._status = this.foo.foo();
  }
}

will be transpiled into:

(function(System) {(function(__moduleName){System.register([], function(exports_1, context_1) {
  "use strict";
  var __moduleName = context_1 && context_1.id;
  var FooBar;
  return {
    setters:[],
    execute: function() {
      FooBar = (function () {
        function FooBar(foo) {
          this.foo = foo;
          this.initFooBar({});
        }
        FooBar.prototype.initFooBar = function (data) {
          this.foo.bar(data);
          this._status = this.foo.foo();
        };
        return FooBar;
      }());
      exports_1("FooBar", FooBar);
    }
  }
})(System);

See this plunkr: https://plnkr.co/edit/calJCF?p=preview.

Python equivalent to 'hold on' in Matlab

check pyplot docs. For completeness,

import numpy as np
import matplotlib.pyplot as plt

#evenly sampled time at 200ms intervals
t = np.arange(0., 5., 0.2)

# red dashes, blue squares and green triangles
plt.plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
plt.show()

Run Function After Delay

You can add timeout function in jQuery (Show alert after 3 seconds):

$(document).ready(function($) {
    setTimeout(function() {
     alert("Hello");
    }, 3000);
});

How do I compare two variables containing strings in JavaScript?

I used below function to compare two strings and It is working good.

function CompareUserId (first, second)
{

   var regex = new RegExp('^' + first+ '$', 'i');
   if (regex.test(second)) 
   {
        return true;
   }
   else 
   {
        return false;
   }
   return false;
}

.htaccess file to allow access to images folder to view pictures?

<Directory /uploads>
   Options +Indexes
</Directory>

How to display div after click the button in Javascript?

HTML

<div id="myDiv" style="display:none;" class="answer_list" >WELCOME</div>
<input type="button" name="answer" onclick="ShowDiv()" />

JavaScript

function ShowDiv() {
    document.getElementById("myDiv").style.display = "";
}

Or if you wanted to use jQuery with a nice little animation:

<input id="myButton" type="button" name="answer" />

$('#myButton').click(function() {
  $('#myDiv').toggle('slow', function() {
    // Animation complete.
  });
});

What is a C++ delegate?

The need for C++ delegate implementations are a long lasting embarassment to the C++ community. Every C++ programmer would love to have them, so they eventually use them despite the facts that:

  1. std::function() uses heap operations (and is out of reach for serious embedded programming).

  2. All other implementations make concessions towards either portability or standard conformity to larger or lesser degrees (please verify by inspecting the various delegate implementations here and on codeproject). I have yet to see an implementation which does not use wild reinterpret_casts, Nested class "prototypes" which hopefully produce function pointers of the same size as the one passed in by the user, compiler tricks like first forward declare, then typedef then declare again, this time inheriting from another class or similar shady techniques. While it is a great accomplishment for the implementers who built that, it is still a sad testimoney on how C++ evolves.

  3. Only rarely is it pointed out, that now over 3 C++ standard revisions, delegates were not properly addressed. (Or the lack of language features which allow for straightforward delegate implementations.)

  4. With the way C++11 lambda functions are defined by the standard (each lambda has anonymous, different type), the situation has only improved in some use cases. But for the use case of using delegates in (DLL) library APIs, lambdas alone are still not usable. The common technique here, is to first pack the lambda into a std::function and then pass it across the API.

How to change column datatype from character to numeric in PostgreSQL 8.4

If your VARCHAR column contains empty strings (which are not the same as NULL for PostgreSQL as you might recall) you will have to use something in the line of the following to set a default:

ALTER TABLE presales ALTER COLUMN code TYPE NUMERIC(10,0)
            USING COALESCE(NULLIF(code, '')::NUMERIC, 0);

(found with the help of this answer)

Uncaught (in promise): Error: StaticInjectorError(AppModule)[options]

Faced the same error. In my case , what i did wrong was that i injected the service(named DataService in my case) inside the constructor within the Component but I simply forgot to import it within the component.

 constructor(private dataService:DataService ) {
    console.log("constructor called");
  }

I missed the below import code.

import { DataService } from '../../services/data.service';

How to get the full url in Express?

async function (request, response, next) {
  const url = request.rawHeaders[9] + request.originalUrl;
  //or
  const url = request.headers.host + request.originalUrl;
}

How to add Web API to an existing ASP.NET MVC 4 Web Application project?

You can install from nuget as the the below image:

enter image description here

Or, run the below command line on Package Manager Console:

Install-Package Microsoft.AspNet.WebApi

Multithreading in Bash

You can run several copies of your script in parallel, each copy for different input data, e.g. to process all *.cfg files on 4 cores:

    ls *.cfg | xargs -P 4 -n 1 read_cfg.sh

The read_cfg.sh script takes just one parameters (as enforced by -n)

Node.js ES6 classes with require

The ES6 way of require is import. You can export your class and import it somewhere else using import { ClassName } from 'path/to/ClassName'syntax.

import fs from 'fs';
export default class Animal {

  constructor(name){
    this.name = name ;
  }

  print(){
    console.log('Name is :'+ this.name);
  }
}

import Animal from 'path/to/Animal.js';

How to put a tooltip on a user-defined function

I just create a "help" version of the function. Shows up right below the function in autocomplete - the user can select it instead in an adjacent cell for instructions.

Public Function Foo(param1 as range, param2 as string) As String

    Foo = "Hello world"

End Function

Public Function Foo_Help() as String

Foo_Help = "The Foo function was designed to return the Foo value for a specified range a cells given a specified constant." & CHR(10) & "Parameters:" & CHR(10)
& "  param1 as Range   :   Specifies the range of cells the Foo function should operate on." & CHR(10)
&"  param2 as String  :   Specifies the constant the function should use to calculate Foo"
&" contact the Foo master at [email protected] for more information."

END FUNCTION

The carriage returns improve readability with wordwrap on. 2 birds with one stone, now the function has some documentation.

How do I update the password for Git?

None of the other answers worked for me on MacOS Sierra 10.12.4

Here is what I had to do:

git config --global --unset user.password

Then run your git command (ex. git push) and reenter your username and password.

How to prevent the "Confirm Form Resubmission" dialog?

Edit: It's been a few years since I originally posted this answer, and even though I got a few upvotes, I'm not really happy with my previous answer, so I have redone it completely. I hope this helps.


When to use GET and POST:

One way to get rid of this error message is to make your form use GET instead of POST. Just keep in mind that this is not always an appropriate solution (read below).

Always use POST if you are performing an action that you don't want to be repeated, if sensitive information is being transferred or if your form contains either a file upload or the length of all data sent is longer than ~2000 characters.

Examples of when to use POST would include:

  • A login form
  • A contact form
  • A submit payment form
  • Something that adds, edits or deletes entries from a database
  • An image uploader (note, if using GET with an <input type="file"> field, only the filename will be sent to the server, which 99.73% of the time is not what you want.)
  • A form with many fields (which would create a long URL if using GET)

In any of these cases, you don't want people refreshing the page and re-sending the data. If you are sending sensitive information, using GET would not only be inappropriate, it would be a security issue (even if the form is sent by AJAX) since the sensitive item (e.g. user's password) is sent in the URL and will therefore show up in server access logs.

Use GET for basically anything else. This means, when you don't mind if it is repeated, for anything that you could provide a direct link to, when no sensitive information is being transferred, when you are pretty sure your URL lengths are not going to get out of control and when your forms don't have any file uploads.

Examples would include:

  • Performing a search in a search engine
  • A navigation form for navigating around the website
  • Performing one-time actions using a nonce or single use password (such as an "unsubscribe" link in an email).

In these cases POST would be completely inappropriate. Imagine if search engines used POST for their searches. You would receive this message every time you refreshed the page and you wouldn't be able to just copy and paste the results URL to people, they would have to manually fill out the form themselves.

If you use POST:

To me, in most cases even having the "Confirm form resubmission" dialog pop up shows that there is a design flaw. By the very nature of POST being used to perform destructive actions, web designers should prevent users from ever performing them more than once by accidentally (or intentionally) refreshing the page. Many users do not even know what this dialog means and will therefore just click on "Continue". What if that was after a "submit payment" request? Does the payment get sent again?

So what do you do? Fortunately we have the Post/Redirect/Get design pattern. The user submits a POST request to the server, the server redirects the user's browser to another page and that page is then retrieved using GET.

Here is a simple example using PHP:

if(!empty($_POST['username'] && !empty($_POST['password'])) {
    $user = new User;
    $user->login($_POST['username'], $_POST['password']);

    if ($user->isLoggedIn()) {
        header("Location: /admin/welcome.php");
        exit;
    }
    else {
        header("Location: /login.php?invalid_login");
    }
}

Notice how in this example even when the password is incorrect, I am still redirecting back to the login form. To display an invalid login message to the user, just do something like:

if (isset($_GET['invalid_login'])) {
    echo "Your username and password combination is invalid";
}

Python - List of unique dictionaries

We can do with pandas

import pandas as pd
yourdict=pd.DataFrame(L).drop_duplicates().to_dict('r')
Out[293]: [{'age': 34, 'id': 1, 'name': 'john'}, {'age': 30, 'id': 2, 'name': 'hanna'}]

Notice slightly different from the accept answer.

drop_duplicates will check all column in pandas , if all same then the row will be dropped .

For example :

If we change the 2nd dict name from john to peter

L=[
    {'id': 1, 'name': 'john', 'age': 34},
    {'id': 1, 'name': 'peter', 'age': 34},
    {'id': 2, 'name': 'hanna', 'age': 30},
]
pd.DataFrame(L).drop_duplicates().to_dict('r')
Out[295]: 
[{'age': 34, 'id': 1, 'name': 'john'},
 {'age': 34, 'id': 1, 'name': 'peter'},# here will still keeping the dict in the out put 
 {'age': 30, 'id': 2, 'name': 'hanna'}]

jquery to validate phone number

I know this is an old post, but I thought I would share my solution to help others.

This function will work if you want to valid 10 digits phone number "US number"

function getValidNumber(value)
{
    value = $.trim(value).replace(/\D/g, '');

    if (value.substring(0, 1) == '1') {
        value = value.substring(1);
    }

    if (value.length == 10) {

        return value;
    }

    return false;
}

Here how to use this method

var num = getValidNumber('(123) 456-7890');
if(num !== false){
     alert('The valid number is: ' + num);
} else {
     alert('The number you passed is not a valid US phone number');
}

calling server side event from html button control

The easiest way to accomplish this is to override the RaisePostBackEvent method.

<input type="button" ID="btnRaisePostBack" runat="server" onclick="raisePostBack();" ... />

And in your JavaScript:

raisePostBack = function(){
    __doPostBack("<%=btnRaisePostBack.ClientID%>", "");
}

And in your code:

protected override void RaisePostBackEvent(IPostBackEventHandler source, string eventArgument)
{
    //call the RaisePostBack event 
    base.RaisePostBackEvent(source, eventArgument);

    if (source == btnRaisePostBack)
    {
         //do some logic
    }
}

Delete all files of specific type (extension) recursively down a directory using a batch file

I wrote a batch script a while ago that allows you to pick a file extension to delete. The script will look in the folder it is in and all subfolders for any file with that extension and delete it.

@ECHO OFF
CLS

SET found=0
ECHO Enter the file extension you want to delete...
SET /p ext="> "

IF EXIST *.%ext% (           rem Check if there are any in the current folder :)
  DEL *.%ext%
  SET found=1
)
FOR /D /R %%G IN ("*") DO (  rem Iterate through all subfolders
  IF EXIST %%G CD %%G
  IF EXIST *.%ext% (
    DEL *.%ext%
    SET found=1
  )
)

IF %found%==1 (
  ECHO.
  ECHO Deleted all .%ext% files.
  ECHO.
) ELSE (
  ECHO.
  ECHO There were no .%ext% files.
  ECHO Nothing has been deleted.
  ECHO.
)

PAUSE
EXIT

Hope this comes in useful to anyone who wants it :)

Ring Buffer in Java

None of the previously given examples were meeting my needs completely, so I wrote my own queue that allows following functionality: iteration, index access, indexOf, lastIndexOf, get first, get last, offer, remaining capacity, expand capacity, dequeue last, dequeue first, enqueue / add element, dequeue / remove element, subQueueCopy, subArrayCopy, toArray, snapshot, basics like size, remove or contains.

EjectingQueue

EjectingIntQueue

PHP parse/syntax errors; and how to solve them

Unexpected 'continue' (T_CONTINUE)

continue is a statement (like for, or if) and must appear standalone. It cannot be used as part of an expression. Partly because continue doesn't return a value, but in an expression every sub-expression must result in some value so the overall expression results in a value. That's the difference between a statement and an expression.

That means continue cannot be used in a ternary statement or any statement that requires a return value.

Unexpected 'break' (T_BREAK)

Same goes for break; of course. It's also not usable in expression context, but a strict statement (on the same level as foreach or an if block).

Unexpected 'return' (T_RETURN)

Now this might be more surprising for return, but that's also just a block-level statement. It does return a value (or NULL) to the higher scope/function, but it does not evaluate as expression itself. ? That is: there's no point in doing return(return(false);;

Circle-Rectangle collision detection (intersection)

Works, just figured this out a week ago, and just now got to testing it.

double theta = Math.atan2(cir.getX()-sqr.getX()*1.0,
                          cir.getY()-sqr.getY()*1.0); //radians of the angle
double dBox; //distance from box to edge of box in direction of the circle

if((theta >  Math.PI/4 && theta <  3*Math.PI / 4) ||
   (theta < -Math.PI/4 && theta > -3*Math.PI / 4)) {
    dBox = sqr.getS() / (2*Math.sin(theta));
} else {
    dBox = sqr.getS() / (2*Math.cos(theta));
}
boolean touching = (Math.abs(dBox) >=
                    Math.sqrt(Math.pow(sqr.getX()-cir.getX(), 2) +
                              Math.pow(sqr.getY()-cir.getY(), 2)));

How to search file text for a pattern and replace it with a given value

This works for me:

filename = "foo"
text = File.read(filename) 
content = text.gsub(/search_regexp/, "replacestring")
File.open(filename, "w") { |file| file << content }

How do I check if a Sql server string is null or empty

Select              
Coalesce(NullIf(listing.OfferText, ''), NullIf(company.OfferText, ''), '') As Offer_Text,         
from tbl_directorylisting listing  
 Inner Join tbl_companymaster company            
  On listing.company_id= company.company_id

How to flush output of print function?

I first struggled to understand how the flush option was working. I wanted to do a 'loading display' and here is the solution I found:

for i in range(100000):
    print('{:s}\r'.format(''), end='', flush=True)
    print('Loading index: {:d}/100000'.format(i+1), end='')

The first line flushes the previous print and the second line prints a new updated message. I don't know if an one-line syntax exists here.

Fix footer to bottom of page

A very simple example that shows how to fix the footer at the bottom in your application's layout.

_x000D_
_x000D_
/* Styles go here */_x000D_
html{ height: 100%;}_x000D_
body{ min-height: 100%; background: #fff;}_x000D_
.page-layout{ border: none; width: 100%; height: 100vh; }_x000D_
.page-layout td{ vertical-align: top; }_x000D_
.page-layout .header{ background: #aaa; }_x000D_
.page-layout .main-content{ height: 100%; background: #f1f1f1; text-align: center; padding-top: 50px; }_x000D_
.page-layout .main-content .container{ text-align: center; padding-top: 50px; }_x000D_
.page-layout .footer{ background: #333; color: #fff; } 
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <link data-require="bootstrap@*" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />_x000D_
    <link rel="stylesheet" href="style.css" />_x000D_
    <script src="script.js"></script>_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <table class="page-layout">_x000D_
      <tr>_x000D_
        <td class="header">_x000D_
          <div>_x000D_
            This is the site header._x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td class="main-content">_x000D_
          <div>_x000D_
            <h1>Fix footer always to the bottom</h1>_x000D_
            <div>_x000D_
              This is how you can simply fix the footer to the bottom._x000D_
            </div>_x000D_
            <div>_x000D_
              The footer will always stick to the bottom until the main-content doesn't grow till footer._x000D_
            </div>_x000D_
            <div>_x000D_
              Even if the content grows, the footer will start to move down naturally as like the normal behavior of page._x000D_
            </div>_x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td class="footer">_x000D_
          <div>_x000D_
            This is the site footer._x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
    </table>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to add spacing between columns?

How about just adding a border the same color as the background using css? I'm new to this, so maybe there's a good reason not to, but it looked good when I tried it.

how to add json library

AFAIK the json module was added in version 2.6, see here. I'm guessing you can update your python installation to the latest stable 2.6 from this page.

Oracle - How to create a materialized view with FAST REFRESH and JOINS

You will get the error on REFRESH_FAST, if you do not create materialized view logs for the master table(s) the query is referring to. If anyone is not familiar with materialized views or using it for the first time, the better way is to use oracle sqldeveloper and graphically put in the options, and the errors also provide much better sense.

Jquery change background color

This is how it should be:

Code:

$(function(){
  $("button").mouseover(function(){
    var $p = $("#P44");
    $p.stop()
      .css("background-color","yellow")
      .hide(1500, function() {
          $p.css("background-color","red")
            .show(1500);
      });
  });
});

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

Explanation:

You have to wait for the callback on the animating functions before you switch background color. You should also not use only numeric ID:s, and if you have an ID of your <p> there you shouldn't include a class in your selector.

I also enhanced your code (caching of the jQuery object, chaining, etc.)

Update: As suggested by VKolev the color is now changing when the item is hidden.

How to print all key and values from HashMap in Android?

    for (String entry : map.keySet()) {
      String value = map.get(entry);
      System.out.print(entry + "" + value + " ");
      // do stuff
    }

How do I analyze a program's core dump file with GDB when it has command-line parameters?

objdump + gdb minimal runnable example

TL;DR:

Now for the full educational test setup:

main.c

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int myfunc(int i) {
    *(int*)(NULL) = i; /* line 7 */
    return i - 1;
}

int main(int argc, char **argv) {
    /* Setup some memory. */
    char data_ptr[] = "string in data segment";
    char *mmap_ptr;
    char *text_ptr = "string in text segment";
    (void)argv;
    mmap_ptr = (char *)malloc(sizeof(data_ptr) + 1);
    strcpy(mmap_ptr, data_ptr);
    mmap_ptr[10] = 'm';
    mmap_ptr[11] = 'm';
    mmap_ptr[12] = 'a';
    mmap_ptr[13] = 'p';
    printf("text addr: %p\n", text_ptr);
    printf("data addr: %p\n", data_ptr);
    printf("mmap addr: %p\n", mmap_ptr);

    /* Call a function to prepare a stack trace. */
    return myfunc(argc);
}

Compile, and run to generate core:

gcc -ggdb3 -std=c99 -Wall -Wextra -pedantic -o main.out main.c
ulimit -c unlimited
rm -f core
./main.out

Output:

text addr: 0x4007d4
data addr: 0x7ffec6739220
mmap addr: 0x1612010
Segmentation fault (core dumped)

GDB points us to the exact line where the segmentation fault happened, which is what most users want while debugging:

gdb -q -nh main.out core

then:

Reading symbols from main.out...done.
[New LWP 27479]
Core was generated by `./main.out'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x0000000000400635 in myfunc (i=1) at main.c:7
7           *(int*)(NULL) = i;
(gdb) bt
#0  0x0000000000400635 in myfunc (i=1) at main.c:7
#1  0x000000000040072b in main (argc=1, argv=0x7ffec6739328) at main.c:28

which points us directly to the buggy line 7.

CLI arguments are stored in the core file and don't need to be passed again

To answer the specific CLI argument questions, we see that if we change the cli arguments e.g. with:

rm -f core
./main.out 1 2

then this does get reflected in the previous bactrace without any changes in our commands:

Reading symbols from main.out...done.
[New LWP 21838]
Core was generated by `./main.out 1 2'.
Program terminated with signal SIGSEGV, Segmentation fault.
#0  0x0000564583cf2759 in myfunc (i=3) at main.c:7
7           *(int*)(NULL) = i; /* line 7 */
(gdb) bt
#0  0x0000564583cf2759 in myfunc (i=3) at main.c:7
#1  0x0000564583cf2858 in main (argc=3, argv=0x7ffcca4effa8) at main.c:2

So note how now argc=3. Therefore this must mean that the core file stores that information. I'm guessing it just stores it as the arguments of main, just like it stores the arguments of any other functions.

This makes sense if you consider that the core dump must be storing the entire memory and register state of the program, and so it has all the information needed to determine the value of function arguments on the current stack.

Less obvious is how to inspect the environment variables: How to get environment variable from a core dump Environment variables are also present in memory so the objdump does contain that information, but I'm not sure how to list all of them in one go conveniently, one by one as follows did work on my tests though:

p __environ[0]

Binutils analysis

By using binutils tools like readelf and objdump, we can bulk dump information contained in the core file such as the memory state.

Most/all of it must also be visible through GDB, but those binutils tools offer a more bulk approach which is convenient for certain use cases, while GDB is more convenient for a more interactive exploration.

First:

file core

tells us that the core file is actually an ELF file:

core: ELF 64-bit LSB core file x86-64, version 1 (SYSV), SVR4-style, from './main.out'

which is why we are able to inspect it more directly with usual binutils tools.

A quick look at the ELF standard shows that there is actually an ELF type dedicated to it:

Elf32_Ehd.e_type == ET_CORE

Further format information can be found at:

man 5 core

Then:

readelf -Wa core

gives some hints about the file structure. Memory appears to be contained in regular program headers:

Program Headers:
  Type           Offset   VirtAddr           PhysAddr           FileSiz  MemSiz   Flg Align
  NOTE           0x000468 0x0000000000000000 0x0000000000000000 0x000b9c 0x000000     0
  LOAD           0x002000 0x0000000000400000 0x0000000000000000 0x001000 0x001000 R E 0x1000
  LOAD           0x003000 0x0000000000600000 0x0000000000000000 0x001000 0x001000 R   0x1000
  LOAD           0x004000 0x0000000000601000 0x0000000000000000 0x001000 0x001000 RW  0x1000

and there is some more metadata present in a notes area, notably prstatus contains the PC:

Displaying notes found at file offset 0x00000468 with length 0x00000b9c:
  Owner                 Data size       Description
  CORE                 0x00000150       NT_PRSTATUS (prstatus structure)
  CORE                 0x00000088       NT_PRPSINFO (prpsinfo structure)
  CORE                 0x00000080       NT_SIGINFO (siginfo_t data)
  CORE                 0x00000130       NT_AUXV (auxiliary vector)
  CORE                 0x00000246       NT_FILE (mapped files)
    Page size: 4096
                 Start                 End         Page Offset
    0x0000000000400000  0x0000000000401000  0x0000000000000000
        /home/ciro/test/main.out
    0x0000000000600000  0x0000000000601000  0x0000000000000000
        /home/ciro/test/main.out
    0x0000000000601000  0x0000000000602000  0x0000000000000001
        /home/ciro/test/main.out
    0x00007f8d939ee000  0x00007f8d93bae000  0x0000000000000000
        /lib/x86_64-linux-gnu/libc-2.23.so
    0x00007f8d93bae000  0x00007f8d93dae000  0x00000000000001c0
        /lib/x86_64-linux-gnu/libc-2.23.so
    0x00007f8d93dae000  0x00007f8d93db2000  0x00000000000001c0
        /lib/x86_64-linux-gnu/libc-2.23.so
    0x00007f8d93db2000  0x00007f8d93db4000  0x00000000000001c4
        /lib/x86_64-linux-gnu/libc-2.23.so
    0x00007f8d93db8000  0x00007f8d93dde000  0x0000000000000000
        /lib/x86_64-linux-gnu/ld-2.23.so
    0x00007f8d93fdd000  0x00007f8d93fde000  0x0000000000000025
        /lib/x86_64-linux-gnu/ld-2.23.so
    0x00007f8d93fde000  0x00007f8d93fdf000  0x0000000000000026
        /lib/x86_64-linux-gnu/ld-2.23.so
  CORE                 0x00000200       NT_FPREGSET (floating point registers)
  LINUX                0x00000340       NT_X86_XSTATE (x86 XSAVE extended state)

objdump can easily dump all memory with:

objdump -s core

which contains:

Contents of section load1:

 4007d0 01000200 73747269 6e672069 6e207465  ....string in te
 4007e0 78742073 65676d65 6e740074 65787420  xt segment.text 

Contents of section load15:

 7ffec6739220 73747269 6e672069 6e206461 74612073  string in data s
 7ffec6739230 65676d65 6e740000 00a8677b 9c6778cd  egment....g{.gx.

Contents of section load4:

 1612010 73747269 6e672069 6e206d6d 61702073  string in mmap s
 1612020 65676d65 6e740000 11040000 00000000  egment..........

which matches exactly with the stdout value in our run.

This was tested on Ubuntu 16.04 amd64, GCC 6.4.0, and binutils 2.26.1.

How do I rename both a Git local and remote branch name?

It can also be done the following way.

At first rename local branch, then remote branch.

Renaming the local branch:

If logged in another branch,

git branch -m old_branch new_branch 

If logged in the same branch,

git branch -m new_branch

Renaming remote branch:

git push origin :old_branch    // Delete the remote branch

git push --set-upstream origin new_branch   // Create a new remote branch

import httplib ImportError: No module named httplib

You are running Python 2 code on Python 3. In Python 3, the module has been renamed to http.client.

You could try to run the 2to3 tool on your code, and try to have it translated automatically. References to httplib will automatically be rewritten to use http.client instead.

How do I clone a generic list in C#?

I'll be lucky if anybody ever reads this... but in order to not return a list of type object in my Clone methods, I created an interface:

public interface IMyCloneable<T>
{
    T Clone();
}

Then I specified the extension:

public static List<T> Clone<T>(this List<T> listToClone) where T : IMyCloneable<T>
{
    return listToClone.Select(item => (T)item.Clone()).ToList();
}

And here is an implementation of the interface in my A/V marking software. I wanted to have my Clone() method return a list of VidMark (while the ICloneable interface wanted my method to return a list of object):

public class VidMark : IMyCloneable<VidMark>
{
    public long Beg { get; set; }
    public long End { get; set; }
    public string Desc { get; set; }
    public int Rank { get; set; } = 0;

    public VidMark Clone()
    {
        return (VidMark)this.MemberwiseClone();
    }
}

And finally, the usage of the extension inside a class:

private List<VidMark> _VidMarks;
private List<VidMark> _UndoVidMarks;

//Other methods instantiate and fill the lists

private void SetUndoVidMarks()
{
    _UndoVidMarks = _VidMarks.Clone();
}

Anybody like it? Any improvements?

How to check if a file exists in a shell script

If you're using a NFS, "test" is a better solution, because you can add a timeout to it, in case your NFS is down:

time timeout 3 test -f 
/nfs/my_nfs_is_currently_down
real    0m3.004s <<== timeout is taken into account
user    0m0.001s
sys     0m0.004s
echo $?
124   <= 124 means the timeout has been reached

A "[ -e my_file ]" construct will freeze until the NFS is functional again:

if [ -e /nfs/my_nfs_is_currently_down ]; then echo "ok" else echo "ko" ; fi

<no answer from the system, my session is "frozen">

Targeting .NET Framework 4.5 via Visual Studio 2010

I have been struggling with VS2010/DNFW 4.5 integration and have finally got this working. Starting in VS 2008, a cache of assemblies was introduced that is used by Visual Studio called the "Referenced Assemblies". This file cache for VS 2010 is located at \Reference Assemblies\Microsoft\Framework.NetFramework\v4.0. Visual Studio loads framework assemblies from this location instead of from the framework installation directory. When Microsoft says that VS 2010 does not support DNFW 4.5 what they mean is that this directory does not get updated when DNFW 4.5 is installed. Once you have replace the files in this location with the updated DNFW 4.5 files, you will find that VS 2010 will happily function with DNFW 4.5.

Callback functions in Java

Create an Interface, and Create the Same Interface Property in Callback Class.

interface dataFetchDelegate {
    void didFetchdata(String data);
}
//callback class
public class BackendManager{
   public dataFetchDelegate Delegate;

   public void getData() {
       //Do something, Http calls/ Any other work
       Delegate.didFetchdata("this is callbackdata");
   }

}

Now in the class where you want to get called back implement the above Created Interface. and Also Pass "this" Object/Reference of your class to be called back.

public class Main implements dataFetchDelegate
{       
    public static void main( String[] args )
    {
        new Main().getDatafromBackend();
    }

    public void getDatafromBackend() {
        BackendManager inc = new BackendManager();
        //Pass this object as reference.in this Scenario this is Main Object            
        inc.Delegate = this;
        //make call
        inc.getData();
    }

    //This method is called after task/Code Completion
    public void didFetchdata(String callbackData) {
        // TODO Auto-generated method stub
        System.out.println(callbackData);
    }
}

Validate decimal numbers in JavaScript - IsNumeric()

A simple and clean solution by leveraging language's dynamic type checking:

function IsNumeric (string) {
   if(string === ' '.repeat(string.length)){
     return false
   }
   return string - 0 === string * 1
}

if you don't care about white-spaces you can remove that " if "

see test cases below

_x000D_
_x000D_
function IsNumeric (string) {_x000D_
   if(string === ' '.repeat(string.length)){_x000D_
      return false_x000D_
   }_x000D_
   return string - 0 === string * 1_x000D_
}_x000D_
_x000D_
_x000D_
console.log('-1' + ' ? ' + IsNumeric('-1'))    _x000D_
console.log('-1.5' + ' ? ' + IsNumeric('-1.5')) _x000D_
console.log('0' + ' ? ' + IsNumeric('0'))     _x000D_
console.log('0.42' + ' ? ' + IsNumeric('0.42'))   _x000D_
console.log('.42' + ' ? ' + IsNumeric('.42'))    _x000D_
console.log('99,999' + ' ? ' + IsNumeric('99,999'))_x000D_
console.log('0x89f' + ' ? ' + IsNumeric('0x89f'))  _x000D_
console.log('#abcdef' + ' ? ' + IsNumeric('#abcdef'))_x000D_
console.log('1.2.3' + ' ? ' + IsNumeric('1.2.3')) _x000D_
console.log('' + ' ? ' + IsNumeric(''))    _x000D_
console.log('33 ' + ' ? ' + IsNumeric('33 '))
_x000D_
_x000D_
_x000D_

how to overlap two div in css?

check this fiddle , and if you want to move the overlapped div you set its position to absolute then change it's top and left values

TypeScript: Interfaces vs Types

Other answers are great! Few other things which Type can do but Interface can't

You can use union in type

type Name = string | { FullName: string };

const myName = "Jon"; // works fine

const myFullName: Name = {
  FullName: "Jon Doe", //also works fine
};

Iterating over union properties in type

type Keys = "firstName" | "lastName";

type Name = {
  [key in Keys]: string;
};

const myName: Name = {
  firstName: "jon",
  lastName: "doe",
};

Intersection in type ( however, also supported in Interface with extends)

type Name = {
  firstName: string;
  lastName: string;
};

type Address = {
  city: string;
};

const person: Name & Address = {
  firstName: "jon",
  lastName: "doe",
  city: "scranton",
};

Also not that type was introduced later as compared to interface and according to the latest release of TS type can do *almost everything which interface can and much more!


*except Declaration merging (personal opinion: It's good that it's not supported in type as it may lead to inconsistency in code)

Initializing default values in a struct

An explicit default initialization can help:

struct foo {
    bool a {};
    bool b {};
    bool c {};
 } bar;

Behavior bool a {} is same as bool b = bool(); and return false.

Batch command to move files to a new directory

this will also work, if you like

 xcopy  C:\Test\Log "c:\Test\Backup-%date:~4,2%-%date:~7,2%-%date:~10,4%_%time:~0,2%%time:~3,2%" /s /i
 del C:\Test\Log

Python date string to date object

There is another library called arrow really great to make manipulation on python date.

import arrow
import datetime

a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True

How to Lock Android App's Orientation to Portrait in Phones and Landscape in Tablets?

Just Add:

android:screenOrientation="portrait"

in "AndroidManifest.xml" :

<activity
android:screenOrientation="portrait"
android:name=".MainActivity"
android:label="@string/app_name">
</activity>

How to copy JavaScript object to new variable NOT by reference?

Your only option is to somehow clone the object.

See this stackoverflow question on how you can achieve this.

For simple JSON objects, the simplest way would be:

var newObject = JSON.parse(JSON.stringify(oldObject));

if you use jQuery, you can use:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

UPDATE 2017: I should mention, since this is a popular answer, that there are now better ways to achieve this using newer versions of javascript:

In ES6 or TypeScript (2.1+):

var shallowCopy = { ...oldObject };

var shallowCopyWithExtraProp = { ...oldObject, extraProp: "abc" };

Note that if extraProp is also a property on oldObject, its value will not be used because the extraProp : "abc" is specified later in the expression, which essentially overrides it. Of course, oldObject will not be modified.

Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

This is a well-known issue and based on this answer you could add setLenient:

Gson gson = new GsonBuilder()
        .setLenient()
        .create();

Retrofit retrofit = new Retrofit.Builder()
        .baseUrl(BASE_URL)
        .client(client)
        .addConverterFactory(GsonConverterFactory.create(gson))
        .build();

Now, if you add this to your retrofit, it gives you another error:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 1 path $

This is another well-known error you can find answer here (this error means that your server response is not well-formatted); So change server response to return something:

{
    android:[
        { ver:"1.5", name:"Cupcace", api:"Api Level 3" }
        ...
    ]
}

For better comprehension, compare your response with Github api.

Suggestion: to find out what's going on to your request/response add HttpLoggingInterceptor in your retrofit.

Based on this answer your ServiceHelper would be:

private ServiceHelper() {
        httpClient = new OkHttpClient.Builder();
        HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
        interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        httpClient.interceptors().add(interceptor);
        Retrofit retrofit = createAdapter().build();
        service = retrofit.create(IService.class);
    }

Also don't forget to add:

compile 'com.squareup.okhttp3:logging-interceptor:3.3.1'

Configuration Error: <compilation debug="true" targetFramework="4.0"> ASP.NET MVC3

If your application is 32 bit, and you want to deploy in a 64 bit machine, You need to set 'Enable 32 Bit Applications' property to 'True' in the application pool - advanced settings.

javascript filter array of objects

The most straightforward and readable approach will be the usage of native javascript filter method.

Native javaScript filter takes a declarative approach in filtering array elements. Since it is a method defined on Array.prototype, it iterates on a provided array and invokes a callback on it. This callback, which acts as our filtering function, takes three parameters:

element — the current item in the array being iterated over

index — the index or location of the current element in the array that is being iterated over

array — the original array that the filter method was applied on Let’s use this filter method in an example. Note that the filter can be applied on any sort of array. In this example, we are going to filter an array of objects based on an object property.

An example of filtering an array of objects based on object properties could look something like this:

// Please do not hate me for bashing on pizza and burgers.
// and FYI, I totally made up the healthMetric param :)
let foods = [
  { type: "pizza", healthMetric: 25 },
  { type: "burger", healthMetric: 10 },
  { type: "salad", healthMetric: 60 },
  { type: "apple", healthMetric: 82 }
];
let isHealthy = food => food.healthMetric >= 50;

const result = foods.filter(isHealthy);

console.log(result.map(food => food.type));
// Result: ['salad', 'apple']

To learn more about filtering arrays in functions and yo build your own filtering, check out this article: https://medium.com/better-programming/build-your-own-filter-e88ba0dcbfae

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

By default, IUSR account is used for anonymous user.

All you need to do is:

IIS -> Authentication --> Set Anonymous Authentication to Application Pool Identity.

Problem solved :)

There is already an object named in the database

Maybe you have changed the namespace in your project!
There is a table in your data base called dbo.__MigrationHistory. The table has a column called ContextKey.
The value of this column is based on your namespace. for example is "DataAccess.Migrations.Configuration".
When you change the namespace, it causes duplicate table names with different namespaces.
So, after you change namespace in code side, change the namespace in this table in database, too, (for all rows).
For example, if you change the namespace to EFDataAccess, then you should change the values of ContextKey column in dbo.__MigrationHistory to "EFDataAccess.Migrations.Configuration".
Then in code side, in Tools => Package Manager Console, use the update-database command.

Another option instead of changing the context value in the database is to hard code the context value in your code to the old namespace value. This is possible by inheriting DbMigrationsConfiguration<YourDbContext> and in the constructor just assign the old context value to ContextKey, than inherit from MigrateDatabaseToLatestVersion<YourDbContext, YourDbMigrationConfiguration> and leave that class empty. The last thing to do is call Database.SetInitializer(new YourDbInitializer()); in your DbContext in a static constructor.

I hope your problem will be fixed.

Update statement using with clause

You can always do something like this:

update  mytable t
set     SomeColumn = c.ComputedValue
from    (select *, 42 as ComputedValue from mytable where id = 1) c
where t.id = c.id 

You can now also use with statement inside update

update  mytable t
set     SomeColumn = c.ComputedValue
from    (with abc as (select *, 43 as ComputedValue_new from mytable where id = 1
         select *, 42 as ComputedValue, abc.ComputedValue_new  from mytable n1
           inner join abc on n1.id=abc.id) c
where t.id = c.id 

Sending JSON to PHP using ajax

If you want to get the values via the $_POST variable then you should not specify the contentType as "application/json" but rather use the default "application/x-www-form-urlencoded; charset=UTF-8":

JavaScript:

var person = { name: "John" };

$.ajax({
    //contentType: "application/json", // php://input
    contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: {data: person}
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

// $_POST

$jsonString = $_POST['data'];

$newJsonString = json_encode($jsonString);
header('Content-Type: application/json');
echo $newJsonString;

Else if you want to send a JSON from JavaScript to PHP:

JavaScript:

var person = { name: "John" };

$.ajax({
    contentType: "application/json", // php://input
    //contentType: "application/x-www-form-urlencoded; charset=UTF-8", // $_POST
    dataType : "json",
    method: "POST",
    url: "http://localhost/test/test.php",
    data: person
})
.done(function(data) {  
    console.log("test: ", data);
    $("#result").text(data.name);
})
.fail(function(data) {
    console.log("error: ", data);
});

PHP:

<?php

$jsonString = file_get_contents("php://input");
$phpObject = json_decode($jsonString);

$newJsonString = json_encode($phpObject);
header('Content-Type: application/json');
echo $newJsonString;

How to reset form body in bootstrap modal box?

If you using ajax to load modal's body such way and want to be able to reload it's content

<a data-toggle="modal" data-target="#myModal" href="./add">Add</a>
<a data-toggle="modal" data-target="#myModal" href="./edit/id">Modify</a>

<div id="myModal" class="modal fade">
    <div class="modal-dialog">
        <div class="modal-content">
            <!-- Content will be loaded here -->
        </div>
    </div>
</div>

use

<script>
    $(function() {
        $('.modal').on('hidden.bs.modal', function(){
            $(this).removeData('bs.modal');
        });
    });
</script>

Is there a way to remove unused imports and declarations from Angular 2+?

To be able to detect unused imports, code or variables, make sure you have this options in tsconfig.json file

"compilerOptions": {
    "noUnusedLocals": true,
    "noUnusedParameters": true
}

have the typescript compiler installed, ifnot install it with:

npm install -g typescript

and the tslint extension installed in Vcode, this worked for me, but after enabling I notice an increase amount of CPU usage, specially on big projects.

I would also recomend using typescript hero extension for organizing your imports.

Understanding REST: Verbs, error codes, and authentication

I noticed this question a couple of days late, but I feel that I can add some insight. I hope this can be helpful towards your RESTful venture.


Point 1: Am I understanding it right?

You understood right. That is a correct representation of a RESTful architecture. You may find the following matrix from Wikipedia very helpful in defining your nouns and verbs:


When dealing with a Collection URI like: http://example.com/resources/

  • GET: List the members of the collection, complete with their member URIs for further navigation. For example, list all the cars for sale.

  • PUT: Meaning defined as "replace the entire collection with another collection".

  • POST: Create a new entry in the collection where the ID is assigned automatically by the collection. The ID created is usually included as part of the data returned by this operation.

  • DELETE: Meaning defined as "delete the entire collection".


When dealing with a Member URI like: http://example.com/resources/7HOU57Y

  • GET: Retrieve a representation of the addressed member of the collection expressed in an appropriate MIME type.

  • PUT: Update the addressed member of the collection or create it with the specified ID.

  • POST: Treats the addressed member as a collection in its own right and creates a new subordinate of it.

  • DELETE: Delete the addressed member of the collection.


Point 2: I need more verbs

In general, when you think you need more verbs, it may actually mean that your resources need to be re-identified. Remember that in REST you are always acting on a resource, or on a collection of resources. What you choose as the resource is quite important for your API definition.

Activate/Deactivate Login: If you are creating a new session, then you may want to consider "the session" as the resource. To create a new session, use POST to http://example.com/sessions/ with the credentials in the body. To expire it use PUT or a DELETE (maybe depending on whether you intend to keep a session history) to http://example.com/sessions/SESSION_ID.

Change Password: This time the resource is "the user". You would need a PUT to http://example.com/users/USER_ID with the old and new passwords in the body. You are acting on "the user" resource, and a change password is simply an update request. It's quite similar to the UPDATE statement in a relational database.

My instinct would be to do a GET call to a URL like /api/users/1/activate_login

This goes against a very core REST principle: The correct usage of HTTP verbs. Any GET request should never leave any side effect.

For example, a GET request should never create a session on the database, return a cookie with a new Session ID, or leave any residue on the server. The GET verb is like the SELECT statement in a database engine. Remember that the response to any request with the GET verb should be cache-able when requested with the same parameters, just like when you request a static web page.


Point 3: How to return error messages and codes

Consider the 4xx or 5xx HTTP status codes as error categories. You can elaborate the error in the body.

Failed to Connect to Database: / Incorrect Database Login: In general you should use a 500 error for these types of errors. This is a server-side error. The client did nothing wrong. 500 errors are normally considered "retryable". i.e. the client can retry the same exact request, and expect it to succeed once the server's troubles are resolved. Specify the details in the body, so that the client will be able to provide some context to us humans.

The other category of errors would be the 4xx family, which in general indicate that the client did something wrong. In particular, this category of errors normally indicate to the client that there is no need to retry the request as it is, because it will continue to fail permanently. i.e. the client needs to change something before retrying this request. For example, "Resource not found" (HTTP 404) or "Malformed Request" (HTTP 400) errors would fall in this category.


Point 4: How to do authentication

As pointed out in point 1, instead of authenticating a user, you may want to think about creating a session. You will be returned a new "Session ID", along with the appropriate HTTP status code (200: Access Granted or 403: Access Denied).

You will then be asking your RESTful server: "Can you GET me the resource for this Session ID?".

There is no authenticated mode - REST is stateless: You create a session, you ask the server to give you resources using this Session ID as a parameter, and on logout you drop or expire the session.

Accessing members of items in a JSONArray with Java

By looking at your code, I sense you are using JSONLIB. If that was the case, look at the following snippet to convert json array to java array..

 JSONArray jsonArray = (JSONArray) JSONSerializer.toJSON( input );  
 JsonConfig jsonConfig = new JsonConfig();  
 jsonConfig.setArrayMode( JsonConfig.MODE_OBJECT_ARRAY );  
 jsonConfig.setRootClass( Integer.TYPE );  
 int[] output = (int[]) JSONSerializer.toJava( jsonArray, jsonConfig );  

Default port for SQL Server

You can use SQL Configuration Manager to set individual IP addresses to use dynamic ports or not (value of 0 = yes, use dynamic port), and to set the TCP port used for each IP.

But be careful: I recommend first mapping out your instances, IPs, and ports, and planning such that no instances or IPs step on each other before starting to make changes willy-nilly.

How to save MySQL query output to excel or .txt file?

You can write following codes to achieve this task:

SELECT ... FROM ... WHERE ... 
INTO OUTFILE 'textfile.csv'
FIELDS TERMINATED BY '|'

It export the result to CSV and then export it to excel sheet.

Return value of x = os.system(..)

os.system('command') returns a 16 bit number, which first 8 bits from left(lsb) talks about signal used by os to close the command, Next 8 bits talks about return code of command.

Refer my answer for more detail in What is the return value of os.system() in Python?

Difference between nVidia Quadro and Geforce cards?

Surfing the web, you will find many technical justifications for Quadro price. Real answer is in "demand for reliable and task specific graphic cards".

Imagine you have an architectural firm with many fat projects on deadline. Your computers are only used in working with one specific CAD software. If foundation of your business is supposed to rely on these computers, you would want to make sure this foundation is strong.

For such clients, Nvidia engineered cards like Quadro, providing what they call "Professional Solution". And if you are among the targeted clients, you would really appreciate reliability of these graphic cards.

Many believe Geforce have become powerful and reliable enough to take Quadro's place. But in the end, it depends on the software you are mostly going to use and importance of reliability in what you do.

HashMap and int as key

If you are using Netty and want to use a map with primitive int type keys, you can use its IntObjectHashMap

Some of the reasons to use primitive type collections:

  • improve performance by having specialized code
  • reduce garbage that can put pressure on the GC

The question of specialized vs generalized collections can make or break programs with high throughput requirements.

How to get the unix timestamp in C#

There is a ToUnixTimeMilliseconds for DateTimeOffset in System

You can write similar method for DateTime:

public static long ToUnixTimeSeconds(this DateTime value)
{
    return value.Ticks / 10000000L - 62135596800L;
}

10000000L - converting ticks to seconds

62135596800L - converting 01.01.01 to 01.01.1978

There is no problem with Utc and leaks

How to set the style -webkit-transform dynamically using JavaScript?

Here are the JavaScript notations for most common vendors:

webkitProperty
MozProperty
msProperty
OProperty
property

I reset inline transform styles like:

element.style.webkitTransform = "";
element.style.MozTransform = "";
element.style.msTransform = "";
element.style.OTransform = "";
element.style.transform = "";

And like this using jQuery:

$(element).css({
    "webkitTransform":"",
    "MozTransform":"",
    "msTransform":"",
    "OTransform":"",
    "transform":""
});

See blog post Coding Vendor Prefixes with JavaScript (2012-03-21).

Getting the names of all files in a directory with PHP

You could just try the scandir(Path) function. it is fast and easy to implement

Syntax:

$files = scandir("somePath");

This Function returns a list of file into an Array.

to view the result, you can try

var_dump($files);

Or

foreach($files as $file)
{ 
echo $file."< br>";
} 

CSS On hover show another element

we just can show same label div on hovering like this

<style>
#b {
    display: none;
}

#content:hover~#b{
    display: block;
}

</style>

Using Pairs or 2-tuples in Java

As an extension to @maerics nice answer, I've added a few useful methods:

public class Tuple<X, Y> { 
    public final X x; 
    public final Y y; 
    public Tuple(X x, Y y) { 
        this.x = x; 
        this.y = y; 
    }

    @Override
    public String toString() {
        return "(" + x + "," + y + ")";
    }

    @Override
    public boolean equals(Object other) {
        if (other == this) {
            return true;
        }

        if (!(other instanceof Tuple)){
            return false;
        }

        Tuple<X,Y> other_ = (Tuple<X,Y>) other;

        // this may cause NPE if nulls are valid values for x or y. The logic may be improved to handle nulls properly, if needed.
        return other_.x.equals(this.x) && other_.y.equals(this.y);
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((x == null) ? 0 : x.hashCode());
        result = prime * result + ((y == null) ? 0 : y.hashCode());
        return result;
    }
}

update package.json version automatically

I am using husky and git-branch-is:

As of husky v1+:

// package.json
{
  "husky": {
    "hooks": {
      "post-merge": "(git-branch-is master && npm version minor || 
  (git-branch-is dev && npm --no-git-tag-version version patch)",
    }
  }
}

Prior to husky V1:

"scripts": {
  ...
  "postmerge": "(git-branch-is master && npm version minor || 
  (git-branch-is dev && npm --no-git-tag-version version patch)",
  ...
},

Read more about npm version

Webpack or Vue.js

If you are using webpack or Vue.js, you can display this in the UI using Auto inject version - Webpack plugin

NUXT

In nuxt.config.js:

var WebpackAutoInject = require('webpack-auto-inject-version');

module.exports = {
  build: {
    plugins: [
      new WebpackAutoInject({
        // options
        // example:
        components: {
          InjectAsComment: false
        },
      }),
    ]
  },
}

Inside your template for example in the footer:

<p> All rights reserved © 2018 [v[AIV]{version}[/AIV]]</p>

Display exact matches only with grep

You need a more specific expression. Try grep " OK$" or grep "[0-9]* OK". You want to choose a pattern that matches what you want, but won't match what you don't want. That pattern will depend upon what your whole file contents might look like.

You can also do: grep -w "OK" which will only match a whole word "OK", such as "1 OK" but won't match "1OK" or "OKFINE".

$ cat test.txt | grep -w "OK"
1 OK
2 OK
4 OK

Find most frequent value in SQL column

One way I like to use is:

select ,COUNT()as VAR1 from Table_Name

group by

order by VAR1 desc

limit 1

How to pass a null variable to a SQL Stored Procedure from C#.net code

try this! syntax less lines and even more compact! don't forget to add the properties you want to add with this approach!

cmd.Parameters.Add(new SqlParameter{SqlValue=(object)username??DBNull.Value,ParameterName="user" }  );

The shortest possible output from git log containing author and date

git log --pretty=format:"%H %an %ad"

use --date= to set a date format

git log --pretty=format:"%H %an %ad" --date=short

Job for httpd.service failed because the control process exited with error code. See "systemctl status httpd.service" and "journalctl -xe" for details

Allow Apache Through the Firewall

Allow the default HTTP and HTTPS port, ports 80 and 443, through firewalld:

sudo firewall-cmd --permanent --add-port=80/tcp
sudo firewall-cmd --permanent --add-port=443/tcp

And reload the firewall:

sudo firewall-cmd --reload

How can I remove text within parentheses with a regex?

If you don't absolutely need to use a regex, useconsider using Perl's Text::Balanced to remove the parenthesis.

use Text::Balanced qw(extract_bracketed);

my ($extracted, $remainder, $prefix) = extract_bracketed( $filename, '()', '[^(]*' );

{   no warnings 'uninitialized';

    $filename = (defined $prefix or defined $remainder)
                ? $prefix . $remainder
                : $extracted;
}

You may be thinking, "Why do all this when a regex does the trick in one line?"

$filename =~ s/\([^}]*\)//;

Text::Balanced handles nested parenthesis. So $filename = 'foo_(bar(baz)buz)).foo' will be extracted properly. The regex based solutions offered here will fail on this string. The one will stop at the first closing paren, and the other will eat them all.

   $filename =~ s/\([^}]*\)//;
   # returns 'foo_buz)).foo'

   $filename =~ s/\(.*\)//;
   # returns 'foo_.foo'

   # text balanced example returns 'foo_).foo'

If either of the regex behaviors is acceptable, use a regex--but document the limitations and the assumptions being made.

Create Table from View

To create a table on the fly us this syntax:

SELECT *
INTO A
FROM dbo.myView

Android Studio error: "Environment variable does not point to a valid JVM installation"

You have a problem with your Java JDK installation. So, try reinstalling it. You can download it from: http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html

It looks that you have a 64-bit system, so download the "Windows x64" version.

HTML 5 Geo Location Prompt in Chrome

As already mentioned in the answer by robertc, Chrome blocks certain functionality, like the geo location with local files. An easier alternative to setting up an own web server would be to just start Chrome with the parameter --allow-file-access-from-files. Then you can use the geo location, provided you didn't turn it off in your settings.

Checking if a key exists in a JS object

var obj = {
    "key1" : "k1",
    "key2" : "k2",
    "key3" : "k3"
};

if ("key1" in obj)
    console.log("has key1 in obj");

=========================================================================

To access a child key of another key

var obj = {
    "key1": "k1",
    "key2": "k2",
    "key3": "k3",
    "key4": {
        "keyF": "kf"
    }
};

if ("keyF" in obj.key4)
    console.log("has keyF in obj");

How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

In swift 4.2 I used following code to show and hide code using NSNotification

 @objc func keyboardWillShow(notification: NSNotification) {
    if let keyboardSize = (notification.userInfo? [UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardheight = keyboardSize.height
        print(keyboardheight)
    }
}

convert string date to java.sql.Date

This works for me without throwing an exception:

package com.sandbox;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Sandbox {

    public static void main(String[] args) throws ParseException {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        Date parsed = format.parse("20110210");
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
    }


}

How to change the icon of .bat file programmatically?

Try BatToExe converter. It will convert your batch file to an executable, and allow you to set an icon for it.

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

I fixed this by generating my provisioning profile again (and again).

Global environment variables in a shell script

source myscript.sh is also feasible.

Description for linux command source:

source is a Unix command that evaluates the file following the command, 
as a list of commands, executed in the current context

SQL Server String or binary data would be truncated

I wrote a useful store procedure to help identify and resolve the problem of text truncation (String or binary data would be truncated) when the INSERT SELECT statement is used. It compares fields CHAR, VARCHAR, NCHAR AND NVARCHAR only and returns an evaluation field by field in case of being the possible cause of the error.

EXEC dbo.GetFieldStringTruncate SourceTableName, TargetTableName

This stored procedure is oriented to the problem of text truncation when an INSERT SELECT statement is made.

The operation of this stored procedure depends on the user previously identifying the INSERT statement with the problem. Then inserting the source data into a global temporary table. The SELECT INTO statement is recommended.

You must use the same name of the field of the destination table in the alias of each field of the SELECT statement.

FUNCTION CODE:

DECLARE @strSQL nvarchar(1000)
IF NOT EXISTS (SELECT * FROM dbo.sysobjects where id = OBJECT_ID(N'[dbo].[GetFieldStringTruncate]'))
    BEGIN
        SET @strSQL = 'CREATE PROCEDURE [dbo].[GetFieldStringTruncate] AS RETURN'
        EXEC sys.sp_executesql @strSQL
    END

GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

/*
------------------------------------------------------------------------------------------------------------------------
    Description:    
                    Syntax 
                    ---------------
                    dbo.GetFieldStringTruncate(SourceTable, TargetTable)
                    +---------------------------+-----------------------+
                    |   SourceTableName         |   VARCHAR(255)        |
                    +---------------------------+-----------------------+
                    |   TargetTableName         |   VARCHAR(255)        |
                    +---------------------------+-----------------------+

                    Arguments
                    ---------------
                    SourceTableName
                    The name of the source table. It should be a temporary table using double charp '##'. E.g. '##temp'

                    TargetTableName
                    The name of the target table. It is the table that receives the data used in the INSERT INTO stament.

                    Return Type
                    ----------------
                    Returns a table with a list of all the fields with the type defined as text and performs an evaluation indicating which field would present the problem of string truncation.

                    Remarks
                    ----------------
                    This stored procedure is oriented to the problem of text truncation when an INSERT SELECT statement is made.
                    The operation of this stored procedure depends on the user previously identifying the INSERT statement with the problem. Then inserting the source data into a global temporary table. The SELECT INTO statement is recommended.
                    You must use the same name of the field of the destination table in the alias of each field of the SELECT statement.

                    Examples
                    ====================================================================================================

                    --A. Test basic

                        IF EXISTS (SELECT * FROM sys.objects  WHERE OBJECT_ID = OBJECT_ID(N'[dbo].[tblDestino]') AND TYPE IN (N'U'))
                            DROP TABLE tblDestino

                        CREATE TABLE tblDestino
                        (
                            Id INT IDENTITY,
                            Field1 VARCHAR(10),
                            Field2 VARCHAR(12),
                            Field3 VARCHAR(11),
                            Field4 VARCHAR(16),
                            Field5 VARCHAR(5),
                            Field6 VARCHAR(1),
                            Field7 VARCHAR(1),
                            Field8 VARCHAR(6),
                            Field9 VARCHAR(6),
                            Field10 VARCHAR(50),
                            Field11 VARCHAR(50),
                            Field12 VARCHAR(50)
                        )

                        INSERT INTO dbo.tblDestino
                        (
                             Field1 ,
                             Field2 ,
                             Field3 ,
                             Field4 ,
                             Field5 ,
                             Field6 ,
                             Field7 ,
                             Field8 ,
                             Field9 ,
                             Field10 ,
                             Field11 ,
                             Field12
                            )
                        SELECT 
                             '123456789' , -- Field1 - varchar(10)
                             '123456789' , -- Field2 - varchar(12)
                             '123456789' , -- Field3 - varchar(11)
                             '123456789' , -- Field4 - varchar(16)
                             '123456789' , -- Field5 - varchar(5)
                             '123456789' , -- Field6 - varchar(1)
                             '123456789' , -- Field7 - varchar(1)
                             '123456789' , -- Field8 - varchar(6)
                             '123456789' , -- Field9 - varchar(6)
                             '123456789' , -- Field10 - varchar(50)
                             '123456789' , -- Field11 - varchar(50)
                             '123456789'  -- Field12 - varchar(50)
                        GO  

                    Result:
                        String or binary data would be truncated


                    *Here you get the truncation error. Then, we proceed to save the information in a global temporary table. 
                    *IMPORTANT REMINDER: You must use the same name of the field of the destination table in the alias of each field of the SELECT statement.


                    Process:

                        IF OBJECT_ID('tempdb..##TEMP') IS NOT NULL DROP TABLE ##TEMP
                        go
                        SELECT 
                             [Field1] = '123456789' ,
                             [Field2] = '123456789' ,
                             [Field3] = '123456789' ,
                             [Field4] = '123456789' ,
                             [Field5] = '123456789' ,
                             [Field6] = '123456789' ,
                             [Field7] = '123456789' ,
                             [Field8] = '123456789' ,
                             [Field9] = '123456789' ,
                             [Field10] = '123456789' ,
                             [Field11] = '123456789' ,
                             [Field12] = '123456789'  
                        INTO ##TEMP

                    Result:
                    (1 row(s) affected)

                    Test:
                        EXEC dbo.GetFieldStringTruncate @SourceTableName = '##TEMP', @TargetTableName = 'tblDestino'

                    Result:

                        (12 row(s) affected)
                        ORIGEN Nombre Campo        ORIGEN Maximo Largo  DESTINO Nombre Campo     DESTINO Tipo de campo   Evaluación
                        -------------------------- -------------------- ------------------------ ----------------------- -------------------------
                        Field1                     9                    02 - Field1              VARCHAR(10)             
                        Field2                     9                    03 - Field2              VARCHAR(12)             
                        Field3                     9                    04 - Field3              VARCHAR(11)             
                        Field4                     9                    05 - Field4              VARCHAR(16)             
                        Field5                     9                    06 - Field5              VARCHAR(5)              possible field with error
                        Field6                     9                    07 - Field6              VARCHAR(1)              possible field with error
                        Field7                     9                    08 - Field7              VARCHAR(1)              possible field with error
                        Field8                     9                    09 - Field8              VARCHAR(6)              possible field with error
                        Field9                     9                    10 - Field9              VARCHAR(6)              possible field with error
                        Field10                    9                    11 - Field10             VARCHAR(50)             
                        Field11                    9                    12 - Field11             VARCHAR(50)             
                        Field12                    9                    13 - Field12             VARCHAR(50)             

                    ====================================================================================================

    ------------------------------------------------------------------------------------------------------------

    Responsible:    Javier Pardo 
    Date:           October 19/2018
    WB tests:       Javier Pardo 

    ------------------------------------------------------------------------------------------------------------

*/

ALTER PROCEDURE dbo.GetFieldStringTruncate
(
    @SourceTableName AS VARCHAR(255)
    , @TargetTableName AS VARCHAR(255)
)
AS
BEGIN
    BEGIN TRY

        DECLARE @colsUnpivot AS NVARCHAR(MAX),
            @colsUnpivotConverted AS NVARCHAR(MAX),
           @query  AS NVARCHAR(MAX)

        SELECT @colsUnpivot = stuff((
                    SELECT DISTINCT ',' + QUOTENAME(col.NAME)
                    FROM tempdb.sys.tables tab
                    INNER JOIN tempdb.sys.columns col
                        ON col.object_id = tab.object_id
                    INNER JOIN tempdb.sys.types typ
                        ON col.system_type_id = TYP.system_type_id
                    WHERE tab.NAME = @SourceTableName
                    FOR XML path('')
                    ), 1, 1, '')
                ,@colsUnpivotConverted = stuff((
                    SELECT DISTINCT ',' + 'CONVERT(VARCHAR(MAX),' + QUOTENAME(col.NAME) + ') AS ' + QUOTENAME(col.NAME)
                    FROM tempdb.sys.tables tab
                    INNER JOIN tempdb.sys.columns col
                        ON col.object_id = tab.object_id
                    INNER JOIN tempdb.sys.types typ
                        ON col.system_type_id = TYP.system_type_id
                    WHERE tab.NAME = @SourceTableName
                    FOR XML path('')
                    ), 1, 1, '')


        --https://stackoverflow.com/questions/11158017/column-conflicts-with-the-type-of-other-columns-in-the-unpivot-list
        IF OBJECT_ID('tempdb..##TablaConMaximos') IS NOT NULL DROP TABLE ##TablaConMaximos

        set @query 
          = 'SELECT u.d AS colname, MAX(LEN(u.data)) as [maximo_largo]
            INTO ##TablaConMaximos
            FROM 
            (
                SELECT ' + @colsUnpivotConverted + '
                FROM ' + @SourceTableName + '
            ) T
            UNPIVOT
             (
                data
                for d in ('+ @colsunpivot +')
             ) u
             GROUP BY u.d'

        PRINT @query

        exec sp_executesql @query;

        ------------------------------------------------------------------------------------------------------------
        SELECT --'Nombre de campo' = RIGHT('00' + ISNULL(CONVERT(VARCHAR,col.column_id),''),2) + ' - ' + col.name + ' '
            --, 'Tipo de campo' = ISNULL(CONVERT(VARCHAR,upper(typ.name)),'') + '(' + ISNULL(CONVERT(VARCHAR,col.max_length),'') + ')'
            [ORIGEN Nombre Campo] = tcm.colname
            , [ORIGEN Maximo Largo] = tcm.maximo_largo
            , [DESTINO Nombre Campo] = DESTINO.[Nombre de campo]
            , [DESTINO Tipo de campo] = DESTINO.[Tipo de campo]
            , [Evaluación] = CASE WHEN DESTINO.maximo_largo < tcm.maximo_largo THEN 'possible field with error' ELSE '' END
            --, * 
        FROM tempdb.sys.tables tab
            INNER JOIN tempdb.sys.columns col
                ON col.object_id = tab.object_id
            INNER JOIN tempdb.sys.types typ
                ON col.system_type_id = TYP.system_type_id
            RIGHT JOIN 
                (
                    SELECT column_id
                        , [Nombre de campo] = RIGHT('00' + ISNULL(CONVERT(VARCHAR,col.column_id),''),2) + ' - ' + col.name + ' '
                        , [Tipo de campo] = ISNULL(CONVERT(VARCHAR,upper(typ.name)),'') + '(' + ISNULL(CONVERT(VARCHAR,col.max_length),'') + ')'
                        , [maximo_largo] = col.max_length
                        , [colname] = col.name
                    FROM sys.tables tab
                        INNER JOIN sys.columns col
                            ON col.object_id = tab.object_id
                        INNER JOIN sys.types typ
                            ON col.system_type_id = TYP.system_type_id
                    WHERE tab.NAME = @TargetTableName
                ) AS DESTINO
                    ON col.name = DESTINO.colname
            INNER JOIN ##TablaConMaximos tcm
                ON tcm.colname = DESTINO.colname

        WHERE tab.NAME = @SourceTableName
            AND typ.name LIKE '%char%'
        ORDER BY col.column_id

    END TRY
    BEGIN CATCH
        SELECT 'Internal error ocurred' AS Message
    END CATCH   

END

For now only supports the data types CHAR, VARCHAR, NCHAR and NVARCHAR. You can find the last versión of this code in the next link below and we help each other to improve it. GetFieldStringTruncate.sql

https://gist.github.com/jotapardo/210e85338f87507742701aa9d41cc51d

Java Multiple Inheritance

I have a stupid idea:

public class Pegasus {
    private Horse horseFeatures; 
    private Bird birdFeatures; 

   public Pegasus(Horse horse, Bird bird) {
     this.horseFeatures = horse;
     this.birdFeatures = bird;
   }

  public void jump() {
    horseFeatures.jump();
  }

  public void fly() {
    birdFeatures.fly();
  }
}

How do I schedule a task to run at periodic intervals?

Use timer.scheduleAtFixedRate

public void scheduleAtFixedRate(TimerTask task,
                                long delay,
                                long period)

Schedules the specified task for repeated fixed-rate execution, beginning after the specified delay. Subsequent executions take place at approximately regular intervals, separated by the specified period.
In fixed-rate execution, each execution is scheduled relative to the scheduled execution time of the initial execution. If an execution is delayed for any reason (such as garbage collection or other background activity), two or more executions will occur in rapid succession to "catch up." In the long run, the frequency of execution will be exactly the reciprocal of the specified period (assuming the system clock underlying Object.wait(long) is accurate).

Fixed-rate execution is appropriate for recurring activities that are sensitive to absolute time, such as ringing a chime every hour on the hour, or running scheduled maintenance every day at a particular time. It is also appropriate for recurring activities where the total time to perform a fixed number of executions is important, such as a countdown timer that ticks once every second for ten seconds. Finally, fixed-rate execution is appropriate for scheduling multiple repeating timer tasks that must remain synchronized with respect to one another.

Parameters:

  • task - task to be scheduled.
  • delay - delay in milliseconds before task is to be executed.
  • period - time in milliseconds between successive task executions.

Throws:

  • IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is negative.
  • IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or timer thread terminated.

How to get a float result by dividing two integer values using T-SQL?

The suggestions from stb and xiowl are fine if you're looking for a constant. If you need to use existing fields or parameters which are integers, you can cast them to be floats first:

SELECT CAST(1 AS float) / CAST(3 AS float)

or

SELECT CAST(MyIntField1 AS float) / CAST(MyIntField2 AS float)

Android: How to rotate a bitmap on a center point

I came back to this problem now that we are finalizing the game and I just thought to post what worked for me.

This is the method for rotating the Matrix:

this.matrix.reset();
this.matrix.setTranslate(this.floatXpos, this.floatYpos);
this.matrix.postRotate((float)this.direction, this.getCenterX(), this.getCenterY()); 

(this.getCenterX() is basically the bitmaps X position + the bitmaps width / 2)

And the method for Drawing the bitmap (called via a RenderManager Class):

canvas.drawBitmap(this.bitmap, this.matrix, null);

So it is prettey straight forward but I find it abit strange that I couldn't get it to work by setRotate followed by postTranslate. Maybe some knows why this doesn't work? Now all the bitmaps rotate properly but it is not without some minor decrease in bitmap quality :/

Anyways, thanks for your help!

How to get controls in WPF to fill available space?

There are also some properties you can set to force a control to fill its available space when it would otherwise not do so. For example, you can say:

HorizontalContentAlignment="Stretch"

... to force the contents of a control to stretch horizontally. Or you can say:

HorizontalAlignment="Stretch"

... to force the control itself to stretch horizontally to fill its parent.

How can I open a URL in Android's web browser from my application?

String url = "http://www.example.com";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);

How to install a certificate in Xcode (preparing for app store submission)

Under

Provisioning -> Distribution -> Distribution Provisioning Profiles

I downloaded the desired certificate again and installed it. Now I don't see an empty file in Xcode. The build also works now (no code sign error).

What I also did: I downloaded the WWDR and installed it, but I don't know if that was the reason (because I think it's always the same)

How to use MySQL dump from a remote machine

This is how you would restore a backup after you successfully backup your .sql file

mysql -u [username] [databasename]

And choose your sql file with this command:

source MY-BACKED-UP-DATABASE-FILE.sql

C++ unordered_map using a custom class type as the key

Most basic possible copy/paste complete runnable example of using a custom class as the key for an unordered_map (basic implementation of a sparse matrix):

// UnorderedMapObjectAsKey.cpp

#include <iostream>
#include <vector>
#include <unordered_map>

struct Pos
{
  int row;
  int col;

  Pos() { }
  Pos(int row, int col)
  {
    this->row = row;
    this->col = col;
  }

  bool operator==(const Pos& otherPos) const
  {
    if (this->row == otherPos.row && this->col == otherPos.col) return true;
    else return false;
  }

  struct HashFunction
  {
    size_t operator()(const Pos& pos) const
    {
      size_t rowHash = std::hash<int>()(pos.row);
      size_t colHash = std::hash<int>()(pos.col) << 1;
      return rowHash ^ colHash;
    }
  };
};

int main(void)
{
  std::unordered_map<Pos, int, Pos::HashFunction> umap;

  // at row 1, col 2, set value to 5
  umap[Pos(1, 2)] = 5;

  // at row 3, col 4, set value to 10
  umap[Pos(3, 4)] = 10;

  // print the umap
  std::cout << "\n";
  for (auto& element : umap)
  {
    std::cout << "( " << element.first.row << ", " << element.first.col << " ) = " << element.second << "\n";
  }
  std::cout << "\n";

  return 0;
}

WAMP/XAMPP is responding very slow over localhost

I had this problem too.

I added the entries suggested above but it failed to work.

It was due to the fact Spybot Search and Destroy had added 15,000 lines of immunized site (ie prevents you from visiting them) to my hosts file.

My hosts file was 433k - I removed those lines and my page load speed improved immensely.

How to convert DateTime to VarChar

Either Cast or Convert:

Syntax for CAST:

CAST ( expression AS data_type [ (length ) ])

Syntax for CONVERT:

CONVERT ( data_type [ ( length ) ] , expression [ , style ] )

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

Actually since you asked for a specific format:

REPLACE(CONVERT(varchar(10), Date, 102), '.', '-')

c++ compile error: ISO C++ forbids comparison between pointer and integer

You have two ways to fix this. The preferred way is to use:

string answer;

(instead of char). The other possible way to fix it is:

if (answer == 'y') ...

(note single quotes instead of double, representing a char constant).

RandomForestClassfier.fit(): ValueError: could not convert string to float

You can't pass str to your model fit() method. as it mentioned here

The training input samples. Internally, it will be converted to dtype=np.float32 and if a sparse matrix is provided to a sparse csc_matrix.

Try transforming your data to float and give a try to LabelEncoder.

What does it mean when MySQL is in the state "Sending data"?

In this state:

The thread is reading and processing rows for a SELECT statement, and sending data to the client.

Because operations occurring during this this state tend to perform large amounts of disk access (reads).

That's why it takes more time to complete and so is the longest-running state over the lifetime of a given query.

Print multiple arguments in Python

Keeping it simple, I personally like string concatenation:

print("Total score for " + name + " is " + score)

It works with both Python 2.7 an 3.X.

NOTE: If score is an int, then, you should convert it to str:

print("Total score for " + name + " is " + str(score))

How to clear browser cache with php?

It seams you need to versionate, so when some change happens browser will catch something new and user won't need to clear browser's cache.

You can do it by subfolders (example /css/v1/style.css) or by filename (example: css/style_v1.css) or even by setting different folders for your website, example:

www.mywebsite.com/site1

www.mywebsite.com/site2

www.mywebsite.com/site3

And use a .htaccess or even change httpd.conf to redirect to your current application.

If's about one image or page:

    <?$time = date("H:i:s");?>
    <img src="myfile.jpg?time=<?$time;?>">

You can use $time on parts when you don't wanna cache. So it will always pull a new image. Versionate it seams a better approach, otherwise it can overload your server. Remember, browser's cache it's not only good to user experience, but also for your server.

PHP convert date format dd/mm/yyyy => yyyy-mm-dd

Do this:

date('Y-m-d', strtotime('dd/mm/yyyy'));

But make sure 'dd/mm/yyyy' is the actual date.