Programs & Examples On #Fsyacc

Fsyacc is a F# version of yacc, a program generates a parser (the part of a compiler that tries to make syntactic sense of the source code) based on an analytic grammar written in a notation similar to BNF.

SQL to add column and comment in table in single command

Query to add column with comment are :

alter table table_name 
add( "NISFLAG"    NUMBER(1,0) )

comment on column "ELIXIR"."PRD_INFO_1"."NISPRODGSTAPPL" is 'comment here'

commit;

Sublime Text 2 - View whitespace characters

If you really only want to see trailing spaces, this ST2 plugin will do the trick: https://github.com/SublimeText/TrailingSpaces

How to open spss data files in excel?

(Not exactly an answer for you, since do you want avoid opening the files, but maybe this helps others).

I have been using the open source GNU PSPP package to convert the sav tile to csv. You can download the Windows version at least from SourceForge [1]. Once you have the software, you can convert sav file to csv with following command line:

pspp-convert <input.sav> <output.csv>

[1] http://sourceforge.net/projects/pspp4windows/files/?source=navbar

SQL: how to use UNION and order by a specific select?

You want to do this:

select * from 
(
    SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
    UNION
    SELECT id, 1 as ordered FROM b -- returns 2,1
)
order by ordered

Update

I noticed that even though you have two different tables, you join the IDs, that means, if you have 1 in both tables, you are getting only one occurrence. If that's the desired behavior, you should stick to UNION. If not, change to UNION ALL.

So I also notice that if you change to the code I proposed, You would start getting both 1 and 2 (from both a and b). In that case, you might want to change the proposed code to:

select distinct id from 
(
    SELECT id, 2 as ordered FROM a -- returns 1,4,2,3
    UNION
    SELECT id, 1 as ordered FROM b -- returns 2,1
)
order by ordered

How to convert a full date to a short date in javascript?

Built-in toLocaleDateString() does the job, but it will remove the leading 0s for the day and month, so we will get something like "1/9/1970", which is not perfect in my opinion. To get a proper format MM/DD/YYYY we can use something like:

new Date(dateString).toLocaleDateString('en-US', {
  day: '2-digit',
  month: '2-digit',
  year: 'numeric',
})

Cannot open include file: 'unistd.h': No such file or directory

The "uni" in unistd stands for "UNIX" - you won't find it on a Windows system.

Most widely used, portable libraries should offer alternative builds or detect the platform and only try to use headers/functions that will be provided, so it's worth checking documentation to see if you've missed some build step - e.g. perhaps running "make" instead of loading a ".sln" Visual C++ solution file.

If you need to fix it yourself, remove the include and see which functions are actually needed, then try to find a Windows equivalent.

Node JS Error: ENOENT

use "temp" in lieu of "tmp"

"/temp/test.png"

it worked for me after i realized the tmp is a temporary folder that didn't exist on my computer, but my temp was my temporary folder

///

EDIT:

I also created a new folder "tmp" in my C: drive and everything worked perfectly. The book may have missed mentioning that small step

check out http://webchat.freenode.net/?channels=node.js to chat with some of the node.js community

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

Cause: A trigger was attempted to be retrieved for execution and was found to be invalid. This also means that compilation/authorization failed for the trigger.

Action: Options are to resolve the compilation/authorization errors, disable the trigger, or drop the trigger.

Syntax

ALTER TRIGGER trigger Name DISABLE;

ALTER TRIGGER trigger_Name ENABLE;

Disable browser 'Save Password' functionality

Markus raised a great point. I decided to look up the autocomplete attribute and got the following:

The only downside to using this attribute is that it is not standard (it works in IE and Mozilla browsers), and would cause XHTML validation to fail. I think this is a case where it's reasonable to break validation however. (source)

So I would have to say that although it doesn't work 100% across the board it is handled in the major browsers so its a great solution.

Fatal error: Call to undefined function pg_connect()

I encountered this error and it ended up being related to how PHP's extension_dir was loading.

If upon printing out phpinfo() you find that under the PDO header PDO drivers is set to no value, you may want to check that you are successfully loading your extension directory as detailed in this post:

https://stackoverflow.com/a/14786808/2578505

Required attribute HTML5

I just ran into this issue with Safari 5 and it has been an issue with Opera 10 for some time, but I never spent time to fix it. Now I need to fix it and saw your post but no solution yet on how to cancel the form. After much searching I finally found something:

http://www.w3.org/TR/html5/forms.html#attr-fs-formnovalidate

<input type=submit formnovalidate name=cancel value="Cancel">

Works on Safari 5 and Opera 10.

JavaScript get window X/Y position for scroll

The method jQuery (v1.10) uses to find this is:

var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

That is:

  • It tests for window.pageXOffset first and uses that if it exists.
  • Otherwise, it uses document.documentElement.scrollLeft.
  • It then subtracts document.documentElement.clientLeft if it exists.

The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.

What's the difference between the Window.Loaded and Window.ContentRendered events

If you're using data binding, then you need to use the ContentRendered event.

For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.

<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />

How to compare datetime with only date in SQL Server

You can use LIKE statement instead of =. But to do this with DateStamp you need to CONVERT it first to VARCHAR:

SELECT * 
FROM [User] U
WHERE CONVERT(VARCHAR, U.DateCreated, 120) LIKE '2014-02-07%'

'uint32_t' identifier not found error

This type is defined in the C header <stdint.h> which is part of the C++11 standard but not standard in C++03. According to the Wikipedia page on the header, it hasn't shipped with Visual Studio until VS2010.

In the meantime, you could probably fake up your own version of the header by adding typedefs that map Microsoft's custom integer types to the types expected by C. For example:

typedef __int32 int32_t;
typedef unsigned __int32 uint32_t;
/* ... etc. ... */

Hope this helps!

How to use range-based for() loop with std::map?

Each element of the container is a map<K, V>::value_type, which is a typedef for std::pair<const K, V>. Consequently, in C++17 or higher, you can write

for (auto& [key, value]: myMap) {
    std::cout << key << " has value " << value << std::endl;
}

or as

for (const auto& [key, value]: myMap) {
    std::cout << key << " has value " << value << std::endl;
}

if you don't plan on modifying the values.

In C++11 and C++14, you can use enhanced for loops to extract out each pair on its own, then manually extract the keys and values:

for (const auto& kv : myMap) {
    std::cout << kv.first << " has value " << kv.second << std::endl;
}

You could also consider marking the kv variable const if you want a read-only view of the values.

convert php date to mysql format

There is several options.

Either convert it to timestamp and use as instructed in other posts with strtotime() or use MySQL’s date parsing option

What's the difference between REST & RESTful

Representational state transfer (REST) is a style of software architecture. As described in a dissertation by Roy Fielding, REST is an "architectural style" that basically exploits the existing technology and protocols of the Web.

RESTful is typically used to refer to web services implementing such an architecture.

Skip a submodule during a Maven build

there is now (from 1.1.1 version) a 'skip' flag in pit.

So you can do things like :

    <profile>
        <id>pit</id>
        <build>
            <plugins>
                <plugin>
                    <groupId>org.pitest</groupId>
                    <artifactId>pitest-maven</artifactId>
                    <configuration>
                        <skip>true</skip>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </profile>

in your module, and pit will skip

[INFO] --- pitest-maven:1.1.3:mutationCoverage (default-cli) @ module-selenium --- [INFO] Skipping project

IF - ELSE IF - ELSE Structure in Excel

When FIND returns #VALUE!, it is an error, not a string, so you can't compare FIND(...) with "#VALUE!", you need to check if FIND returns an error with ISERROR. Also FIND can work on multiple characters.

So a simplified and working version of your formula would be:

=IF(ISERROR(FIND("abc",A1))=FALSE, "Green", IF(ISERROR(FIND("xyz",A1))=FALSE, "Yellow", "Red"))

Or, to remove the double negations:

=IF(ISERROR(FIND("abc",A1)), IF(ISERROR(FIND("xyz",A1)), "Red", "Yellow"),"Green")

Android ADB device offline, can't issue commands

I needed to kill multiple adb processes (adb kill-server & adb start-server still left a lingering process alive.)

$ ps aux | grep adb

$ killall adb

finding and replacing elements in a list

The answers for this old but relevant question are wildly variable in speed.

The fastest of the solution posted by kxr.

However, this is even faster and otherwise not here:

def f1(arr, find, replace):
    # fast and readable
    base=0
    for cnt in range(arr.count(find)):
        offset=arr.index(find, base)
        arr[offset]=replace
        base=offset+1

Here is timing for the various solutions. The faster ones are 3X faster than accepted answer and 5X faster than the slowest answer here.

To be fair, all methods needed to do inlace replacement of the array sent to the function.

Please see timing code below:

def f1(arr, find, replace):
    # fast and readable
    base=0
    for cnt in range(arr.count(find)):
        offset=arr.index(find, base)
        arr[offset]=replace
        base=offset+1
        
def f2(arr,find,replace):
    # accepted answer
    for i,e in enumerate(arr):
        if e==find: 
            arr[i]=replace
        
def f3(arr,find,replace):
    # in place list comprehension
    arr[:]=[replace if e==find else e for e in arr]
    
def f4(arr,find,replace):
    # in place map and lambda -- SLOW
    arr[:]=list(map(lambda x: x if x != find else replace, arr))
    
def f5(arr,find,replace):
    # find index with comprehension
    for i in [i for i, e in enumerate(arr) if e==find]:
        arr[i]=replace
        
def f6(arr,find,replace):
    # FASTEST but a little les clear
    try:
        while True:
            arr[arr.index(find)]=replace
    except ValueError:
        pass    

def f7(lst, old, new):
    """replace list elements (inplace)"""
    i = -1
    try:
        while 1:
            i = lst.index(old, i + 1)
            lst[i] = new
    except ValueError:
        pass
    
    
import time     

def cmpthese(funcs, args=(), cnt=1000, rate=True, micro=True):
    """Generate a Perl style function benchmark"""                   
    def pprint_table(table):
        """Perl style table output"""
        def format_field(field, fmt='{:,.0f}'):
            if type(field) is str: return field
            if type(field) is tuple: return field[1].format(field[0])
            return fmt.format(field)     

        def get_max_col_w(table, index):
            return max([len(format_field(row[index])) for row in table])         

        col_paddings=[get_max_col_w(table, i) for i in range(len(table[0]))]
        for i,row in enumerate(table):
            # left col
            row_tab=[row[0].ljust(col_paddings[0])]
            # rest of the cols
            row_tab+=[format_field(row[j]).rjust(col_paddings[j]) for j in range(1,len(row))]
            print(' '.join(row_tab))                

    results={}
    for i in range(cnt):
        for f in funcs:
            start=time.perf_counter_ns()
            f(*args)
            stop=time.perf_counter_ns()
            results.setdefault(f.__name__, []).append(stop-start)
    results={k:float(sum(v))/len(v) for k,v in results.items()}     
    fastest=sorted(results,key=results.get, reverse=True)
    table=[['']]
    if rate: table[0].append('rate/sec')
    if micro: table[0].append('\u03bcsec/pass')
    table[0].extend(fastest)
    for e in fastest:
        tmp=[e]
        if rate:
            tmp.append('{:,}'.format(int(round(float(cnt)*1000000.0/results[e]))))

        if micro:
            tmp.append('{:,.1f}'.format(results[e]/float(cnt)))

        for x in fastest:
            if x==e: tmp.append('--')
            else: tmp.append('{:.1%}'.format((results[x]-results[e])/results[e]))
        table.append(tmp) 

    pprint_table(table)                    



if __name__=='__main__':
    import sys
    import time 
    print(sys.version)
    cases=(
        ('small, found', 9, 100),
        ('small, not found', 99, 100),
        ('large, found', 9, 1000),
        ('large, not found', 99, 1000)
    )
    for txt, tgt, mul in cases:
        print(f'\n{txt}:')
        arr=[1,2,3,4,5,6,7,8,9,0]*mul 
        args=(arr,tgt,'X')
        cmpthese([f1,f2,f3, f4, f5, f6, f7],args)   

And the results:

3.9.1 (default, Feb  3 2021, 07:38:02) 
[Clang 12.0.0 (clang-1200.0.32.29)]

small, found:
   rate/sec µsec/pass     f4     f3     f5     f2     f6     f7     f1
f4  133,982       7.5     -- -38.8% -49.0% -52.5% -78.5% -78.6% -82.9%
f3  219,090       4.6  63.5%     -- -16.6% -22.4% -64.8% -65.0% -72.0%
f5  262,801       3.8  96.1%  20.0%     --  -6.9% -57.8% -58.0% -66.4%
f2  282,259       3.5 110.7%  28.8%   7.4%     -- -54.6% -54.9% -63.9%
f6  622,122       1.6 364.3% 184.0% 136.7% 120.4%     --  -0.7% -20.5%
f7  626,367       1.6 367.5% 185.9% 138.3% 121.9%   0.7%     -- -19.9%
f1  782,307       1.3 483.9% 257.1% 197.7% 177.2%  25.7%  24.9%     --

small, not found:
   rate/sec µsec/pass     f4     f5     f2     f3     f6     f7     f1
f4   13,846      72.2     -- -40.3% -41.4% -47.8% -85.2% -85.4% -86.2%
f5   23,186      43.1  67.5%     --  -1.9% -12.5% -75.2% -75.5% -76.9%
f2   23,646      42.3  70.8%   2.0%     -- -10.8% -74.8% -75.0% -76.4%
f3   26,512      37.7  91.5%  14.3%  12.1%     -- -71.7% -72.0% -73.5%
f6   93,656      10.7 576.4% 303.9% 296.1% 253.3%     --  -1.0%  -6.5%
f7   94,594      10.6 583.2% 308.0% 300.0% 256.8%   1.0%     --  -5.6%
f1  100,206      10.0 623.7% 332.2% 323.8% 278.0%   7.0%   5.9%     --

large, found:
   rate/sec µsec/pass     f4     f2     f5     f3     f6     f7     f1
f4      145   6,889.4     -- -33.3% -34.8% -48.6% -85.3% -85.4% -85.8%
f2      218   4,593.5  50.0%     --  -2.2% -22.8% -78.0% -78.1% -78.6%
f5      223   4,492.4  53.4%   2.3%     -- -21.1% -77.5% -77.6% -78.2%
f3      282   3,544.0  94.4%  29.6%  26.8%     -- -71.5% -71.6% -72.3%
f6      991   1,009.5 582.4% 355.0% 345.0% 251.1%     --  -0.4%  -2.8%
f7      995   1,005.4 585.2% 356.9% 346.8% 252.5%   0.4%     --  -2.4%
f1    1,019     981.3 602.1% 368.1% 357.8% 261.2%   2.9%   2.5%     --

large, not found:
   rate/sec µsec/pass     f4     f5     f2     f3     f6     f7     f1
f4      147   6,812.0     -- -35.0% -36.4% -48.9% -85.7% -85.8% -86.1%
f5      226   4,424.8  54.0%     --  -2.0% -21.3% -78.0% -78.1% -78.6%
f2      231   4,334.9  57.1%   2.1%     -- -19.6% -77.6% -77.7% -78.2%
f3      287   3,484.0  95.5%  27.0%  24.4%     -- -72.1% -72.2% -72.8%
f6    1,028     972.3 600.6% 355.1% 345.8% 258.3%     --  -0.4%  -2.7%
f7    1,033     968.2 603.6% 357.0% 347.7% 259.8%   0.4%     --  -2.3%
f1    1,057     946.2 619.9% 367.6% 358.1% 268.2%   2.8%   2.3%     --

Dark color scheme for Eclipse

These are the pleasing colors for my eyes during coding. Jazz music not included in theme.

Screenshot of LukinaJama3

Eclipse Color Themes Plugin file: LukinaJama3.xml on depositfiles

how to align img inside the div to the right?

vertical-align:middle; text-align:right;

Does :before not work on img elements?

Just give the Image "position: relative" and it will work

Oracle date to string conversion

Try this. Oracle has this feature to distinguish the millennium years..

As you mentioned, if your column is a varchar, then the below query will yield you 1989..

select to_date(column_name,'dd/mm/rr') from table1;

When the format rr is used in year, the following would be done by oracle.

if rr->00 to 49 ---> result will be 2000 - 2049, if rr->50 to 99 ---> result will be 1950 - 1999

Convert a string to an enum in C#

public static T ParseEnum<T>(string value)            //function declaration  
{
    return (T) Enum.Parse(typeof(T), value);
}

Importance imp = EnumUtil.ParseEnum<Importance>("Active");   //function call

====================A Complete Program====================

using System;

class Program
{
    enum PetType
    {
    None,
    Cat = 1,
    Dog = 2
    }

    static void Main()
    {

    // Possible user input:
    string value = "Dog";

    // Try to convert the string to an enum:
    PetType pet = (PetType)Enum.Parse(typeof(PetType), value);

    // See if the conversion succeeded:
    if (pet == PetType.Dog)
    {
        Console.WriteLine("Equals dog.");
    }
    }
}
-------------
Output

Equals dog.

How to remove class from all elements jquery

The best to remove a class in jquery from all the elements is to target via element tag. e.g.,

$("div").removeClass("highlight");

How do I use PHP namespaces with autoload?

I'll throw in my two cents for relative beginners or whatnot wanting a simple spl_autoload_register() setup without all the theory: Just create one php file for each class, name that php file the same as your class name, and keep your class files in the same directory as your php file in question, then this will work:

spl_autoload_register(function ($class_name) {
    require_once dirname(__FILE__) . DIRECTORY_SEPARATOR . $class_name . '.php';
});

Googling the pieces inside this function should answer how it works. PS: I use Linux, and this works on Linux. Windows folks should test it out first.

If input value is blank, assign a value of "empty" with Javascript

If you're using pure JS you can simply do it like:

var input = document.getElementById('myInput');

if(input.value.length == 0)
    input.value = "Empty";

Here's a demo: http://jsfiddle.net/nYtm8/

Adding value labels on a matplotlib bar chart

Firstly freq_series.plot returns an axis not a figure so to make my answer a little more clear I've changed your given code to refer to it as ax rather than fig to be more consistent with other code examples.

You can get the list of the bars produced in the plot from the ax.patches member. Then you can use the technique demonstrated in this matplotlib gallery example to add the labels using the ax.text method.

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

# Bring some raw data.
frequencies = [6, 16, 75, 160, 244, 260, 145, 73, 16, 4, 1]
# In my original code I create a series and run on that, 
# so for consistency I create a series from the list.
freq_series = pd.Series.from_array(frequencies)

x_labels = [108300.0, 110540.0, 112780.0, 115020.0, 117260.0, 119500.0,
            121740.0, 123980.0, 126220.0, 128460.0, 130700.0]

# Plot the figure.
plt.figure(figsize=(12, 8))
ax = freq_series.plot(kind='bar')
ax.set_title('Amount Frequency')
ax.set_xlabel('Amount ($)')
ax.set_ylabel('Frequency')
ax.set_xticklabels(x_labels)

rects = ax.patches

# Make some labels.
labels = ["label%d" % i for i in xrange(len(rects))]

for rect, label in zip(rects, labels):
    height = rect.get_height()
    ax.text(rect.get_x() + rect.get_width() / 2, height + 5, label,
            ha='center', va='bottom')

This produces a labeled plot that looks like:

enter image description here

Difference between a theta join, equijoin and natural join

@outis's answer is good: concise and correct as regards relations.

However, the situation is slightly more complicated as regards SQL.

Consider the usual suppliers and parts database but implemented in SQL:

SELECT * FROM S NATURAL JOIN SP;

would return a resultset** with columns

SNO, SNAME, STATUS, CITY, PNO, QTY

The join is performed on the column with the same name in both tables, SNO. Note that the resultset has six columns and only contains one column for SNO.

Now consider a theta eqijoin, where the column names for the join must be explicitly specified (plus range variables S and SP are required):

SELECT * FROM S JOIN SP ON S.SNO = SP.SNO;

The resultset will have seven columns, including two columns for SNO. The names of the resultset are what the SQL Standard refers to as "implementation dependent" but could look like this:

SNO, SNAME, STATUS, CITY, SNO, PNO, QTY

or perhaps this

S.SNO, SNAME, STATUS, CITY, SP.SNO, PNO, QTY

In other words, NATURAL JOIN in SQL can be considered to remove columns with duplicated names from the resultset (but alas will not remove duplicate rows - you must remember to change SELECT to SELECT DISTINCT yourself).


** I don't quite know what the result of SELECT * FROM table_expression; is. I know it is not a relation because, among other reasons, it can have columns with duplicate names or a column with no name. I know it is not a set because, among other reasons, the column order is significant. It's not even a SQL table or SQL table expression. I call it a resultset.

Change Placeholder Text using jQuery

this worked for me:

jQuery('form').attr("placeholder","Wert eingeben");

but now this don't work:

// Prioritize "important" elements on medium.
            skel.on('+medium -medium', function() {
                jQuery.prioritize(
                    '.important\\28 medium\\29',
                    skel.breakpoint('medium').active
                );
            });

Disable validation of HTML5 form elements

The best solution is to use a text input and add the attribute inputmode="url" to provide the URL keyboard facilities. The HTML5 specification was thought for this purpose. If you keep type="url" you get the syntax validation which is not useful in every case (it is better to check if it returns a 404 error instead of the syntax which is quite permissive and is not of a great help).

You also have the possibility to override the default pattern with the attribute pattern="https?://.+" for example to be more permissive.

Putting the novalidate attribute to the form is not the right answer to the asked question because it removes validation for all the fields in the form and you may want to keep validation for email fields for example.

Using jQuery to disable validation is also a bad solution because it should absolutely work without JavaScript.

In my case, I put a select element with 2 options (http:// or https://) before the URL input because I just need websites (and no ftp:// or other things). This way I avoid typing this weird prefix (the biggest regret of Tim Berners-Lee and maybe the main source of URL syntax errors) and I use a simple text input with inputmode="url" with placeholders (without HTTP). I use jQuery and server side script to validate the real existence of the web site (no 404) and to remove the HTTP prefix if inserted (I avoid to use a pattern like pattern="^((?http).)*$" to prevent putting the prefix because I think it is better to be more permissive)

SQL update from one Table to another based on a ID match

The simple Way to copy the content from one table to other is as follow:

UPDATE table2 
SET table2.col1 = table1.col1, 
table2.col2 = table1.col2,
...
FROM table1, table2 
WHERE table1.memberid = table2.memberid

You can also add the condition to get the particular data copied.

How to create multiple output paths in Webpack config

If it's not obvious after all the answers you can also output to a completely different directories (for example a directory outside your standard dist folder). You can do that by using your root as a path (because you only have one path) and by moving the full "directory part" of your path to the entry option (because you can have multiple entries):

entry: {
  'dist/main': './src/index.js',
  'docs/main': './src/index.js'
},
output: {
  filename: '[name].js',
  path: path.resolve(__dirname, './'),
}

This config results in the ./dist/main.js and ./docs/main.js being created.

How to set custom JsonSerializerSettings for Json.NET in ASP.NET Web API?

You can customize the JsonSerializerSettings by using the Formatters.JsonFormatter.SerializerSettings property in the HttpConfiguration object.

For example, you could do that in the Application_Start() method:

protected void Application_Start()
{
    HttpConfiguration config = GlobalConfiguration.Configuration;
    config.Formatters.JsonFormatter.SerializerSettings.Formatting =
        Newtonsoft.Json.Formatting.Indented;
}

SQL Row_Number() function in Where Clause

based on OP's answer to question:

Please see this link. Its having a different solution, which looks working for the person who asked the question. I'm trying to figure out a solution like this.

Paginated query using sorting on different columns using ROW_NUMBER() OVER () in SQL Server 2005

~Joseph

"method 1" is like the OP's query from the linked question, and "method 2" is like the query from the selected answer. You had to look at the code linked in this answer to see what was really going on, since the code in the selected answer was modified to make it work. Try this:

DECLARE @YourTable table (RowID int not null primary key identity, Value1 int, Value2 int, value3 int)
SET NOCOUNT ON
INSERT INTO @YourTable VALUES (1,1,1)
INSERT INTO @YourTable VALUES (1,1,2)
INSERT INTO @YourTable VALUES (1,1,3)
INSERT INTO @YourTable VALUES (1,2,1)
INSERT INTO @YourTable VALUES (1,2,2)
INSERT INTO @YourTable VALUES (1,2,3)
INSERT INTO @YourTable VALUES (1,3,1)
INSERT INTO @YourTable VALUES (1,3,2)
INSERT INTO @YourTable VALUES (1,3,3)
INSERT INTO @YourTable VALUES (2,1,1)
INSERT INTO @YourTable VALUES (2,1,2)
INSERT INTO @YourTable VALUES (2,1,3)
INSERT INTO @YourTable VALUES (2,2,1)
INSERT INTO @YourTable VALUES (2,2,2)
INSERT INTO @YourTable VALUES (2,2,3)
INSERT INTO @YourTable VALUES (2,3,1)
INSERT INTO @YourTable VALUES (2,3,2)
INSERT INTO @YourTable VALUES (2,3,3)
INSERT INTO @YourTable VALUES (3,1,1)
INSERT INTO @YourTable VALUES (3,1,2)
INSERT INTO @YourTable VALUES (3,1,3)
INSERT INTO @YourTable VALUES (3,2,1)
INSERT INTO @YourTable VALUES (3,2,2)
INSERT INTO @YourTable VALUES (3,2,3)
INSERT INTO @YourTable VALUES (3,3,1)
INSERT INTO @YourTable VALUES (3,3,2)
INSERT INTO @YourTable VALUES (3,3,3)
SET NOCOUNT OFF

DECLARE @PageNumber     int
DECLARE @PageSize       int
DECLARE @SortBy         int

SET @PageNumber=3
SET @PageSize=5
SET @SortBy=1


--SELECT * FROM @YourTable

--Method 1
;WITH PaginatedYourTable AS (
SELECT
    RowID,Value1,Value2,Value3
        ,CASE @SortBy
             WHEN  1 THEN ROW_NUMBER() OVER (ORDER BY Value1 ASC)
             WHEN  2 THEN ROW_NUMBER() OVER (ORDER BY Value2 ASC)
             WHEN  3 THEN ROW_NUMBER() OVER (ORDER BY Value3 ASC)
             WHEN -1 THEN ROW_NUMBER() OVER (ORDER BY Value1 DESC)
             WHEN -2 THEN ROW_NUMBER() OVER (ORDER BY Value2 DESC)
             WHEN -3 THEN ROW_NUMBER() OVER (ORDER BY Value3 DESC)
         END AS RowNumber
    FROM @YourTable
    --WHERE
)
SELECT
    RowID,Value1,Value2,Value3,RowNumber
        ,@PageNumber AS PageNumber, @PageSize AS PageSize, @SortBy AS SortBy
    FROM PaginatedYourTable
    WHERE RowNumber>=(@PageNumber-1)*@PageSize AND RowNumber<=(@PageNumber*@PageSize)-1
    ORDER BY RowNumber



--------------------------------------------
--Method 2
;WITH PaginatedYourTable AS (
SELECT
    RowID,Value1,Value2,Value3
        ,ROW_NUMBER() OVER
         (
             ORDER BY
                 CASE @SortBy
                     WHEN  1 THEN Value1
                     WHEN  2 THEN Value2
                     WHEN  3 THEN Value3
                 END ASC
                ,CASE @SortBy
                     WHEN -1 THEN Value1
                     WHEN -2 THEN Value2
                     WHEN -3 THEN Value3
                 END DESC
         ) RowNumber
    FROM @YourTable
    --WHERE  more conditions here
)
SELECT
    RowID,Value1,Value2,Value3,RowNumber
        ,@PageNumber AS PageNumber, @PageSize AS PageSize, @SortBy AS SortBy
    FROM PaginatedYourTable
    WHERE 
        RowNumber>=(@PageNumber-1)*@PageSize AND RowNumber<=(@PageNumber*@PageSize)-1
        --AND more conditions here
    ORDER BY
        CASE @SortBy
            WHEN  1 THEN Value1
            WHEN  2 THEN Value2
            WHEN  3 THEN Value3
        END ASC
       ,CASE @SortBy
            WHEN -1 THEN Value1
            WHEN -2 THEN Value2
            WHEN -3 THEN Value3
        END DESC

OUTPUT:

RowID  Value1 Value2 Value3 RowNumber  PageNumber  PageSize    SortBy
------ ------ ------ ------ ---------- ----------- ----------- -----------
10     2      1      1      10         3           5           1
11     2      1      2      11         3           5           1
12     2      1      3      12         3           5           1
13     2      2      1      13         3           5           1
14     2      2      2      14         3           5           1

(5 row(s) affected

RowID  Value1 Value2 Value3 RowNumber  PageNumber  PageSize    SortBy
------ ------ ------ ------ ---------- ----------- ----------- -----------
10     2      1      1      10         3           5           1
11     2      1      2      11         3           5           1
12     2      1      3      12         3           5           1
13     2      2      1      13         3           5           1
14     2      2      2      14         3           5           1

(5 row(s) affected)

Android custom Row Item for ListView

create resource layout file list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
          android:orientation="vertical"
          android:layout_width="match_parent"
          android:layout_height="wrap_content">
<TextView
        android:id="@+id/header_text"
        android:layout_height="0dp"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        android:text="Header"
        />
<TextView
        android:id="@+id/item_text"
        android:layout_height="0dp"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        android:text="dynamic text"
        />
</LinearLayout>

and initialise adaptor like this

adapter = new ArrayAdapter<String>(this, R.layout.list_item,R.id.item_text,data_array);

The imported project "C:\Microsoft.CSharp.targets" was not found

I used to have this following line in the csproj file:

<Import Project="$(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v10.0\WebApplications\Microsoft.WebApplication.targets" />

After deleting this file, it works fine.

What does the arrow operator, '->', do in Java?

It's a lambda expression.

It means that, from the listOfCars, arg0 is one of the items of that list. With that item he is going to do, hence the ->, whatever is inside of the brackets.

In this example, he's going to return a list of cars that fit the condition

Car.SEDAN == ((Car)arg0).getStyle();

Concrete Javascript Regex for Accented Characters (Diacritics)

What about this?

^([a-zA-Z]|[à-ú]|[À-Ú])+$

It will match every word with accented characters or not.

Converting HTML to Excel?

So long as Excel can open the file, the functionality to change the format of the opened file is built in.

To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).

To do it using VBA, the code would look like this:

Sub Open_HTML_Save_XLSX()

    Workbooks.Open Filename:="C:\Temp\Example.html"
    ActiveWorkbook.SaveAs Filename:= _
        "C:\Temp\Example.xlsx", FileFormat:= _
        xlOpenXMLWorkbook

End Sub

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I recommend to use SMO (Enable TCP/IP Network Protocol for SQL Server). However, it was not available in my case.

I rewrote the WMI commands from Krzysztof Kozielczyk to PowerShell.

# Enable TCP/IP

Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocol -Filter "InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'" |
Invoke-CimMethod -Name SetEnable

# Open the right ports in the firewall
New-NetFirewallRule -DisplayName 'MSSQL$SQLEXPRESS' -Direction Inbound -Action Allow -Protocol TCP -LocalPort 1433

# Modify TCP/IP properties to enable an IP address

$properties = Get-CimInstance -Namespace root/Microsoft/SqlServer/ComputerManagement10 -ClassName ServerNetworkProtocolProperty -Filter "InstanceName='SQLEXPRESS' and ProtocolName = 'Tcp' and IPAddressName='IPAll'"
$properties | ? { $_.PropertyName -eq 'TcpPort' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '1433' }
$properties | ? { $_.PropertyName -eq 'TcpPortDynamic' } | Invoke-CimMethod -Name SetStringValue -Arguments @{ StrValue = '' }

# Restart SQL Server

Restart-Service 'MSSQL$SQLEXPRESS'

How to clone git repository with specific revision/changeset?

You Can use simply git checkout <commit hash>

in this sequence

bash git clone [URLTORepository] git checkout [commithash]

commit hash looks like this "45ef55ac20ce2389c9180658fdba35f4a663d204"

Set environment variables from file of key/value pairs

Building on other answers, here is a way to export only a subset of lines in a file, including values with spaces like PREFIX_ONE="a word":

set -a
. <(grep '^[ ]*PREFIX_' conf-file)
set +a

Input mask for numeric and decimal

Use tow function to solve it ,Very simple and useful:

HTML:

<input class="int-number" type="text" />
<input class="decimal-number" type="text" />

JQuery:

//Integer Number
$(document).on("input", ".int-number", function (e) {
  this.value = this.value.replace(/[^0-9]/g, '');
});

//Decimal Number
$(document).on("input", ".decimal-number", function (e) {
    this.value = this.value.replace(/[^0-9.]/g, '').replace(/(\..*)\./g, '$1');
});

What’s the difference between Response.Write() andResponse.Output.Write()?

Response.write() is used to display the normal text and Response.output.write() is used to display the formated text.

PHP preg replace only allow numbers

This should do what you want:

preg_replace("/[^0-9]/", "",$c);

How to print current date on python3?

I always use this code, which print the year to second in a tuple

import datetime

now = datetime.datetime.now()

time_now = (now.year, now.month, now.day, now.hour, now.minute, now.second)

print(time_now)

JavaScript: function returning an object

You can simply do it like this with an object literal:

function makeGamePlayer(name,totalScore,gamesPlayed) {
    return {
        name: name,
        totalscore: totalScore,
        gamesPlayed: gamesPlayed
    };
}

Correct way to try/except using Python requests module?

One additional suggestion to be explicit. It seems best to go from specific to general down the stack of errors to get the desired error to be caught, so the specific ones don't get masked by the general one.

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)

Http Error: 404 Client Error: Not Found for url: http://www.google.com/blahblah

vs

url='http://www.google.com/blahblah'

try:
    r = requests.get(url,timeout=3)
    r.raise_for_status()
except requests.exceptions.RequestException as err:
    print ("OOps: Something Else",err)
except requests.exceptions.HTTPError as errh:
    print ("Http Error:",errh)
except requests.exceptions.ConnectionError as errc:
    print ("Error Connecting:",errc)
except requests.exceptions.Timeout as errt:
    print ("Timeout Error:",errt)     

OOps: Something Else 404 Client Error: Not Found for url: http://www.google.com/blahblah

Get the value of checked checkbox?

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  var ckbox = $("input[name='ips']");_x000D_
  var chkId = '';_x000D_
  $('input').on('click', function() {_x000D_
    _x000D_
    if (ckbox.is(':checked')) {_x000D_
      $("input[name='ips']:checked").each ( function() {_x000D_
      chkId = $(this).val() + ",";_x000D_
        chkId = chkId.slice(0, -1);_x000D_
    });_x000D_
       _x000D_
       alert ( $(this).val() ); // return all values of checkboxes checked_x000D_
       alert(chkId); // return value of checkbox checked_x000D_
    }     _x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="ips" value="12520">_x000D_
<input type="checkbox" name="ips" value="12521">_x000D_
<input type="checkbox" name="ips" value="12522">
_x000D_
_x000D_
_x000D_

Communication between tabs or windows

I created a module that works equal to the official Broadcastchannel but has fallbacks based on localstorage, indexeddb and unix-sockets. This makes sure it always works even with Webworkers or NodeJS. See pubkey:BroadcastChannel

Cannot open include file: 'stdio.h' - Visual Studio Community 2017 - C++ Error

Similar problem for me but a little different. I can compile and run the default CUDA 10 code with no problem, but there are a lots of error related to the stdio.h file show in the edit window. Which is annoying. I solve it by change the code file name from "kernel.cu" to "kernel.cpp". That is wired but works for me. And it runs well so far.

Print second last column/field in awk

You weren't far from the result! This does it:

awk '{NF--; print $NF}' file

This decrements the number of fields in one, so that $NF contains the former penultimate.

Test

Let's generate some numbers and print them on groups of 5:

$ seq 12 | xargs -n5
1 2 3 4 5
6 7 8 9 10
11 12

Let's print the penultimate on each line:

$ seq 12 | xargs -n5 | awk '{NF--; print $NF}'
4
9
11

Can I call a constructor from another constructor (do constructor chaining) in C++?

If I understand your question correctly, you're asking if you can call multiple constructors in C++?

If that's what you're looking for, then no - that is not possible.

You certainly can have multiple constructors, each with unique argument signatures, and then call the one you want when you instantiate a new object.

You can even have one constructor with defaulted arguments on the end.

But you may not have multiple constructors, and then call each of them separately.

Check if file is already open

Using the Apache Commons IO library...

boolean isFileUnlocked = false;
try {
    org.apache.commons.io.FileUtils.touch(yourFile);
    isFileUnlocked = true;
} catch (IOException e) {
    isFileUnlocked = false;
}

if(isFileUnlocked){
    // Do stuff you need to do with a file that is NOT locked.
} else {
    // Do stuff you need to do with a file that IS locked
}

Getting value from JQUERY datepicker

To position the datepicker next to the input field you could use following code.

$('#datepicker').datepicker({
    beforeShow: function(input, inst)
    {
        inst.dpDiv.css({marginLeft: input.offsetWidth + 'px'});
    }
});

How to build splash screen in windows forms application?

Try this code

public partial class ssplashscreen : Form
    {
        public ssplashscreen()
        {                
            InitializeComponent();    
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            progressBar1.Increment(1);
            if (progressBar1.Value == 100)
            {
                timer1.Stop();
                this.Hide();
                Form frm = new login();
                frm.Show();
            }
        }
    }

Selenium -- How to wait until page is completely loaded

3 answers, which you can combine:

  1. Set implicit wait immediately after creating the web driver instance:

    _ = driver.Manage().Timeouts().ImplicitWait;

    This will try to wait until the page is fully loaded on every page navigation or page reload.

  2. After page navigation, call JavaScript return document.readyState until "complete" is returned. The web driver instance can serve as JavaScript executor. Sample code:

    C#

    new WebDriverWait(driver, MyDefaultTimeout).Until(
    d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
    

    Java

    new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
          webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
    
  3. Check if the URL matches the pattern you expect.

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

This means the file isn't really a gzipped tar file -- or any kind of gzipped file -- in spite of being named like one.

When you download a file with wget, check for indications like Length: unspecified [text/html] which shows it is plain text (text) and that it is intended to be interpreted as html. Check the wget output below -

[root@XXXXX opt]# wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz"
--2017-10-12 12:39:40--  http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving download.oracle.com (download.oracle.com)... 23.72.136.27, 23.72.136.67
Connecting to download.oracle.com (download.oracle.com)|23.72.136.27|:80... connected.
HTTP request sent, awaiting response... 302 Not Allowed
Location: http://XXXX/FAQs/URLFiltering/ProxyWarning.html [following]
--2017-10-12 12:39:40--  http://XXXX/FAQs/URLFiltering/ProxyWarning.html
Resolving XXXX (XXXXX)... XXX.XX.XX.XXX
Connecting to XXXX (XXXX)|XXX.XX.XX.XXX|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 17121 (17K) [text/html]
Saving to: ‘jdk-8u144-linux-x64.tar.gz’

100%[=========================================================================================================================================================================>] 17,121      --.-K/s   in 0.05s   

2017-10-12 12:39:40 (349 KB/s) - ‘jdk-8u144-linux-x64.tar.gz’ saved [17121/17121]

This sort of confirms that you haven't received a gzip file.

For a correct file, the wget output will show something like Length: 185515842 (177M) [application/x-gzip] as shown in the below output -

[root@txcdtl01ss270n opt]# wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz"
--2017-10-12 12:50:06--  http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving download.oracle.com (download.oracle.com)... XX.XXX.XX.XX, XX.XX.XXX.XX
Connecting to download.oracle.com (download.oracle.com)|XX.XX.XXX.XX|:80... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: https://edelivery.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz [following]
--2017-10-12 12:50:06--  https://edelivery.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz
Resolving edelivery.oracle.com (edelivery.oracle.com)... XXX.XX.XXX.XX, 2600:1404:16:188::2d3e, 2600:1404:16:180::2d3e
Connecting to edelivery.oracle.com (edelivery.oracle.com)|XXX.XX.XX.XXX|:443... connected.
HTTP request sent, awaiting response... 302 Moved Temporarily
Location: http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz?AuthParam=1507827127_f44251ebbb44c6e61e7f202677f94afd [following]
--2017-10-12 12:50:07--  http://download.oracle.com/otn-pub/java/jdk/8u144-b01/090f390dda5b47b9b721c7dfaa008135/jdk-8u144-linux-x64.tar.gz?AuthParam=1507827127_f44251ebbb44c6e61
Connecting to download.oracle.com (download.oracle.com)|XX.XX.XXX.XX|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 185515842 (177M) [application/x-gzip]
Saving to: ‘jdk-8u144-linux-x64.tar.gz’

100%[=========================================================================================================================================================================>] 185,515,842 6.60MB/s   in 28s    

2017-10-12 12:50:34 (6.43 MB/s) - ‘jdk-8u144-linux-x64.tar.gz’ saved [185515842/185515842]

The above shows a correct gzip application file has been downloaded.

You can also file, head, less, view utilities to check the file. For example a HTML file would give below output -

[root@XXXXXX opt]# head jdk-8u144-linux-x64.tar.gz
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link href="/css/print.css" rel="stylesheet" media="print">
    <link href="/css/main.css" rel="stylesheet" media="screen">
    <link href="/css/font-awesome.min.css" rel="stylesheet">

The above shows it is indeed an HTML page which we are trying to unzip/untar - something that won't work. If it was indeed a correct zip file (binary in nature) the output of head would have produced garbage - something like below -

[root@XXXX opt]# head jdk-8u144-linux-x64.tar.gz 
x?rY?[ms?F???????t?l???DR??????j
                                       $?$,`0?h?_????/??=?@Q?w+???*?Hbfz?{?~?{?i?x??k?????}????z???w????g?????{???;{s????w?????7?N????i?
?????}
?¿g????????????7??s??????î??????~i??j?/??????#???=??=>???{}??|?????????????3???X???]9??????u?????%g?<^)?H?8?F?R?t?o?L?u??S%?ds5?2_EZn?t^??
                                                                                                                                                 ?N3??(??<??|'?q???R?N?gq?Uv!???p???rL??M??u??.?Q?5?T??BNw?!$??<>?7G'$?,Mt4WY?Gi"?=??p?)?VIN3????\ek??0??G
                                            ?<L?c?e?t-???2???G:?ia??I?<?g3???d?H????[2`?<I?A?6?W??<??C???????h??A0QL?2?4?-*
?x?????t%t1??f?>+A??,Lr?
                        ?Fe:MBH????
C?Q?r?S??<M?b?<,5???@???s???c??sp?f?=g?????k???4?}??kh)?¹Z??#d?*{???-?.N?)?e??s:?H(VQ??3*?$2??r?v?"o?_??!A???????B?l=A?|??@??0??1??5??4g?
?
???Se????H[2?????t??5?Df????$1???b$? h?Op????!Lvb!p??b?8^?Y???n?
                                                                          O??????|??lW?lu??*?N?M???
?/?^0~?~?#??q????????K??;?d???aw4?????'?~?7??ky?o?????????t?'k??f????!vo???'o???     ?.?Pn\?
               ?+??K"FA{????n2????v??!/Ok??r4?c5?x$'?.?&w?!?%??o??????2???i
                                                                               ?a0??Ag?d????GH)G7~?g???b??%?b??rt?m~?   ?????t0??   <????????????5?q?t??K(??+Z<??=???:1?\?x?p=t?`??G@F??    i?????p8?????H.???dMLE??e[?`?'n??*h[??;?0w'??6A??M?x?fpeB>&???MO???????`?@á/?"?????(??^???n??=????5??@?Mx??d:\YAn???]|?w>??S??FA9?J?k!?@?

Try downloading from the official site and check if their download links have changed. Also check your proxy settings and make sure you have the right proxies enabled to download/wget it from the correct source.

Hope this helps.

Install gitk on Mac

As of macOS Catalina 10.15.6, I run:

brew install git
brew install git-gui

and it worked for me.

How to set a default value with Html.TextBoxFor?

This should work for MVC3 & MVC4

 @Html.TextBoxFor(m => m.Age, new { @Value = "12" }) 

If you want it to be a hidden field

 @Html.TextBoxFor(m => m.Age, new { @Value = "12",@type="hidden" }) 

Why I can't access remote Jupyter Notebook server?

I got the same problem but none of workarounds above work for me. But if I setup a docker version jupyter notebook, with the same configuration, it works out for me.

For my stituation, it might be iptables rule issues. Sometimes you may just using ufw to allow all route to your server. But mine just iptables -F to clear all rule. Then check iptables -L -n to see if its works.

Problem fixed.

How to bind 'touchstart' and 'click' events but not respond to both?

I just came up with the idea to memorize if ontouchstart was ever triggered. In this case we are on a device which supports it and want to ignore the onclick event. Since ontouchstart should always be triggered before onclick, I'm using this:

_x000D_
_x000D_
<script> touchAvailable = false; </script>_x000D_
<button ontouchstart="touchAvailable=true; myFunction();" onclick="if(!touchAvailable) myFunction();">Button</button>
_x000D_
_x000D_
_x000D_

What is the simplest way to swap each pair of adjoining chars in a string with Python?

To swap characters in a string a of position l and r

def swap(a, l, r):
    a = a[0:l] + a[r] + a[l+1:r] + a[l] + a[r+1:]
    return a

Example: swap("aaabcccdeee", 3, 7) returns "aaadcccbeee"

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Please check if you got the x64 edition of eclipse. Someone answered this just a few hours ago.

How do I view the Explain Plan in Oracle Sql developer?

Explain only shows how the optimizer thinks the query will execute.

To show the real plan, you will need to run the sql once. Then use the same session run the following:

@yoursql 
select * from table(dbms_xplan.display_cursor()) 

This way can show the real plan used during execution. There are several other ways in showing plan using dbms_xplan. You can Google with term "dbms_xplan".

New self vs. new static

will I get the same results?

Not really. I don't know of a workaround for PHP 5.2, though.

What is the difference between new self and new static?

self refers to the same class in which the new keyword is actually written.

static, in PHP 5.3's late static bindings, refers to whatever class in the hierarchy you called the method on.

In the following example, B inherits both methods from A. The self invocation is bound to A because it's defined in A's implementation of the first method, whereas static is bound to the called class (also see get_called_class()).

class A {
    public static function get_self() {
        return new self();
    }

    public static function get_static() {
        return new static();
    }
}

class B extends A {}

echo get_class(B::get_self());  // A
echo get_class(B::get_static()); // B
echo get_class(A::get_self()); // A
echo get_class(A::get_static()); // A

Change Toolbar color in Appcompat 21

UPDATE 12/11/2019: Material Components Library

With the Material Components and Androidx libraries you can use:

  • the android:background attribute in the layout:

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
    
  • apply the default style: style="@style/Widget.MaterialComponents.Toolbar.Primary" or customize the style inheriting from it:

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        style="@style/Widget.MaterialComponents.Toolbar.Primary"
    
  • override the default color using the android:theme attribute:

    <com.google.android.material.appbar.MaterialToolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/MyThemeOverlay_Toolbar"
    

with:

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <item name="android:textColorPrimary">....</item>
    <item name="colorPrimary">@color/.....
    <item name="colorOnPrimary">@color/....</item>
  </style>

OLD: Support libraries:
You can use a app:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar" theme as suggested in other answers, but you can also use a solution like this:

<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    style="@style/HeaderBar"
    app:theme="@style/ActionBarThemeOverlay"
    app:popupTheme="@style/ActionBarPopupThemeOverlay"/>

And you can have the full control of your ui elements with these styles:

<style name="ActionBarThemeOverlay" parent="">
    <item name="android:textColorPrimary">#fff</item>
    <item name="colorControlNormal">#fff</item>
    <item name="colorControlHighlight">#3fff</item>
</style>

<style name="HeaderBar">
    <item name="android:background">?colorPrimary</item>
</style>

<style name="ActionBarPopupThemeOverlay" parent="ThemeOverlay.AppCompat.Light" >
    <item name="android:background">@android:color/white</item>
    <item name="android:textColor">#000</item>
</style>

How do I search for an object by its ObjectId in the mongo console?

To use Objectid method you don't need to import it. It is already on the mongodb object.

_x000D_
_x000D_
var ObjectId = new db.ObjectId('58c85d1b7932a14c7a0a320d');_x000D_
db.yourCollection.findOne({ _id: ObjectId }, function (err, info) {_x000D_
   console.log(info)_x000D_
});_x000D_
               
_x000D_
_x000D_
_x000D_

How to Update Multiple Array Elements in mongodb

Please be aware that some answers in this thread suggesting use $[] is WRONG.

db.collection.update(
   {"events.profile":10},
   {$set:{"events.$[].handled":0}},
   {multi:true}
)

The above code will update "handled" to 0 for all elements in "events" array, regardless of its "profile" value. The query {"events.profile":10} is only to filter the whole document, not the documents in the array. In this situation it is a must to use $[elem] with arrayFilters to specify the condition of array items so Neil Lunn's answer is correct.

How do I get the first element from an IEnumerable<T> in .net?

If you can use LINQ you can use:

var e = enumerable.First();

This will throw an exception though if enumerable is empty: in which case you can use:

var e = enumerable.FirstOrDefault();

FirstOrDefault() will return default(T) if the enumerable is empty, which will be null for reference types or the default 'zero-value' for value types.

If you can't use LINQ, then your approach is technically correct and no different than creating an enumerator using the GetEnumerator and MoveNext methods to retrieve the first result (this example assumes enumerable is an IEnumerable<Elem>):

Elem e = myDefault;
using (IEnumerator<Elem> enumer = enumerable.GetEnumerator()) {
    if (enumer.MoveNext()) e = enumer.Current;
}

Joel Coehoorn mentioned .Single() in the comments; this will also work, if you are expecting your enumerable to contain exactly one element - however it will throw an exception if it is either empty or larger than one element. There is a corresponding SingleOrDefault() method that covers this scenario in a similar fashion to FirstOrDefault(). However, David B explains that SingleOrDefault() may still throw an exception in the case where the enumerable contains more than one item.

Edit: Thanks Marc Gravell for pointing out that I need to dispose of my IEnumerator object after using it - I've edited the non-LINQ example to display the using keyword to implement this pattern.

Writing Unicode text to a text file?

How to print unicode characters into a file:

Save this to file: foo.py:

#!/usr/bin/python -tt
# -*- coding: utf-8 -*-
import codecs
import sys 
UTF8Writer = codecs.getwriter('utf8')
sys.stdout = UTF8Writer(sys.stdout)
print(u'e with obfuscation: é')

Run it and pipe output to file:

python foo.py > tmp.txt

Open tmp.txt and look inside, you see this:

el@apollo:~$ cat tmp.txt 
e with obfuscation: é

Thus you have saved unicode e with a obfuscation mark on it to a file.

Excel 2010: how to use autocomplete in validation list

Excel automatically does this whenever you have a vertical column of items. If you select the blank cell below (or above) the column and start typing, it does autocomplete based on everything in the column.

new Image(), how to know if image 100% loaded or not?

Use the load event:

img = new Image();

img.onload = function(){
  // image  has been loaded
};

img.src = image_url;

Also have a look at:

How to run composer from anywhere?

Some of this may be due to the OS your server is running. I recently did a migration to a new hosting environment running Ubuntu. Adding this alias alias composer="/path/to/your/composer" to .bashrc or .bash_aliases didn't work at first because of two reasons:

The server was running csh, not bash, by default. To check if this is an issue in your case, run echo $0. If the what is returned is -csh you will want to change it to bash, since some processes run by Composer will fail using csh/tcsh.

To change it, first check if bash is available on your server by running cat /etc/shells. If, in the list returned, you see bin/bash, you can change the default to bash by running chsh -s /bin/csh.

Now, at this point, you should be able to run Composer, but normally, on Ubuntu, you will have to load the script at every session by sourcing your Bash scripts by running source ~/.bashrc or source ~/.bash_profile. This is because, in most cases, Ubuntu won't load your Bash script, since it loads .profile as the default script.

To load your Bash scripts when you open a session, try adding this to your .profile (this is if your Bash script is .bashrc—modify accordingly if .bash_profile or other):

if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
        . "$HOME/.bashrc"
    fi
fi

To test, close your session and reload. If it's working properly, running composer -v or which composer should behave as expected.

apt-get for Cygwin?

Update: you can read the more complex answer, which contains more methods and information.

There exists a couple of scripts, which can be used as simple package managers. But as far as I know, none of them allows you to upgrade packages, because it’s not an easy task on Windows since there is not possible to overwrite files in use. So you have to close all Cygwin instances first and then you can use Cygwin’s native setup.exe (which itself does the upgrade via “replace after reboot” method, when files are in use).


apt-cyg

The best one for me. Simply because it’s one of the most recent. It works correctly for both platforms - x86 and x86_64. There exists a lot of forks with some additional features. For example the kou1okada fork is one of improved versions.


Cygwin’s setup.exe

It has also command line mode. Moreover it allows you to upgrade all installed packages at once.

setup.exe-x86_64.exe -q --packages=bash,vim

Example use:

setup.exe-x86_64.exe -q --packages="bash,vim"

You can create an alias for easier use, for example:

alias cyg-get="/cygdrive/d/path/to/cygwin/setup-x86_64.exe -q -P"

Then you can for example install the Vim package with:

cyg-get vim

Spring application context external properties?

<context:property-placeholder location="file:/apps/tomcat/ath/ath_conf/pcr.application.properties" />

This works for me. Local development machine path is C:\apps\tomcat\ath\ath_conf and in server /apps/tomcat/ath/ath_conf

Both works for me

Visual Studio 2013 error MS8020 Build tools v140 cannot be found

@bku_drytt's solution didn't do it for me.

I solved it by additionally changing every occurence of 14.0 to 12.0 and v140 to v120 manually in the .vcxproj files.

Then it compiled!

Session variables not working php

Just talked to the hosting service, it was an issue at their end. he said " your account session.save_path was not set as a result issue arise. I set it for you now."

And it works fine after that :)

Best way to check if a Data Table has a null value in it

I will do like....

(!DBNull.Value.Equals(dataSet.Tables[6].Rows[0]["_id"]))

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

How do I create a local database inside of Microsoft SQL Server 2014?

install Local DB from following link https://www.microsoft.com/en-us/download/details.aspx?id=42299 then connect to the local db using windows authentication. (localdb)\MSSQLLocalDB

How to stop C# console applications from closing automatically?

Use:

Console.ReadKey();

For it to close when someone presses any key, or:

Console.ReadLine();

For when the user types something and presses enter.

Why doesn't margin:auto center an image?

I've found that I must define a specific width for the object or nothing else will make it center. A relative width doesn't work.

Convert java.util.Date to java.time.LocalDate

I have had problems with @JodaStephen's implementation on JBoss EAP 6. So, I rewrote the conversion following Oracle's Java Tutorial in http://docs.oracle.com/javase/tutorial/datetime/iso/legacy.html.

    Date input = new Date();
    GregorianCalendar gregorianCalendar = (GregorianCalendar) Calendar.getInstance();
    gregorianCalendar.setTime(input);
    ZonedDateTime zonedDateTime = gregorianCalendar.toZonedDateTime();
    zonedDateTime.toLocalDate();

error: request for member '..' in '..' which is of non-class type

If you want to declare a new substance with no parameter (knowing that the object have default parameters) don't write

 type substance1();

but

 type substance;

Does "display:none" prevent an image from loading?

Yes it will render faster, slightly, only because it doesn't have to render the image and is one less element to sort on the screen.

If you don't want it loaded, leave a DIV empty where you can load html into it later containing an <img> tag.

Try using firebug or wireshark as I've mentioned before and you'll see that the files DO get transferred even if display:none is present.

Opera is the only browser which will not load the image if the display is set to none. Opera has now moved to webkit and will render all images even if their display is set to none.

Here is a testing page that will prove it:

http://www.quirksmode.org/css/displayimg.html

Refused to load the script because it violates the following Content Security Policy directive

Try replacing your meta tag with this below:

<meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' http://* 'unsafe-inline'; script-src 'self' http://* 'unsafe-inline' 'unsafe-eval'" />

Or in addition to what you have, you should add http://* to both style-src and script-src as seen above added after 'self'.

If your server is including the Content-Security-Policy header, the header will override the meta.

How can I indent multiple lines in Xcode?

The keyboard shortcuts are ?+] for indent and ?+[ for un-indent.

  • In Xcode's preferences window, click the Key Bindings toolbar button. The Key Bindings section is where you customize keyboard shortcuts.

How to use ArrayAdapter<myClass>

You could just add a toString() method to MyClass, per http://developer.android.com/reference/android/widget/ArrayAdapter.html:

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

class MyClass {

 @Override
 public String toString() {
  return "Hello, world.";
 }
}

SQL Query Multiple Columns Using Distinct on One Column Only

you have various ways to distinct values on one column or multi columns.

  • using the GROUP BY

    SELECT DISTINCT MIN(o.tblFruit_ID)  AS tblFruit_ID,
       o.tblFruit_FruitType,
       MAX(o.tblFruit_FruitName)
    FROM   tblFruit  AS o
    GROUP BY
         tblFruit_FruitType
    
  • using the subquery

    SELECT b.tblFruit_ID,
       b.tblFruit_FruitType,
       b.tblFruit_FruitName
    FROM   (
           SELECT DISTINCT(tblFruit_FruitType),
                  MIN(tblFruit_ID) tblFruit_ID
           FROM   tblFruit
           GROUP BY
                  tblFruit_FruitType
       ) AS a
       INNER JOIN tblFruit b
            ON  a.tblFruit_ID = b.tblFruit_I
    
  • using the join with subquery

    SELECT t1.tblFruit_ID,
        t1.tblFruit_FruitType,
        t1.tblFruit_FruitName
    FROM   tblFruit  AS t1
       INNER JOIN (
                SELECT DISTINCT MAX(tblFruit_ID) AS tblFruit_ID,
                       tblFruit_FruitType
                FROM   tblFruit
                GROUP BY
                       tblFruit_FruitType
            )  AS t2
            ON  t1.tblFruit_ID = t2.tblFruit_ID 
    
  • using the window functions only one column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType ORDER BY tblFruit_ID) 
        rn
           FROM   tblFruit
        ) t
        WHERE  rn = 1 
    
  • using the window functions multi column distinct

    SELECT tblFruit_ID,
        tblFruit_FruitType,
        tblFruit_FruitName
    FROM   (
             SELECT tblFruit_ID,
                  tblFruit_FruitType,
                  tblFruit_FruitName,
                  ROW_NUMBER() OVER(PARTITION BY tblFruit_FruitType,     tblFruit_FruitName 
        ORDER BY tblFruit_ID) rn
              FROM   tblFruit
         ) t
        WHERE  rn = 1 
    

Search and get a line in Python

With regular expressions

import re
s="""
    qwertyuiop
    asdfghjkl

    zxcvbnm
    token qwerty

    asdfghjklñ
"""
>>> items=re.findall("token.*$",s,re.MULTILINE)
>>> for x in items:
...     print x
...
token qwerty

What is the meaning of {...this.props} in Reactjs

It is ES-6 feature. It means you extract all the properties of props in div.{... }

operator is used to extract properties of an object.

Get div to take up 100% body height, minus fixed-height header and footer

Here's a solution that doesn't use negative margins or calc. Run the snippet below to see the final result.

Explanation

We give the header and the footer a fixed height of 30px and position them absolutely at the top and bottom, respectively. To prevent the content from falling underneath, we use two classes: below-header and above-footer to pad the div above and below with 30px.

All of the content is wrapped in a position: relative div so that the header and footer are at the top/bottom of the content and not the window.

We use the classes fit-to-parent and min-fit-to-parent to make the content fill out the page. This gives us a sticky footer which is at least as low as the window, but hidden if the content is longer than the window.

Inside the header and footer, we use the display: table and display: table-cell styles to give the header and footer some vertical padding without disrupting the shrink-wrap quality of the page. (Giving them real padding can cause the total height of the page to be more than 100%, which causes a scroll bar to appear when it isn't really needed.)

_x000D_
_x000D_
.fit-parent {_x000D_
    height: 100%;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
.min-fit-parent {_x000D_
    min-height: 100%;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
.below-header {_x000D_
    padding-top: 30px;_x000D_
}_x000D_
.above-footer {_x000D_
    padding-bottom: 30px;_x000D_
}_x000D_
.header {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    height: 30px;_x000D_
    width: 100%;_x000D_
}_x000D_
.footer {_x000D_
    position: absolute;_x000D_
    bottom: 0;_x000D_
    height: 30px;_x000D_
    width: 100%;_x000D_
}_x000D_
_x000D_
/* helper classes */_x000D_
_x000D_
.padding-lr-small {_x000D_
    padding: 0 5px;_x000D_
}_x000D_
.relative {_x000D_
    position: relative;_x000D_
}_x000D_
.auto-scroll {_x000D_
  overflow: auto;_x000D_
}_x000D_
/* these two classes work together to create vertical centering */_x000D_
.valign-outer {_x000D_
    display: table;_x000D_
}_x000D_
.valign-inner {_x000D_
    display: table-cell;_x000D_
    vertical-align: middle;_x000D_
}
_x000D_
<html class='fit-parent'>_x000D_
  <body class='fit-parent'>_x000D_
<div class='min-fit-parent auto-scroll relative' style='background-color: lightblue'>_x000D_
<div class='header valign-outer' style='background-color: black; color: white;'>_x000D_
        <div class='valign-inner padding-lr-small'>_x000D_
            My webpage_x000D_
        </div>_x000D_
    </div>_x000D_
    <div class='fit-parent above-footer below-header'>_x000D_
        <div class='fit-parent' id='main-inner'>_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
          Lorem ipsum doloris finding dory Lorem ipsum doloris finding_x000D_
          dory Lorem ipsum doloris finding dory Lorem ipsum doloris_x000D_
          finding dory Lorem ipsum doloris finding dory Lorem ipsum_x000D_
          doloris finding dory Lorem ipsum doloris finding dory Lorem_x000D_
          ipsum doloris finding dory Lorem ipsum doloris finding dory_x000D_
        </div>_x000D_
    </div>_x000D_
    <div class='footer valign-outer' style='background-color: white'>_x000D_
        <div class='valign-inner padding-lr-small'>_x000D_
            &copy; 2005 Old Web Design_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
    </body>_x000D_
  </html>
_x000D_
_x000D_
_x000D_

How to add and remove item from array in components in Vue 2

You can use Array.push() for appending elements to an array.

For deleting, it is best to use this.$delete(array, index) for reactive objects.

Vue.delete( target, key ): Delete a property on an object. If the object is reactive, ensure the deletion triggers view updates. This is primarily used to get around the limitation that Vue cannot detect property deletions, but you should rarely need to use it.

https://vuejs.org/v2/api/#Vue-delete

Import Error: No module named numpy

You installed the Numpy Version for Python 2.6 - so you can only use it with Python 2.6. You have to install Numpy for Python 3.x, e.g. that one: http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/numpy-1.6.1-win32-superpack-python3.2.exe/download

For an overview of the different versions, see here: http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/

Passing an array of parameters to a stored procedure

You could use a temp table which the stored procedure expects to exist. This will work on older versions of SQL Server, which do not support XML etc.

CREATE TABLE #temp
(INT myid)
GO
CREATE PROC myproc
AS
BEGIN
    DELETE YourTable
    FROM YourTable                    
    LEFT OUTER JOIN #temp T ON T.myid=s.id
    WHERE s.id IS NULL
END

Postgres could not connect to server

This happens when postgres server is not running. Steps to properly install Postgres via Homebrew on MAC :

  1. brew install postgres

  2. initdb /Users/<username>/db -E utf8 [This initializes postgres to use the given directory as the database directory. Normally it is not adviced to use the user directory for database storage. Edit sudoers file to add initdb and similar commands and then run initdb on /usr/local/var/postgres]

  3. pg_ctl -D /Users/<username>/db -l logfile start [After getting success with step 2 it will prompt to run step 3. This command manually starts the server.]

How to compare two files in Notepad++ v6.6.8

Alternatively, you can install "SourceForge Notepad++ Compare Plugin 1.5.6". It provides compare functionality between two files and show the differences between two files.

Link to refer : https://sourceforge.net/projects/npp-compare/files/1.5.6/

How to add days to the current date?

can try this

select (CONVERT(VARCHAR(10),GETDATE()+360,110)) as Date_Result

Storing Images in PostgreSQL

Updating to 2012, when we see that image sizes, and number of images, are growing and growing, in all applications...

We need some distinction between "original image" and "processed image", like thumbnail.

As Jcoby's answer says, there are two options, then, I recommend:

  • use blob (Binary Large OBject): for original image store, at your table. See Ivan's answer (no problem with backing up blobs!), PostgreSQL additional supplied modules, How-tos etc.

  • use a separate database with DBlink: for original image store, at another (unified/specialized) database. In this case, I prefer bytea, but blob is near the same. Separating database is the best way for a "unified image webservice".

  • use bytea (BYTE Array): for caching thumbnail images. Cache the little images to send it fast to the web-browser (to avoiding rendering problems) and reduce server processing. Cache also essential metadata, like width and height. Database caching is the easiest way, but check your needs and server configs (ex. Apache modules): store thumbnails at file system may be better, compare performances. Remember that it is a (unified) web-service, then can be stored at a separate database (with no backups), serving many tables. See also PostgreSQL binary data types manual, tests with bytea column, etc.

NOTE1: today the use of "dual solutions" (database+filesystem) is deprecated (!). There are many advantages to using "only database" instead dual. PostgreSQL have comparable performance and good tools for export/import/input/output.

NOTE2: remember that PostgreSQL have only bytea, not have a default Oracle's BLOB: "The SQL standard defines (...) BLOB. The input format is different from bytea, but the provided functions and operators are mostly the same",Manual.


EDIT 2014: I have not changed the original text above today (my answer was Apr 22 '12, now with 14 votes), I am opening the answer for your changes (see "Wiki mode", you can edit!), for proofreading and for updates.
The question is stable (@Ivans's '08 answer with 19 votes), please, help to improve this text.

How to replace multiple substrings of a string?

Here is a short example that should do the trick with regular expressions:

import re

rep = {"condition1": "", "condition2": "text"} # define desired replacements here

# use these three lines to do the replacement
rep = dict((re.escape(k), v) for k, v in rep.iteritems()) 
#Python 3 renamed dict.iteritems to dict.items so use rep.items() for latest versions
pattern = re.compile("|".join(rep.keys()))
text = pattern.sub(lambda m: rep[re.escape(m.group(0))], text)

For example:

>>> pattern.sub(lambda m: rep[re.escape(m.group(0))], "(condition1) and --condition2--")
'() and --text--'

Show/hide forms using buttons and JavaScript

If you have a container and two sub containers, you can do like this

jQuery

    $("#previousbutton").click(function() {
    $("#form_sub_container1").show();
    $("#form_sub_container2").hide(); })

    $("#nextbutton").click(function() {
    $("#form_container").find(":hidden").show().next();
    $("#form_sub_container1").hide();
})

HTML

     <div id="form_container">
            <div id="form_sub_container1" style="display: block;">
            </div>

            <div id="form_sub_container2" style="display: none;">
            </div>
     </div>

The server principal is not able to access the database under the current security context in SQL Server MS 2012

In my case, the message was caused by a synonym which inadvertently included the database name in the "object name". When I restored the database under a new name, the synonym still pointed to the old DB name. Since the user did not have permissions in the old DB, the message appeared. To fix, I dropped and recreated the synonym without qualifying the object name with the database name:

    USE [new_db]
GO

/****** Object:  Synonym [dbo].[synTable]    Script Date: 10/15/2015 9:45:01 AM ******/
DROP SYNONYM [dbo].[synTable]
GO

/****** Object:  Synonym [dbo].[synTable]    Script Date: 10/15/2015 9:45:01 AM ******/
CREATE SYNONYM [dbo].[synTable] FOR [dbo].[tTheRealTable]
GO

Exception Error c0000005 in VC++

I was having the same problem while running bulk tests for an assignment. Turns out when I relocated some iostream operations (printing to console) from class constructor to a method in class it was solved.

I assume it was something to do with iostream manipulations in the constructor.

Here is the fix:

// Before
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {
    cout << "Some text I was printing.." << endl;
};


// After
CommandPrompt::CommandPrompt() : afs(nullptr), aff(nullptr) {

};

Please feel free to explain more what the error is behind the scenes since it goes beyond my cpp knowledge.

Returning Arrays in Java

It is returning the array, but all returning something (including an Array) does is just what it sounds like: returns the value. In your case, you are getting the value of numbers(), which happens to be an array (it could be anything and you would still have this issue), and just letting it sit there.

When a function returns anything, it is essentially replacing the line in which it is called (in your case: numbers();) with the return value. So, what your main method is really executing is essentially the following:

public static void main(String[] args) {
    {1,2,3};
}

Which, of course, will appear to do nothing. If you wanted to do something with the return value, you could do something like this:

public static void main(String[] args){
    int[] result = numbers();
    for (int i=0; i<result.length; i++) {
        System.out.print(result[i]+" ");
    }
}

What is the best way to trigger onchange event in react js

If you are using Backbone and React, I'd recommend one of the following,

They both help integrate Backbone models and collections with React views. You can use Backbone events just like you do with Backbone views. I've dabbled in both and didn't see much of a difference except one is a mixin and the other changes React.createClass to React.createBackboneClass.

Nodemailer with Gmail and NodeJS

You should use an XOAuth2 token to connect to Gmail. No worries, Nodemailer already knows about that:

var smtpTransport = nodemailer.createTransport('SMTP', {
    service: 'Gmail',
    auth: {
      XOAuth2: {
        user: smtpConfig.user,
        clientId: smtpConfig.client_id,
        clientSecret: smtpConfig.client_secret,
        refreshToken: smtpConfig.refresh_token,
        accessToken: smtpConfig.access_token,
        timeout: smtpConfig.access_timeout - Date.now()
      }
    }
  };

You'll need to go to the Google Cloud Console to register your app. Then you need to retrieve access tokens for the accounts you wish to use. You can use passportjs for that.

Here's how it looks in my code:

var passport = require('passport'),
    GoogleStrategy = require('./google_oauth2'),
    config = require('../config');

passport.use('google-imap', new GoogleStrategy({
  clientID: config('google.api.client_id'),
  clientSecret: config('google.api.client_secret')
}, function (accessToken, refreshToken, profile, done) {
  console.log(accessToken, refreshToken, profile);
  done(null, {
    access_token: accessToken,
    refresh_token: refreshToken,
    profile: profile
  });
}));

exports.mount = function (app) {
  app.get('/add-imap/:address?', function (req, res, next) {
    passport.authorize('google-imap', {
        scope: [
          'https://mail.google.com/',
          'https://www.googleapis.com/auth/userinfo.email'
        ],
        callbackURL: config('web.vhost') + '/add-imap',
        accessType: 'offline',
        approvalPrompt: 'force',
        loginHint: req.params.address
      })(req, res, function () {
        res.send(req.user);
      });
  });
};

CSS: background-color only inside the margin

If your margin is set on the body, then setting the background color of the html tag should color the margin area

html { background-color: black; }
body { margin:50px; background-color: white; }

http://jsfiddle.net/m3zzb/

Or as dmackerman suggestions, set a margin of 0, but a border of the size you want the margin to be and set the border-color

How to make HTML input tag only accept numerical values?

How about using <input type="number"...>?

http://www.w3schools.com/tags/tag_input.asp

Also, here is a question that has some examples of using Javascript for validation.

Update: linked to better question (thanks alexblum).

Creating a system overlay window (always on top)

Try this. Works fine in ICS. If You want to stop service simply click the notification generated in statusbar.

 public class HUD extends Service
 {
    protected boolean foreground = false;
    protected boolean cancelNotification = false;
    private Notification notification;
    private View myView;
    protected int id = 0;
    private WindowManager wm;
    private WindowManager.LayoutParams params;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
       // System.exit(0);
        Toast.makeText(getBaseContext(),"onCreate", Toast.LENGTH_SHORT).show();
        params = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                        | WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT);
        params.gravity=Gravity.TOP|Gravity.LEFT;
    wm = (WindowManager) getSystemService(WINDOW_SERVICE);
    inflateview();
    foregroundNotification(1);
    //moveToForeground(1,n,true);
    }     
   @Override
    public void onDestroy() {
        super.onDestroy();
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).cancel(0);
        Toast.makeText(getBaseContext(),"onDestroy", Toast.LENGTH_SHORT).show();
        if(myView != null)
        {
            ((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(myView);
            myView = null;
        }
    }
    protected Notification foregroundNotification(int notificationId) 
   {    
    notification = new Notification(R.drawable.ic_launcher, "my Notification", System.currentTimeMillis());    
        notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT | Notification.FLAG_ONLY_ALERT_ONCE;   
        notification.setLatestEventInfo(this, "my Notification", "my Notification", notificationIntent());          
        ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(id, notification);            
        return notification;
    }
    private PendingIntent notificationIntent() {
        Intent intent = new Intent(this, stopservice.class);    
        PendingIntent pending = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);    
        return pending;
    }
    public void inflateview()
    {
         LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
            myView = inflater.inflate(R.layout.activity_button, null);
            myView.setOnTouchListener(new OnTouchListener() {
               @Override
               public boolean onTouch(View v, MotionEvent event) {
                   Toast.makeText(getBaseContext(),"onToasttt", Toast.LENGTH_SHORT).show();
                   return false;
               }
             });
            // Add layout to window manager
            wm.addView(myView, params); 
    }
}

UPDATE

Sample here

To create an overlay view, when setting up the LayoutParams DON'T set the type to TYPE_SYSTEM_OVERLAY.

Instead set it to TYPE_PHONE.

Use the following flags:

FLAG_NOT_TOUCH_MODAL

FLAG_WATCH_OUTSIDE_TOUCH

input type=file show only button

I Don't Know what your talking about, if you trying to style a input type file into a button that is easy for me all you will need is just html and css.

<div id="File-Body">
  <label id="File-Lable" for="File-For">
    <div id="Filebutton">Edit</div>
  </label>
  <input id="File-For" type="file">
</div>

css:

#File-Body > #File-For {
  display: none;
}

#Filebutton {
  width: 50px;
  height: 20px;
  border: 1px solid;
  border-radius: 2px;
  text-align: center;
}
#File-Body {
  width: 300px;
  height: 30px;
}

If you want to test it Here it is http://jsfiddle.net/qm8j45c3/

Java better way to delete file if exists

if you have the file inside a dirrectory called uploads in your project. bellow code can be used.

Path root = Paths.get("uploads");
File existingFile = new File(this.root.resolve("img.png").toUri());

if (existingFile.exists() && existingFile.isFile()) {
     existingFile.delete();
   }

OR

If it is inside a different directory this solution can be used.

File existingFile = new File("D:\\<path>\\img.png");

if (existingFile.exists() && existingFile.isFile()) {
    existingFile.delete();
  }

Sync data between Android App and webserver

If we think about today, accepted answer is too old. As we know that we have many new libraries which can help you to make this types of application.

You should learn following topics that will helps you surely:

  • SyncAdapter: The sync adapter component in your app encapsulates the code for the tasks that transfer data between the device and a server. Based on the scheduling and triggers you provide in your app, the sync adapter framework runs the code in the sync adapter component.

  • Realm: Realm is a mobile database: a replacement for SQLite & Core Data.

  • Retrofit Type-safe HTTP client for Android and Java by Square, Inc. Must Learn a-smart-way-to-use-retrofit

And your sync logic for database like: How to sync SQLite database on Android phone with MySQL database on server?

Best Luck to all new learner. :)

get all the images from a folder in php

//path to the directory to search/scan
        $directory = "";
         //echo "$directory"
        //get all files in a directory. If any specific extension needed just have to put the .extension
        //$local = glob($directory . "*"); 
        $local = glob("" . $directory . "{*.jpg,*.gif,*.png}", GLOB_BRACE);
        //print each file name
        echo "<ul>";

        foreach($local as $item)
        {
        echo '<li><a href="'.$item.'">'.$item.'</a></li>';
        }

        echo "</ul>";

Add params to given URL in Python

Here is how I implemented it.

import urllib

params = urllib.urlencode({'lang':'en','tag':'python'})
url = ''
if request.GET:
   url = request.url + '&' + params
else:
   url = request.url + '?' + params    

Worked like a charm. However, I would have liked a more cleaner way to implement this.

Another way of implementing the above is put it in a method.

import urllib

def add_url_param(request, **params):
   new_url = ''
   _params = dict(**params)
   _params = urllib.urlencode(_params)

   if _params:
      if request.GET:
         new_url = request.url + '&' + _params
      else:
         new_url = request.url + '?' + _params
   else:
      new_url = request.url

   return new_ur

How to get POST data in WebAPI?

It is hard to handle multiple parameters on the action directly. The better way to do it is to create a view model class. Then you have a single parameter but the parameter contains multiple data properties.

public class MyParameters
{
    public string a { get; set; } 
    public string b { get; set; }
}

public MyController : ApiController
{
    public HttpResponseMessage Get([FromUri] MyParameters parameters) { ... }
}

Then you go to:

http://localhost:12345/api/MyController?a=par1&b=par2

Reference: http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

If you want to use "/par1/par2", you can register an asp routing rule. eg routeTemplate: "API/{controller}/{action}/{a}/{b}".

See http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api

How does Java handle integer underflows and overflows and how would you check for it?

There are libraries that provide safe arithmetic operations, which check integer overflow/underflow . For example, Guava's IntMath.checkedAdd(int a, int b) returns the sum of a and b, provided it does not overflow, and throws ArithmeticException if a + b overflows in signed int arithmetic.

Passing multiple values for a single parameter in Reporting Services

If you want to pass multiple values to RS via a query string all you need to do is repeat the report parameter for each value.

For example; I have a RS column called COLS and this column expects one or more values.

&rp:COLS=1&rp:COLS=1&rp:COLS=5 etc..

Reduce git repository size

In my case, I pushed several big (> 100Mb) files and then proceeded to remove them. But they were still in the history of my repo, so I had to remove them from it as well.

What did the trick was:

bfg -b 100M  # To remove all blobs from history, whose size is superior to 100Mb
git reflog expire --expire=now --all
git gc --prune=now --aggressive

Then, you need to push force on your branch:

git push origin <your_branch_name> --force

Note: bfg is a tool that can be installed on Linux and macOS using brew:

brew install bfg

Java Date vs Calendar

Date is best for storing a date object. It is the persisted one, the Serialized one ...

Calendar is best for manipulating Dates.

Note: we also sometimes favor java.lang.Long over Date, because Date is mutable and therefore not thread-safe. On a Date object, use setTime() and getTime() to switch between the two. For example, a constant Date in the application (examples: the zero 1970/01/01, or an applicative END_OF_TIME that you set to 2099/12/31 ; those are very useful to replace null values as start time and end time, especially when you persist them in the database, as SQL is so peculiar with nulls).

CSS Resize/Zoom-In effect on Image while keeping Dimensions

You could achieve that simply by wrapping the image by a <div> and adding overflow: hidden to that element:

<div class="img-wrapper">
    <img src="..." />
</div>
.img-wrapper {
    display: inline-block; /* change the default display type to inline-block */
    overflow: hidden;      /* hide the overflow */
}

WORKING DEMO.


Also it's worth noting that <img> element (like the other inline elements) sits on its baseline by default. And there would be a 4~5px gap at the bottom of the image.

That vertical gap belongs to the reserved space of descenders like: g j p q y. You could fix the alignment issue by adding vertical-align property to the image with a value other than baseline.

Additionally for a better user experience, you could add transition to the images.

Thus we'll end up with the following:

.img-wrapper img {
    transition: all .2s ease;
    vertical-align: middle;
}

UPDATED DEMO.

Get the first element of each tuple in a list in Python

The functional way of achieving this is to unzip the list using:

sample = [(2, 9), (2, 9), (8, 9), (10, 9), (23, 26), (1, 9), (43, 44)]
first,snd = zip(*sample)
print(first,snd)

(2, 2, 8, 10, 23, 1, 43) (9, 9, 9, 9, 26, 9, 44)

Fastest way to update 120 Million records

I break the task up into smaller units. Test with different batch size intervals for your table, until you find an interval that performs optimally. Here is a sample that I have used in the past.

declare @counter int 
declare @numOfRecords int
declare @batchsize int

set @numOfRecords = (SELECT COUNT(*) AS NumberOfRecords FROM <TABLE> with(nolock))
set @counter = 0 
set @batchsize = 2500

set rowcount @batchsize
while @counter < (@numOfRecords/@batchsize) +1
begin 
set @counter = @counter + 1 
Update table set int_field = -1 where int_field <> -1;
end 
set rowcount 0

Understanding The Modulus Operator %

lets put it in this way:
actually Modulus operator does the same division but it does not care about the answer , it DOES CARE ABOUT reminder for example if you divide 7 to 5 ,
so , lets me take you through a simple example:
think 5 is a block, then for example we going to have 3 blocks in 15 (WITH Nothing Left) , but when that loginc comes to this kinda numbers {1,3,5,7,9,11,...} , here is where the Modulus comes out , so take that logic that i said before and apply it for 7 , so the answer gonna be that we have 1 block of 5 in 7 => with 2 reminds in our hand! that is the modulus!!!
but you were asking about 5 % 7 , right ?
so take the logic that i said , how many 7 blocks do we have in 5 ???? 0
so the modulus returns 0...
that's it ...

What is the best way to implement a "timer"?

By using System.Windows.Forms.Timer class you can achieve what you need.

System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();


t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();

void timer_Tick(object sender, EventArgs e)
{
      //Call method
}

By using stop() method you can stop timer.

t.Stop();

How to efficiently remove duplicates from an array without using Set

Just a trick to remove duplicates.

public class RemoveDuplicates {
    public static void main(String[] args) {
        int[] arr = {2,2,2,2,2,5,9, 4,5,6,1,6,6,2,4,7};
        arr = removeDuplicates(arr);    
        print(arr);
    }

    public static int[] removeDuplicates(int [] arr) {
        final int garbage = -2147483648;
        int duplicates = 0;

        for(int i=0; i<arr.length; i++) {
            for(int j=i+1; j<arr.length; j++) {
                if (arr[i] == arr[j]) {
                    arr[i] = garbage;
                    duplicates++;
                }
            }
        }

        int[] nArr = new int[arr.length - duplicates];
        int nItr = 0;
        for(int i=0; i<arr.length; i++) {
            if (arr[i] != garbage) {
                nArr[nItr] = arr[i];
                nItr++;
            } 
        }
        return nArr;
    }

    public static void print(int [] arr) {
        for (int n : arr) {
            System.out.print(n + "\t");
        }
    }

}

Git: Could not resolve host github.com error while cloning remote repository in git

another possibility, I ran into this problem myself. But it was after I had installed a VPN (which was unrelated and running)

turning off the VPN, fixed the issue.

for the record, I was running "Viscosity" VPN on my MacBookPro

What is NODE_ENV and how to use it in Express?

I assume the original question included how does Express use this environment variable.

Express uses NODE_ENV to alter its own default behavior. For example, in development mode, the default error handler will send back a stacktrace to the browser. In production mode, the response is simply Internal Server Error, to avoid leaking implementation details to the world.

Count indexes using "for" in Python

Just use

for i in range(0, 5):
    print i

to iterate through your data set and print each value.

For large data sets, you want to use xrange, which has a very similar signature, but works more effectively for larger data sets. http://docs.python.org/library/functions.html#xrange

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

Things to check when enabling the bundle optimization;

BundleTable.EnableOptimizations = true;

and

webconfig debug = "false"
  1. the bundles.IgnoreList.Clear();

this will ignore the minified assets of your bundles like *.min.css or *.min.js which can cause an undefine error of your script. To fix is replace the .min asset to original. if you do this you may not need the bundles.IgnoreList.Clear(); e.g.

bundles.Add(new ScriptBundle("~/bundles/datatablesjs")
      .Include("~/Scripts/datatables.min.js") <---- change this to non minified ver.
  1. Make sure the names of the bundles of your css and js are unique.

    bundles.Add(new StyleBundle("~/bundles/datatablescss").Include( ...) );

    bundles.Add(new ScriptBundle("~/bundles/datatablesjs").Include( ...) );

  2. Make sure you use the Render name of your @Script.Render and Style.Render are the same on your bundle config. e.g.

    @Styles.Render("~/bundles/datatablescss")

    @Scripts.Render("~/bundles/datatablesjs")

MySQL and GROUP_CONCAT() maximum length

The correct parameter to set the maximum length is:

SET @@group_concat_max_len = value_numeric;

value_numeric must be > 1024; by default the group_concat_max_len value is 1024.

Custom Drawable for ProgressBar/ProgressDialog

I was having some trouble using an Indeterminate Progress Dialog with the solution here, after some work and trial and error I got it to work.

First, create the animation you want to use for the Progress Dialog. In my case I used 5 images.

../res/anim/progress_dialog_icon_drawable_animation.xml:

<animation-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/icon_progress_dialog_drawable_1" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_2" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_3" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_4" android:duration="150" />
    <item android:drawable="@drawable/icon_progress_dialog_drawable_5" android:duration="150" />
</animation-list>

Where you want to show a ProgressDialog:

dialog = new ProgressDialog(Context.this);
dialog.setIndeterminate(true);
dialog.setIndeterminateDrawable(getResources().getDrawable(R.anim.progress_dialog_icon_drawable_animation));
dialog.setMessage("Some Text");
dialog.show();

This solution is really simple and worked for me, you could extend ProgressDialog and make it override the drawable internally, however, this was really too complicated for what I needed so I did not do it.

"Undefined reference to" template class constructor

This is a common question in C++ programming. There are two valid answers to this. There are advantages and disadvantages to both answers and your choice will depend on context. The common answer is to put all the implementation in the header file, but there's another approach will will be suitable in some cases. The choice is yours.

The code in a template is merely a 'pattern' known to the compiler. The compiler won't compile the constructors cola<float>::cola(...) and cola<string>::cola(...) until it is forced to do so. And we must ensure that this compilation happens for the constructors at least once in the entire compilation process, or we will get the 'undefined reference' error. (This applies to the other methods of cola<T> also.)

Understanding the problem

The problem is caused by the fact that main.cpp and cola.cpp will be compiled separately first. In main.cpp, the compiler will implicitly instantiate the template classes cola<float> and cola<string> because those particular instantiations are used in main.cpp. The bad news is that the implementations of those member functions are not in main.cpp, nor in any header file included in main.cpp, and therefore the compiler can't include complete versions of those functions in main.o. When compiling cola.cpp, the compiler won't compile those instantiations either, because there are no implicit or explicit instantiations of cola<float> or cola<string>. Remember, when compiling cola.cpp, the compiler has no clue which instantiations will be needed; and we can't expect it to compile for every type in order to ensure this problem never happens! (cola<int>, cola<char>, cola<ostream>, cola< cola<int> > ... and so on ...)

The two answers are:

  • Tell the compiler, at the end of cola.cpp, which particular template classes will be required, forcing it to compile cola<float> and cola<string>.
  • Put the implementation of the member functions in a header file that will be included every time any other 'translation unit' (such as main.cpp) uses the template class.

Answer 1: Explicitly instantiate the template, and its member definitions

At the end of cola.cpp, you should add lines explicitly instantiating all the relevant templates, such as

template class cola<float>;
template class cola<string>;

and you add the following two lines at the end of nodo_colaypila.cpp:

template class nodo_colaypila<float>;
template class nodo_colaypila<std :: string>;

This will ensure that, when the compiler is compiling cola.cpp that it will explicitly compile all the code for the cola<float> and cola<string> classes. Similarly, nodo_colaypila.cpp contains the implementations of the nodo_colaypila<...> classes.

In this approach, you should ensure that all the of the implementation is placed into one .cpp file (i.e. one translation unit) and that the explicit instantation is placed after the definition of all the functions (i.e. at the end of the file).

Answer 2: Copy the code into the relevant header file

The common answer is to move all the code from the implementation files cola.cpp and nodo_colaypila.cpp into cola.h and nodo_colaypila.h. In the long run, this is more flexible as it means you can use extra instantiations (e.g. cola<char>) without any more work. But it could mean the same functions are compiled many times, once in each translation unit. This is not a big problem, as the linker will correctly ignore the duplicate implementations. But it might slow down the compilation a little.

Summary

The default answer, used by the STL for example and in most of the code that any of us will write, is to put all the implementations in the header files. But in a more private project, you will have more knowledge and control of which particular template classes will be instantiated. In fact, this 'bug' might be seen as a feature, as it stops users of your code from accidentally using instantiations you have not tested for or planned for ("I know this works for cola<float> and cola<string>, if you want to use something else, tell me first and will can verify it works before enabling it.").

Finally, there are three other minor typos in the code in your question:

  • You are missing an #endif at the end of nodo_colaypila.h
  • in cola.h nodo_colaypila<T>* ult, pri; should be nodo_colaypila<T> *ult, *pri; - both are pointers.
  • nodo_colaypila.cpp: The default parameter should be in the header file nodo_colaypila.h, not in this implementation file.

Can not change UILabel text color

Add attributed text color in swift code.

Swift 4:

  let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
  let attributedStringColor = [NSAttributedStringKey.foregroundColor : greenColor];

  let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor)
  label.attributedText = attributedString

for Swift 3:

  let greenColor = UIColor(red: 10/255, green: 190/255, blue: 50/255, alpha: 1)
  let attributedStringColor : NSDictionary = [NSForegroundColorAttributeName : greenColor];


  let attributedString = NSAttributedString(string: "Hello World!", attributes: attributedStringColor as? [String : AnyObject])
  label.attributedText = attributedString 

Submit form without page reloading

It's a must to take help of jquery-ajax in this case. Without ajax, there is currently no solution.

First, call a JavaScript function when the form is submitted. Just set onsubmit="func()". Even if the function is called, the default action of the submission would be performed. If it is performed there would be no way of stoping the page from refreshing or redirecting. So, next task is to prevent the default action. Insert the following line at the start of func().

event.preventDefault()

Now, there will be no redirecting or refreshing. So, you simply make an ajax call from func() and do whatever you want to do when call ends.

Example:

Form:

<form id="form-id" onsubmit="func()">
    <input id="input-id" type="text">
</form>

Javascript:

function func(){
    event.preventDefault();
    var newValue = $('#input-field-id').val();
    $.ajax({
        type: 'POST',
        url: '...',
        data: {...},
        datatype: 'JSON',
        success: function(data){...},
        error: function(){...},
    });
}

Javascript : array.length returns undefined

One option is:

Object.keys(myObject).length

Sadly it not works under older IE versions (under 9).

If you need that compatibility, use the painful version:

var key, count = 0;
for(key in myObject) {
  if(myObject.hasOwnProperty(key)) {
    count++;
  }
}

T-SQL: Looping through an array of known values

CREATE TABLE #ListOfIDs (IDValue INT)

DECLARE @IDs VARCHAR(50), @ID VARCHAR(5)
SET @IDs = @OriginalListOfIDs + ','

WHILE LEN(@IDs) > 1
BEGIN
SET @ID = SUBSTRING(@IDs, 0, CHARINDEX(',', @IDs));
INSERT INTO #ListOfIDs (IDValue) VALUES(@ID);
SET @IDs = REPLACE(',' + @IDs, ',' + @ID + ',', '')
END

SELECT * 
FROM #ListOfIDs

public static const in TypeScript

If you did want something that behaved more like a static constant value in modern browsers (in that it can't be changed by other code), you could add a get only accessor to the Library class (this will only work for ES5+ browsers and NodeJS):

export class Library {
    public static get BOOK_SHELF_NONE():string { return "None"; }
    public static get BOOK_SHELF_FULL():string { return "Full"; }   
}

var x = Library.BOOK_SHELF_NONE;
console.log(x);
Library.BOOK_SHELF_NONE = "Not Full";
x = Library.BOOK_SHELF_NONE;
console.log(x);

If you run it, you'll see how the attempt to set the BOOK_SHELF_NONE property to a new value doesn't work.

2.0

In TypeScript 2.0, you can use readonly to achieve very similar results:

export class Library {
    public static readonly BOOK_SHELF_NONE = "None";
    public static readonly BOOK_SHELF_FULL = "Full";
}

The syntax is a bit simpler and more obvious. However, the compiler prevents changes rather than the run time (unlike in the first example, where the change would not be allowed at all as demonstrated).

select a value where it doesn't exist in another table

select ID from A where ID not in (select ID from B);

or

select ID from A except select ID from B;

Your second question:

delete from A where ID not in (select ID from B);

What is the difference between `new Object()` and object literal notation?

They both do the same thing (unless someone's done something unusual), other than that your second one creates an object and adds a property to it. But literal notation takes less space in the source code. It's clearly recognizable as to what is happening, so using new Object(), you are really just typing more and (in theory, if not optimized out by the JavaScript engine) doing an unnecessary function call.

These

person = new Object() /*You should put a semicolon here too.  
It's not required, but it is good practice.*/ 
-or-

person = {
    property1 : "Hello"
};

technically do not do the same thing. The first just creates an object. The second creates one and assigns a property. For the first one to be the same you then need a second step to create and assign the property.

The "something unusual" that someone could do would be to shadow or assign to the default Object global:

// Don't do this
Object = 23;

In that highly-unusual case, new Object will fail but {} will work.

In practice, there's never a reason to use new Object rather than {} (unless you've done that very unusual thing).

How to list all users in a Linux group?

lid -g groupname | cut -f1 -d'(' 

How do I edit $PATH (.bash_profile) on OSX?

Set the path JAVA_HOME and ANDROID_HOME > You have to open terminal and enter the below cmd.

touch ~/.bash_profile; open ~/.bash_profile

After that paste below paths in base profile file and save it

export ANDROID_HOME=/Users/<username>/Library/Android/sdk 
export PATH="$JAVA_HOME/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$PATH"
export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_221.jdk/Contents/Home

"SELECT ... IN (SELECT ...)" query in CodeIgniter

Also, to note - the Active Record Class also has a $this->db->where_in() method.

How to generate XML from an Excel VBA macro?

Here is the example macro to convert the Excel worksheet to XML file.

#'vba code to convert excel to xml

Sub vba_code_to_convert_excel_to_xml()
Set wb = Workbooks.Open("C:\temp\testwb.xlsx")
wb.SaveAs fileName:="C:\temp\testX.xml", FileFormat:= _
        xlXMLSpreadsheet, ReadOnlyRecommended:=False, CreateBackup:=False

End Sub

This macro will open an existing Excel workbook from the C drive and Convert the file into XML and Save the file with .xml extension in the specified Folder. We are using Workbook Open method to open a file. SaveAs method to Save the file into destination folder. This example will be help full, if you wan to convert all excel files in a directory into XML (xlXMLSpreadsheet format) file.

Import module from subfolder

There's no need to mess with your PYTHONPATH or sys.path here.

To properly use absolute imports in a package you should include the "root" packagename as well, e.g.:

from dirFoo.dirFoo1.foo1 import Foo1
from dirFoo.dirFoo2.foo2 import Foo2

Or you can use relative imports:

from .dirfoo1.foo1 import Foo1
from .dirfoo2.foo2 import Foo2

Accessing last x characters of a string in Bash

You can use tail:

$ foo="1234567890"
$ echo -n $foo | tail -c 3
890

A somewhat roundabout way to get the last three characters would be to say:

echo $foo | rev | cut -c1-3 | rev

Setting Curl's Timeout in PHP

If you are using PHP as a fastCGI application then make sure you check the fastCGI timeout settings. See: PHP curl put 500 error

Hive insert query like SQL

No. This INSERT INTO tablename VALUES (x,y,z) syntax is currently not supported in Hive.

Using CSS :before and :after pseudo-elements with inline CSS?

as mentioned above: its not possible to call a css pseudo-class / -element inline. what i now did, is: give your element a unique identifier, f.ex. an id or a unique class. and write a fitting <style> element

<style>#id29:before { content: "*";}</style>
<article id="id29">
  <!-- something -->
</article>

fugly, but what inline css isnt..?

What is the difference between signed and unsigned int

Sometimes we know in advance that the value stored in a given integer variable will always be positive-when it is being used to only count things, for example. In such a case we can declare the variable to be unsigned, as in, unsigned int num student;. With such a declaration, the range of permissible integer values (for a 32-bit compiler) will shift from the range -2147483648 to +2147483647 to range 0 to 4294967295. Thus, declaring an integer as unsigned almost doubles the size of the largest possible value that it can otherwise hold.

round() for float in C++

These days it shouldn't be a problem to use a C++11 compiler which includes a C99/C++11 math library. But then the question becomes: which rounding function do you pick?

C99/C++11 round() is often not actually the rounding function you want. It uses a funky rounding mode that rounds away from 0 as a tie-break on half-way cases (+-xxx.5000). If you do specifically want that rounding mode, or you're targeting a C++ implementation where round() is faster than rint(), then use it (or emulate its behaviour with one of the other answers on this question which took it at face value and carefully reproduced that specific rounding behaviour.)

round()'s rounding is different from the IEEE754 default round to nearest mode with even as a tie-break. Nearest-even avoids statistical bias in the average magnitude of numbers, but does bias towards even numbers.

There are two math library rounding functions that use the current default rounding mode: std::nearbyint() and std::rint(), both added in C99/C++11, so they're available any time std::round() is. The only difference is that nearbyint never raises FE_INEXACT.

Prefer rint() for performance reasons: gcc and clang both inline it more easily, but gcc never inlines nearbyint() (even with -ffast-math)


gcc/clang for x86-64 and AArch64

I put some test functions on Matt Godbolt's Compiler Explorer, where you can see source + asm output (for multiple compilers). For more about reading compiler output, see this Q&A, and Matt's CppCon2017 talk: “What Has My Compiler Done for Me Lately? Unbolting the Compiler's Lid”,

In FP code, it's usually a big win to inline small functions. Especially on non-Windows, where the standard calling convention has no call-preserved registers, so the compiler can't keep any FP values in XMM registers across a call. So even if you don't really know asm, you can still easily see whether it's just a tail-call to the library function or whether it inlined to one or two math instructions. Anything that inlines to one or two instructions is better than a function call (for this particular task on x86 or ARM).

On x86, anything that inlines to SSE4.1 roundsd can auto-vectorize with SSE4.1 roundpd (or AVX vroundpd). (FP->integer conversions are also available in packed SIMD form, except for FP->64-bit integer which requires AVX512.)

  • std::nearbyint():

    • x86 clang: inlines to a single insn with -msse4.1.
    • x86 gcc: inlines to a single insn only with -msse4.1 -ffast-math, and only on gcc 5.4 and earlier. Later gcc never inlines it (maybe they didn't realize that one of the immediate bits can suppress the inexact exception? That's what clang uses, but older gcc uses the same immediate as for rint when it does inline it)
    • AArch64 gcc6.3: inlines to a single insn by default.
  • std::rint:

    • x86 clang: inlines to a single insn with -msse4.1
    • x86 gcc7: inlines to a single insn with -msse4.1. (Without SSE4.1, inlines to several instructions)
    • x86 gcc6.x and earlier: inlines to a single insn with -ffast-math -msse4.1.
    • AArch64 gcc: inlines to a single insn by default
  • std::round:

    • x86 clang: doesn't inline
    • x86 gcc: inlines to multiple instructions with -ffast-math -msse4.1, requiring two vector constants.
    • AArch64 gcc: inlines to a single instruction (HW support for this rounding mode as well as IEEE default and most others.)
  • std::floor / std::ceil / std::trunc

    • x86 clang: inlines to a single insn with -msse4.1
    • x86 gcc7.x: inlines to a single insn with -msse4.1
    • x86 gcc6.x and earlier: inlines to a single insn with -ffast-math -msse4.1
    • AArch64 gcc: inlines by default to a single instruction

Rounding to int / long / long long:

You have two options here: use lrint (like rint but returns long, or long long for llrint), or use an FP->FP rounding function and then convert to an integer type the normal way (with truncation). Some compilers optimize one way better than the other.

long l = lrint(x);

int  i = (int)rint(x);

Note that int i = lrint(x) converts float or double -> long first, and then truncates the integer to int. This makes a difference for out-of-range integers: Undefined Behaviour in C++, but well-defined for the x86 FP -> int instructions (which the compiler will emit unless it sees the UB at compile time while doing constant propagation, then it's allowed to make code that breaks if it's ever executed).

On x86, an FP->integer conversion that overflows the integer produces INT_MIN or LLONG_MIN (a bit-pattern of 0x8000000 or the 64-bit equivalent, with just the sign-bit set). Intel calls this the "integer indefinite" value. (See the cvttsd2si manual entry, the SSE2 instruction that converts (with truncation) scalar double to signed integer. It's available with 32-bit or 64-bit integer destination (in 64-bit mode only). There's also a cvtsd2si (convert with current rounding mode), which is what we'd like the compiler to emit, but unfortunately gcc and clang won't do that without -ffast-math.

Also beware that FP to/from unsigned int / long is less efficient on x86 (without AVX512). Conversion to 32-bit unsigned on a 64-bit machine is pretty cheap; just convert to 64-bit signed and truncate. But otherwise it's significantly slower.

  • x86 clang with/without -ffast-math -msse4.1: (int/long)rint inlines to roundsd / cvttsd2si. (missed optimization to cvtsd2si). lrint doesn't inline at all.

  • x86 gcc6.x and earlier without -ffast-math: neither way inlines

  • x86 gcc7 without -ffast-math: (int/long)rint rounds and converts separately (with 2 total instructions of SSE4.1 is enabled, otherwise with a bunch of code inlined for rint without roundsd). lrint doesn't inline.
  • x86 gcc with -ffast-math: all ways inline to cvtsd2si (optimal), no need for SSE4.1.

  • AArch64 gcc6.3 without -ffast-math: (int/long)rint inlines to 2 instructions. lrint doesn't inline

  • AArch64 gcc6.3 with -ffast-math: (int/long)rint compiles to a call to lrint. lrint doesn't inline. This may be a missed optimization unless the two instructions we get without -ffast-math are very slow.

Use jQuery to change a second select list based on the first select list option

I have found the solution as followiing... working for me perfectly :)

$(document).ready(function(){
$("#selectbox1").change(function() {
    var id = $(this).val();
    $("#selectbox2").val(id);
 });   });

How to write UTF-8 in a CSV file

For python2 you can use this code before csv_writer.writerows(rows)
This code will NOT convert integers to utf-8 strings

def encode_rows_to_utf8(rows):
    encoded_rows = []
    for row in rows:
        encoded_row = []
        for value in row:
            if isinstance(value, basestring):
                value = unicode(value).encode("utf-8")
            encoded_row.append(value)
        encoded_rows.append(encoded_row)
    return encoded_rows

Removing path and extension from filename in PowerShell

The command below will store in a variable all the file in your folder, matchting the extension ".txt":

$allfiles=Get-ChildItem -Path C:\temp\*" -Include *.txt
foreach ($file in $allfiles) {
    Write-Host $file
    Write-Host $file.name
    Write-Host $file.basename
}

$file gives the file with path, name and extension: c:\temp\myfile.txt

$file.name gives file name & extension: myfile.txt

$file.basename gives only filename: myfile

How to set component default props on React component

You forgot to close the Class bracket.

_x000D_
_x000D_
class AddAddressComponent extends React.Component {_x000D_
  render() {_x000D_
    let {provinceList,cityList} = this.props_x000D_
    if(cityList === undefined || provinceList === undefined){_x000D_
      console.log('undefined props')_x000D_
    } else {_x000D_
      console.log('defined props')_x000D_
    }_x000D_
_x000D_
    return (_x000D_
      <div>rendered</div>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
AddAddressComponent.contextTypes = {_x000D_
  router: React.PropTypes.object.isRequired_x000D_
};_x000D_
_x000D_
AddAddressComponent.defaultProps = {_x000D_
  cityList: [],_x000D_
  provinceList: [],_x000D_
};_x000D_
_x000D_
AddAddressComponent.propTypes = {_x000D_
  userInfo: React.PropTypes.object,_x000D_
  cityList: React.PropTypes.array.isRequired,_x000D_
  provinceList: React.PropTypes.array.isRequired,_x000D_
}_x000D_
_x000D_
ReactDOM.render(_x000D_
  <AddAddressComponent />,_x000D_
  document.getElementById('app')_x000D_
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="app" />
_x000D_
_x000D_
_x000D_

Gather multiple sets of columns

This approach seems pretty natural to me:

df %>%
  gather(key, value, -id, -time) %>%
  extract(key, c("question", "loop_number"), "(Q.\\..)\\.(.)") %>%
  spread(question, value)

First gather all question columns, use extract() to separate into question and loop_number, then spread() question back into the columns.

#>    id       time loop_number         Q3.2        Q3.3
#> 1   1 2009-01-01           1  0.142259203 -0.35842736
#> 2   1 2009-01-01           2  0.061034802  0.79354061
#> 3   1 2009-01-01           3 -0.525686204 -0.67456611
#> 4   2 2009-01-02           1 -1.044461185 -1.19662936
#> 5   2 2009-01-02           2  0.393808163  0.42384717

When is it acceptable to call GC.Collect?

This isn't that relevant to the question, but for XSLT transforms in .NET (XSLCompiledTranform) then you might have no choice. Another candidate is the MSHTML control.

How can I remove the "No file chosen" tooltip from a file input in Chrome?

It's better to avoid using unnecessary javascript. You can take advantage of the label tag to expand the click target of the input like so:

<label>
  <input type="file" style="display: none;">
  <a>Open</a>
</label>

Even though input is hidden, the link still works as a click target for it, and you can style it however you want.

disable editing default value of text input

I don't think all the other answerers understood the question correctly. The question requires disabling editing part of the text. One solution I can think of is simulating a textbox with a fixed prefix which is not part of the textarea or input.

An example of this approach is:

<div style="border:1px solid gray; color:#999999; font-family:arial; font-size:10pt; width:200px; white-space:nowrap;">Default Notes<br/>
<textarea style="border:0px solid black;" cols="39" rows="5"></textarea></div>

The other approach, which I end up using is using JS and JQuery to simulate "Disable" feature. Example with pseudo-code (cannot be specific cause of legal issue):

  // disable existing notes by preventing keystroke
  document.getElementById("txtNotes").addEventListener('keydown', function (e) {
    if (cursorLocation < defaultNoteLength ) {
            e.preventDefault();
  });

    // disable existing notes by preventing right click
    document.addEventListener('contextmenu', function (e) {
        if (cursorLocation < defaultNoteLength )
            e.preventDefault();
    });

Thanks, Carsten, for mentioning that this question is old, but I found that the solution might help other people in the future.

Check table exist or not before create it in Oracle

As Rene also commented, it's quite uncommon to check first and then create the table. If you want to have a running code according to your method, this will be:

declare
nCount NUMBER;
v_sql LONG;

begin
SELECT count(*) into nCount FROM dba_tables where table_name = 'EMPLOYEE';
IF(nCount <= 0)
THEN
v_sql:='
create table EMPLOYEE
(
ID NUMBER(3),
NAME VARCHAR2(30) NOT NULL
)';
execute immediate v_sql;

END IF;
end;

But I'd rather go catch on the Exception, saves you some unnecessary lines of code:

declare
v_sql LONG;
begin

v_sql:='create table EMPLOYEE
  (
  ID NUMBER(3),
  NAME VARCHAR2(30) NOT NULL
  )';
execute immediate v_sql;

EXCEPTION
    WHEN OTHERS THEN
      IF SQLCODE = -955 THEN
        NULL; -- suppresses ORA-00955 exception
      ELSE
         RAISE;
      END IF;
END; 
/

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

libxml install error using pip

sudo apt install libxslt-dev libxml2-dev

and then try upgrading python setuptools

pip install -U pip setuptools

this should resolve it.

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

Deleting Global.asax and restarting Visual Studio fixed the problem for me.

Maven plugins can not be found in IntelliJ

  1. Check the plugins which cannot be found (maven-site-plugin,maven-resources-plugin)
  2. go to '.m2/repository/org/apache/maven/plugins/'
  3. delete the directory rm -rf plugin-directory-name (eg: rm -rf maven-site-plugin)
  4. exit project from intellij
  5. import project again
  6. Do a Maven reimport

Explanation: when you do a maven reimport, it will download all the missing plugins again.

Happy Coding

How can I get column names from a table in SQL Server?

SELECT COLUMN_NAME
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'name_of_your_table'

Change working directory in my current shell context when running Node script

There is no built-in method for Node to change the CWD of the underlying shell running the Node process.

You can change the current working directory of the Node process through the command process.chdir().

var process = require('process');
process.chdir('../');

When the Node process exists, you will find yourself back in the CWD you started the process in.

How can I view all historical changes to a file in SVN

Start with

svn log -q file | grep '^r' | cut -f1 -d' '

That will get you a list of revisions where the file changed, which you can then use to script repeated calls to svn diff.

How do I compare if a string is not equal to?

Either != or ne will work, but you need to get the accessor syntax and nested quotes sorted out.

<c:if test="${content.contentType.name ne 'MCE'}">
    <%-- snip --%>
</c:if>

Bash command to sum a column of numbers

The following command will add all the lines(first field of the awk output)

awk '{s+=$1} END {print s}' filename

how to remove the first two columns in a file using shell (awk, sed, whatever)

You can do it with cut:

cut -d " " -f 3- input_filename > output_filename

Explanation:

  • cut: invoke the cut command
  • -d " ": use a single space as the delimiter (cut uses TAB by default)
  • -f: specify fields to keep
  • 3-: all the fields starting with field 3
  • input_filename: use this file as the input
  • > output_filename: write the output to this file.

Alternatively, you can do it with awk:

awk '{$1=""; $2=""; sub("  ", " "); print}' input_filename > output_filename

Explanation:

  • awk: invoke the awk command
  • $1=""; $2="";: set field 1 and 2 to the empty string
  • sub(...);: clean up the output fields because fields 1 & 2 will still be delimited by " "
  • print: print the modified line
  • input_filename > output_filename: same as above.

SVN 405 Method Not Allowed

I encountered the same issue and was able to fix it by:

  1. Copy the folder to another place.
  2. Delete .svn from copied folder
  3. Right click the original folder and select 'SVN Checkout'
  4. If you can't find (3), then your case is different than mine.
  5. See if the directory on the REPO-BROWSER is correct. For my case, this was the cause.
  6. Check out
  7. Get back the files from the copied folder into the original directory.
  8. Commit.

Error "The goal you specified requires a project to execute but there is no POM in this directory" after executing maven command

Add the Jenkinsfile where the pom.xml file has present. Provide the directory path on dir('project-dir'),

Ex:

node {

    withMaven(maven:'maven') {

        stage('Checkout') {
            git url: 'http://xxxxxxx/gitlab/root/XXX.git', credentialsId: 'xxxxx', branch: 'xxx'
        }

        stage('Build') {

            **dir('project-dir') {**
                sh 'mvn clean install'

                def pom = readMavenPom file:'pom.xml'

                print pom.version
                env.version = pom.version
            }
        }
    }
}

How to print variables without spaces between values

It's the comma which is providing that extra white space.

One way is to use the string % method:

print 'Value is "%d"' % (value)

which is like printf in C, allowing you to incorporate and format the items after % by using format specifiers in the string itself. Another example, showing the use of multiple values:

print '%s is %3d.%d' % ('pi', 3, 14159)

For what it's worth, Python 3 greatly improves the situation by allowing you to specify the separator and terminator for a single print call:

>>> print(1,2,3,4,5)
1 2 3 4 5

>>> print(1,2,3,4,5,end='<<\n')
1 2 3 4 5<<

>>> print(1,2,3,4,5,sep=':',end='<<\n')
1:2:3:4:5<<

How to continue the code on the next line in VBA

In VBA (and VB.NET) the line terminator (carriage return) is used to signal the end of a statement. To break long statements into several lines, you need to

Use the line-continuation character, which is an underscore (_), at the point at which you want the line to break. The underscore must be immediately preceded by a space and immediately followed by a line terminator (carriage return).

(From How to: Break and Combine Statements in Code)

In other words: Whenever the interpreter encounters the sequence <space>_<line terminator>, it is ignored and parsing continues on the next line. Note, that even when ignored, the line continuation still acts as a token separator, so it cannot be used in the middle of a variable name, for example. You also cannot continue a comment by using a line-continuation character.

To break the statement in your question into several lines you could do the following:

U_matrix(i, j, n + 1) = _
     k * b_xyt(xi, yi, tn) / (4 * hx * hy) * U_matrix(i + 1, j + 1, n) + _
     (k * (a_xyt(xi, yi, tn) / hx ^ 2 + d_xyt(xi, yi, tn) / (2 * hx)))

(Leading whitespaces are ignored.)

How to store arrays in MySQL?

In MySQL, use the JSON type.

Contra the answers above, the SQL standard has included array types for almost twenty years; they are useful, even if MySQL has not implemented them.

In your example, however, you'll likely want to create three tables: person and fruit, then person_fruit to join them.

DROP TABLE IF EXISTS person_fruit;
DROP TABLE IF EXISTS person;
DROP TABLE IF EXISTS fruit;

CREATE TABLE person (
  person_id   INT           NOT NULL AUTO_INCREMENT,
  person_name VARCHAR(1000) NOT NULL,
  PRIMARY KEY (person_id)
);

CREATE TABLE fruit (
  fruit_id    INT           NOT NULL AUTO_INCREMENT,
  fruit_name  VARCHAR(1000) NOT NULL,
  fruit_color VARCHAR(1000) NOT NULL,
  fruit_price INT           NOT NULL,
  PRIMARY KEY (fruit_id)
);

CREATE TABLE person_fruit (
  pf_id     INT NOT NULL AUTO_INCREMENT,
  pf_person INT NOT NULL,
  pf_fruit  INT NOT NULL,
  PRIMARY KEY (pf_id),
  FOREIGN KEY (pf_person) REFERENCES person (person_id),
  FOREIGN KEY (pf_fruit) REFERENCES fruit (fruit_id)
);

INSERT INTO person (person_name)
VALUES
  ('John'),
  ('Mary'),
  ('John'); -- again

INSERT INTO fruit (fruit_name, fruit_color, fruit_price)
VALUES
  ('apple', 'red', 1),
  ('orange', 'orange', 2),
  ('pineapple', 'yellow', 3);

INSERT INTO person_fruit (pf_person, pf_fruit)
VALUES
  (1, 1),
  (1, 2),
  (2, 2),
  (2, 3),
  (3, 1),
  (3, 2),
  (3, 3);

If you wish to associate the person with an array of fruits, you can do so with a view:

DROP VIEW IF EXISTS person_fruit_summary;
CREATE VIEW person_fruit_summary AS
  SELECT
    person_id                                                                                              AS pfs_person_id,
    max(person_name)                                                                                       AS pfs_person_name,
    cast(concat('[', group_concat(json_quote(fruit_name) ORDER BY fruit_name SEPARATOR ','), ']') as json) AS pfs_fruit_name_array
  FROM
    person
    INNER JOIN person_fruit
      ON person.person_id = person_fruit.pf_person
    INNER JOIN fruit
      ON person_fruit.pf_fruit = fruit.fruit_id
  GROUP BY
    person_id;

The view shows the following data:

+---------------+-----------------+----------------------------------+
| pfs_person_id | pfs_person_name | pfs_fruit_name_array             |
+---------------+-----------------+----------------------------------+
|             1 | John            | ["apple", "orange"]              |
|             2 | Mary            | ["orange", "pineapple"]          |
|             3 | John            | ["apple", "orange", "pineapple"] |
+---------------+-----------------+----------------------------------+

In 5.7.22, you'll want to use JSON_ARRAYAGG, rather than hack the array together from a string.

TypeError: coercing to Unicode: need string or buffer

For the less specific case (not just the code in the question - since this is one of the first results in Google for this generic error message. This error also occurs when running certain os command with None argument.

For example:

os.path.exists(arg)  
os.stat(arg)

Will raise this exception when arg is None.

angularjs getting previous route path

modification for the code above:

$scope.$on('$locationChangeStart',function(evt, absNewUrl, absOldUrl) {
   console.log('prev path: ' + absOldUrl.$$route.originalPath);
});

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

Do not use arrow function to create functional components.

Do as one of the examples below:

function MyComponent(props) {
  const [states, setStates] = React.useState({ value: '' });

  return (
    <input
      type="text"
      value={states.value}
      onChange={(event) => setStates({ value: event.target.value })}
    />
  );
}

Or

//IMPORTANT: Repeat the function name

const MyComponent = function MyComponent(props) { 
  const [states, setStates] = React.useState({ value: '' });

  return (
    <input
      type="text"
      value={states.value}
      onChange={(event) => setStates({ value: event.target.value })}
    />
  );
};

If you have problems with "ref" (probably in loops), the solution is to use forwardRef():

// IMPORTANT: Repeat the function name
// Add the "ref" argument to the function, in case you need to use it.

const MyComponent = React.forwardRef( function MyComponent(props, ref) {
  const [states, setStates] = React.useState({ value: '' });

  return (
    <input
      type="text"
      value={states.value}
      onChange={(event) => setStates({ value: event.target.value })}
    />
  );
});

Update records using LINQ

This worked best.

(from p in Context.person_account_portfolio 
 where p.person_id == personId select p).ToList()
                                        .ForEach(x => x.is_default = false);

Context.SaveChanges();

Android and Facebook share intent

In Lollipop (21), you can use Intent.EXTRA_REPLACEMENT_EXTRAS to override the intent for Facebook specifically (and specify a link only)

https://developer.android.com/reference/android/content/Intent.html#EXTRA_REPLACEMENT_EXTRAS

private void doShareLink(String text, String link) {
  Intent shareIntent = new Intent(Intent.ACTION_SEND);
  shareIntent.setType("text/plain");
  Intent chooserIntent = Intent.createChooser(shareIntent, getString(R.string.share_via));

  // for 21+, we can use EXTRA_REPLACEMENT_EXTRAS to support the specific case of Facebook
  // (only supports a link)
  // >=21: facebook=link, other=text+link
  // <=20: all=link
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
    shareIntent.putExtra(Intent.EXTRA_TEXT, text + " " + link);
    Bundle facebookBundle = new Bundle();
    facebookBundle.putString(Intent.EXTRA_TEXT, link);
    Bundle replacement = new Bundle();
    replacement.putBundle("com.facebook.katana", facebookBundle);
    chooserIntent.putExtra(Intent.EXTRA_REPLACEMENT_EXTRAS, replacement);
  } else {
    shareIntent.putExtra(Intent.EXTRA_TEXT, link);
  }

  chooserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  startActivity(chooserIntent);
}

Android Error [Attempt to invoke virtual method 'void android.app.ActionBar' on a null object reference]

Whenever such an error occurs. Try to check Following Things

  1. Check what kind of Activity is being used, is it a simple android.app Activity or an AppCompatActivity or an ActionBarActivity and so on.

  2. Check if your activity type which is extended falls under the compat category

example android.app based Activity/Fragment are non appCompat types, whereas android.support.v4.app.Fragment or android.support.v4.app.ActivityCompat are appCompat based

if it falls under appCompat we use getSupportActionBar() else for android.app types we can use getActionBar()

  1. Check the theme applied to the activity in question in the manifest file

example: In the manifest file if theme applied is say android:theme="@android:style/Theme.Holo.Dialog" getActionBar() will work

but if theme applied for the activity in the manifest is as follows android:theme="@style/Theme.AppCompat.Light" then you have to use getSupportActionBar()

What does 'killed' mean when a processing of a huge CSV with Python, which suddenly stops?

There are two storage areas involved: the stack and the heap.The stack is where the current state of a method call is kept (ie local variables and references), and the heap is where objects are stored. recursion and memory

I gues there are too many keys in the counter dict that will consume too much memory of the heap region, so the Python runtime will raise a OutOfMemory exception.

To save it, don't create a giant object, e.g. the counter.

1.StackOverflow

a program that create too many local variables.

Python 2.7.9 (default, Mar  1 2015, 12:57:24) 
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> f = open('stack_overflow.py','w')
>>> f.write('def foo():\n')
>>> for x in xrange(10000000):
...   f.write('\tx%d = %d\n' % (x, x))
... 
>>> f.write('foo()')
>>> f.close()
>>> execfile('stack_overflow.py')
Killed

2.OutOfMemory

a program that creats a giant dict includes too many keys.

>>> f = open('out_of_memory.py','w')
>>> f.write('def foo():\n')
>>> f.write('\tcounter = {}\n')
>>> for x in xrange(10000000):
...   f.write('counter[%d] = %d\n' % (x, x))
... 
>>> f.write('foo()\n')
>>> f.close()
>>> execfile('out_of_memory.py')
Killed

References

How do I make a JSON object with multiple arrays?

var cars = [
    manufacturer: [
        {
            color: 'gray',
            model: '1',
            nOfDoors: 4
        },
        {
            color: 'yellow',
            model: '2',
            nOfDoors: 4
        }
    ]
]

Move UIView up when the keyboard appears in iOS

Here you go. I have used this code with UIView, though. You should be able to make those adjustments for scrollview.

    func addKeyboardNotifications() {
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillShow(notification:)),
                                               name: NSNotification.Name.UIKeyboardWillShow, object: nil)
        NotificationCenter.default.addObserver(self,
                                               selector: #selector(keyboardWillHide(notification:)),
                                               name: NSNotification.Name.UIKeyboardWillHide, object: nil)
    }

    func keyboardWillShow(notification: NSNotification) {

        if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue {
            let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
// if using constraints            
// bottomViewBottomSpaceConstraint.constant = keyboardSize.height
self.view.frame.origin.y -= keyboardSize.height
            UIView.animate(withDuration: duration) {
                self.view.layoutIfNeeded()
            }
        }
    }
    func keyboardWillHide(notification: NSNotification) {

        let duration = notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! Double
//if using constraint
//        bottomViewBottomSpaceConstraint.constant = 0
self.view.frame.origin.y = 0
        UIView.animate(withDuration: duration) {
            self.view.layoutIfNeeded()
        }
    }

Don't forget to remove notifications at right place.

func removeKeyboardNotifications() {
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillShow, object: nil)
    NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIKeyboardWillHide, object: nil)
}

jQuery and AJAX response header

try this:

type: "GET",
async: false,
complete: function (XMLHttpRequest, textStatus) {
    var headers = XMLHttpRequest.getAllResponseHeaders();
}

Width equal to content

I set width as max-content and it worked for me.

width: max-content;

Angular: Cannot Get /

See this answer here. You need to redirect all routes that Node is not using to Angular:

app.get('*', function(req, res) {
  res.sendfile('./server/views/index.html')
})

How do I run a class in a WAR from the command line?

A war is a webapp. If you want to have a console/standalone application reusing the same classes as you webapp, consider packaging your shared classes in a jar, which you can put in WEB-INF/lib. Then use that jar from the command line. Thus you get both your console application, and you can use the same classes in your servlets, without making two different packages. This, of course, is true when the war is exploded.

How to list files inside a folder with SQL Server

If you want you can achieve this using a CLR Function/Assembly.

  1. Create a SQL Server CLR Assembly Project.
  2. Go to properties and ensure the permission level on the Connection is setup to external
  3. Add A Sql Function to the Assembly.

Here's an example which will allow you to select form your result set like a table.

public partial class UserDefinedFunctions
{
    [SqlFunction(DataAccess = DataAccessKind.Read,
        FillRowMethodName = "GetFiles_FillRow", TableDefinition = "FilePath nvarchar(4000)")]
    public static IEnumerable GetFiles(SqlString path)
    {
        return System.IO.Directory.GetFiles(path.ToString()).Select(s => new SqlString(s));
    }

    public static void GetFiles_FillRow(object obj,out SqlString filePath)
    {
        filePath = (SqlString)obj;
    }
};

And your SQL query.

use MyDb

select * From GetFiles('C:\Temp\');

Be aware though, your database needs to have CLR Assembly functionaliy enabled using the following SQL Command.

sp_configure 'clr enabled', 1
GO
RECONFIGURE
GO

CLR Assemblies (like XP_CMDShell) are disabled by default so if the reason for not using XP Cmd Shell is because you don't have permission, then you may be stuck with this option as well... just FYI.

Can I check if Bootstrap Modal Shown / Hidden?

Use hasClass('in'). It will return true if modal is in OPEN state.

E.g:

if($('.modal').hasClass('in')){
   //Do something here
}

How do I reset the scale/zoom of a web app on an orientation change on the iPhone?

Here's another way to do it, which seems to work well.

  1. Set the meta tag to restrict the viewport to scale=1, which prevents zooming:

    < meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1">

  2. With javascript, change the meta tag 1/2 second later to allow zooming:

    setTimeout(function(){ document.querySelector("meta[name=viewport]").setAttribute('content','width=device-width, initial-scale=1');}, 500);

  3. Again with javascript, on orientation change, reload the page:

    window.onorientationchange = function(){window.location.reload();};

Every time you reorient the device, the page reloads, initially without zoom. But 1/2 second later, ability to zoom is restored.

What are enums and why are they useful?

In addition to @BradB Answer :

That is so true... It's strange that it is the only answer who mention that. When beginners discover enums, they quickly take that as a magic-trick for valid identifier checking for the compiler. And when the code is intended to be use on distributed systems, they cry... some month later. Maintain backward compatibility with enums that contains non static list of values is a real concern, and pain. This is because when you add a value to an existing enum, its type change (despite the name does not).

"Ho, wait, it may look like the same type, right? After all, they’re enums with the same name – and aren’t enums just integers under the hood?" And for these reasons, your compiler will likely not flag the use of one definition of the type itself where it was expecting the other. But in fact, they are (in most important ways) different types. Most importantly, they have different data domains – values that are acceptable given the type. By adding a value, we’ve effectively changed the type of the enum and therefore break backward compatibility.

In conclusion : Use it when you want, but, please, check that the data domain used is a finite, already known, fixed set.