Programs & Examples On #Pattern recognition

Pattern recognition is the term given to the science of automating the classification of input into pre-determined categories, or on the other hand, of being able to recognise particular categories of input by their characteristics.

Centering Bootstrap input fields

Ok, this is best solution for me. Bootstrap includes mobile-first fluid grid system that appropriately scales up to 12 columns as the device or viewport size increases. So this worked perfectly on every browser and device:

        <div class="row">
            <div class="col-lg-4"></div>
            <div class="col-lg-4">
                <div class="input-group">
                    <input type="text" class="form-control" /> 
                    <span class="input-group-btn">
                        <button class="btn btn-default" type="button">Go!</button>
                    </span>
                </div><!-- /input-group -->
            </div><!-- /.col-lg-4 -->
            <div class="col-lg-4"></div>
        </div><!-- /.row -->

It means 4 + 4 + 4 =12... so second div will be in the middle that way.

Example: http://jsfiddle.net/jpGwm/embedded/result/

How do I upload a file with metadata using a REST web service?

If your file and its metadata creating one resource, its perfectly fine to upload them both in one request. Sample request would be :

POST https://target.com/myresources/resourcename HTTP/1.1

Accept: application/json

Content-Type: multipart/form-data; 

boundary=-----------------------------28947758029299

Host: target.com

-------------------------------28947758029299

Content-Disposition: form-data; name="application/json"

{"markers": [
        {
            "point":new GLatLng(40.266044,-74.718479), 
            "homeTeam":"Lawrence Library",
            "awayTeam":"LUGip",
            "markerImage":"images/red.png",
            "information": "Linux users group meets second Wednesday of each month.",
            "fixture":"Wednesday 7pm",
            "capacity":"",
            "previousScore":""
        },
        {
            "point":new GLatLng(40.211600,-74.695702),
            "homeTeam":"Hamilton Library",
            "awayTeam":"LUGip HW SIG",
            "markerImage":"images/white.png",
            "information": "Linux users can meet the first Tuesday of the month to work out harward and configuration issues.",
            "fixture":"Tuesday 7pm",
            "capacity":"",
            "tv":""
        },
        {
            "point":new GLatLng(40.294535,-74.682012),
            "homeTeam":"Applebees",
            "awayTeam":"After LUPip Mtg Spot",
            "markerImage":"images/newcastle.png",
            "information": "Some of us go there after the main LUGip meeting, drink brews, and talk.",
            "fixture":"Wednesday whenever",
            "capacity":"2 to 4 pints",
            "tv":""
        },
] }

-------------------------------28947758029299

Content-Disposition: form-data; name="name"; filename="myfilename.pdf"

Content-Type: application/octet-stream

%PDF-1.4
%
2 0 obj
<</Length 57/Filter/FlateDecode>>stream
x+r
26S00SI2P0Qn
F
!i\
)%[email protected]
[
endstream
endobj
4 0 obj
<</Type/Page/MediaBox[0 0 595 842]/Resources<</Font<</F1 1 0 R>>>>/Contents 2 0 R/Parent 3 0 R>>
endobj
1 0 obj
<</Type/Font/Subtype/Type1/BaseFont/Helvetica/Encoding/WinAnsiEncoding>>
endobj
3 0 obj
<</Type/Pages/Count 1/Kids[4 0 R]>>
endobj
5 0 obj
<</Type/Catalog/Pages 3 0 R>>
endobj
6 0 obj
<</Producer(iTextSharp 5.5.11 2000-2017 iText Group NV \(AGPL-version\))/CreationDate(D:20170630120636+02'00')/ModDate(D:20170630120636+02'00')>>
endobj
xref
0 7
0000000000 65535 f 
0000000250 00000 n 
0000000015 00000 n 
0000000338 00000 n 
0000000138 00000 n 
0000000389 00000 n 
0000000434 00000 n 
trailer
<</Size 7/Root 5 0 R/Info 6 0 R/ID [<c7c34272c2e618698de73f4e1a65a1b5><c7c34272c2e618698de73f4e1a65a1b5>]>>
%iText-5.5.11
startxref
597
%%EOF

-------------------------------28947758029299--

Passing the argument to CMAKE via command prompt

In the CMakeLists.txt file, create a cache variable, as documented here:

SET(FAB "po" CACHE STRING "Some user-specified option")

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#command:set

Then, either use the GUI (ccmake or cmake-gui) to set the cache variable, or specify the value of the variable on the cmake command line:

cmake -DFAB:STRING=po

Source: http://cmake.org/cmake/help/v2.8.8/cmake.html#opt:-Dvar:typevalue

Modify your cache variable to a boolean if, in fact, your option is boolean.

How do I convert an NSString value to NSData?

NSString* str = @"teststring";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];

How to create friendly URL in php?

There are lots of different ways to do this. One way is to use the RewriteRule techniques mentioned earlier to mask query string values.

One of the ways I really like is if you use the front controller pattern, you can also use urls like http://yoursite.com/index.php/path/to/your/page/here and parse the value of $_SERVER['REQUEST_URI'].

You can easily extract the /path/to/your/page/here bit with the following bit of code:

$route = substr($_SERVER['REQUEST_URI'], strlen($_SERVER['SCRIPT_NAME']));

From there, you can parse it however you please, but for pete's sake make sure you sanitise it ;)

Laravel Eloquent Sum of relation's column

Also using query builder

DB::table("rates")->get()->sum("rate_value")

To get summation of all rate value inside table rates.

To get summation of user products.

DB::table("users")->get()->sum("products")

How to make RatingBar to show five stars

I found that the RatingBar stretched to a maximum number of stars because it was enclosed in a Table with the attribute android:stretchColumns = "*".

Once I took stretchCoulumns off all columns, the RatingBar displayed according to the android:numStars value

What is the difference between `let` and `var` in swift?

The

Declaring Constants and Variables section of The Swift Programming Language documentation specifies the following:

You declare constants with the let keyword and variables with the var keyword.

Make sure to understand how this works for Reference types. Unlike Value Types, the object's underlying properties can change despite an instance of a reference type being declared as a constant. See the Classes are Reference Types section of the documentation, and look at the example where they change the frameRate property.

How to delete rows in tables that contain foreign keys to other tables

First, as a one-time data-scrubbing exercise, delete the orphaned rows e.g.

DELETE 
  FROM ReferencingTable 
 WHERE NOT EXISTS (
                   SELECT * 
                     FROM MainTable AS T1
                    WHERE T1.pk_col_1 = ReferencingTable.pk_col_1
                  );

Second, as a one-time schema-alteration exercise, add the ON DELETE CASCADE referential action to the foreign key on the referencing table e.g.

ALTER TABLE ReferencingTable DROP 
   CONSTRAINT fk__ReferencingTable__MainTable;

ALTER TABLE ReferencingTable ADD 
   CONSTRAINT fk__ReferencingTable__MainTable 
      FOREIGN KEY (pk_col_1)
      REFERENCES MainTable (pk_col_1)
      ON DELETE CASCADE;

Then, forevermore, rows in the referencing tables will automatically be deleted when their referenced row is deleted.

How does the communication between a browser and a web server take place?

Hyper Text Transfer Protocol (HTTP) is a protocol used for transferring web pages (like the one you're reading right now). A protocol is really nothing but a standard way of doing things. If you were to meet the President of the United States, or the king of a country, there would be specific procedures that you'd have to follow. You couldn't just walk up and say "hey dude". There would be a specific way to walk, to talk, a standard greeting, and a standard way to end the conversation. Protocols in the TCP/IP stack serve the same purpose.

The TCP/IP stack has four layers: Application, Transport, Internet, and Network. At each layer there are different protocols that are used to standardize the flow of information, and each one is a computer program (running on your computer) that's used to format the information into a packet as it's moving down the TCP/IP stack. A packet is a combination of the Application Layer data, the Transport Layer header (TCP or UDP), and the IP layer header (the Network Layer takes the packet and turns it into a frame).

The Application Layer

...consists of all applications that use the network to transfer data. It does not care about how the data gets between two points and it knows very little about the status of the network. Applications pass data to the next layer in the TCP/IP stack and then continue to perform other functions until a reply is received. The Application Layer uses host names (like www.dalantech.com) for addressing. Examples of application layer protocols: Hyper Text Transfer Protocol (HTTP -web browsing), Simple Mail Transfer Protocol (SMTP -electronic mail), Domain Name Services (DNS -resolving a host name to an IP address), to name just a few.

The main purpose of the Application Layer is to provide a common command language and syntax between applications that are running on different operating systems -kind of like an interpreter. The data that is sent by an application that uses the network is formatted to conform to one of several set standards. The receiving computer can understand the data that is being sent even if it is running a different operating system than the sender due to the standards that all network applications conform to.

The Transport Layer

...is responsible for assigning source and destination port numbers to applications. Port numbers are used by the Transport Layer for addressing and they range from 1 to 65,535. Port numbers from 0 to 1023 are called "well known ports". The numbers below 256 are reserved for public (standard) services that run at the Application Layer. Here are a few: 25 for SMTP, 53 for DNS (udp for domain resolution and tcp for zone transfers) , and 80 for HTTP. The port numbers from 256 to 1023 are assigned by the IANA to companies for the applications that they sell.

Port numbers from 1024 to 65,535 are used for client side applications -the web browser you are using to read this page, for example. Windows will only assign port numbers up to 5000 -more than enough port numbers for a Windows based PC. Each application has a unique port number assigned to it by the transport layer so that as data is received by the Transport Layer it knows which application to give the data to. An example is when you have more than one browser window running. Each window is a separate instance of the program that you use to surf the web, and each one has a different port number assigned to it so you can go to www.dalantech.com in one browser window and this site does not load into another browser window. Applications like FireFox that use tabbed windows simply have a unique port number assigned to each tab

The Internet Layer

...is the "glue" that holds networking together. It permits the sending, receiving, and routing of data.

The Network Layer

...consists of your Network Interface Card (NIC) and the cable connected to it. It is the physical medium that is used to transmit and receive data. The Network Layer uses Media Access Control (MAC) addresses, discussed earlier, for addressing. The MAC address is fixed at the time an interface was manufactured and cannot be changed. There are a few exceptions, like DSL routers that allow you to clone the MAC address of the NIC in your PC.

For more info:

How to remove pip package after deleting it manually

I met the same issue while experimenting with my own Python library and what I've found out is that pip freeze will show you the library as installed if your current directory contains lib.egg-info folder. And pip uninstall <lib> will give you the same error message.

  1. Make sure your current directory doesn't have any egg-info folders
  2. Check pip show <lib-name> to see the details about the location of the library, so you can remove files manually.

What is the simplest way to SSH using Python?

I haven't tried it, but this pysftp module might help, which in turn uses paramiko. I believe everything is client-side.

The interesting command is probably .execute() which executes an arbitrary command on the remote machine. (The module also features .get() and .put methods which allude more to its FTP character).

UPDATE:

I've re-written the answer after the blog post I originally linked to is not available anymore. Some of the comments that refer to the old version of this answer will now look weird.

Disabling Warnings generated via _CRT_SECURE_NO_DEPRECATE

Another late answer... Here's how Microsoft uses it in their wchar.h. Notice they also disable Warning C6386:

__inline _CRT_INSECURE_DEPRECATE_MEMORY(wmemcpy_s) wchar_t * __CRTDECL
wmemcpy(_Out_opt_cap_(_N) wchar_t *_S1, _In_opt_count_(_N) const wchar_t *_S2, _In_ size_t _N)
{
    #pragma warning( push )
    #pragma warning( disable : 4996 6386 )
        return (wchar_t *)memcpy(_S1, _S2, _N*sizeof(wchar_t));
    #pragma warning( pop )
} 

Under what circumstances can I call findViewById with an Options Menu / Action Bar item?

I am trying to obtain a handle on one of the views in the Action Bar

I will assume that you mean something established via android:actionLayout in your <item> element of your <menu> resource.

I have tried calling findViewById(R.id.menu_item)

To retrieve the View associated with your android:actionLayout, call findItem() on the Menu to retrieve the MenuItem, then call getActionView() on the MenuItem. This can be done any time after you have inflated the menu resource.

multiprocessing: How do I share a dict among multiple processes?

A general answer involves using a Manager object. Adapted from the docs:

from multiprocessing import Process, Manager

def f(d):
    d[1] += '1'
    d['2'] += 2

if __name__ == '__main__':
    manager = Manager()

    d = manager.dict()
    d[1] = '1'
    d['2'] = 2

    p1 = Process(target=f, args=(d,))
    p2 = Process(target=f, args=(d,))
    p1.start()
    p2.start()
    p1.join()
    p2.join()

    print d

Output:

$ python mul.py 
{1: '111', '2': 6}

Convert string to number and add one

Have you tried flip-flopping it a bit?

var newcurrentpageTemp = parseInt($(this).attr("id"));
newcurrentpageTemp++;
alert(newcurrentpageTemp));

Why is Tkinter Entry's get function returning nothing?

You could also use a StringVar variable, even if it's not strictly necessary:

v = StringVar()

e = Entry(master, textvariable=v)
e.pack()

v.set("a default value")
s = v.get()

For more information, see this page on effbot.org.

How to redirect in a servlet filter?

In Filter the response is of ServletResponse rather than HttpServletResponse. Hence do the cast to HttpServletResponse.

HttpServletResponse httpResponse = (HttpServletResponse) response;
httpResponse.sendRedirect("/login.jsp");

If using a context path:

httpResponse.sendRedirect(req.getContextPath() + "/login.jsp");

Also don't forget to call return; at the end.

Javascript/Jquery to change class onclick?

Your getElementById is looking for an element with id "myclass", but in your html the id of the DIV is showhide. Change to:

<script>
function changeclass() {

var NAME = document.getElementById("showhide")

NAME.className="mynewclass"

} 
</script>

Unless you are trying to target a different element with the id "myclass", then you need to make sure such an element exists.

How to split a string of space separated numbers into integers?

Here is my answer for python 3.

some_string = "2 3 8 61 "

list(map(int, some_string.strip().split()))

How to check whether a select box is empty using JQuery/Javascript

To check whether select box has any values:

if( $('#fruit_name').has('option').length > 0 ) {

To check whether selected value is empty:

if( !$('#fruit_name').val() ) { 

How to convert a currency string to a double with jQuery or Javascript?

accounting.js is the way to go. I used it at a project and had very good experience using it.

accounting.formatMoney(4999.99, "€", 2, ".", ","); // €4.999,99
accounting.unformat("€ 1.000.000,00", ","); // 1000000

You can find it at GitHub

Make UINavigationBar transparent

C# / Xamarin Solution

NavigationController.NavigationBar.SetBackgroundImage(new UIImage(), UIBarMetrics.Default);
NavigationController.NavigationBar.ShadowImage = new UIImage();
NavigationController.NavigationBar.Translucent = true;

apache redirect from non www to www

RewriteEngine On RewriteCond %{HTTP_HOST} ^yourdomain.com [NC] RewriteRule ^(.*)$ http://www.yourdomain.com/$1 [L,R=301]

check this perfect work

JSON array get length

I came here and looking how to get the number of elements inside a JSONArray. From your question i used length() like that:

JSONArray jar = myjson.getJSONArray("_types");
System.out.println(jar.length());

and it worked as expected. On the other hand jar.size();(as proposed in the other answer) is not working for me.

So for future users searching (like me) how to get the size of a JSONArray, length() works just fine.

jquery stop child triggering parent event

Or, rather than having an extra event handler to prevent another handler, you can use the Event Object argument passed to your click event handler to determine whether a child was clicked. target will be the clicked element and currentTarget will be the .header div:

$(".header").click(function(e){
     //Do nothing if .header was not directly clicked
     if(e.target !== e.currentTarget) return;

     $(this).children(".children").toggle();
});

How do you do a limit query in JPQL or HQL?

The setFirstResult and setMaxResults Query methods

For a JPA and Hibernate Query, the setFirstResult method is the equivalent of OFFSET, and the setMaxResults method is the equivalent of LIMIT:

List<Post> posts = entityManager
.createQuery(
    "select p " +
    "from Post p " +
    "order by p.createdOn ")
.setFirstResult(10)
.setMaxResults(10)
.getResultList();

The LimitHandler abstraction

The Hibernate LimitHandler defines the database-specific pagination logic, and as illustrated by the following diagram, Hibernate supports many database-specific pagination options:

LimitHandler implementations

Now, depending on the underlying relational database system you are using, the above JPQL query will use the proper pagination syntax.

MySQL

SELECT p.id AS id1_0_,
       p.created_on AS created_2_0_,
       p.title AS title3_0_
FROM post p
ORDER BY p.created_on
LIMIT ?, ?

PostgreSQL

SELECT p.id AS id1_0_,
       p.created_on AS created_2_0_,
       p.title AS title3_0_
FROM post p
ORDER BY p.created_on
LIMIT ?
OFFSET ?

SQL Server

SELECT p.id AS id1_0_,
       p.created_on AS created_on2_0_,
       p.title AS title3_0_
FROM post p
ORDER BY p.created_on
OFFSET ? ROWS 
FETCH NEXT ? ROWS ONLY

Oracle

SELECT *
FROM (
    SELECT 
        row_.*, rownum rownum_
    FROM (
        SELECT 
            p.id AS id1_0_,
            p.created_on AS created_on2_0_,
            p.title AS title3_0_
        FROM post p
        ORDER BY p.created_on
    ) row_
    WHERE rownum <= ?
)
WHERE rownum_ > ?

The advantage of using setFirstResult and setMaxResults is that Hibernate can generate the database-specific pagination syntax for any supported relational databases.

And, you are not limited to JPQL queries only. You can use the setFirstResult and setMaxResults method seven for native SQL queries.

Native SQL queries

You don't have to hardcode the database-specific pagination when using native SQL queries. Hibernate can add that to your queries.

So, if you're executing this SQL query on PostgreSQL:

List<Tuple> posts = entityManager
.createNativeQuery(
    "SELECT " +
    "   p.id AS id, " +
    "   p.title AS title " +
    "from post p " +
    "ORDER BY p.created_on", Tuple.class)
.setFirstResult(10)
.setMaxResults(10)
.getResultList();

Hibernate will transform it as follows:

SELECT p.id AS id,
       p.title AS title
FROM post p
ORDER BY p.created_on
LIMIT ?
OFFSET ?

Cool, right?

Beyond SQL-based pagination

Pagination is good when you can index the filtering and sorting criteria. If your pagination requirements imply dynamic filtering, it's a much better approach to use an inverted-index solution, like ElasticSearch.

Hash Table/Associative Array in VBA

I've used Francesco Balena's HashTable class several times in the past when a Collection or Dictionary wasn't a perfect fit and i just needed a HashTable.

Is it possible to modify a registry entry via a .bat/.cmd script?

In addition to reg.exe, I highly recommend that you also check out powershell, its vastly more capable in its registry handling.

Programmatically close aspx page from code behind

UPDATE: I have taken all of your input and came up with the following solution:

In code behind:

protected void Page_Load(object sender, EventArgs e)    
{
    Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();");
}

In aspx page:

function CloseWindow() {
    window.close();
}

Difference between javacore, thread dump and heap dump in Websphere

Heap dumps anytime you wish to see what is being held in memory Out-of-memory errors Heap dumps - picture of in memory objects - used for memory analysis Java cores - also known as thread dumps or java dumps, used for viewing the thread activity inside the JVM at a given time. IBM javacores should a lot of additional information besides just the threads and stacks -- used to determine hangs, deadlocks, and reasons for performance degredation System cores

Variable not accessible when initialized outside function

It really depends on where your JavaScript code is located.

The problem is probably caused by the DOM not being loaded when the line

var systemStatus = document.getElementById("system-status");

is executed. You could try calling this in an onload event, or ideally use a DOM ready type event from a JavaScript framework.

facet label font size

This should get you started:

R> qplot(hwy, cty, data = mpg) + 
       facet_grid(. ~ manufacturer) + 
       theme(strip.text.x = element_text(size = 8, colour = "orange", angle = 90))

See also this question: How can I manipulate the strip text of facet plots in ggplot2?

Authentication issue when debugging in VS2013 - iis express

You could also modify the project properties for your web project, choose "Web" from left tabs, then change the Servers drop down to "Local IIS". Create a new virtual directory and use IIS manager to setup your site/app pool as desired.

I prefer this method, as you would typically have a local IIS v-directory (or site) to test locally. You won't affect any other sites this way either.

Web Project Properties

Lua String replace

Try:

name = "^aH^ai"
name = name:gsub("%^a", "")

See also: http://lua-users.org/wiki/StringLibraryTutorial

VBScript to send email without running Outlook

Yes. Blat or any other self contained SMTP mailer. Blat is a fairly full featured SMTP client that runs from command line

Blat is here

How do I protect javascript files?

Forget it, this is not doable.

No matter what you try it will not work. All a user needs to do to discover your code and it's location is to look in the net tab in firebug or use fiddler to see what requests are being made.

Declare a dictionary inside a static class

You can use the static/class constructor to initialize your dictionary:

public static class ErrorCode
{
    public const IDictionary<string, string> ErrorCodeDic;
    public static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

How can I escape a double quote inside double quotes?

Use a backslash:

echo "\""     # Prints one " character.

How does autowiring work in Spring?

How does @Autowired work internally?

Example:

class EnglishGreeting {
   private Greeting greeting;
   //setter and getter
}

class Greeting {
   private String message;
   //setter and getter
}

.xml file it will look alike if not using @Autowired:

<bean id="englishGreeting" class="com.bean.EnglishGreeting">
   <property name="greeting" ref="greeting"/>
</bean>

<bean id="greeting" class="com.bean.Greeting">
   <property name="message" value="Hello World"/>
</bean>

If you are using @Autowired then:

class EnglishGreeting {
   @Autowired //so automatically based on the name it will identify the bean and inject.
   private Greeting greeting;
   //setter and getter
}

.xml file it will look alike if not using @Autowired:

<bean id="englishGreeting" class="com.bean.EnglishGreeting"></bean>

<bean id="greeting" class="com.bean.Greeting">
   <property name="message" value="Hello World"/>
</bean>

If still have some doubt then go through below live demo

How does @Autowired work internally ?

How to edit/save a file through Ubuntu Terminal

Normal text editors are nano, or vi.

For example:

root@user:# nano galfit.feedme

or

root@user:# vi galfit.feedme

What's the difference between identifying and non-identifying relationships?

Here's a good description:

Relationships between two entities may be classified as being either "identifying" or "non-identifying". Identifying relationships exist when the primary key of the parent entity is included in the primary key of the child entity. On the other hand, a non-identifying relationship exists when the primary key of the parent entity is included in the child entity but not as part of the child entity's primary key. In addition, non-identifying relationships may be further classified as being either "mandatory" or "non-mandatory". A mandatory non-identifying relationship exists when the value in the child table cannot be null. On the other hand, a non-mandatory non-identifying relationship exists when the value in the child table can be null.

http://www.sqlteam.com/article/database-design-and-modeling-fundamentals

Here's a simple example of an identifying relationship:

Parent
------
ID (PK)
Name

Child
-----
ID (PK)
ParentID (PK, FK to Parent.ID) -- notice PK
Name

Here's a corresponding non-identifying relationship:

Parent
------
ID (PK)
Name

Child
-----
ID (PK)
ParentID (FK to Parent.ID) -- notice no PK
Name

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

If you just have a Python shell running, type:

import idlelib.PyShell
idlelib.PyShell.main()

How to find GCD, LCM on a set of numbers

int lcmcal(int i,int y)
{
    int n,x,s=1,t=1;
    for(n=1;;n++)
    {
        s=i*n;
        for(x=1;t<s;x++)
        {
            t=y*x;
        }
        if(s==t)
            break;
    }
    return(s);
}

ECONNREFUSED error when connecting to mongodb from node.js

ECONNREFUSED error

There are few reasons of this error in node :

  1. Your port is already serving some service so it will refuse your connection.

    go to command line and get pid by using following command

    $ lsof -i:port_number

    Now kill pid by using

    $ kill -9 pid(which you will get by above command)

  2. Your server is not running e.g. in this case please check your mongoose server is running or run by using following command.

    $ mongod

  3. There is also possibility your localhost is not configured properly so use 127.0.0.1:27017 instead of localhost.

String comparison in Objective-C

You can compare string with below functions.

NSString *first = @"abc";
NSString *second = @"abc";
NSString *third = [[NSString alloc] initWithString:@"abc"];
NSLog(@"%d", (second == third))  
NSLog(@"%d", (first == second)); 
NSLog(@"%d", [first isEqualToString:second]); 
NSLog(@"%d", [first isEqualToString:third]); 

Output will be :-
    0
    1
    1
    1

Python mock multiple return values

You can assign an iterable to side_effect, and the mock will return the next value in the sequence each time it is called:

>>> from unittest.mock import Mock
>>> m = Mock()
>>> m.side_effect = ['foo', 'bar', 'baz']
>>> m()
'foo'
>>> m()
'bar'
>>> m()
'baz'

Quoting the Mock() documentation:

If side_effect is an iterable then each call to the mock will return the next value from the iterable.

How to create a generic array?

You should not mix-up arrays and generics. They don't go well together. There are differences in how arrays and generic types enforce the type check. We say that arrays are reified, but generics are not. As a result of this, you see these differences working with arrays and generics.

Arrays are covariant, Generics are not:

What that means? You must be knowing by now that the following assignment is valid:

Object[] arr = new String[10];

Basically, an Object[] is a super type of String[], because Object is a super type of String. This is not true with generics. So, the following declaration is not valid, and won't compile:

List<Object> list = new ArrayList<String>(); // Will not compile.

Reason being, generics are invariant.

Enforcing Type Check:

Generics were introduced in Java to enforce stronger type check at compile time. As such, generic types don't have any type information at runtime due to type erasure. So, a List<String> has a static type of List<String> but a dynamic type of List.

However, arrays carry with them the runtime type information of the component type. At runtime, arrays use Array Store check to check whether you are inserting elements compatible with actual array type. So, the following code:

Object[] arr = new String[10];
arr[0] = new Integer(10);

will compile fine, but will fail at runtime, as a result of ArrayStoreCheck. With generics, this is not possible, as the compiler will try to prevent the runtime exception by providing compile time check, by avoiding creation of reference like this, as shown above.

So, what's the issue with Generic Array Creation?

Creation of array whose component type is either a type parameter, a concrete parameterized type or a bounded wildcard parameterized type, is type-unsafe.

Consider the code as below:

public <T> T[] getArray(int size) {
    T[] arr = new T[size];  // Suppose this was allowed for the time being.
    return arr;
}

Since the type of T is not known at runtime, the array created is actually an Object[]. So the above method at runtime will look like:

public Object[] getArray(int size) {
    Object[] arr = new Object[size];
    return arr;
}

Now, suppose you call this method as:

Integer[] arr = getArray(10);

Here's the problem. You have just assigned an Object[] to a reference of Integer[]. The above code will compile fine, but will fail at runtime.

That is why generic array creation is forbidden.

Why typecasting new Object[10] to E[] works?

Now your last doubt, why the below code works:

E[] elements = (E[]) new Object[10];

The above code have the same implications as explained above. If you notice, the compiler would be giving you an Unchecked Cast Warning there, as you are typecasting to an array of unknown component type. That means, the cast may fail at runtime. For e.g, if you have that code in the above method:

public <T> T[] getArray(int size) {
    T[] arr = (T[])new Object[size];        
    return arr;
}

and you call invoke it like this:

String[] arr = getArray(10);

this will fail at runtime with a ClassCastException. So, no this way will not work always.

What about creating an array of type List<String>[]?

The issue is the same. Due to type erasure, a List<String>[] is nothing but a List[]. So, had the creation of such arrays allowed, let's see what could happen:

List<String>[] strlistarr = new List<String>[10];  // Won't compile. but just consider it
Object[] objarr = strlistarr;    // this will be fine
objarr[0] = new ArrayList<Integer>(); // This should fail but succeeds.

Now the ArrayStoreCheck in the above case will succeed at runtime although that should have thrown an ArrayStoreException. That's because both List<String>[] and List<Integer>[] are compiled to List[] at runtime.

So can we create array of unbounded wildcard parameterized types?

Yes. The reason being, a List<?> is a reifiable type. And that makes sense, as there is no type associated at all. So there is nothing to loose as a result of type erasure. So, it is perfectly type-safe to create an array of such type.

List<?>[] listArr = new List<?>[10];
listArr[0] = new ArrayList<String>();  // Fine.
listArr[1] = new ArrayList<Integer>(); // Fine

Both the above case is fine, because List<?> is super type of all the instantiation of the generic type List<E>. So, it won't issue an ArrayStoreException at runtime. The case is same with raw types array. As raw types are also reifiable types, you can create an array List[].

So, it goes like, you can only create an array of reifiable types, but not non-reifiable types. Note that, in all the above cases, declaration of array is fine, it's the creation of array with new operator, which gives issues. But, there is no point in declaring an array of those reference types, as they can't point to anything but null (Ignoring the unbounded types).

Is there any workaround for E[]?

Yes, you can create the array using Array#newInstance() method:

public <E> E[] getArray(Class<E> clazz, int size) {
    @SuppressWarnings("unchecked")
    E[] arr = (E[]) Array.newInstance(clazz, size);

    return arr;
}

Typecast is needed because that method returns an Object. But you can be sure that it's a safe cast. So, you can even use @SuppressWarnings on that variable.

showDialog deprecated. What's the alternative?

package com.keshav.datePicker_With_Hide_Future_Past_Date;

import android.app.DatePickerDialog;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;

import java.util.Calendar;

public class MainActivity extends AppCompatActivity {

    EditText ed_date;
    int year;
    int month;
    int day;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ed_date=(EditText) findViewById(R.id.et_date);

        ed_date.setOnClickListener(new View.OnClickListener()
        {
            @Override
            public void onClick(View v)
            {
                Calendar mcurrentDate=Calendar.getInstance();
                year=mcurrentDate.get(Calendar.YEAR);
                month=mcurrentDate.get(Calendar.MONTH);
                day=mcurrentDate.get(Calendar.DAY_OF_MONTH);

                final DatePickerDialog   mDatePicker =new DatePickerDialog(MainActivity.this, new DatePickerDialog.OnDateSetListener()
                {
                    @Override
                    public void onDateSet(DatePicker datepicker, int selectedyear, int selectedmonth, int selectedday)
                    {
                              ed_date.setText(new StringBuilder().append(year).append("-").append(month+1).append("-").append(day));
                            int month_k=selectedmonth+1;

                    }
                },year, month, day);
                mDatePicker.setTitle("Please select date");
                // TODO Hide Future Date Here
                mDatePicker.getDatePicker().setMaxDate(System.currentTimeMillis());

                // TODO Hide Past Date Here
                //  mDatePicker.getDatePicker().setMinDate(System.currentTimeMillis());
                mDatePicker.show();
            }
        });
    }
}


// Its Working 

Bulk Insert Correctly Quoted CSV File in SQL Server

Per CSV format specification, I don't think it matters if data is correctly quoted or not, as long as it adheres to specification. Excessive quotes should be handled by the parser, if it's properly implemented. FIELDTERMINATOR should be comma and ROWTERMINATOR is line end - this denotes a standard CSV file. Did you try to import your data with these settings?

Regex to match any character including new lines

Add the s modifier to your regex to cause . to match newlines:

$string =~ /(START)(.+?)(END)/s;

npm install private github repositories by dependency in package.json

Try this:

"dependencies" : {
  "name1" : "git://github.com/user/project.git#commit-ish",
  "name2" : "git://github.com/user/project.git#commit-ish"
}

You could also try this, where visionmedia/express is name/repo:

"dependencies" : {
   "express" : "visionmedia/express"
}

Or (if the npm package module exists):

"dependencies" : {
  "name": "*"
}

Taken from NPM docs

Mixed mode assembly is built against version ‘v2.0.50727' of the runtime

The exception clearly identifies some .NET 2.0.50727 component was included in .NET 4.0. In App.config file use this:

<startup useLegacyV2RuntimeActivationPolicy="true" /> 

It solved my problem

How to fix "unable to open stdio.h in Turbo C" error?

On most systems, you'd have to be trying fairly hard not to find '<stdio.h>', to the point where the first reaction is "is <stdio.h> installed". So, I'd be looking to see if the file exists in a plausible location. If not, then your installation of Turbo C is broken; reinstall. If you can find it, then you will have to establish why the compiler is not searching for it in the right place - what are the compiler options you've specified and where is the compiler searching for its headers (and why isn't it searching where the header is).

How can I build for release/distribution on the Xcode 4?

That part is now located under Schemes. If you edit your schemes you will see that you can set the debug/release/adhoc/distribution build config for each scheme.

What is the difference between prefix and postfix operators?

Actually what happens is when you use postfix i.e. i++, the initial value of i is used for returning rather than the incremented one. After this the value of i is increased by 1. And this happens with any statement that uses i++, i.e. first initial value of i is used in the expression and then it is incremented.

And the exact opposite happens in prefix. If you would have returned ++i, then the incremented value i.e. 11 is returned, which is because adding 1 is performed first and then it is returned.

What are NDF Files?

An NDF file is a user defined secondary database file of Microsoft SQL Server with an extension .ndf, which store user data. Moreover, when the size of the database file growing automatically from its specified size, you can use .ndf file for extra storage and the .ndf file could be stored on a separate disk drive. Every NDF file uses the same filename as its corresponding MDF file. We cannot open an .ndf file in SQL Server Without attaching its associated .mdf file.

Can someone explain Microsoft Unity?

I just watched the 30 minute Unity Dependency Injection IoC Screencast by David Hayden and felt that was a good explaination with examples. Here is a snippet from the show notes:

The screencast shows several common usages of the Unity IoC, such as:

  • Creating Types Not In Container
  • Registering and Resolving TypeMappings
  • Registering and Resolving Named TypeMappings
  • Singletons, LifetimeManagers, and the ContainerControlledLifetimeManager
  • Registering Existing Instances
  • Injecting Dependencies into Existing Instances
  • Populating the UnityContainer via App.config / Web.config
  • Specifying Dependencies via Injection API as opposed to Dependency Attributes
  • Using Nested ( Parent-Child ) Containers

Generating random whole numbers in JavaScript in a specific range?

Crypto-Strong

To get crypto-strong random integer number in ragne [x,y] try

_x000D_
_x000D_
let cs= (x,y)=>x+(y-x+1)*crypto.getRandomValues(new Uint32Array(1))[0]/2**32|0_x000D_
_x000D_
console.log(cs(4,8))
_x000D_
_x000D_
_x000D_

How to select all instances of selected region in Sublime Text

In the other posts, you have the shortcut keys, but if you want the menu option in every system, just go to Find > Quick Find All, as shown in the image attached.

Also, check the other answers for key binding to do it faster than menu clicking.

Sublime Text 3

How to compare different branches in Visual Studio Code

Use the Git History Diff plugin for easy side-by-side branch diffing:

https://marketplace.visualstudio.com/items?itemName=huizhou.githd

Visit the link above and scroll down to the animated GIF image titled Diff Branch. You'll see you can easily pick any branch and do side-by-side comparison with the branch you are on! It is like getting a preview of what you will see in the GitHub Pull Request. For other Git stuff I prefer Visual Studio Code's built-in functionality or Git Lens as others have mentioned.

However, the above plugin is outstanding for doing branch diffing (i.e., for those doing a rebase Git flow and need to preview before a force push up to a GitHub PR).

Passing std::string by Value or Reference

Check this answer for C++11. Basically, if you pass an lvalue the rvalue reference

From this article:

void f1(String s) {
    vector<String> v;
    v.push_back(std::move(s));
}
void f2(const String &s) {
    vector<String> v;
    v.push_back(s);
}

"For lvalue argument, ‘f1’ has one extra copy to pass the argument because it is by-value, while ‘f2’ has one extra copy to call push_back. So no difference; for rvalue argument, the compiler has to create a temporary ‘String(L“”)’ and pass the temporary to ‘f1’ or ‘f2’ anyway. Because ‘f2’ can take advantage of move ctor when the argument is a temporary (which is an rvalue), the costs to pass the argument are the same now for ‘f1’ and ‘f2’."

Continuing: " This means in C++11 we can get better performance by using pass-by-value approach when:

  1. The parameter type supports move semantics - All standard library components do in C++11
  2. The cost of move constructor is much cheaper than the copy constructor (both the time and stack usage).
  3. Inside the function, the parameter type will be passed to another function or operation which supports both copy and move.
  4. It is common to pass a temporary as the argument - You can organize you code to do this more.

"

OTOH, for C++98 it is best to pass by reference - less data gets copied around. Passing const or non const depend of whether you need to change the argument or not.

Deployment error:Starting of Tomcat failed, the server port 8080 is already in use

By changing proxy settings to "no proxy" in netbeans the tomcat prbolem got solved.Try this it's seriously working.

How would I get a cron job to run every 30 minutes?

You mention you are using OS X- I have used cronnix in the past. It's not as geeky as editing it yourself, but it helped me learn what the columns are in a jiffy. Just a thought.

Multiple lines of input in <input type="text" />

Use the textarea

<textarea name="textarea" style="width:250px;height:150px;"></textarea>

don't leave any space between the opening and closing tags Or Else This will leave some empty lines or spaces.

Loop and get key/value pair for JSON array using jQuery

You can get the values directly in case of one array like this:

var resultJSON = '{"FirstName":"John","LastName":"Doe","Email":"[email protected]","Phone":"123 dead drive"}';
var result = $.parseJSON(resultJSON);
result['FirstName']; // return 'John'
result['LastName'];  // return ''Doe'
result['Email']; // return '[email protected]'
result['Phone'];  // return '123'

What's an Aggregate Root?

The aggregate root is a complex name for a simple idea.


General idea

Well designed class diagram encapsulates its internals. Point through which you access this structure is called aggregate root.

enter image description here

Internals of your solution may be very complicated, but users of this hierarchy will just use root.doSomethingWhichHasBusinessMeaning().


Example

Check this simple class hierarchy enter image description here

How do you want to ride your car? Chose better API

Option A (it just somehow works):

car.ride();

Option B (user has access to class inernals):

if(car.getTires().getUsageLevel()< Car.ACCEPTABLE_TIRE_USAGE)
    for (Wheel w: car:getWheels()){
        w.spin();
    }
}

If you think that option A is better then congratulations. You get the main reason behind aggregate root.


Aggregate root encapsulates multiple classes. you can manipulate the whole hierarchy only through the main object.

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

I had to do this to get it to work:

$pair = "$($user):$($pass)"
$encodedCredentials = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($Pair))
$headers = @{ Authorization = "Basic $encodedCredentials" }
Invoke-WebRequest -Uri $url -Method Get -Headers $headers -OutFile Config.html

CMake does not find Visual C++ compiler

Look in the Cmakelists.txt if you find ARM you need to install C++ for ARM and as well vcvarsall.bat use for ARM bin folder.

It's these packages:

C++ Universal Windows Platform for ARM64 "Not Required"

Visual C++ Compilers and libraries for ARM "Not Required"

Visual C++ Compilers and libraries for ARM64 "Very Likely Required"

Required for finding Threads on ARM 
enable_language(C) 
enable_language(CXX)

Then the problems might disappear:

No CMAKE_C_COMPILER could be found.

No CMAKE_CXX_COMPILER could be found.

If above does not resolve your problem?

Optionally you can remove the options C and CXX in cmakelists.txt by setting # infront of where the enable_language(C) is. And avoid Android ARM processor compilation.

Javascript form validation with password confirming

add this to your form:

<form  id="regform" action="insert.php" method="post">

add this to your function:

<script>
    function myFunction() {
        var pass1 = document.getElementById("pass1").value;
        var pass2 = document.getElementById("pass2").value;
        if (pass1 != pass2) {
            //alert("Passwords Do not match");
            document.getElementById("pass1").style.borderColor = "#E34234";
            document.getElementById("pass2").style.borderColor = "#E34234";
        }
        else {
            alert("Passwords Match!!!");
            document.getElementById("regForm").submit();
        }
    }
</script>

How to remove all the punctuation in a string? (Python)

A really simple implementation is:

out = "".join(c for c in asking if c not in ('!','.',':'))

and keep adding any other types of punctuation.

A more efficient way would be

import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)

Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python

What is the easiest way to parse an INI file in Java?

It is just as simple as this.....

//import java.io.FileInputStream;
//import java.io.FileInputStream;

Properties prop = new Properties();
//c:\\myapp\\config.ini is the location of the ini file
//ini file should look like host=localhost
prop.load(new FileInputStream("c:\\myapp\\config.ini"));
String host = prop.getProperty("host");

Normalize columns of pandas data frame

If you like using the sklearn package, you can keep the column and index names by using pandas loc like so:

from sklearn.preprocessing import MinMaxScaler

scaler = MinMaxScaler() 
scaled_values = scaler.fit_transform(df) 
df.loc[:,:] = scaled_values

How can I hide an HTML table row <tr> so that it takes up no space?

var result_style = document.getElementById('result_tr').style;
result_style.display = '';

is working perfectly for me..

OpenJDK availability for Windows OS

Only OpenJDK 7. OpenJDK6 is basically the same code base as SUN's version, that's why it redirects you to the official Oracle site.

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in fix.by(by.x, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

String replace method is not replacing characters

Strings are immutable, meaning their contents cannot change. When you call replace(this,that) you end up with a totally new String. If you want to keep this new copy, you need to assign it to a variable. You can overwrite the old reference (a la sentence = sentence.replace(this,that) or a new reference as seen below:

public class Test{

    public static void main(String[] args) {

        String sentence = "Define, Measure, Analyze, Design and Verify";

        String replaced = sentence.replace("and", "");
        System.out.println(replaced);

    }
}

As an aside, note that I've removed the contains() check, as it is an unnecessary call here. If it didn't contain it, the replace will just fail to make any replacements. You'd only want that contains method if what you're replacing was different than the actual condition you're checking.

Understanding ibeacon distancing

I'm very thoroughly investigating the matter of accuracy/rssi/proximity with iBeacons and I really really think that all the resources in the Internet (blogs, posts in StackOverflow) get it wrong.

davidgyoung (accepted answer, > 100 upvotes) says:

Note that the term "accuracy" here is iOS speak for distance in meters.

Actually, most people say this but I have no idea why! Documentation makes it very very clear that CLBeacon.proximity:

Indicates the one sigma horizontal accuracy in meters. Use this property to differentiate between beacons with the same proximity value. Do not use it to identify a precise location for the beacon. Accuracy values may fluctuate due to RF interference.

Let me repeat: one sigma accuracy in meters. All 10 top pages in google on the subject has term "one sigma" only in quotation from docs, but none of them analyses the term, which is core to understand this.

Very important is to explain what is actually one sigma accuracy. Following URLs to start with: http://en.wikipedia.org/wiki/Standard_error, http://en.wikipedia.org/wiki/Uncertainty

In physical world, when you make some measurement, you always get different results (because of noise, distortion, etc) and very often results form Gaussian distribution. There are two main parameters describing Gaussian curve:

  1. mean (which is easy to understand, it's value for which peak of the curve occurs).
  2. standard deviation, which says how wide or narrow the curve is. The narrower curve, the better accuracy, because all results are close to each other. If curve is wide and not steep, then it means that measurements of the same phenomenon differ very much from each other, so measurement has a bad quality.

one sigma is another way to describe how narrow/wide is gaussian curve.
It simply says that if mean of measurement is X, and one sigma is s, then 68% of all measurements will be between X - s and X + s.

Example. We measure distance and get a gaussian distribution as a result. The mean is 10m. If s is 4m, then it means that 68% of measurements were between 6m and 14m.

When we measure distance with beacons, we get RSSI and 1-meter calibration value, which allow us to measure distance in meters. But every measurement gives different values, which form gaussian curve. And one sigma (and accuracy) is accuracy of the measurement, not distance!

It may be misleading, because when we move beacon further away, one sigma actually increases because signal is worse. But with different beacon power-levels we can get totally different accuracy values without actually changing distance. The higher power, the less error.

There is a blog post which thoroughly analyses the matter: http://blog.shinetech.com/2014/02/17/the-beacon-experiments-low-energy-bluetooth-devices-in-action/

Author has a hypothesis that accuracy is actually distance. He claims that beacons from Kontakt.io are faulty beacuse when he increased power to the max value, accuracy value was very small for 1, 5 and even 15 meters. Before increasing power, accuracy was quite close to the distance values. I personally think that it's correct, because the higher power level, the less impact of interference. And it's strange why Estimote beacons don't behave this way.

I'm not saying I'm 100% right, but apart from being iOS developer I have degree in wireless electronics and I think that we shouldn't ignore "one sigma" term from docs and I would like to start discussion about it.

It may be possible that Apple's algorithm for accuracy just collects recent measurements and analyses the gaussian distribution of them. And that's how it sets accuracy. I wouldn't exclude possibility that they use info form accelerometer to detect whether user is moving (and how fast) in order to reset the previous distribution distance values because they have certainly changed.

How can I remove the search bar and footer added by the jQuery DataTables plugin?

A quick and dirty way is to find out the class of the footer and hide it using jQuery or CSS:

$(".dataTables_info").hide();

Saving ssh key fails

If you're using Windows, the unix-style default path of ssh-keygen is at fault.

In Line 2 it says Enter file in which to save the key (/c/Users/Eva/.ssh/id_rsa):. That full filename in the parantheses is the default, obviously Windows cannot access a file like that. If you type the Windows equivalent (c:\Users\Eva\.ssh\id_rsa), it should work.

Before running this, you also need to create the folder. You can do this by running mkdir c:\Users\Eva\.ssh, or by created the folder ".ssh." from File Explorer (note the second dot at the end, which will get removed automatically, and is required to create a folder that has a dot at the beginning).

c:\Users\Administrator\.ssh>ssh-keygen -t rsa -C "[email protected]"
Generating public/private rsa key pair.
Enter file in which to save the key (/home/Administrator/.ssh/id_rsa): C:\Users\Administrator\.ssh\id_rsa
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in C:\Users\Administrator\.ssh\id_rsa.
Your public key has been saved in C:\Users\Administrator\.ssh\id_rsa.pub.
The key fingerprint is:
... [email protected]
The key's randomart image is:...`

I know this is an old thread, but I thought the answer might help others.

How to send email to multiple address using System.Net.Mail

 string[] MultiEmails = email.Split(',');
 foreach (string ToEmail in MultiEmails)
 {
    message.To.Add(new MailAddress(ToEmail)); //adding multiple email addresses
 }

Redis - Connect to Remote Server

I've been stuck with the same issue, and the preceding answer did not help me (albeit well written).

The solution is here : check your /etc/redis/redis.conf, and make sure to change the default

bind 127.0.0.1

to

bind 0.0.0.0

Then restart your service (service redis-server restart)

You can then now check that redis is listening on non-local interface with

redis-cli -h 192.168.x.x ping

(replace 192.168.x.x with your IP adress)

Important note : as several users stated, it is not safe to set this on a server which is exposed to the Internet. You should be certain that you redis is protected with any means that fits your needs.

How do I combine a background-image and CSS3 gradient on the same element?

If you also want to set background position for your image, than you can use this:

background-color: #444; // fallback
background: url('PATH-TO-IMG') center center no-repeat; // fallback

background: url('PATH-TO-IMG') center center no-repeat, -moz-linear-gradient(top, @startColor, @endColor); // FF 3.6+
background: url('PATH-TO-IMG') center center no-repeat, -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+
background: url('PATH-TO-IMG') center center no-repeat, -webkit-linear-gradient(top, @startColor, @endColor); // Safari 5.1+, Chrome 10+
background: url('PATH-TO-IMG') center center no-repeat, -o-linear-gradient(top, @startColor, @endColor); // Opera 11.10
background: url('PATH-TO-IMG') center center no-repeat, linear-gradient(to bottom, @startColor, @endColor); // Standard, IE10

or you can also create a LESS mixin (bootstrap style):

#gradient {
    .vertical-with-image(@startColor: #555, @endColor: #333, @image) {
        background-color: mix(@startColor, @endColor, 60%); // fallback
        background-image: @image; // fallback

        background: @image, -moz-linear-gradient(top, @startColor, @endColor); // FF 3.6+
        background: @image, -webkit-gradient(linear, 0 0, 0 100%, from(@startColor), to(@endColor)); // Safari 4+, Chrome 2+
        background: @image, -webkit-linear-gradient(top, @startColor, @endColor); // Safari 5.1+, Chrome 10+
        background: @image, -o-linear-gradient(top, @startColor, @endColor); // Opera 11.10
        background: @image, linear-gradient(to bottom, @startColor, @endColor); // Standard, IE10
    }
}

Opening XML page shows "This XML file does not appear to have any style information associated with it."

This XML file does not appear to have any style information associated with it. The document tree is shown below.

You will get this error in the client side when the client (the webbrowser) for some reason interprets the HTTP response content as text/xml instead of text/html and the parsed XML tree doesn't have any XML-stylesheet. In other words, the webbrowser incorrectly parsed the retrieved HTTP response content as XML instead of as HTML due to the wrong or missing HTTP response content type.

In case of JSF/Facelets files which have the default extension of .xhtml, that can in turn happen if the HTTP request hasn't invoked the FacesServlet and thus it wasn't able to parse the Facelets file and generate the desired HTML output based on the XHTML source code. Firefox is then merely guessing the HTTP response content type based on the .xhtml file extension which is in your Firefox configuration apparently by default interpreted as text/xml.

You need to make sure that the HTTP request URL, as you see in browser's address bar, matches the <url-pattern> of the FacesServlet as registered in webapp's web.xml, so that it will be invoked and be able to generate the desired HTML output based on the XHTML source code. If it's for example *.jsf, then you need to open the page by /some.jsf instead of /some.xhtml. Alternatively, you can also just change the <url-pattern> to *.xhtml. This way you never need to fiddle with virtual URLs.

See also:


Note thus that you don't actually need a XML stylesheet. This all was just misinterpretation by the webbrowser while trying to do its best to make something presentable out of the retrieved HTTP response content. It should actually have retrieved the properly generated HTML output, Firefox surely knows precisely how to deal with HTML content.

Delete a row in DataGridView Control in VB.NET

Assuming you are using Windows forms, you could allow the user to select a row and in the delete key click event. It is recommended that you allow the user to select 1 row only and not a group of rows (myDataGridView.MultiSelect = false)

Private Sub pbtnDelete_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDelete.Click

        If myDataGridView.SelectedRows.Count > 0 Then
            'you may want to add a confirmation message, and if the user confirms delete
            myDataGridView.Rows.Remove(myDataGridView.SelectedRows(0))
        Else
            MessageBox.Show("Select 1 row before you hit Delete")
        End If

    End Sub

Note that this will not delete the row form the database until you perform the delete in the database.

How to model type-safe enum types?

Dotty (Scala 3) will have native enums supported. Check here and here.

Multiple conditions in an IF statement in Excel VBA

In VBA we can not use if jj = 5 or 6 then we must use if jj = 5 or jj = 6 then

maybe this:

If inputWks.Range("d9") > 0 And (inputWks.Range("d11") = "Restricted_Expenditure" Or inputWks.Range("d11") = "Unrestricted_Expenditure") Then

How to check the first character in a string in Bash or UNIX shell?

Many ways to do this. You could use wildcards in double brackets:

str="/some/directory/file"
if [[ $str == /* ]]; then echo 1; else echo 0; fi

You can use substring expansion:

if [[ ${str:0:1} == "/" ]] ; then echo 1; else echo 0; fi

Or a regex:

if [[ $str =~ ^/ ]]; then echo 1; else echo 0; fi

Getting Chrome to accept self-signed localhost certificate

  1. Add the CA certificate in the trusted root CA Store.

  2. Go to chrome and enable this flag!

chrome://flags/#allow-insecure-localhost

At last, simply use the *.me domain or any valid domains like *.com and *.net and maintain them in the host file. For my local devs, I use *.me or *.com with a host file maintained as follows:

  1. Add to host. C:/windows/system32/drivers/etc/hosts

    127.0.0.1 nextwebapp.me

Note: If the browser is already opened when doing this, the error will keep on showing. So, please close the browser and start again. Better yet, go incognito or start a new session for immediate effect.

How do I change selected value of select2 dropdown with JqGrid?

For select2 version >= 4.0.0

The other solutions might not work, however the following examples should work.

Solution 1: Causes all attached change events to trigger, including select2

$('select').val('1').trigger('change');

Solution 2: Causes JUST select2 change event to trigger

$('select').val('1').trigger('change.select2');

See this jsfiddle for examples of these. Thanks to @minlare for Solution 2.

Explanation:

Say I have a best friend select with people's names. So Bob, Bill and John (in this example I assume the Value is the same as the name). First I initialize select2 on my select:

$('#my-best-friend').select2();

Now I manually select Bob in the browser. Next Bob does something naughty and I don't like him anymore. So the system unselects Bob for me:

$('#my-best-friend').val('').trigger('change');

Or say I make the system select the next in the list instead of Bob:

// I have assume you can write code to select the next guy in the list
$('#my-best-friend').val('Bill').trigger('change');  

Notes on Select 2 website (see Deprecated and removed methods) that might be useful for others:

.select2('val') The "val" method has been deprecated and will be removed in Select2 4.1. The deprecated method no longer includes the triggerChange parameter.

You should directly call .val on the underlying element instead. If you needed the second parameter (triggerChange), you should also call .trigger("change") on the element.

$('select').val('1').trigger('change'); // instead of $('select').select2('val', '1');

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

I found the solution :) finally.

We can append data in the request as multipartformdata.

Below is my code.

  Alamofire.upload(
        .POST,
        URLString: fullUrl, // http://httpbin.org/post
        multipartFormData: { multipartFormData in
            multipartFormData.appendBodyPart(fileURL: imagePathUrl!, name: "photo")
            multipartFormData.appendBodyPart(fileURL: videoPathUrl!, name: "video")
            multipartFormData.appendBodyPart(data: Constants.AuthKey.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"authKey")
            multipartFormData.appendBodyPart(data: "\(16)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"idUserChallenge")
            multipartFormData.appendBodyPart(data: "comment".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"comment")
            multipartFormData.appendBodyPart(data:"\(0.00)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"latitude")
            multipartFormData.appendBodyPart(data:"\(0.00)".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"longitude")
            multipartFormData.appendBodyPart(data:"India".dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!, name :"location")
        },
        encodingCompletion: { encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { request, response, JSON, error in


                }
            case .Failure(let encodingError):

            }
        }
    )

EDIT 1: For those who are trying to send an array instead of float, int or string, They can convert their array or any kind of data-structure in Json String, pass this JSON string as a normal string. And parse this json string at backend to get original array

how to set radio button checked in edit mode in MVC razor view

Don't do this at the view level. Just set the default value to the property in your view model's constructor. Clean and simple. In your post-backs, your selected value will automatically populate the correct selection.

For example

public class MyViewModel
{
        public MyViewModel()
        {
            Gender = "Male";
        }
}

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
 <td><label>@Html.RadioButtonFor(i => i.Gender, "Male")Male</label></td>_x000D_
 <td><label>@Html.RadioButtonFor(i => i.Gender, "Female")Female</label></td>_x000D_
  </tr>_x000D_
 </table>
_x000D_
_x000D_
_x000D_

How can I access global variable inside class in Python

By declaring it global inside the function that accesses it:

g_c = 0

class TestClass():
    def run(self):
        global g_c
        for i in range(10):
            g_c = 1
            print(g_c)

The Python documentation says this, about the global statement:

The global statement is a declaration which holds for the entire current code block.

Open Facebook page from Android app?

As of July 2018 this works perfectly with or without the Facebook app on all the devices.

private void goToFacebook() {
    try {
        String facebookUrl = getFacebookPageURL();
        Intent facebookIntent = new Intent(Intent.ACTION_VIEW);
        facebookIntent.setData(Uri.parse(facebookUrl));
        startActivity(facebookIntent);
    } catch (Exception e) {
        e.printStackTrace();
    }
}

private String getFacebookPageURL() {
    String FACEBOOK_URL = "https://www.facebook.com/Yourpage-1548219792xxxxxx/";
    String facebookurl = null;

    try {
        PackageManager packageManager = getPackageManager();

        if (packageManager != null) {
            Intent activated = packageManager.getLaunchIntentForPackage("com.facebook.katana");

            if (activated != null) {
                int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;

                if (versionCode >= 3002850) {
                    facebookurl = "fb://page/1548219792xxxxxx";
                }
            } else {
                facebookurl = FACEBOOK_URL;
            }
        } else {
            facebookurl = FACEBOOK_URL;
        }
    } catch (Exception e) {
        facebookurl = FACEBOOK_URL;
    }
    return facebookurl;
}

Initializing an Array of Structs in C#

Are you using C# 3.0? You can use object initializers like so:

static MyStruct[] myArray = 
            new MyStruct[]{
                new MyStruct() { id = 1, label = "1" },
                new MyStruct() { id = 2, label = "2" },
                new MyStruct() { id = 3, label = "3" }
            };

Display tooltip on Label's hover?

Are you find with using standard tooltip? You could use title attribute like

<label for="male" title="Hello This Will Have Some Value">Hello...</label>

You could add the title attribute of same value to the element that label is for as well.

Get RETURN value from stored procedure in SQL

The accepted answer is invalid with the double EXEC (only need the first EXEC):

DECLARE @returnvalue int;
EXEC @returnvalue = SP_SomeProc
PRINT @returnvalue

And you still need to call PRINT (at least in Visual Studio).

Strip off URL parameter with PHP

Wow, there are a lot of examples here. I am providing one that does some error handling. It rebuilds and returns the entire URL with the query-string-param-to-be-removed, removed. It also provides a bonus function that builds the current URL on the fly. Tested, works!

Credit to Mark B for the steps. This is a complete solution to tpow's "strip off this return parameter" original question -- might be handy for beginners, trying to avoid PHP gotchas. :-)

<?php

function currenturl_without_queryparam( $queryparamkey ) {
    $current_url = current_url();
    $parsed_url = parse_url( $current_url );
    if( array_key_exists( 'query', $parsed_url )) {
        $query_portion = $parsed_url['query'];
    } else {
        return $current_url;
    }

    parse_str( $query_portion, $query_array );

    if( array_key_exists( $queryparamkey , $query_array ) ) {
        unset( $query_array[$queryparamkey] );
        $q = ( count( $query_array ) === 0 ) ? '' : '?';
        return $parsed_url['scheme'] . '://' . $parsed_url['host'] . $parsed_url['path'] . $q . http_build_query( $query_array );
    } else {
        return $current_url;
    }
}

function current_url() {
    $current_url = 'http' . (isset($_SERVER['HTTPS']) ? 's' : '') . '://' . "{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
    return $current_url;
}

echo currenturl_without_queryparam( 'key' );

?>

Permission denied (publickey) when deploying heroku code. fatal: The remote end hung up unexpectedly

You have to upload your public key to Heroku:

heroku keys:add ~/.ssh/id_rsa.pub

If you don't have a public key, Heroku will prompt you to add one automatically which works seamlessly. Just use:

heroku keys:add

To clear all your previous keys do :

heroku keys:clear

To display all your existing keys do :

heroku keys

EDIT:

The above did not seem to work for me. I had messed around with the HOME environment variable and so SSH was searching for keys in the wrong directory.

To ensure that SSH checks for the key in the correct directory do :

ssh -vT [email protected]

Which will display the following ( Sample ) lines

OpenSSH_4.6p1, OpenSSL 0.9.8e 23 Feb 2007
debug1: Connecting to heroku.com [50.19.85.156] port 22.
debug1: Connection established.
debug1: identity file /c/Wrong/Directory/.ssh/identity type -1
debug1: identity file /c/Wrong/Directory/.ssh/id_rsa type -1
debug1: identity file /c/Wrong/Directory/.ssh/id_dsa type -1
debug1: Remote protocol version 2.0, remote software version Twisted
debug1: no match: Twisted
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_4.6
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: server->client aes128-cbc hmac-md5 none
debug1: kex: client->server aes128-cbc hmac-md5 none
debug1: sending SSH2_MSG_KEXDH_INIT
debug1: expecting SSH2_MSG_KEXDH_REPLY
debug1: Host 'heroku.com' is known and matches the RSA host key.
debug1: Found key in /c/Wrong/Directory/.ssh/known_hosts:1
debug1: ssh_rsa_verify: signature correct
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: SSH2_MSG_SERVICE_REQUEST sent
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /c/Wrong/Directory/.ssh/identity
debug1: Trying private key: /c/Wrong/Directory/.ssh/id_rsa
debug1: Trying private key: /c/Wrong/Directory/.ssh/id_dsa
debug1: No more authentication methods to try.

Permission denied (publickey).

From the above you could observe that ssh looks for the keys in the /c/Wrong/Directory/.ssh directory which is not where we have the public keys that we just added to heroku ( using heroku keys:add ~/.ssh/id_rsa.pub ) ( Please note that in windows OS ~ refers to the HOME path which in win 7 / 8 is C:\Users\UserName )

To view your current home directory do : echo $HOME or echo %HOME% ( Windows )

To set your HOME directory correctly ( by correctly I mean the parent directory of .ssh directory, so that ssh could look for keys in the correct directory ) refer these links :

  1. SO Answer on how to set Unix environment variable permanently

  2. SO Question regarding ssh looking for keys in the wrong directory and a solution for the same.

How to access session variables from any class in ASP.NET?

I had the same error, because I was trying to manipulate session variables inside a custom Session class.

I had to pass the current context (system.web.httpcontext.current) into the class, and then everything worked out fine.

MA

Link to add to Google calendar

Here's an example link you can use to see the format:

https://www.google.com/calendar/render?action=TEMPLATE&text=Your+Event+Name&dates=20140127T224000Z/20140320T221500Z&details=For+details,+link+here:+http://www.example.com&location=Waldorf+Astoria,+301+Park+Ave+,+New+York,+NY+10022&sf=true&output=xml

Note the key query parameters:

text
dates
details
location

Here's another example (taken from http://wordpress.org/support/topic/direct-link-to-add-specific-google-calendar-event):

<a href="http://www.google.com/calendar/render?
action=TEMPLATE
&text=[event-title]
&dates=[start-custom format='Ymd\\THi00\\Z']/[end-custom format='Ymd\\THi00\\Z']
&details=[description]
&location=[location]
&trp=false
&sprop=
&sprop=name:"
target="_blank" rel="nofollow">Add to my calendar</a>

Here's a form which will help you construct such a link if you want (mentioned in earlier answers):

https://support.google.com/calendar/answer/3033039 Edit: This link no longer gives you a form you can use

How can I get the application's path in a .NET console application?

I didn't see anyone convert the LocalPath provided by .Net Core reflection into a usable System.IO path so here's my version.

public static string GetApplicationRoot()
{
   var exePath = new Uri(System.Reflection.
   Assembly.GetExecutingAssembly().CodeBase).LocalPath;

   return new FileInfo(exePath).DirectoryName;
       
}

This will return the full C:\\xxx\\xxx formatted path to where your code is.

Use chrome as browser in C#?

Update for 2014:

I use geckofx, a healthy open source project that (as of this writing) keeps up to date pretty well with the latest Firefox releases.

To embed Chrome, you might consider another healthy looking open source project, Xilium.cefGlue, based on The Chromium Embedded Framework (CEF).

Both of these support WPF and Winforms, and both projects have support for .net and mono.

Quick way to create a list of values in C#?

A list of values quickly? Or even a list of objects!

I am just a beginner at the C# language but I like using

  • Hashtable
  • Arraylist
  • Datatable
  • Datasets

etc.

There's just too many ways to store items

Alter and Assign Object Without Side Effects

That's because object values are passed by reference. You can clone the object like this:

var myArray = [];
var myElement = {
  id: 0,
  value: 0
}

myElement.id =0;
myElement.value=1;
myArray[0] = myElement;

var obj = {};
obj = clone(myElement);
obj.id = 2;
obj.value = 3; 

myArray[1] = obj;

function clone(obj){
  if(obj == null || typeof(obj) != 'object')
    return obj;

  var temp = new obj.constructor(); 
  for(var key in obj)
    temp[key] = clone(obj[key]);

  return temp;
}    

console.log(myArray[0]);
console.log(myArray[1]);

Result:

 - id: 0
 - value: 1
 - id: 2
 - value: 3

Error in data frame undefined columns selected

Are you meaning?

data2 <- data1[good,]

With

data1[good]

you're selecting columns in a wrong way (using a logical vector of complete rows).

Consider that parameter pollutant is not used; is it a column name that you want to extract? if so it should be something like

data2 <- data1[good, pollutant]

Furthermore consider that you have to rbind the data.frames inside the for loop, otherwise you get only the last data.frame (its completed.cases)

And last but not least, i'd prefer generating filenames eg with

id <- 1:322
paste0( directory, "/", gsub(" ", "0", sprintf("%3d",id)), ".csv")

A little modified chunk of ?sprintf

The string fmt (in our case "%3d") contains normal characters, which are passed through to the output string, and also conversion specifications which operate on the arguments provided through .... The allowed conversion specifications start with a % and end with one of the letters in the set aAdifeEgGosxX%. These letters denote the following types:

  • d: integer

Eg a more general example

    sprintf("I am %10d years old", 25)
[1] "I am         25 years old"
          ^^^^^^^^^^
          |        |
          1       10

How to set lifetime of session

As long as the User does not delete their cookies or close their browser, the session should stay in existence.

How can I style the border and title bar of a window in WPF?

I suggest you to start from an existing solution and customize it to fit your needs, that's better than starting from scratch!

I was looking for the same thing and I fall on this open source solution, I hope it will help.

What is the difference between an expression and a statement in Python?

Python calls expressions "expression statements", so the question is perhaps not fully formed.

A statement consists of pretty much anything you can do in Python: calculating a value, assigning a value, deleting a variable, printing a value, returning from a function, raising an exception, etc. The full list is here: http://docs.python.org/reference/simple_stmts.html#

An expression statement is limited to calling functions (e.g., math.cos(theta)"), operators ( e.g., "2+3"), etc. to produce a value.

Location of Django logs and errors

Setup https://docs.djangoproject.com/en/dev/topics/logging/ and then these error's will echo where you point them. By default they tend to go off in the weeds so I always start off with a good logging setup before anything else.

Here is a really good example for a basic setup: https://ian.pizza/b/2013/04/16/getting-started-with-django-logging-in-5-minutes/

Edit: The new link is moved to: https://github.com/ianalexander/ianalexander/blob/master/content/blog/getting-started-with-django-logging-in-5-minutes.html

How to validate numeric values which may contain dots or commas?

\d means a digit in most languages. You can also use [0-9] in all languages. For the "period or comma" use [\.,]. Depending on your language you may need more backslashes based on how you quote the expression. Ultimately, the regular expression engine needs to see a single backslash.

* means "zero-or-more", so \d* and [0-9]* mean "zero or more numbers". ? means "zero-or-one". Neither of those qualifiers means exactly one. Most languages also let you use {m,n} to mean "between m and n" (ie: {1,2} means "between 1 and 2")

Since the dot or comma and additional numbers are optional, you can put them in a group and use the ? quantifier to mean "zero-or-one" of that group.

Putting that all together you can use:

\d{1,2}([\.,][\d{1,2}])?

Meaning, one or two digits \d{1,2}, followed by zero-or-one of a group (...)? consisting of a dot or comma followed by one or two digits [\.,]\d{1,2}

How to uninstall Anaconda completely from macOS

The following line doesn't work?

rm -rf ~/anaconda3 

You should know where your anaconda3(or anaconda1, anaconda2) is installed. So write

which anaconda

output

output: somewhere

Now use that somewhere and run:

rm -rf somewhere 

Using the "With Clause" SQL Server 2008

There are two types of WITH clauses:

Here is the FizzBuzz in SQL form, using a WITH common table expression (CTE).

;WITH mil AS (
 SELECT TOP 1000000 ROW_NUMBER() OVER ( ORDER BY c.column_id ) [n]
 FROM master.sys.all_columns as c
 CROSS JOIN master.sys.all_columns as c2
)                
 SELECT CASE WHEN n  % 3 = 0 THEN
             CASE WHEN n  % 5 = 0 THEN 'FizzBuzz' ELSE 'Fizz' END
        WHEN n % 5 = 0 THEN 'Buzz'
        ELSE CAST(n AS char(6))
     END + CHAR(13)
 FROM mil

Here is a select statement also using a WITH clause

SELECT * FROM orders WITH (NOLOCK) where order_id = 123

How to compile a c++ program in Linux?

Use g++

g++ -o hi hi.cpp

g++ is for C++, gcc is for C although with the -libstdc++ you can compile c++ most people don't do this.

Bootstrap date and time picker

If you are still interested in a javascript api to select both date and time data, have a look at these projects which are forks of bootstrap datepicker:

The first fork is a big refactor on the parsing/formatting codebase and besides providing all views to select date/time using mouse/touch, it also has a mask option (by default) which lets the user to quickly type the date/time based on a pre-specified format.

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

I don't know if this is still actual for you, but I still leave my comment so maybe it will help somebody else. I had same issue, and the solution proposed by @dighan on bountysource.com/issues/ solved it for me.

So here is the code that solved my problem:

var media = document.getElementById("YourVideo");
const playPromise = media.play();
if (playPromise !== null){
    playPromise.catch(() => { media.play(); })
}

It still throws an error into console, but at least the video is playing :)

How to put an image in div with CSS?

Take this as a sample code. Replace imageheight and image width with your image dimensions.

<div style="background:yourimage.jpg no-repeat;height:imageheight px;width:imagewidth px">
</div>

How can I get a uitableViewCell by indexPath?

[(UITableViewCell *)[(UITableView *)self cellForRowAtIndexPath:nowIndex]

will give you uitableviewcell. But I am not sure what exactly you are asking for! Because you have this code and still you asking how to get uitableviewcell. Some more information will help to answer you :)

ADD: Here is an alternate syntax that achieves the same thing without the cast.

UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:nowIndex];

Typedef function pointer?

typedef is a language construct that associates a name to a type.
You use it the same way you would use the original type, for instance

  typedef int myinteger;
  typedef char *mystring;
  typedef void (*myfunc)();

using them like

  myinteger i;   // is equivalent to    int i;
  mystring s;    // is the same as      char *s;
  myfunc f;      // compile equally as  void (*f)();

As you can see, you could just replace the typedefed name with its definition given above.

The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.

The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.

To answer your three questions

  • Why is typedef used? To ease the reading of the code - especially for pointers to functions, or structure names.

  • The syntax looks odd (in the pointer to function declaration) That syntax is not obvious to read, at least when beginning. Using a typedef declaration instead eases the reading

  • Is a function pointer created to store the memory address of a function? Yes, a function pointer stores the address of a function. This has nothing to do with the typedef construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.

Example:

typedef int (*t_somefunc)(int,int);

int product(int u, int v) {
  return u*v;
}

t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456

SVN repository backup strategies

We use svnadmin hotcopy, e.g.:

svnadmin hotcopy C:\svn\repo D:\backups\svn\repo

As per the book:

You can run this command at any time and make a safe copy of the repository, regardless of whether other processes are using the repository.

You can of course ZIP (preferably 7-Zip) the backup copy. IMHO It's the most straightforward of the backup options: in case of disaster there's little to do other than unzip it back into position.

How to SUM and SUBTRACT using SQL?

ah homework...

So wait, you need to deduct the balance of items in stock from the total number of those items that have been ordered? I have to tell you that sounds a bit backwards. Generally I think people do it the other way round. Deduct the total number of items ordered from the balance.

If you really need to do that though... Assuming that ITEM is unique in stock_bal...

SELECT s.ITEM, SUM(m.QTY) - s.QTY AS result
FROM stock_bal s
INNER JOIN master_table m ON m.ITEM = s.ITEM
GROUP BY s.ITEM, s.QTY

Could not load file or assembly System.Web.Http.WebHost after published to Azure web site

I was missing several DLLs. Even if I manually copied them to the directory the next time I published they would disappear. Each one was already set to Copy Locally in VS. The fix for me was to set each one to Copy Locally false, save, build then set each one to copy locally true. This time when I published all of the DLLs published correctly. Strange

How to merge two files line by line in Bash

Try following.

pr -tmJ a.txt b.txt > c.txt

Set div height equal to screen size

Using CSS {height: 100%;} matches the height of the parent. This could be anything, meaning smaller or bigger than the screen. Using {height: 100vh;} matches the height of the viewport.

.container {
    height: 100vh;
    overflow: auto;
}

According to Mozilla's official documents, 1vh is:

Equal to 1% of the height of the viewport's initial containing block.

Absolute and Flexbox in React Native

This solution worked for me:

tabBarOptions: {
      showIcon: true,
      showLabel: false,
      style: {
        backgroundColor: '#000',
        borderTopLeftRadius: 40,
        borderTopRightRadius: 40,
        position: 'relative',
        zIndex: 2,
        marginTop: -48
      }
  }

Add views in UIStackView programmatically

Following two lines fixed my issue

view.heightAnchor.constraintEqualToConstant(50).active = true;
view.widthAnchor.constraintEqualToConstant(350).active = true;

Swift version -

var DynamicView=UIView(frame: CGRectMake(100, 200, 100, 100))
DynamicView.backgroundColor=UIColor.greenColor()
DynamicView.layer.cornerRadius=25
DynamicView.layer.borderWidth=2
self.view.addSubview(DynamicView)
DynamicView.heightAnchor.constraintEqualToConstant(50).active = true;
DynamicView.widthAnchor.constraintEqualToConstant(350).active = true;

var DynamicView2=UIView(frame: CGRectMake(100, 310, 100, 100))
DynamicView2.backgroundColor=UIColor.greenColor()
DynamicView2.layer.cornerRadius=25
DynamicView2.layer.borderWidth=2
self.view.addSubview(DynamicView2)
DynamicView2.heightAnchor.constraintEqualToConstant(50).active = true;
DynamicView2.widthAnchor.constraintEqualToConstant(350).active = true;

var DynamicView3:UIView=UIView(frame: CGRectMake(10, 420, 355, 100))
DynamicView3.backgroundColor=UIColor.greenColor()
DynamicView3.layer.cornerRadius=25
DynamicView3.layer.borderWidth=2
self.view.addSubview(DynamicView3)

let yourLabel:UILabel = UILabel(frame: CGRectMake(110, 10, 200, 20))
yourLabel.textColor = UIColor.whiteColor()
//yourLabel.backgroundColor = UIColor.blackColor()
yourLabel.text = "mylabel text"
DynamicView3.addSubview(yourLabel)
DynamicView3.heightAnchor.constraintEqualToConstant(50).active = true;
DynamicView3.widthAnchor.constraintEqualToConstant(350).active = true;

let stackView   = UIStackView()
stackView.axis  = UILayoutConstraintAxis.Vertical
stackView.distribution  = UIStackViewDistribution.EqualSpacing
stackView.alignment = UIStackViewAlignment.Center
stackView.spacing   = 30

stackView.addArrangedSubview(DynamicView)
stackView.addArrangedSubview(DynamicView2)
stackView.addArrangedSubview(DynamicView3)

stackView.translatesAutoresizingMaskIntoConstraints = false;

self.view.addSubview(stackView)

//Constraints
stackView.centerXAnchor.constraintEqualToAnchor(self.view.centerXAnchor).active = true
stackView.centerYAnchor.constraintEqualToAnchor(self.view.centerYAnchor).active = true

JQuery post JSON object to a server

To send json to the server, you first have to create json

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify({
            name:"Bob",
            ...
        }),
        dataType: 'json'
    });
}

This is how you would structure the ajax request to send the json as a post var.

function sendData() {
    $.ajax({
        url: '/helloworld',
        type: 'POST',
        data: { json: JSON.stringify({
            name:"Bob",
            ...
        })},
        dataType: 'json'
    });
}

The json will now be in the json post var.

Convert UTF-8 to base64 string

It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
string base64 = Convert.ToBase64String(bytes);
Console.WriteLine(base64);

This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

Edit:

To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

string base64 = "YWJjZGVmPT0=";
byte[] bytes = Convert.FromBase64String(base64);

At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

string str = Encoding.UTF8.GetString(bytes);
Console.WriteLine(str);

This will output the original input string, abcdef== in this case.

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

SonarQube reported Return an empty collection instead of null. and I had a problem with the error with casting as in the title of this question. I was able to get rid of both only using return XYZ.ToList().AsQueryable(); in a method with IQueryable like so:

public IQueryable<SomeType> MethodName (...) {
  IQueryable<SomeType> XYZ;
  ...
  return XYZ.ToList().AsQueryable();
}

Hope so it helps for those in a similar scenario(s).

How to create a Calendar table for 100 years in Sql

 declare @date int
 WITH CTE_DatesTable
AS
(
  SELECT CAST('20000101' as date) AS [date]
  UNION ALL
  SELECT   DATEADD(dd, 1, [date])
  FROM CTE_DatesTable
  WHERE DATEADD(dd, 1, [date]) <= '21001231'
)
SELECT [DWDateKey]=[date],[DayDate]=datepart(dd,[date]),[DayOfWeekName]=datename(dw,[date]),[WeekNumber]=DATEPART( WEEK , [date]),[MonthNumber]=DATEPART( MONTH , [date]),[MonthName]=DATENAME( MONTH , [date]),[MonthShortName]=substring(LTRIM( DATENAME(MONTH,[date])),0, 4),[Year]=DATEPART(YY,[date]),[QuarterNumber]=DATENAME(quarter, [date]),[QuarterName]=DATENAME(quarter, [date]) into DimDate   FROM CTE_DatesTable

OPTION (MAXRECURSION 0);

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

Can Python test the membership of multiple values in a list?

The Python parser evaluated that statement as a tuple, where the first value was 'a', and the second value is the expression 'b' in ['b', 'a', 'foo', 'bar'] (which evaluates to True).

You can write a simple function do do what you want, though:

def all_in(candidates, sequence):
    for element in candidates:
        if element not in sequence:
            return False
    return True

And call it like:

>>> all_in(('a', 'b'), ['b', 'a', 'foo', 'bar'])
True

React Native: Getting the position of an element

React Native provides a .measure(...) method which takes a callback and calls it with the offsets and width/height of a component:

myComponent.measure( (fx, fy, width, height, px, py) => {

    console.log('Component width is: ' + width)
    console.log('Component height is: ' + height)
    console.log('X offset to frame: ' + fx)
    console.log('Y offset to frame: ' + fy)
    console.log('X offset to page: ' + px)
    console.log('Y offset to page: ' + py)
})

Example...

The following calculates the layout of a custom component after it is rendered:

class MyComponent extends React.Component {
    render() {
        return <View ref={view => { this.myComponent = view; }} />
    }
    componentDidMount() {
        // Print component dimensions to console
        this.myComponent.measure( (fx, fy, width, height, px, py) => {
            console.log('Component width is: ' + width)
            console.log('Component height is: ' + height)
            console.log('X offset to frame: ' + fx)
            console.log('Y offset to frame: ' + fy)
            console.log('X offset to page: ' + px)
            console.log('Y offset to page: ' + py)
        })        
    }
}

Bug notes

  • Note that sometimes the component does not finish rendering before componentDidMount() is called. If you are getting zeros as a result from measure(...), then wrapping it in a setTimeout should solve the problem, i.e.:

    setTimeout( myComponent.measure(...), 0 )
    

Starting ssh-agent on Windows 10 fails: "unable to start ssh-agent service, error :1058"

I get the same error in Cygwin. I had to install the openssh package in Cygwin Setup.

(The strange thing was that all ssh-* commands were valid, (bash could execute as program) but the openssh package wasn't installed.)

Setting SMTP details for php mail () function

Check out your php.ini, you can set these values there.

Here's the description in the php manual: http://php.net/manual/en/mail.configuration.php

If you want to use several different SMTP servers in your application, I recommend using a "bigger" mailing framework, p.e. Swiftmailer

Mount current directory as a volume in Docker on Windows 10

Other solutions for Git Bash provided by others didn't work for me. Apparently there is currently a bug/limitation in Git for Windows. See this and this.

I finally managed to get it working after finding this GitHub thread (which provides some additional solutions if you're interested, which might work for you, but didn't for me).

I ended up using the following syntax:

MSYS_NO_PATHCONV=1 docker run --rm -it -v $(pwd):/usr/src/project gcc:4.9

Note the MSYS_NO_PATHCONV=1 in front of the docker command and $(pwd) - round brackets, lower-case pwd, no quotes, no backslashes.

Also, I'm using Linux containers on Windows if that matters..

I tested this in the new Windows Terminal, ConEmu and GitBash, and all of them worked for me.

C++ float array initialization

You only initialize the first N positions to the values in braces and all others are initialized to 0. In this case, N is the number of arguments you passed to the initialization list, i.e.,

float arr1[10] = { };       // all elements are 0
float arr2[10] = { 0 };     // all elements are 0
float arr3[10] = { 1 };     // first element is 1, all others are 0
float arr4[10] = { 1, 2 };  // first element is 1, second is 2, all others are 0

ScalaTest in sbt: is there a way to run a single test without tags?

Just to simplify the example of Tyler.

test:-prefix is not needed.

So according to his example:

In the sbt-console:

testOnly *LoginServiceSpec

And in the terminal:

sbt "testOnly *LoginServiceSpec"

How to make the web page height to fit screen height

you can use css to set the body tag to these settings:

body
{
padding:0px;
margin:0px;
width:100%;
height:100%;
}

Making PHP var_dump() values display one line per value

Personally I like the replacement function provided by Symfony's var dumper component

Install with composer require symfony/var-dumper and just use dump($var)

It takes care of the rest. I believe there's also a bit of JS injected there to allow you to interact with the output a bit.

Vertical and horizontal align (middle and center) with CSS

This blog post describes two methods of centering a div both horizontally and vertically. One uses only CSS and will work with divs that have a fixed size; the other uses jQuery and will work divs for which you do not know the size in advance.

I've duplicated the CSS and jQuery examples from the blog post's demo here:

CSS

Assuming you have a div with a class of .classname, the css below should work.

The left:50%; top:50%; sets the top left corner of the div to the center of the screen; the margin:-75px 0 0 -135px; moves it to the left and up by half of the width and height of the fixed-size div respectively.

.className{
    width:270px;
    height:150px;
    position:absolute;
    left:50%;
    top:50%;
    margin:-75px 0 0 -135px;
}

jQuery

$(document).ready(function(){
    $(window).resize(function(){
        $('.className').css({
            position:'absolute',
            left: ($(window).width() - $('.className').outerWidth())/2,
            top: ($(window).height() - $('.className').outerHeight())/2
        });
    });
    // To initially run the function:
    $(window).resize();
});

Here's a demo of the techniques in practice.

Determining the size of an Android view at runtime

In Kotlin file, change accordingly

 Handler().postDelayed({

           Your Code

        }, 1)

Offline Speech Recognition In Android (JellyBean)

In short, I don't have the implementation, but the explanation.

Google did not make offline speech recognition available to third party apps. Offline recognition is only accessable via the keyboard. Ben Randall (the developer of utter!) explains his workaround in an article at Android Police:

I had implemented my own keyboard and was switching between Google Voice Typing and the users default keyboard with an invisible edit text field and transparent Activity to get the input. Dirty hack!

This was the only way to do it, as offline Voice Typing could only be triggered by an IME or a system application (that was my root hack) . The other type of recognition API … didn't trigger it and just failed with a server error. … A lot of work wasted for me on the workaround! But at least I was ready for the implementation...

From Utter! Claims To Be The First Non-IME App To Utilize Offline Voice Recognition In Jelly Bean

How to convert a string to utf-8 in Python

Might be a bit overkill, but when I work with ascii and unicode in same files, repeating decode can be a pain, this is what I use:

def make_unicode(input):
    if type(input) != unicode:
        input =  input.decode('utf-8')
    return input

how to know status of currently running jobs

It looks like you can use msdb.dbo.sysjobactivity, checking for a record with a non-null start_execution_date and a null stop_execution_date, meaning the job was started, but has not yet completed.

This would give you currently running jobs:

SELECT sj.name
   , sja.*
FROM msdb.dbo.sysjobactivity AS sja
INNER JOIN msdb.dbo.sysjobs AS sj ON sja.job_id = sj.job_id
WHERE sja.start_execution_date IS NOT NULL
   AND sja.stop_execution_date IS NULL

Windows 10 SSH keys

Create private/public key:

  1. Open up terminal (git bash, PowerShell, cmd.exe etc.)
  2. Type in ssh-keygen
  3. Press enter for default file save (~/.ssh/id_rsa)
  4. Press enter for default passphrase (no passphrase)
  5. Press enter again
  6. Look at the output and make sure that the RSA is 3072 or above

You have now created a private/public key pair.

For GIT the key must have a strength of 2048, must be located in the users .ssh directory and be called id_rsa and id_rsa.pub. When pasting the keys anywhere make sure to use a program that does not add new lines like VIM.

Ant: How to execute a command for each file in directory?

Do what blak3r suggested and define your targets classpath like so

<taskdef resource="net/sf/antcontrib/antlib.xml">
    <classpath>
        <fileset dir="lib">
          <include name="**/*.jar"/>
        </fileset>
    </classpath>        
</taskdef>

where lib is where you store your jar's

How and when to use SLEEP() correctly in MySQL?

If you don't want to SELECT SLEEP(1);, you can also DO SLEEP(1); It's useful for those situations in procedures where you don't want to see output.

e.g.

SELECT ...
DO SLEEP(5);
SELECT ...

Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in

This error comes when there is error in your query syntax check field names table name, mean check your query syntax.

Reference excel worksheet by name?

To expand on Ryan's answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below. screenshot of predictive text in VBE

If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.

You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you'll get it for sure.

How to add facebook share button on my website?

You can do this by using asynchronous Javascript SDK provided by facebook

Have a look at the following code

FB Javascript SDK initialization

<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({appId: 'YOUR APP ID', status: true, cookie: true,
xfbml: true});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>

Note: Remember to replace YOUR APP ID with your facebook AppId. If you don't have facebook AppId and you don't know how to create please check this

Add JQuery Library, I would preferred Google Library

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" type="text/javascript"></script>

Add share dialog box (You can customize this dialog box by setting up parameters

<script type="text/javascript">
$(document).ready(function(){
$('#share_button').click(function(e){
e.preventDefault();
FB.ui(
{
method: 'feed',
name: 'This is the content of the "name" field.',
link: 'http://www.groupstudy.in/articlePost.php?id=A_111213073144',
picture: 'http://www.groupstudy.in/img/logo3.jpeg',
caption: 'Top 3 reasons why you should care about your finance',
description: "What happens when you don't take care of your finances? Just look at our country -- you spend irresponsibly, get in debt up to your eyeballs, and stress about how you're going to make ends meet. The difference is that you don't have a glut of taxpayers…",
message: ""
});
});
});
</script>

Now finally add image button

<img src = "share_button.png" id = "share_button">

For more detailed kind of information. please click here

How to get the id of the element clicked using jQuery

You can get the id of clicked one by this code

$("span").on("click",function(e){
    console.log(e.target.Id);
});

Use .on() event for future compatibility

How can I divide two integers to get a double?

I have went through most of the answers and im pretty sure that it's unachievable. Whatever you try to divide two int into double or float is not gonna happen. But you have tons of methods to make the calculation happen, just cast them into float or double before the calculation will be fine.

Linq to SQL how to do "where [column] in (list of values)"

I had been using the method in Jon Skeet's answer, but another one occurred to me using Concat. The Concat method performed slightly better in a limited test, but it's a hassle and I'll probably just stick with Contains, or maybe I'll write a helper method to do this for me. Either way, here's another option if anyone is interested:

The Method

// Given an array of id's
var ids = new Guid[] { ... };

// and a DataContext
var dc = new MyDataContext();

// start the queryable
var query = (
    from thing in dc.Things
    where thing.Id == ids[ 0 ]
    select thing 
);

// then, for each other id
for( var i = 1; i < ids.Count(); i++ ) {
    // select that thing and concat to queryable
    query.Concat(
        from thing in dc.Things
        where thing.Id == ids[ i ]
        select thing
    );
}

Performance Test

This was not remotely scientific. I imagine your database structure and the number of IDs involved in the list would have a significant impact.

I set up a test where I did 100 trials each of Concat and Contains where each trial involved selecting 25 rows specified by a randomized list of primary keys. I've run this about a dozen times, and most times the Concat method comes out 5 - 10% faster, although one time the Contains method won by just a smidgen.

What is the connection string for localdb for version 11

You need to install Dot Net 4.0.2 or above as mentioned here.
The 4.0 bits don't understand the syntax required by LocalDB

See this question here

You can dowload the update here

How to disable keypad popup when on edittext?

It issue can be sorted by using, No need to set editText inputType to any values, just add the below line, editText.setTextIsSelectable(true);

how to empty recyclebin through command prompt?

I know I'm a little late to the party, but I thought I might contribute my subjectively more graceful solution.

I was looking for a script that would empty the Recycle Bin with an API call, rather than crudely deleting all files and folders from the filesystem. Having failed in my attempts to RecycleBinObject.InvokeVerb("Empty Recycle &Bin") (which apparently only works in XP or older), I stumbled upon discussions of using a function embedded in shell32.dll called SHEmptyRecycleBin() from a compiled language. I thought, hey, I can do that in PowerShell and wrap it in a batch script hybrid.

Save this with a .bat extension and run it to empty your Recycle Bin. Run it with a /y switch to skip the confirmation.

<# : batch portion (begins PowerShell multi-line comment block)
:: empty.bat -- http://stackoverflow.com/a/41195176/1683264

@echo off & setlocal

if /i "%~1"=="/y" goto empty

choice /n /m "Are you sure you want to empty the Recycle Bin? [y/n] "
if not errorlevel 2 goto empty
goto :EOF

:empty
powershell -noprofile "iex (${%~f0} | out-string)" && (
    echo Recycle Bin successfully emptied.
)
goto :EOF

: end batch / begin PowerShell chimera #>
Add-Type shell32 @'
    [DllImport("shell32.dll")]
    public static extern int SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath,
        int dwFlags);
'@ -Namespace System

$SHERB_NOCONFIRMATION = 0x1
$SHERB_NOPROGRESSUI = 0x2
$SHERB_NOSOUND = 0x4

$dwFlags = $SHERB_NOCONFIRMATION
$res = [shell32]::SHEmptyRecycleBin([IntPtr]::Zero, $null, $dwFlags)

if ($res) { "Error 0x{0:x8}: {1}" -f $res,`
    (New-Object ComponentModel.Win32Exception($res)).Message }
exit $res

Here's a more complex version which first invokes SHQueryRecycleBin() to determine whether the bin is already empty prior to invoking SHEmptyRecycleBin(). For this one, I got rid of the choice confirmation and /y switch.

<# : batch portion (begins PowerShell multi-line comment block)
:: empty.bat -- http://stackoverflow.com/a/41195176/1683264

@echo off & setlocal
powershell -noprofile "iex (${%~f0} | out-string)"
goto :EOF

: end batch / begin PowerShell chimera #>
Add-Type @'

using System;
using System.Runtime.InteropServices;

namespace shell32 {
    public struct SHQUERYRBINFO {
        public Int32 cbSize; public UInt64 i64Size; public UInt64 i64NumItems;
    };

    public static class dll {
        [DllImport("shell32.dll")]
        public static extern int SHQueryRecycleBin(string pszRootPath,
            out SHQUERYRBINFO pSHQueryRBInfo);

        [DllImport("shell32.dll")]
        public static extern int SHEmptyRecycleBin(IntPtr hwnd, string pszRootPath,
            int dwFlags);
    }
}
'@

$rb = new-object shell32.SHQUERYRBINFO

# for Win 10 / PowerShell v5
try { $rb.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($rb) }
# for Win 7 / PowerShell v2
catch { $rb.cbSize = [Runtime.InteropServices.Marshal]::SizeOf($rb.GetType()) }

[void][shell32.dll]::SHQueryRecycleBin($null, [ref]$rb)
"Current size of Recycle Bin: {0:N0} bytes" -f $rb.i64Size
"Recycle Bin contains {0:N0} item{1}." -f $rb.i64NumItems, ("s" * ($rb.i64NumItems -ne 1))

if (-not $rb.i64NumItems) { exit 0 }

$dwFlags = @{
    "SHERB_NOCONFIRMATION" = 0x1
    "SHERB_NOPROGRESSUI" = 0x2
    "SHERB_NOSOUND" = 0x4
}
$flags = $dwFlags.SHERB_NOCONFIRMATION
$res = [shell32.dll]::SHEmptyRecycleBin([IntPtr]::Zero, $null, $flags)

if ($res) { 
    write-host -f yellow ("Error 0x{0:x8}: {1}" -f $res,`
        (New-Object ComponentModel.Win32Exception($res)).Message)
} else {
    write-host "Recycle Bin successfully emptied." -f green
}
exit $res

PHPExcel - set cell type before writing a value in it

Followed Mark's advise and did this to set the default number formatting to text in the whole workbook:

$objPHPExcel = new PHPExcel(); 
$objPHPExcel->getDefaultStyle()
    ->getNumberFormat()
    ->setFormatCode(
        PHPExcel_Style_NumberFormat::FORMAT_TEXT
    );

And it works flawlessly. Thank you, Mark Baker.

How to programmatically close a JFrame

Based on the answers already provided here, this is the way I implemented it:

JFrame frame= new JFrame()
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

// frame stuffs here ...

frame.dispatchEvent(new WindowEvent(frame, WindowEvent.WINDOW_CLOSING));

The JFrame gets the event to close and upon closing, exits.

In an array of objects, fastest way to find the index of an object whose attributes match a search

var indices = [];
var IDs = [0, 1, 2, 3, 4];

for(var i = 0, len = array.length; i < len; i++) {
    for(var j = 0; j < IDs.length; j++) {
        if(array[i].id == ID) indices.push(i);
    }
}

Java - Convert String to valid URI object

Well I tried using

String converted = URLDecoder.decode("toconvert","UTF-8");

I hope this is what you were actually looking for?

How to check for Is not Null And Is not Empty string in SQL server?

Coalesce will fold nulls into a default:

COALESCE (fieldName, '') <> ''

Why does range(start, end) not include end?

Because it's more common to call range(0, 10) which returns [0,1,2,3,4,5,6,7,8,9] which contains 10 elements which equals len(range(0, 10)). Remember that programmers prefer 0-based indexing.

Also, consider the following common code snippet:

for i in range(len(li)):
    pass

Could you see that if range() went up to exactly len(li) that this would be problematic? The programmer would need to explicitly subtract 1. This also follows the common trend of programmers preferring for(int i = 0; i < 10; i++) over for(int i = 0; i <= 9; i++).

If you are calling range with a start of 1 frequently, you might want to define your own function:

>>> def range1(start, end):
...     return range(start, end+1)
...
>>> range1(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Python: Writing to and Reading from serial port

ser.read(64) should be ser.read(size=64); ser.read uses keyword arguments, not positional.

Also, you're reading from the port twice; what you probably want to do is this:

i=0
for modem in PortList:
    for port in modem:
        try:
            ser = serial.Serial(port, 9600, timeout=1)
            ser.close()
            ser.open()
            ser.write("ati")
            time.sleep(3)
            read_val = ser.read(size=64)
            print read_val
            if read_val is not '':
                print port
        except serial.SerialException:
            continue
        i+=1

Why and how to fix? IIS Express "The specified port is in use"

i solve the problem this way...

File -> Open -> Web Site... enter image description here

After that select Local IIS under IIS Express Site remove the unwanted project.

hope this help.

python NameError: name 'file' is not defined

file is not defined in Python3, which you are using apparently. The package you're instaling is not suitable for Python 3, instead, you should install Python 2.7 and try again.

See: http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins

How to permanently remove few commits from remote branch

You git reset --hard your local branch to remove changes from working tree and index, and you git push --force your revised local branch to the remote. (other solution here, involving deleting the remote branch, and re-pushing it)

This SO answer illustrates the danger of such a command, especially if people depends on the remote history for their own local repos.
You need to be prepared to point out people to the RECOVERING FROM UPSTREAM REBASE section of the git rebase man page


With Git 2.23 (August 2019, nine years later), you would use the new command git switch.
That is: git switch -C mybranch origin/mybranch~n
(replace n by the number of commits to remove)

That will restore the index and working tree, like a git reset --hard would.
The documentation adds:

-C <new-branch>
--force-create <new-branch>

Similar to --create except that if <new-branch> already exists, it will be reset to <start-point>.
This is a convenient shortcut for:

$ git branch -f <new-branch>
$ git switch <new-branch>

Pretty print in MongoDB shell as default

You can add

DBQuery.prototype._prettyShell = true

to your file in $HOME/.mongorc.js to enable pretty print globally by default.

How to reset selected file with input tag file type in Angular 2?

I typically reset my file input after capturing the selected files. No need to push a button, you have everything required in the $event object that you're passing to onChange:

onChange(event) {
  // Get your files
  const files: FileList = event.target.files;

  // Clear the input
  event.srcElement.value = null;
}

Different workflow, but the OP doesn't mention pushing a button is a requirement...

Untrack files from git temporarily

git update-index should do what you want

This will tell git you want to start ignoring the changes to the file
git update-index --assume-unchanged path/to/file

When you want to start keeping track again
git update-index --no-assume-unchanged path/to/file

Github Documentation: update-index

Dockerfile if else condition with external arguments

Exactly as others told, shell script would help.

Just an additional case, IMHO it's worth mentioning (for someone else who stumble upon here, looking for an easier case), that is Environment replacement.

Environment variables (declared with the ENV statement) can also be used in certain instructions as variables to be interpreted by the Dockerfile.

The ${variable_name} syntax also supports a few of the standard bash modifiers as specified below:

  • ${variable:-word} indicates that if variable is set then the result will be that value. If variable is not set then word will be the result.

  • ${variable:+word} indicates that if variable is set then word will be the result, otherwise the result is the empty string.

Create a batch file to copy and rename file

Make a bat file with the following in it:

copy /y C:\temp\log1k.txt C:\temp\log1k_copied.txt

However, I think there are issues if there are spaces in your directory names. Notice this was copied to the same directory, but that doesn't matter. If you want to see how it runs, make another bat file that calls the first and outputs to a log:

C:\temp\test.bat > C:\temp\test.log

(assuming the first bat file was called test.bat and was located in that directory)

Installing PG gem on OS X - failure to build native extension

Try:

gem install pg -- --with-pg-config=`which pg_config`

"Auth Failed" error with EGit and GitHub

Have you tried to use the ssh protocol instead on git+ssh ? I've got the same problem, and that solved it, even though official documentation tells to use git+ssh

Order columns through Bootstrap4

I'm using Bootstrap 3, so i don't know if there is an easier way to do it Bootstrap 4 but this css should work for you:

.pull-right-xs {
    float: right;
}

@media (min-width: 768px) {
   .pull-right-xs {
      float: left;
   }
}

...and add class to second column:

<div class="row">
    <div class="col-xs-3 col-md-6">
        1
    </div>
    <div class="col-xs-3 col-md-6 pull-right-xs">
        2
    </div>
    <div class="col-xs-6 col-md-12">
        3
    </div>
</div>

EDIT:

Ohh... it looks like what i was writen above is exacly a .pull-xs-right class in Bootstrap 4 :X Just add it to second column and it should work perfectly.

Solve Cross Origin Resource Sharing with Flask

It worked like a champ, after bit modification to your code

# initialization
app = Flask(__name__)
app.config['SECRET_KEY'] = 'the quick brown fox jumps over the lazy   dog'
app.config['CORS_HEADERS'] = 'Content-Type'

cors = CORS(app, resources={r"/foo": {"origins": "http://localhost:port"}})

@app.route('/foo', methods=['POST'])
@cross_origin(origin='localhost',headers=['Content- Type','Authorization'])
def foo():
    return request.json['inputVar']

if __name__ == '__main__':
   app.run()

I replaced * by localhost. Since as I read in many blogs and posts, you should allow access for specific domain

Best approach to converting Boolean object to string in java

Depends on what you mean by "efficient". Performance-wise both versions are the same as its the same bytecode.

$ ./javap.exe -c java.lang.String | grep -A 10 "valueOf(boolean)"
  public static java.lang.String valueOf(boolean);
    Code:
       0: iload_0
       1: ifeq          9
       4: ldc           #14                 // String true
       6: goto          11
       9: ldc           #10                 // String false
      11: areturn


$ ./javap.exe -c java.lang.Boolean | grep -A 10 "toString(boolean)"
  public static java.lang.String toString(boolean);
    Code:
       0: iload_0
       1: ifeq          9
       4: ldc           #3                  // String true
       6: goto          11
       9: ldc           #2                  // String false
      11: areturn

Android - Get value from HashMap

This with no warnings!

    HashMap<String, String> meMap=new HashMap<String, String>();
    meMap.put("Color1","Red");
    meMap.put("Color2","Blue");
    meMap.put("Color3","Green");
    meMap.put("Color4","White");

    for (Object o : meMap.keySet()) {
        Toast.makeText(getBaseContext(), meMap.get(o.toString()),
                Toast.LENGTH_SHORT).show();
    }

What is the difference between a port and a socket?

A socket is a structure in your software. It's more-or-less a file; it has operations like read and write. It isn't a physical thing; it's a way for your software to refer to physical things.

A port is a device-like thing. Each host has one or more networks (those are physical); a host has an address on each network. Each address can have thousands of ports.

One socket only may be using a port at an address. The socket allocates the port approximately like allocating a device for file system I/O. Once the port is allocated, no other socket can connect to that port. The port will be freed when the socket is closed.

Take a look at TCP/IP Terminology.

String is immutable. What exactly is the meaning?

You are not changing the object in the assignment statement, you replace one immutable object with another one. Object String("a") does not change to String("ty"), it gets discarded, and a reference to ty gets written into a in its stead.

In contrast, StringBuffer represents a mutable object. You can do this:

StringBuffer b = new StringBuffer("Hello");
System.out.writeln(b);
b.append(", world!");
System.out.writeln(b);

Here, you did not re-assign b: it still points to the same object, but the content of that object has changed.

When is it appropriate to use C# partial classes?

Partial classes recently helped with source control where multiple developers were adding to one file where new methods were added into the same part of the file (automated by Resharper).

These pushes to git caused merge conflicts. I found no way to tell the merge tool to take the new methods as a complete code block.

Partial classes in this respect allows for developers to stick to a version of their file, and we can merge them back in later by hand.

example -

  • MainClass.cs - holds fields, constructor, etc
  • MainClass1.cs - a developers new code as they implement
  • MainClass2.cs - is another developers class for their new code.

What's the proper value for a checked attribute of an HTML checkbox?

Well, to use it i dont think matters (similar to disabled and readonly), personally i use checked="checked" but if you are trying to manipulate them with JavaScript, you use true/false

How can I clear the terminal in Visual Studio Code?

Try typing in 'cls', if that doesn't work, type 'Clear' capital C. No quotes for any. Hope this helps.

Page scroll up or down in Selenium WebDriver (Selenium 2) using java

There are many ways to scroll up and down in Selenium Webdriver I always use Java Script to do the same.

Below is the code which always works for me if I want to scroll up or down

 // This  will scroll page 400 pixel vertical
  ((JavascriptExecutor)driver).executeScript("scroll(0,400)");

You can get full code from here Scroll Page in Selenium

If you want to scroll for a element then below piece of code will work for you.

je.executeScript("arguments[0].scrollIntoView(true);",element);

You will get the full doc here Scroll for specific Element

.htaccess rewrite to redirect root URL to subdirectory

I think the main problems with the code you posted are:

  • the first line matches on a host beginning with strictly sample.com, so www.sample.com doesn't match.

  • the second line wants at least one character, followed by www.sample.com which also doesn't match (why did you escape the first w?)

  • none of the included rules redirect to the url you specified in your goal (plus, sample is misspelled as samle, but that's irrelevant).

For reference, here's the code you currently have:

Options +FollowSymlinks
RewriteEngine on

RewriteCond %{HTTP_HOST} ^sample.com$
RewriteRule (.*) http://www.sample.com/$1 [R=301,L]

RewriteCond %{HTTP_HOST} ^(.+)\www.sample\.com$
RewriteRule ^/(.*)$ /samle/%1/$1 [L]

Java SecurityException: signer information does not match

In my case, I had duplicated JAR version of BouncyCastle in my library path :S

Python - Get Yesterday's date as a string in YYYY-MM-DD format

You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.

datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:

>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)

>>> type(yesterday)                                                                                                                                                                                    
>>> datetime.datetime    

>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'

Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:

>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'

As a function:

def yesterday(string=False):
    yesterday = datetime.now() - timedelta(1)
    if string:
        return yesterday.strftime('%Y-%m-%d')
    return yesterday

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

You state in the comments that the returned JSON is this:

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

You're telling Gson that you have an array of Post objects:

List<Post> postsList = Arrays.asList(gson.fromJson(reader,
                    Post[].class));

You don't. The JSON represents exactly one Post object, and Gson is telling you that.

Change your code to be:

Post post = gson.fromJson(reader, Post.class);

How to initailize byte array of 100 bytes in java with all 0's

The default element value of any array of primitives is already zero: false for booleans.

How do I debug "Error: spawn ENOENT" on node.js?

Step 1: Ensure spawn is called the right way

First, review the docs for child_process.spawn( command, args, options ):

Launches a new process with the given command, with command line arguments in args. If omitted, args defaults to an empty Array.

The third argument is used to specify additional options, which defaults to:

{ cwd: undefined, env: process.env }

Use env to specify environment variables that will be visible to the new process, the default is process.env.

Ensure you are not putting any command line arguments in command and the whole spawn call is valid. Proceed to next step.

Step 2: Identify the Event Emitter that emits the error event

Search on your source code for each call to spawn, or child_process.spawn, i.e.

spawn('some-command', [ '--help' ]);

and attach there an event listener for the 'error' event, so you get noticed the exact Event Emitter that is throwing it as 'Unhandled'. After debugging, that handler can be removed.

spawn('some-command', [ '--help' ])
  .on('error', function( err ){ throw err })
;

Execute and you should get the file path and line number where your 'error' listener was registered. Something like:

/file/that/registers/the/error/listener.js:29
      throw err;
            ^
Error: spawn ENOENT
    at errnoException (child_process.js:1000:11)
    at Process.ChildProcess._handle.onexit (child_process.js:791:34)

If the first two lines are still

events.js:72
        throw er; // Unhandled 'error' event

do this step again until they are not. You must identify the listener that emits the error before going on next step.

Step 3: Ensure the environment variable $PATH is set

There are two possible scenarios:

  1. You rely on the default spawn behaviour, so child process environment will be the same as process.env.
  2. You are explicity passing an env object to spawn on the options argument.

In both scenarios, you must inspect the PATH key on the environment object that the spawned child process will use.

Example for scenario 1

// inspect the PATH key on process.env
console.log( process.env.PATH );
spawn('some-command', ['--help']);

Example for scenario 2

var env = getEnvKeyValuePairsSomeHow();
// inspect the PATH key on the env object
console.log( env.PATH );
spawn('some-command', ['--help'], { env: env });

The absence of PATH (i.e., it's undefined) will cause spawn to emit the ENOENT error, as it will not be possible to locate any command unless it's an absolute path to the executable file.

When PATH is correctly set, proceed to next step. It should be a directory, or a list of directories. Last case is the usual.

Step 4: Ensure command exists on a directory of those defined in PATH

Spawn may emit the ENOENT error if the filename command (i.e, 'some-command') does not exist in at least one of the directories defined on PATH.

Locate the exact place of command. On most linux distributions, this can be done from a terminal with the which command. It will tell you the absolute path to the executable file (like above), or tell if it's not found.

Example usage of which and its output when a command is found

> which some-command
some-command is /usr/bin/some-command

Example usage of which and its output when a command is not found

> which some-command
bash: type: some-command: not found

miss-installed programs are the most common cause for a not found command. Refer to each command documentation if needed and install it.

When command is a simple script file ensure it's accessible from a directory on the PATH. If it's not, either move it to one or make a link to it.

Once you determine PATH is correctly set and command is accessible from it, you should be able to spawn your child process without spawn ENOENT being thrown.

How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"

Visual Studio Community 2017

Go here : C:\Program Files (x86)\Windows Kits\10

and do whatever you were supposed to go in the given directory for VS 13.

in the lib folder, you will find some versions, I copied the 32-bit glut.lib files in amd and x86 and 64-bit glut.lib in arm64 and x64 directories in um folder for every version that I could find.

That worked for me.

EDIT : I tried this in windows 10, maybe you need to go to C:\Program Files (x86)\Windows Kits\8.1 folder for windows 8/8.1.

What's the best way to use R scripts on the command line (terminal)?

Try littler. littler provides hash-bang (i.e. script starting with #!/some/path) capability for GNU R, as well as simple command-line and piping use.

CSS background image to fit height, width should auto-scale in proportion

try

.something { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    width: 100%;
    height: 100%;
    position: fixed;
    top: 0;
    left: 0;
    z-index: -100;  
}

What is the best method to merge two PHP objects?

You could create another object that dispatches calls to magic methods to the underlying objects. Here's how you'd handle __get, but to get it working fully you'd have to override all the relevant magic methods. You'll probably find syntax errors since I just entered it off the top of my head.

class Compositor {
  private $obj_a;
  private $obj_b;

  public function __construct($obj_a, $obj_b) {
    $this->obj_a = $obj_a;
    $this->obj_b = $obj_b;
  }

  public function __get($attrib_name) {
    if ($this->obj_a->$attrib_name) {
       return $this->obj_a->$attrib_name;
    } else {
       return $this->obj_b->$attrib_name;
    }
  }
}

Good luck.

How to get screen dimensions as pixels in Android

I think it's simplest

private fun checkDisplayResolution() {
    val displayMetrics = DisplayMetrics().also {
        windowManager.defaultDisplay.getMetrics(it)
    }

    Log.i(TAG, "display width: ${displayMetrics.widthPixels}")
    Log.i(TAG, "display height: ${displayMetrics.heightPixels}")
    Log.i(TAG, "display width dpi: ${displayMetrics.xdpi}")
    Log.i(TAG, "display height dpi: ${displayMetrics.ydpi}")
    Log.i(TAG, "display density: ${displayMetrics.density}")
    Log.i(TAG, "display scaled density: ${displayMetrics.scaledDensity}")
}

What is float in Java?

In JAVA, values like:

  1. 8.5
  2. 3.9
  3. (and so on..)

Is assumed as double and not float.

You can also perform a cast in order to solve the problem:

float b = (float) 3.5;

Another solution:

float b = 3.5f;

Convert char to int in C#

This worked for me:

int bar = int.Parse("" + foo);

How to get images in Bootstrap's card to be the same height/width?

.card-img-top {
    height: 15rem;
    object-fit: cover;
}

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

I just figured. You need to add a shared folder using VirtualBox before you access it with the guest.

Click "Device" in the menu bar--->Shared File--->add a directory and name it

then in the guest terminal, use:

sudo mount -t vboxsf myFileName ~/destination

Dont directly refer to the host directory