Programs & Examples On #Usagepatterns

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

Why can't I initialize non-const static member or static array in class?

static variables are specific to a class . Constructors initialize attributes ESPECIALY for an instance.

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

Two possibilities. Either use a combined key:

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

Or a Map of Map:

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

Get the current time in C

guys i got a new way get system time. though its lengthy and is full of silly works but in this way you can get system time in integer format.

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

int main()
{
    FILE *fp;
    char hc1,hc2,mc1,mc2;
    int hi1,hi2,mi1,mi2,hour,minute;
    system("echo %time% >time.txt");
    fp=fopen("time.txt","r");
    if(fp==NULL)
       exit(1) ;
    hc1=fgetc(fp);
    hc2=fgetc(fp);
    fgetc(fp);
    mc1=fgetc(fp);
    mc2=fgetc(fp);
    fclose(fp);
    remove("time.txt");
    hi1=hc1;
    hi2=hc2;
    mi1=mc1;
    mi2=mc2;
    hi1-=48;
    hi2-=48;
    mi1-=48;
    mi2-=48;
    hour=hi1*10+hi2;
    minute=mi1*10+mi2;
    printf("Current time is %d:%d\n",hour,minute);
    return 0;
}

Support for ES6 in Internet Explorer 11

The statement from Microsoft regarding the end of Internet Explorer 11 support mentions that it will continue to receive security updates, compatibility fixes, and technical support until its end of life. The wording of this statement leads me to believe that Microsoft has no plans to continue adding features to Internet Explorer 11, and instead will be focusing on Edge.

If you require ES6 features in Internet Explorer 11, check out a transpiler such as Babel.

Is #pragma once a safe include guard?

I use it and I'm happy with it, as I have to type much less to make a new header. It worked fine for me in three platforms: Windows, Mac and Linux.

I don't have any performance information but I believe that the difference between #pragma and the include guard will be nothing comparing to the slowness of parsing the C++ grammar. That's the real problem. Try to compile the same number of files and lines with a C# compiler for example, to see the difference.

In the end, using the guard or the pragma, won't matter at all.

How to see my Eclipse version?

Open .eclipseproduct in the product installation folder. Or open Configuration\config.ini and check property eclipse.buildId if exist.

How to make matrices in Python?

I got a simple fix to this by casting the lists into strings and performing string operations to get the proper print out of the matrix.

Creating the function

By creating a function, it saves you the trouble of writing the for loop every time you want to print out a matrix.

def print_matrix(matrix):
    for row in matrix:
        new_row = str(row)
        new_row = new_row.replace(',','')
        new_row = new_row.replace('[','')
        new_row = new_row.replace(']','')
        print(new_row)

Examples

Example of a 5x5 matrix with 0 as every entry:

>>> test_matrix = [[0] * 5 for i in range(5)]
>>> print_matrix(test_matrix)
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0
0 0 0 0 0 

Example of a 2x3 matrix with 0 as every entry:

>>> test_matrix = [[0] * 3 for i in range(2)]
>>> print_matrix(test_matrix)
0 0 0
0 0 0

EDIT

If you want to make it print:

A A A A A
B B B B B
C C C C C
D D D D D 
E E E E E

I suggest you just change the way you enter your data into your lists within lists. In my method, each list within the larger list represents a line in the matrix, not columns.

Location Services not working in iOS 8

I was pulling my hair out with the same problem. Xcode gives you the error:

Trying to start MapKit location updates without prompting for location authorization. Must call -[CLLocationManager requestWhenInUseAuthorization] or -[CLLocationManager requestAlwaysAuthorization] first.

But even if you implement one of the above methods, it won't prompt the user unless there is an entry in the info.plist for NSLocationAlwaysUsageDescription or NSLocationWhenInUseUsageDescription.

Add the following lines to your info.plist where the string values represent the reason you you need to access the users location

<key>NSLocationWhenInUseUsageDescription</key>
<string>This application requires location services to work</string>

<key>NSLocationAlwaysUsageDescription</key>
<string>This application requires location services to work</string>

I think these entries may have been missing since I started this project in Xcode 5. I'm guessing Xcode 6 might add default entries for these keys but have not confirmed.

You can find more information on these two Settings here

Regex pattern for checking if a string starts with a certain substring?

For the extension method fans:

public static bool RegexStartsWith(this string str, params string[] patterns)
{
    return patterns.Any(pattern => 
       Regex.Match(str, "^("+pattern+")").Success);
}

Usage

var answer = str.RegexStartsWith("mailto","ftp","joe");
//or
var answer2 = str.RegexStartsWith("mailto|ftp|joe");
//or
bool startsWithWhiteSpace = "  does this start with space or tab?".RegexStartsWith(@"\s");

is it possible to get the MAC address for machine using nmap

With the recent version of nmap 6.40, it will automatically show you the MAC address. example:

nmap 192.168.0.1-255

this command will scan your network from 192.168.0.1 to 255 and will display the hosts with their MAC address on your network.

in case you want to display the mac address for a single client, use this command make sure you are on root or use "sudo"

sudo nmap -Pn 192.168.0.1

this command will display the host MAC address and the open ports.

hope that is helpful.

Soft hyphen in HTML (<wbr> vs. &shy;)

I use &shy;, inserted manually where necessary.

I always find it a pity that people don’t use techniques because there is some—maybe old or strange—browser around which doesn’t handle them the way they were specified. I found that &shy; is working properly in both recent Internet Explorer and Firefox browsers, that should be enough. You may include a browser check telling people to use something mature or continue at their own risk if they come around with some strange browser.

Syllabification isn’t that easy and I cannot recommend leaving it to some Javascript. It’s a language specific topic and may need to be carefully revised by the deskman if you don’t want it to turn your text irritating. Some languages, such as German, form compound words and are likely to lead to decomposition problems. E.g. Spargelder (germ. saved money, pl.) may, by syllabification rules, be wrapped in two places (Spar-gel-der). However, wrapping it in the second position, turns the first part to show up as Spargel- (germ. asparagus), activating a completely misleading concept in the head of the reader and therefore shoud be avoided.

And what about the string Wachstube? It could either mean ‘guardroom’ (Wach-stu-be) or ‘tube of wax’ (Wachs-tu-be). You may probably find other examples in other languages as well. You should aim to provide an environment in which the deskman can be supported in creating a well-syllabified text, proof-reading every critical word.

How to find which version of TensorFlow is installed in my system?

Easily get KERAS and TENSORFLOW version number --> Run this command in terminal:

[username@usrnm:~] python3

>>import keras; print(keras.__version__)

Using TensorFlow backend.

2.2.4

>>import tensorflow as tf; print(tf.__version__)

1.12.0

JavaScript window resize event

var EM = new events_managment();

EM.addEvent(window, 'resize', function(win,doc, event_){
    console.log('resized');
    //EM.removeEvent(win,doc, event_);
});

function events_managment(){
    this.events = {};
    this.addEvent = function(node, event_, func){
        if(node.addEventListener){
            if(event_ in this.events){
                node.addEventListener(event_, function(){
                    func(node, event_);
                    this.events[event_](win_doc, event_);
                }, true);
            }else{
                node.addEventListener(event_, function(){
                    func(node, event_);
                }, true);
            }
            this.events[event_] = func;
        }else if(node.attachEvent){

            var ie_event = 'on' + event_;
            if(ie_event in this.events){
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                    this.events[ie_event]();
                });
            }else{
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                });
            }
            this.events[ie_event] = func;
        }
    }
    this.removeEvent = function(node, event_){
        if(node.removeEventListener){
            node.removeEventListener(event_, this.events[event_], true);
            this.events[event_] = null;
            delete this.events[event_];
        }else if(node.detachEvent){
            node.detachEvent(event_, this.events[event_]);
            this.events[event_] = null;
            delete this.events[event_];
        }
    }
}

WindowsError: [Error 126] The specified module could not be found

When I see things like this - it is usually because there are backslashes in the path which get converted.

For example - the following will fail - because \t in the string is converted to TAB character.

>>> import ctypes
>>> ctypes.windll.LoadLibrary("c:\tools\depends\depends.dll")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "c:\tools\python271\lib\ctypes\__init__.py", line 431, in LoadLibrary
    return self._dlltype(name)
  File "c:\tools\python271\lib\ctypes\__init__.py", line 353, in __init__
    self._handle = _dlopen(self._name, mode)
WindowsError: [Error 126] The specified module could not be found

There are 3 solutions (if that is the problem)

a) Use double slashes...

>>> import ctypes
>>> ctypes.windll.LoadLibrary("c:\\tools\\depends\\depends.dll")

b) use forward slashes

>>> import ctypes
>>> ctypes.windll.LoadLibrary("c:/tools/depends/depends.dll")

c) use RAW strings (prefacing the string with r

>>> import ctypes
>>> ctypes.windll.LoadLibrary(r"c:\tools\depends\depends.dll")

While this third one works - I have gotten the impression from time to time that it is not considered 'correct' because RAW strings were meant for regular expressions. I have been using it for paths on Windows in Python for years without problem :) )

Creating a simple XML file using python

I just finished writing an xml generator, using bigh_29's method of Templates ... it's a nice way of controlling what you output without too many Objects getting 'in the way'.

As for the tag and value, I used two arrays, one which gave the tag name and position in the output xml and another which referenced a parameter file having the same list of tags. The parameter file, however, also has the position number in the corresponding input (csv) file where the data will be taken from. This way, if there's any changes to the position of the data coming in from the input file, the program doesn't change; it dynamically works out the data field position from the appropriate tag in the parameter file.

How to run the sftp command with a password from Bash script?

I was recently asked to switch over from ftp to sftp, in order to secure the file transmission between servers. We are using Tectia SSH package, which has an option --password to pass the password on the command line.

example : sftp --password="password" "userid"@"servername"

Batch example :

(
  echo "
  ascii
  cd pub
  lcd dir_name
  put filename
  close
  quit
    "
) | sftp --password="password" "userid"@"servername"

I thought I should share this information, since I was looking at various websites, before running the help command (sftp -h), and was i surprised to see the password option.

Google maps API V3 method fitBounds()

LatLngBounds must be defined with points in (south-west, north-east) order. Your points are not in that order.

The general fix, especially if you don't know the points will definitely be in that order, is to extend an empty bounds:

var bounds = new google.maps.LatLngBounds();
bounds.extend(myPlace);
bounds.extend(Item_1);
map.fitBounds(bounds);

The API will sort out the bounds.

What is an .axd file?

Those are not files (they don't exist on disk) - they are just names under which some HTTP handlers are registered. Take a look at the web.config in .NET Framework's directory (e.g. C:\Windows\Microsoft.NET\Framework\v4.0.30319\Config\web.config):

<configuration>
  <system.web>
    <httpHandlers>
      <add path="eurl.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
      <add path="trace.axd" verb="*" type="System.Web.Handlers.TraceHandler" validate="True" />
      <add path="WebResource.axd" verb="GET" type="System.Web.Handlers.AssemblyResourceLoader" validate="True" />
      <add verb="*" path="*_AppService.axd" type="System.Web.Script.Services.ScriptHandlerFactory, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False" />
      <add verb="GET,HEAD" path="ScriptResource.axd" type="System.Web.Handlers.ScriptResourceHandler, System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="False"/>
      <add path="*.axd" verb="*" type="System.Web.HttpNotFoundHandler" validate="True" />
    </httpHandlers>
  </system.web>
<configuration>

You can register your own handlers with a whatever.axd name in your application's web.config. While you can bind your handlers to whatever names you like, .axd has the upside of working on IIS6 out of the box by default (IIS6 passes requests for *.axd to the ASP.NET runtime by default). Using an arbitrary path for the handler, like Document.pdf (or really anything except ASP.NET-specific extensions), requires more configuration work. In IIS7 in integrated pipeline mode this is no longer a problem, as all requests are processed by the ASP.NET stack.

How to convert / cast long to String?

Just do this:

String strLong = Long.toString(longNumber);

SQL Call Stored Procedure for each Row without using a cursor

This is a variation of n3rds solution above. No sorting by using ORDER BY is needed, as MIN() is used.

Remember that CustomerID (or whatever other numerical column you use for progress) must have a unique constraint. Furthermore, to make it as fast as possible CustomerID must be indexed on.

-- Declare & init
DECLARE @CustomerID INT = (SELECT MIN(CustomerID) FROM Sales.Customer); -- First ID
DECLARE @Data1 VARCHAR(200);
DECLARE @Data2 VARCHAR(200);

-- Iterate over all customers
WHILE @CustomerID IS NOT NULL
BEGIN  

  -- Get data based on ID
  SELECT @Data1 = Data1, @Data2 = Data2
    FROM Sales.Customer
    WHERE [ID] = @CustomerID ;

  -- call your sproc
  EXEC dbo.YOURSPROC @Data1, @Data2

  -- Get next customerId
  SELECT @CustomerID = MIN(CustomerID)
    FROM Sales.Customer
    WHERE CustomerID > @CustomerId 

END

I use this approach on some varchars I need to look over, by putting them in a temporary table first, to give them an ID.

Turn off display errors using file "php.ini"

In php.ini, comment out:

error_reporting = E_ALL & ~E_NOTICE
error_reporting = E_ALL & ~E_NOTICE | E_STRICT
error_reporting = E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ER… _ERROR
error_reporting = E_ALL & ~E_NOTICE

By placing a ; ahead of it (i.e., like ;error_reporting = E_ALL & ~E_NOTICE)

For disabling in a single file, place error_reporting(0); after opening a php tag.

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

If you want to use those with columns in another work with col-* classes, you can use order-* classes.

You can control the order of your columns with order classes. see more in Bootstrap 4 documentation

A simple from bootstrap docs:

<div class="container">
  <div class="row">
    <div class="col">
      First, but unordered
    </div>
    <div class="col order-12">
      Second, but last
    </div>
    <div class="col order-1">
      Third, but first
    </div>
  </div>
</div>

MVC 4 @Scripts "does not exist"

The key here is to add

 <add namespace="System.Web.Optimization" /> 

to BOTH web.config files. My scenario was that I had System.Web.Optimization reference in both project and the main/root web.config but @Scripts still didn't work properly. You need to add the namespace reference to the Views web.config file to make it work.

UPDATE:

Since the release of MVC 4 System.Web.Optimization is now obsolete. If you're starting with a blank solution you will need to install the following nuget package:

Install-Package Microsoft.AspNet.Web.Optimization

You will still need to reference System.Web.Optimization in your web.config files. For more information see this topic:

How to add reference to System.Web.Optimization for MVC-3-converted-to-4 app

As many pointed out, restart of VS could be required after the above steps to make this work.

Round number to nearest integer

This one is tricky, to be honest. There are many simple ways to do this nevertheless. Using math.ceil(), round(), and math.floor(), you can get a integer by using for example:

n = int(round(n))

If before we used this function n = 5.23, we would get returned 5. If you wanted to round to different place values, you could use this function:

def Round(n,k):
  point = '%0.' + str(k) + 'f'
  if k == 0:
    return int(point % n)
  else:
    return float(point % n)

If we used n (5.23) again, round it to the nearest tenth, and print the answer to the console, our code would be:

Round(5.23,1)

Which would return 5.2. Finally, if you wanted to round something to the nearest, let's say, 1.2, you can use the code:

def Round(n,k):
    return k * round(n/k)

If we wanted n to be rounded to 1.2, our code would be:

print(Round(n,1.2))

and our result:

4.8

Thank you! If you have any questions, please add a comment. :) (Happy Holidays!)

Pull is not possible because you have unmerged files, git stash doesn't work. Don't want to commit

I've had the same error and I solve it with: git merge -s recursive -X theirs origin/master

Is there a sleep function in JavaScript?

function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

This code blocks for the specified duration. This is CPU hogging code. This is different from a thread blocking itself and releasing CPU cycles to be utilized by another thread. No such thing is going on here. Do not use this code, it's a very bad idea.

Map and filter an array at the same time

Since 2019, Array.prototype.flatMap is good option.

options.flatMap(o => o.assigned ? [o.name] : []);

From the MDN page linked above:

flatMap can be used as a way to add and remove items (modify the number of items) during a map. In other words, it allows you to map many items to many items (by handling each input item separately), rather than always one-to-one. In this sense, it works like the opposite of filter. Simply return a 1-element array to keep the item, a multiple-element array to add items, or a 0-element array to remove the item.

Difference between getAttribute() and getParameter()

request.getParameter()

We use request.getParameter() to extract request parameters (i.e. data sent by posting a html form ). The request.getParameter() always returns String value and the data come from client.

request.getAttribute()

We use request.getAttribute() to get an object added to the request scope on the server side i.e. using request.setAttribute(). You can add any type of object you like here, Strings, Custom objects, in fact any object. You add the attribute to the request and forward the request to another resource, the client does not know about this. So all the code handling this would typically be in JSP/servlets. You can use request.setAttribute() to add extra-information and forward/redirect the current request to another resource.

For example,consider about first.jsp,

//First Page : first.jsp
<%@ page import="java.util.*" import="java.io.*"%>
<% request.setAttribute("PAGE", "first.jsp");%>
<jsp:forward page="/second.jsp"/>

and second.jsp:

<%@ page import="java.util.*" import="java.io.*"%>
From Which Page : <%=request.getAttribute("PAGE")%><br>
Data From Client : <%=request.getParameter("CLIENT")%>

From your browser, run first.jsp?CLIENT=you and the output on your browser is

From Which Page : *first.jsp*
Data From Client : you

The basic difference between getAttribute() and getParameter() is that the first method extracts a (serialized) Java object and the other provides a String value. For both cases a name is given so that its value (be it string or a java bean) can be looked up and extracted.

Configuring ObjectMapper in Spring

It may be because I'm using Spring 3.1 (instead of Spring 3.0.5 as your question specified), but Steve Eastwood's answer didn't work for me. This solution works for Spring 3.1:

In your spring xml context:

<mvc:annotation-driven>
    <mvc:message-converters>
        <bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
        <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">
            <property name="objectMapper" ref="jacksonObjectMapper" />
        </bean>        
    </mvc:message-converters>
</mvc:annotation-driven>

<bean id="jacksonObjectMapper" class="de.Company.backend.web.CompanyObjectMapper" />

Access-Control-Allow-Origin: * in tomcat

At the time of writing this, the current version of Tomcat 7 (7.0.41) has a built-in CORS filter http://tomcat.apache.org/tomcat-7.0-doc/config/filter.html#CORS_Filter

How can I start an Activity from a non-Activity class?

Your onTap override receives the MapView from which you can obtain the Context:

@Override
public boolean onTap(GeoPoint p, MapView mapView)
{
    // ...

    Intent intent = new Intent();
    intent.setClass(mapView.getContext(), FullscreenView.class);
    startActivity(intent);

    // ...
}

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

In case of springboot app on tomcat, I needed to create an additional class as below and this worked:

@SpringBootApplication 
public class SpringBootTomcatApplication extends SpringBootServletInitializer {
}

How to know if docker is already logged in to a docker registry server

The answers here so far are not so useful:

  • docker info no longer provides this info
  • docker logout is a major inconvenience - unless you already know the credentials and can easily re-login
  • docker login response seems quite unreliable and not so easy to parse by the program

My solution that worked for me builds on @noobuntu's comment: I figured that if I already known the image that I want to pull, but I'm not sure if the user is already logged in, I can do this:

try pulling target image
-> on failure:
   try logging in
   -> on failure: throw CannotLogInException
   -> on success:
      try pulling target image
      -> on failure: throw CannotPullImageException
      -> on success: (continue)
-> on success: (continue)

Has been compiled by a more recent version of the Java Runtime (class file version 57.0)

how i solve it in Eclipse

  1. go to the properties of the project enter image description here

  2. go to Java compiler enter image description here

  3. change in the Compiler complicated level to java that my project work with (java 11 in my project) you can see that it your java that you work when the last message disappear

  4. Apply enter image description here

Add leading zeroes/0's to existing Excel values to certain length

I hit this page trying to pad hexadecimal values when I realized that DEC2HEX() provides that very feature for free.

You just need to add a second parameter. For example, tying to turn 12 into 0C
DEC2HEX(12,2) => 0C
DEC2HEX(12,4) => 000C
... and so on

What is difference between arm64 and armhf?

Update: Yes, I understand that this answer does not explain the difference between arm64 and armhf. There is a great answer that does explain that on this page. This answer was intended to help set the asker on the right path, as they clearly had a misunderstanding about the capabilities of the Raspberry Pi at the time of asking.

Where are you seeing that the architecture is armhf? On my Raspberry Pi 3, I get:

$ uname -a
armv7l

Anyway, armv7 indicates that the system architecture is 32-bit. The first ARM architecture offering 64-bit support is armv8. See this table for reference.

You are correct that the CPU in the Raspberry Pi 3 is 64-bit, but the Raspbian OS has not yet been updated for a 64-bit device. 32-bit software can run on a 64-bit system (but not vice versa). This is why you're not seeing the architecture reported as 64-bit.

You can follow the GitHub issue for 64-bit support here, if you're interested.

How to write a cursor inside a stored procedure in SQL Server 2008

What's wrong with just simply using a single, simple UPDATE statement??

UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)

That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.

SQL not a single-group group function

Maybe you find this simpler

select * from (
    select ssn, sum(time) from downloads
    group by ssn
    order by sum(time) desc
) where rownum <= 10 --top 10 downloaders

Regards
K

numpy get index where value is true

A simple and clean way: use np.argwhere to group the indices by element, rather than dimension as in np.nonzero(a) (i.e., np.argwhere returns a row for each non-zero element).

>>> a = np.arange(10)
>>> a
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>> np.argwhere(a>4)
array([[5],
       [6],
       [7],
       [8],
       [9]])

np.argwhere(a) is the same as np.transpose(np.nonzero(a)).

Note: You cannot use a(np.argwhere(a>4)) to get the corresponding values in a. The recommended way is to use a[(a>4).astype(bool)] or a[(a>4) != 0] rather than a[np.nonzero(a>4)] as they handle 0-d arrays correctly. See the documentation for more details. As can be seen in the following example, a[(a>4).astype(bool)] and a[(a>4) != 0] can be simplified to a[a>4].

Another example:

>>> a = np.array([5,-15,-8,-5,10])
>>> a
array([  5, -15,  -8,  -5,  10])
>>> a > 4
array([ True, False, False, False,  True])
>>> a[a > 4]
array([ 5, 10])
>>> a = np.add.outer(a,a)
>>> a
array([[ 10, -10,  -3,   0,  15],
       [-10, -30, -23, -20,  -5],
       [ -3, -23, -16, -13,   2],
       [  0, -20, -13, -10,   5],
       [ 15,  -5,   2,   5,  20]])
>>> a = np.argwhere(a>4)
>>> a
array([[0, 0],
       [0, 4],
       [3, 4],
       [4, 0],
       [4, 3],
       [4, 4]])
>>> [print(i,j) for i,j in a]
0 0
0 4
3 4
4 0
4 3
4 4

Get top 1 row of each group

Verifying Clint's awesome and correct answer from above:

The performance between the two queries below is interesting. 52% being the top one. And 48% being the second one. A 4% improvement in performance using DISTINCT instead of ORDER BY. But ORDER BY has the advantage to sort by multiple columns.

IF (OBJECT_ID('tempdb..#DocumentStatusLogs') IS NOT NULL) BEGIN DROP TABLE #DocumentStatusLogs END

CREATE TABLE #DocumentStatusLogs (
    [ID] int NOT NULL,
    [DocumentID] int NOT NULL,
    [Status] varchar(20),
    [DateCreated] datetime
)

INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (2, 1, 'S1', '7/29/2011 1:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (3, 1, 'S2', '7/30/2011 2:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (6, 1, 'S1', '8/02/2011 3:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (1, 2, 'S1', '7/28/2011 4:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (4, 2, 'S2', '7/30/2011 5:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (5, 2, 'S3', '8/01/2011 6:00:00')
INSERT INTO #DocumentStatusLogs([ID], [DocumentID], [Status], [DateCreated]) VALUES (6, 3, 'S1', '8/02/2011 7:00:00')

Option 1:

    SELECT
    [Extent1].[ID], 
    [Extent1].[DocumentID],
    [Extent1].[Status], 
    [Extent1].[DateCreated]
FROM #DocumentStatusLogs AS [Extent1]
    OUTER APPLY (
        SELECT TOP 1
            [Extent2].[ID], 
            [Extent2].[DocumentID],
            [Extent2].[Status], 
            [Extent2].[DateCreated]
        FROM #DocumentStatusLogs AS [Extent2]
        WHERE [Extent1].[DocumentID] = [Extent2].[DocumentID]
        ORDER BY [Extent2].[DateCreated] DESC, [Extent2].[ID] DESC
    ) AS [Project2]
WHERE ([Project2].[ID] IS NULL OR [Project2].[ID] = [Extent1].[ID])

Option 2:

SELECT 
    [Limit1].[DocumentID] AS [ID], 
    [Limit1].[DocumentID] AS [DocumentID], 
    [Limit1].[Status] AS [Status], 
    [Limit1].[DateCreated] AS [DateCreated]
FROM (
    SELECT DISTINCT [Extent1].[DocumentID] AS [DocumentID] FROM #DocumentStatusLogs AS [Extent1]
) AS [Distinct1]
    OUTER APPLY  (
        SELECT TOP (1) [Project2].[ID] AS [ID], [Project2].[DocumentID] AS [DocumentID], [Project2].[Status] AS [Status], [Project2].[DateCreated] AS [DateCreated]
        FROM (
            SELECT 
                [Extent2].[ID] AS [ID], 
                [Extent2].[DocumentID] AS [DocumentID], 
                [Extent2].[Status] AS [Status], 
                [Extent2].[DateCreated] AS [DateCreated]
            FROM #DocumentStatusLogs AS [Extent2]
            WHERE [Distinct1].[DocumentID] = [Extent2].[DocumentID]
        )  AS [Project2]
        ORDER BY [Project2].[ID] DESC
    ) AS [Limit1]

M$'s Management Studio: After highlighting and running the first block, highlight both Option 1 and Option 2, Right click -> [Display Estimated Execution Plan]. Then run the entire thing to see the results.

Option 1 Results:

ID  DocumentID  Status  DateCreated
6   1   S1  8/2/11 3:00
5   2   S3  8/1/11 6:00
6   3   S1  8/2/11 7:00

Option 2 Results:

ID  DocumentID  Status  DateCreated
6   1   S1  8/2/11 3:00
5   2   S3  8/1/11 6:00
6   3   S1  8/2/11 7:00

Note:

I tend to use APPLY when I want a join to be 1-to-(1 of many).

I use a JOIN if I want the join to be 1-to-many, or many-to-many.

I avoid CTE with ROW_NUMBER() unless I need to do something advanced and am ok with the windowing performance penalty.

I also avoid EXISTS / IN subqueries in the WHERE or ON clause, as I have experienced this causing some terrible execution plans. But mileage varies. Review the execution plan and profile performance where and when needed!

Is there a way to pass jvm args via command line to maven?

I think MAVEN_OPTS would be most appropriate for you. See here: http://maven.apache.org/configure.html

In Unix:

Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.

In Win, you need to set environment variable via the dialogue box

Add ... environment variable by opening up the system properties (WinKey + Pause),... In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.

How to include a font .ttf using CSS?

Only providing .ttf file for webfont won't be good enough for cross-browser support. The best possible combination at present is using the combination as :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff') format('woff'), /* Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

This code assumes you have .eot , .woff , .ttf and svg format for you webfont. To automate all this process , you can use : Transfonter.org.

Also , modern browsers are shifting towards .woff font , so you can probably do this too : :

@font-face {
  font-family: 'MyWebFont';
  src: url('myfont.woff') format('woff'), /* Chrome 6+, Firefox 3.6+, IE 9+, Safari 5.1+ */
   url('myfont.ttf') format('truetype'); /* Chrome 4+, Firefox 3.5, Opera 10+, Safari 3—5 */
}  

Read more here : http://css-tricks.com/snippets/css/using-font-face/


Look for browser support : Can I Use fontface

React-router v4 this.props.history.push(...) not working

I had similar symptoms, but my problem was that I was nesting BrowserRouter


Do not nest BrowserRouter, because the history object will refer to the nearest BrowserRouter parent. So when you do a history.push(targeturl) and that targeturl it's not in that particular BrowserRouter it won't match any of it's route, so it will not load any sub-component.

Solution

Nest the Switch without wrapping it with a BrowserRouter


Example

Let's consider this App.js file

<BrowserRouter>
  <Switch>
    <Route exact path="/nestedrouter" component={NestedRouter}  />
    <Route exact path="/target" component={Target}  />
  </Switch>
</BrowserRouter>

Instead of doing this in the NestedRouter.js file

<BrowserRouter>
  <Switch>
    <Route exact path="/nestedrouter/" component={NestedRouter}  />
    <Route exact path="/nestedrouter/subroute" component={SubRoute}  />
  </Switch>
</BrowserRouter>

Simply remove the BrowserRouter from NestedRouter.js file

  <Switch>
    <Route exact path="/nestedrouter/" component={NestedRouter}  />
    <Route exact path="/nestedrouter/subroute" component={SubRoute}  />
  </Switch>

Why I've got no crontab entry on OS X when using vim?

I did 2 things to solve this problem.

  1. I touched the crontab file, described in this link coderwall.com/p/ry9jwg (Thanks @Andy).
  2. Used Emacs instead of my default vim: EDITOR=emacs crontab -e (I have no idea why vim does not work)

crontab -lnow prints the cronjobs. Now I only need to figure out why the cronjobs are still not running ;-)

What is the difference between %g and %f in C?

They are both examples of floating point input/output.

%g and %G are simplifiers of the scientific notation floats %e and %E.

%g will take a number that could be represented as %f (a simple float or double) or %e (scientific notation) and return it as the shorter of the two.

The output of your print statement will depend on the value of sum.

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

How can I find the latitude and longitude from address?

public void goToLocationFromAddress(String strAddress) {
    //Create coder with Activity context - this
    Geocoder coder = new Geocoder(this);
    List<Address> address;

    try {
        //Get latLng from String
        address = coder.getFromLocationName(strAddress, 5);

        //check for null
        if (address != null) {

            //Lets take first possibility from the all possibilities.
            try {
                Address location = address.get(0);
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

                //Animate and Zoon on that map location
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
            } catch (IndexOutOfBoundsException er) {
                Toast.makeText(this, "Location isn't available", Toast.LENGTH_SHORT).show();
            }

        }


    } catch (IOException e) {
        e.printStackTrace();
    }
}

What is the difference between String.slice and String.substring?

The one answer is fine but requires a little reading into. Especially with the new terminology "stop".

My Go -- organized by differences to make it useful in addition to the first answer by Daniel above:

1) negative indexes. Substring requires positive indexes and will set a negative index to 0. Slice's negative index means the position from the end of the string.

"1234".substring(-2, -1) == "1234".substring(0,0) == ""
"1234".slice(-2, -1) == "1234".slice(2, 3) == "3"

2) Swapping of indexes. Substring will reorder the indexes to make the first index less than or equal to the second index.

"1234".substring(3,2) == "1234".substring(2,3) == "3"
"1234".slice(3,2) == ""

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

General comment -- I find it weird that the second index is the position after the last character of the slice or substring. I would expect "1234".slice(2,2) to return "3". This makes Andy's confusion above justified -- I would expect "1234".slice(2, -1) to return "34". Yes, this means I'm new to Javascript. This means also this behavior:

"1234".slice(-2, -2) == "", "1234".slice(-2, -1) == "3", "1234".slice(-2, -0) == "" <-- you have to use length or omit the argument to get the 4.
"1234".slice(3, -2) == "", "1234".slice(3, -1) == "", "1234".slice(3, -0) == "" <-- same issue, but seems weirder.

My 2c.

SQL Greater than, Equal to AND Less Than

Supposing you use sql server:

WHERE StartTime BETWEEN DATEADD(HOUR, -1, GetDate())
                    AND DATEADD(HOUR, 1, GetDate())

How do I add PHP code/file to HTML(.html) files?

You can modify .htaccess like others said, but the fastest solution is to rename the file extension to .php

What's the HTML to have a horizontal space between two objects?

I guess what you want is:

&nbsp;

But this is usually not a nice way to align some content. You better put your different content in

<div>

tags and then use css for proper alignment.


You can also check out this post with useful extra info:

Pass C# ASP.NET array to Javascript array

In the page file:

<script type="text/javascript">
    var a = eval('[<% =string.Join(", ", numbers) %>]');
</script>

while in code behind:

public int[] numbers = WhatEverGetTheArray();

Which versions of SSL/TLS does System.Net.WebRequest support?

I also put an answer there, but the article @Colonel Panic's update refers to suggests forcing TLS 1.2. In the future, when TLS 1.2 is compromised or just superceded, having your code stuck to TLS 1.2 will be considered a deficiency. Negotiation to TLS1.2 is enabled in .Net 4.6 by default. If you have the option to upgrade your source to .Net 4.6, I would highly recommend that change over forcing TLS 1.2.

If you do force TLS 1.2, strongly consider leaving some type of breadcrumb that will remove that force if you do upgrade to the 4.6 or higher framework.

Android Completely transparent Status Bar?

Just add this line of code to your main java file:

getWindow().setFlags(
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
    WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS
);

Change color of Back button in navigation bar

I'm using this in swift 5 and worked for me

navigationItem.backBarButtonItem?.tintColor = UIColor(named: "uberRed")

How to check user is "logged in"?

if (User.Identity.IsAuthenticated)
{
    Page.Title = "Home page for " + User.Identity.Name;
}
else
{
    Page.Title = "Home page for guest user.";
}

Cut Java String at a number of character

You can use safe substring:

org.apache.commons.lang3.StringUtils.substring(str, 0, LENGTH);

What is the difference between JDK and JRE?

Simply :

JVM is the virtual machine Java code executes on

JRE is the environment (standard libraries and JVM) required to run Java applications

JDK is the JRE with developer tools and documentation

C# Base64 String to JPEG Image

First, convert the base 64 string to an Image, then use the Image.Save method.

To convert from base 64 string to Image:

 public Image Base64ToImage(string base64String)
 {
    // Convert base 64 string to byte[]
    byte[] imageBytes = Convert.FromBase64String(base64String);
    // Convert byte[] to Image
    using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
    {
        Image image = Image.FromStream(ms, true);
        return image;
    }
 }

To convert from Image to base 64 string:

public string ImageToBase64(Image image,System.Drawing.Imaging.ImageFormat format)
{
  using (MemoryStream ms = new MemoryStream())
  {
    // Convert Image to byte[]
    image.Save(ms, format);
    byte[] imageBytes = ms.ToArray();

    // Convert byte[] to base 64 string
    string base64String = Convert.ToBase64String(imageBytes);
    return base64String;
  }
}

Finally, you can easily to call Image.Save(filePath); to save the image.

How to set Spring profile from system variable?

If you provide your JVM the Spring profile there should be no problems:

java -Dspring.profiles.active=development -jar yourApplication.jar 

Also see Spring-Documentation:

http://docs.spring.io/spring-boot/docs/current/reference/html/howto-properties-and-configuration.html

69.5 Set the active Spring profiles

The Spring Environment has an API for this, but normally you would set a System property (spring.profiles.active) or an OS environment variable (SPRING_PROFILES_ACTIVE). E.g. launch your application with a -D argument (remember to put it before the main class or jar archive):

$ java -jar -Dspring.profiles.active=production demo-0.0.1-SNAPSHOT.jar

In Spring Boot you can also set the active profile in application.properties, e.g.

spring.profiles.active=production

A value set this way is replaced by the System property or environment variable setting, but not by the SpringApplicationBuilder.profiles() method. Thus the latter Java API can be used to augment the profiles without changing the defaults.

See Chapter 25, Profiles in the ‘Spring Boot features’ section for more information.

How To Create Table with Identity Column

Unique key allows max 2 NULL values. Explaination:

create table teppp
(
id int identity(1,1) primary key,
name varchar(10 )unique,
addresss varchar(10)
)

insert into teppp ( name,addresss) values ('','address1')
insert into teppp ( name,addresss) values ('NULL','address2')
insert into teppp ( addresss) values ('address3')

select * from teppp
null string , address1
NULL,address2
NULL,address3

If you try inserting same values as below:

insert into teppp ( name,addresss) values ('','address4')
insert into teppp ( name,addresss) values ('NULL','address5')
insert into teppp ( addresss) values ('address6')

Every time you will get error like:

Violation of UNIQUE KEY constraint 'UQ__teppp__72E12F1B2E1BDC42'. Cannot insert duplicate key in object 'dbo.teppp'.
The statement has been terminated.

How do you remove an invalid remote branch reference from Git?

I didn't know about git branch -rd, so the way I have solved issues like this for myself is to treat my repo as a remote repo and do a remote delete. git push . :refs/remotes/public/master. If the other ways don't work and you have some weird reference you want to get rid of, this raw way is surefire. It gives you the exact precision to remove (or create!) any kind of reference.

Arrays.fill with multidimensional array in Java

how can I fill a multidimensional array in Java without using a loop?

Multidimensional arrays are just arrays of arrays and fill(...) doesn't check the type of the array and the value you pass in (this responsibility is upon the developer).

Thus you can't fill a multidimensional array reasonably well without using a loop.

Be aware of the fact that, unlike languages like C or C++, Java arrays are objects and in multidimensional arrays all but the last level contain references to other Array objects. I'm not 100% sure about this, but most likely they are distributed in memory, thus you can't just fill a contiguous block without a loop, like C/C++ would allow you to do.

Collection that allows only unique items in .NET?

Just to add my 2 cents...

if you need a ValueExistingException-throwing HashSet<T> you can also create your collection easily:

public class ThrowingHashSet<T> : ICollection<T>
{
    private HashSet<T> innerHash = new HashSet<T>();

    public void Add(T item)
    {
        if (!innerHash.Add(item))
            throw new ValueExistingException();
    }

    public void Clear()
    {
        innerHash.Clear();
    }

    public bool Contains(T item)
    {
        return innerHash.Contains(item);
    }

    public void CopyTo(T[] array, int arrayIndex)
    {
        innerHash.CopyTo(array, arrayIndex);
    }

    public int Count
    {
        get { return innerHash.Count; }
    }

    public bool IsReadOnly
    {
        get { return false; }
    }

    public bool Remove(T item)
    {
        return innerHash.Remove(item);
    }

    public IEnumerator<T> GetEnumerator()
    {
        return innerHash.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return this.GetEnumerator();
    }
}

this can be useful for example if you need it in many places...

Finding the number of non-blank columns in an Excel sheet using VBA

Your example code gets the row number of the last non-blank cell in the current column, and can be rewritten as follows:

Dim lastRow As Long
lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastRow

It is then easy to see that the equivalent code to get the column number of the last non-blank cell in the current row is:

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn

This may also be of use to you:

With Sheet1.UsedRange
    MsgBox .Rows.Count & " rows and " & .Columns.Count & " columns"
End With

but be aware that if column A and/or row 1 are blank, then this will not yield the same result as the other examples above. For more, read up on the UsedRange property.

Global Git ignore

You should create an exclude file for this. Check out this gist which is pretty self explanatory.

To address your question though, you may need to either de-index the .tmproj file (if you've already added it to the index) with git rm --cached path/to/.tmproj, or git add and commit your .gitignore file.

Copy mysql database from remote server to local computer

Assuming the following command works successfully:

mysql -u username -p -h remote.site.com

The syntax for mysqldump is identical, and outputs the database dump to stdout. Redirect the output to a local file on the computer:

mysqldump -u username -p -h remote.site.com DBNAME > backup.sql

Replace DBNAME with the name of the database you'd like to download to your computer.

Foreign key constraint may cause cycles or multiple cascade paths?

Trigger is solution for this problem:

IF OBJECT_ID('dbo.fktest2', 'U') IS NOT NULL
    drop table fktest2
IF OBJECT_ID('dbo.fktest1', 'U') IS NOT NULL
    drop table fktest1
IF EXISTS (SELECT name FROM sysobjects WHERE name = 'fkTest1Trigger' AND type = 'TR')
    DROP TRIGGER dbo.fkTest1Trigger
go
create table fktest1 (id int primary key, anQId int identity)
go  
    create table fktest2 (id1 int, id2 int, anQId int identity,
        FOREIGN KEY (id1) REFERENCES fktest1 (id)
            ON DELETE CASCADE
            ON UPDATE CASCADE/*,    
        FOREIGN KEY (id2) REFERENCES fktest1 (id) this causes compile error so we have to use triggers
            ON DELETE CASCADE
            ON UPDATE CASCADE*/ 
            )
go

CREATE TRIGGER fkTest1Trigger
ON fkTest1
AFTER INSERT, UPDATE, DELETE
AS
    if @@ROWCOUNT = 0
        return
    set nocount on

    -- This code is replacement for foreign key cascade (auto update of field in destination table when its referenced primary key in source table changes.
    -- Compiler complains only when you use multiple cascased. It throws this compile error:
    -- Rrigger Introducing FOREIGN KEY constraint on table may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, 
    -- or modify other FOREIGN KEY constraints.
    IF ((UPDATE (id) and exists(select 1 from fktest1 A join deleted B on B.anqid = A.anqid where B.id <> A.id)))
    begin       
        update fktest2 set id2 = i.id
            from deleted d
            join fktest2 on d.id = fktest2.id2
            join inserted i on i.anqid = d.anqid        
    end         
    if exists (select 1 from deleted)       
        DELETE one FROM fktest2 one LEFT JOIN fktest1 two ON two.id = one.id2 where two.id is null -- drop all from dest table which are not in source table
GO

insert into fktest1 (id) values (1)
insert into fktest1 (id) values (2)
insert into fktest1 (id) values (3)

insert into fktest2 (id1, id2) values (1,1)
insert into fktest2 (id1, id2) values (2,2)
insert into fktest2 (id1, id2) values (1,3)

select * from fktest1
select * from fktest2

update fktest1 set id=11 where id=1
update fktest1 set id=22 where id=2
update fktest1 set id=33 where id=3
delete from fktest1 where id > 22

select * from fktest1
select * from fktest2

What is the simplest way to convert array to vector?

You're asking the wrong question here - instead of forcing everything into a vector ask how you can convert test to work with iterators instead of a specific container. You can provide an overload too in order to retain compatibility (and handle other containers at the same time for free):

void test(const std::vector<int>& in) {
  // Iterate over vector and do whatever
}

becomes:

template <typename Iterator>
void test(Iterator begin, const Iterator end) {
    // Iterate over range and do whatever
}

template <typename Container>
void test(const Container& in) {
    test(std::begin(in), std::end(in));
}

Which lets you do:

int x[3]={1, 2, 3};
test(x); // Now correct

(Ideone demo)

A simple scenario using wait() and notify() in java

Even though you asked for wait() and notify() specifically, I feel that this quote is still important enough:

Josh Bloch, Effective Java 2nd Edition, Item 69: Prefer concurrency utilities to wait and notify (emphasis his):

Given the difficulty of using wait and notify correctly, you should use the higher-level concurrency utilities instead [...] using wait and notify directly is like programming in "concurrency assembly language", as compared to the higher-level language provided by java.util.concurrent. There is seldom, if ever, reason to use wait and notify in new code.

How to tell which disk Windows Used to Boot

a simpler way search downloads in the start menu and click on downloads in the search results to see where it will take you the drive will be highlighted in the explorer.

How do operator.itemgetter() and sort() work?

You are asking a lot of questions that you could answer yourself by reading the documentation, so I'll give you a general advice: read it and experiment in the python shell. You'll see that itemgetter returns a callable:

>>> func = operator.itemgetter(1)
>>> func(a)
['Paul', 22, 'Car Dealer']
>>> func(a[0])
8

To do it in a different way, you can use lambda:

a.sort(key=lambda x: x[1])

And reverse it:

a.sort(key=operator.itemgetter(1), reverse=True)

Sort by more than one column:

a.sort(key=operator.itemgetter(1,2))

See the sorting How To.

android.app.Application cannot be cast to android.app.Activity

You are getting this error because the parameter required is Activity and you are passing it the Application. So, either you cast application to the Activity like: (Activity)getApplicationContext(); Or you can just type the Activity like: MyActivity.this

Select only rows if its value in a particular column is less than the value in the other column

If you use dplyr package you can do:

library(dplyr)
filter(df, aged <= laclen)

How to use JavaScript source maps (.map files)?

Just to add to how to use map files. I use chrome for ubuntu and if I go to sources and click on a file, if there is a map file a message comes up telling me that I can view the original file and how to do it.

For the Angular files that I worked with today I click

Ctrl-P and a list of original files comes up in a small window.

I can then browse through the list to view the file that I would like to inspect and check where the issue might be.

VirtualBox and vmdk vmx files

VMDK/VMX are VMWare file formats but you can use it with VirtualBox:

  1. Create a new Virtual Machine and when asks for a hard disk choose "Use an existing hard disk"
  2. Click on the "button with folder and green arrow image on the combo box right" which opens Virtual Media Manager, it looks like this (you can open it directly pressing CTRL+D on main window or in File > Virtual Media Manager menu)...
  3. Then you can add the VMDK/VMX hard disk image and setup it for your virtual machine :)

Fixed positioned div within a relative parent div

Try postion:sticky on parent element.

Which way is best for creating an object in JavaScript? Is `var` necessary before an object property?

Majorly there are 3 ways of creating Objects-

Simplest one is using object literals.

const myObject = {}

Though this method is the simplest but has a disadvantage i.e if your object has behaviour(functions in it),then in future if you want to make any changes to it you would have to change it in all the objects.

So in that case it is better to use Factory or Constructor Functions.(anyone that you like)

Factory Functions are those functions that return an object.e.g-

function factoryFunc(exampleValue){
   return{
      exampleProperty: exampleValue 
   }
}

Constructor Functions are those functions that assign properties to objects using "this" keyword.e.g-

function constructorFunc(exampleValue){
   this.exampleProperty= exampleValue;
}
const myObj= new constructorFunc(1);

Updating the list view when the adapter data changes

I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // Edit object data that is represented in Viewat at list's "position"
      view = mAdapter.getView(position, view, parent);
    }
});

Most efficient way to reverse a numpy array

In order to have it working with negative numbers and a long list you can do the following:

b = numpy.flipud(numpy.array(a.split(),float))

Where flipud is for 1d arra

Best way to log POST data in Apache?

You can install mod_security and put in /etc/modsecurity/modsecurity.conf:

SecRuleEngine On
SecAuditEngine On
SecAuditLog /var/log/apache2/modsec_audit.log
SecRequestBodyAccess on
SecAuditLogParts ABIJDFHZ

Why do we need to use flatMap?

flatMap transform the items emitted by an Observable into Observables, then flatten the emissions from those into a single Observable

I am not stupid but had to read this 10 times and still don't get it. When I read the code snippet :

[1,2,3].map(x => [x, x * 10])
// [[1, 10], [2, 20], [3, 30]]

[1,2,3].flatMap(x => [x, x * 10])
// [1, 10, 2, 20, 3, 30]

then I could understand whats happening, it does two things :

flatMap :

  1. map: transform *) emitted items into Observables.
  2. flat: then merge those Observables as one Observable.

*) The transform word says the item can be transformed in something else.

Then the merge operator becomes clear to, it does the flattening without the mapping. Why not calling it mergeMap? It seems there is also an Alias mergeMap with that name for flatMap.

Global npm install location on windows?

These are typical npm paths if you install a package globally:

Windows XP -             %USERPROFILE%\Application Data\npm\node_modules
Newer Windows Versions - %AppData%\npm\node_modules
or -                     %AppData%\roaming\npm\node_modules

java: HashMap<String, int> not working

You can't use primitive types as generic arguments in Java. Use instead:

Map<String, Integer> myMap = new HashMap<String, Integer>();

With auto-boxing/unboxing there is little difference in the code. Auto-boxing means you can write:

myMap.put("foo", 3);

instead of:

myMap.put("foo", new Integer(3));

Auto-boxing means the first version is implicitly converted to the second. Auto-unboxing means you can write:

int i = myMap.get("foo");

instead of:

int i = myMap.get("foo").intValue();

The implicit call to intValue() means if the key isn't found it will generate a NullPointerException, for example:

int i = myMap.get("bar"); // NullPointerException

The reason is type erasure. Unlike, say, in C# generic types aren't retained at runtime. They are just "syntactic sugar" for explicit casting to save you doing this:

Integer i = (Integer)myMap.get("foo");

To give you an example, this code is perfectly legal:

Map<String, Integer> myMap = new HashMap<String, Integer>();
Map<Integer, String> map2 = (Map<Integer, String>)myMap;
map2.put(3, "foo");

Web API Put Request generates an Http 405 Method Not Allowed error

This simple problem can cause a real headache!

I can see your controller EDIT (PUT) method expects 2 parameters: a) an int id, and b) a department object.

It is the default code when you generate this from VS > add controller with read/write options. However, you have to remember to consume this service using the two parameters, otherwise you will get the error 405.

In my case, I did not need the id parameter for PUT, so I just dropped it from the header... after a few hours of not noticing it there! If you keep it there, then the name must also be retained as id, unless you go on to make necessary changes to your configurations.

How to specify a multi-line shell variable?

read does not export the variable (which is a good thing most of the time). Here's an alternative which can be exported in one command, can preserve or discard linefeeds, and allows mixing of quoting-styles as needed. Works for bash and zsh.

oneLine=$(printf %s \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)
multiLine=$(printf '%s\n' \
    a   \
    " b "   \
    $'\tc\t'    \
    'd '    \
)

I admit the need for quoting makes this ugly for SQL, but it answers the (more generally expressed) question in the title.

I use it like this

export LS_COLORS=$(printf %s    \
    ':*rc=36:*.ini=36:*.inf=36:*.cfg=36:*~=33:*.bak=33:*$=33'   \
    ...
    ':bd=40;33;1:cd=40;33;1:or=1;31:mi=31:ex=00')

in a file sourced from both my .bashrc and .zshrc.

Where does VBA Debug.Print log to?

Where do you want to see the output?

Messages being output via Debug.Print will be displayed in the immediate window which you can open by pressing Ctrl+G.

You can also Activate the so called Immediate Window by clicking View -> Immediate Window on the VBE toolbar

enter image description here

Filter items which array contains any of given values

For those looking at this in 2020, you may notice that accepted answer is deprecated in 2020, but there is a similar approach available using terms_set and minimum_should_match_script combination.

Please see the detailed answer here in the SO thread

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

   SELECT CONVERT(varchar(11),getdate(),101)  -- mm/dd/yyyy

   SELECT CONVERT(varchar(11),getdate(),103)  -- dd/mm/yyyy

Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST() function to make it as an character expression because CHARINDEX() works on character expression.
Also I think there is no need of OR condition.

select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0 

then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end

EDIT:

select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0 
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end

See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp

Fastest way to zero out a 2d array in C?

int array[N][M] = {0};

...at least in GCC 4.8.

No WebApplicationContext found: no ContextLoaderListener registered?

And if you would like to use an existing context, rather than a new context which would be loaded from xml configuration by org.springframework.web.context.ContextLoaderListener, then see -> https://stackoverflow.com/a/40694787/3004747

IN-clause in HQL or Java Persistence Query Language

in HQL you can use query parameter and set Collection with setParameterList method.

    Query q = session.createQuery("SELECT entity FROM Entity entity WHERE name IN (:names)");
    q.setParameterList("names", names);

Python list iterator behavior and next(iterator)

What you see is the interpreter echoing back the return value of next() in addition to i being printed each iteration:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    next(a)
... 
0
1
2
3
4
5
6
7
8
9

So 0 is the output of print(i), 1 the return value from next(), echoed by the interactive interpreter, etc. There are just 5 iterations, each iteration resulting in 2 lines being written to the terminal.

If you assign the output of next() things work as expected:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print(i)
...    _ = next(a)
... 
0
2
4
6
8

or print extra information to differentiate the print() output from the interactive interpreter echo:

>>> a = iter(list(range(10)))
>>> for i in a:
...    print('Printing: {}'.format(i))
...    next(a)
... 
Printing: 0
1
Printing: 2
3
Printing: 4
5
Printing: 6
7
Printing: 8
9

In other words, next() is working as expected, but because it returns the next value from the iterator, echoed by the interactive interpreter, you are led to believe that the loop has its own iterator copy somehow.

HTML table: keep the same width for columns

In your case, since you are only showing 3 columns:

Name    Value       Business
  or
Name    Business    Ecommerce Pro

why not set all 3 to have a width of 33.3%. since only 3 are ever shown at once, the browser should render them all a similar width.

nodejs get file name from absolute path?

In NodeJS, __filename.split(/\|//).pop() returns just the file name from the absolute file path on any OS platform. Why need to care about remembering/importing an API while this regex approach also letting us recollect our regex skills.

How to remove all click event handlers using jQuery?

Is there a way to remove all previous click events that have been assigned to a button?

$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});

Maximum call stack size exceeded error

Both invocations of the identical code below if decreased by 1 work in Chrome 32 on my computer e.g. 17905 vs 17904. If run as is they will produce the error "RangeError: Maximum call stack size exceeded". It appears to be this limit is not hardcoded but dependant on the hardware of your machine. It does appear that if invoked as a function this self-imposed limit is higher than if invoked as a method i.e. this particular code uses less memory when invoked as a function.

Invoked as a method:

var ninja = {
    chirp: function(n) {
        return n > 1 ? ninja.chirp(n-1) + "-chirp" : "chirp";
    }
};

ninja.chirp(17905);

Invoked as a function:

function chirp(n) {
    return n > 1 ? chirp( n - 1 ) + "-chirp" : "chirp";
}

chirp(20889);

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

  1. Uninstall mysql using yum remove mysql*

  2. Recursively delete /usr/bin/mysql and /var/lib/mysql

  3. Delete the file /etc/my.cnf.rmp

  4. Use ps -e to check the processes to make sure mysql isn't still running.

  5. Reboot server with reboot

  6. Run yum install mysql-server. This also seems to install the mysql client as a dependency.

  7. Give mysql ownership and group priveleges with:

    chown -R mysql /var/lib/mysql

    chgrp -R mysql /var/lib/mysql

  8. Use service mysqld start to start MySQL Daemon.

Lodash .clone and .cloneDeep behaviors

Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.

As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:

var clone = _.clone(data, true);

data[1].values.d = 'x';

I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.

Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).

Custom Input[type="submit"] style not working with jquerymobile button

jQuery Mobile >= 1.4

Create a custom class, e.g. .custom-btn. Note that to override jQM styles without using !important, CSS hierarchy should be respected. .ui-btn.custom-class or .ui-input-btn.custom-class.

.ui-input-btn.custom-btn {
   border:1px solid red;
   text-decoration:none;
   font-family:helvetica;
   color:red;
   background:url(img.png) repeat-x;
}

Add a data-wrapper-class to input. The custom class will be added to input wrapping div.

<input type="button" data-wrapper-class="custom-btn">

Demo


jQuery Mobile <= 1.3

Input button is wrapped by a DIV with class ui-btn. You need to select that div and the input[type="submit"]. Using !important is essential to override Jquery Mobile styles.

Demo

div.ui-btn, input[type="submit"] {
 border:1px solid red !important;
 text-decoration:none !important;
 font-family:helvetica !important;
 color:red !important;
 background:url(../images/btn_hover.png) repeat-x !important;
}

How to use a keypress event in AngularJS?

I'm a bit late .. but i found a simpler solution using auto-focus .. This could be useful for buttons or other when popping a dialog :

<button auto-focus ng-click="func()">ok</button>

That should be fine if you want to press the button onSpace or Enter clicks .

How to convert JSON object to an Typescript array?

You have a JSON object that contains an Array. You need to access the array results. Change your code to:

this.data = res.json().results

How to use OpenSSL to encrypt/decrypt files?

To Encrypt:

$ openssl bf < arquivo.txt > arquivo.txt.bf

To Decrypt:

$ openssl bf -d < arquivo.txt.bf > arquivo.txt

bf === Blowfish in CBC mode

How to Consolidate Data from Multiple Excel Columns All into One Column

Save your workbook. If this code doesn't do what you want, the only way to go back is to close without saving and reopen.

Select the data you want to list in one column. Must be contiguous columns. May contain blank cells.

Press Alt+F11 to open the VBE

Press Control+R to view the Project Explorer

Navigate to the project for your workbook and choose Insert - Module

Paste this code in the code pane

Sub MakeOneColumn()

    Dim vaCells As Variant
    Dim vOutput() As Variant
    Dim i As Long, j As Long
    Dim lRow As Long

    If TypeName(Selection) = "Range" Then
        If Selection.Count > 1 Then
            If Selection.Count <= Selection.Parent.Rows.Count Then
                vaCells = Selection.Value

                ReDim vOutput(1 To UBound(vaCells, 1) * UBound(vaCells, 2), 1 To 1)

                For j = LBound(vaCells, 2) To UBound(vaCells, 2)
                    For i = LBound(vaCells, 1) To UBound(vaCells, 1)
                        If Len(vaCells(i, j)) > 0 Then
                            lRow = lRow + 1
                            vOutput(lRow, 1) = vaCells(i, j)
                        End If
                    Next i
                Next j

                Selection.ClearContents
                Selection.Cells(1).Resize(lRow).Value = vOutput
            End If
        End If
    End If

End Sub

Press F5 to run the code

How to remove index.php from URLs?

If the other solutions don't work for you, try this:

Step 1: (if your installation is in webroot)

Replace

    #RewriteBase /magento/

with

    RewriteBase /

Step 2:

Add following lines (inclusive exclude admin because backend needs index.php internally)

RewriteCond %{THE_REQUEST} ^.*/index.php
RewriteRule ^(.*)index.php$ http://www.yourdomain.com/$1 [R=301,L]
RewriteRule ^index.php/(admin|user)($|/) - [L]
RewriteRule ^index.php/(.*) $1 [R=301,QSA,L]

right after

RewriteRule .* index.php [L] 

This works for me

In case it is still not working, double check Magento configuration: System->Configuration->Web->Search Engine Optimization. Rewrites must be enabled.

Select the first row by group

What about

DT <- data.table(test)
setkey(DT, id)

DT[J(unique(id)), mult = "first"]

Edit

There is also a unique method for data.tables which will return the the first row by key

jdtu <- function() unique(DT)

I think, if you are ordering test outside the benchmark, then you can removing the setkey and data.table conversion from the benchmark as well (as the setkey basically sorts by id, the same as order).

set.seed(21)
test <- data.frame(id=sample(1e3, 1e5, TRUE), string=sample(LETTERS, 1e5, TRUE))
test <- test[order(test$id), ]
DT <- data.table(DT, key = 'id')
ju <- function() test[!duplicated(test$id),]

jdt <- function() DT[J(unique(id)),mult = 'first']


 library(rbenchmark)
benchmark(ju(), jdt(), replications = 5)
##    test replications elapsed relative user.self sys.self 
## 2 jdt()            5    0.01        1      0.02        0        
## 1  ju()            5    0.05        5      0.05        0         

and with more data

** Edit with unique method**

set.seed(21)
test <- data.frame(id=sample(1e4, 1e6, TRUE), string=sample(LETTERS, 1e6, TRUE))
test <- test[order(test$id), ]
DT <- data.table(test, key = 'id')
       test replications elapsed relative user.self sys.self 
2  jdt()            5    0.09     2.25      0.09     0.00    
3 jdtu()            5    0.04     1.00      0.05     0.00      
1   ju()            5    0.22     5.50      0.19     0.03        

The unique method is fastest here.

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) symfony2

'default' => env('DB_CONNECTION', 'mysql'),

add this in your code

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

I have this version about datetimepicker https://tempusdominus.github.io/bootstrap-4/ and for any reason doesn`t work the change event with jquery but with JS vanilla it does

I figure out like this

document.getElementById('date').onchange = function(){ ...the jquery code...}

I hope work for you

Run bash script from Windows PowerShell

There is now a "native" solution on Windows 10, after enabling Bash on Windows, you can enter Bash shell by typing bash: Bash on Windows

You can run Bash script like bash ./script.sh, but keep in mind that C drive is located at /mnt/c, and external hard drives are not mountable. So you might need to change your script a bit so it is compatible to Windows.

Also, even as root, you can still get permission denied when moving files around in /mnt, but you have your full root power in the / file system.

Also make sure your shell script is formatted with Unix style, or there can be errors. Example script

Different ways of adding to Dictionary

One is assigning a value while the other is adding to the Dictionary a new Key and Value.

How do I copy the contents of one ArrayList into another?

Supopose you want to copy oldList into a new ArrayList object called newList

ArrayList<Object> newList = new ArrayList<>() ;

for (int i = 0 ; i<oldList.size();i++){
    newList.add(oldList.get(i)) ;
}

These two lists are indepedant, changes to one are not reflected to the other one.

How to instantiate a javascript class in another js file?

You can export your methods to access from other files like this:

file1.js

var name = "Jhon";
exports.getName = function() {
  return name;
}

file2.js

var instance = require('./file1.js');
var name = instance.getName();

How to best display in Terminal a MySQL SELECT returning too many fields?

Terminate the query with \G in place of ;. For example:

SELECT * FROM sometable\G

This query displays the rows vertically, like this:

*************************** 1. row ***************************
                 Host: localhost
                   Db: mydatabase1
                 User: myuser1
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          ...
*************************** 2. row ***************************
                 Host: localhost
                   Db: mydatabase2
                 User: myuser2
          Select_priv: Y
          Insert_priv: Y
          Update_priv: Y
          ...

How to Copy Text to Clip Board in Android?

Here the method to copy text to clipboard:

private void setClipboard(Context context, String text) {
  if(android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.HONEYCOMB) {
    android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    clipboard.setText(text);
  } else {
    android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
    android.content.ClipData clip = android.content.ClipData.newPlainText("Copied Text", text);
    clipboard.setPrimaryClip(clip);
  }
}

This method is working on all android devices.

Browse files and subfolders in Python

You can use os.walk() to recursively iterate through a directory and all its subdirectories:

for root, dirs, files in os.walk(path):
    for name in files:
        if name.endswith((".html", ".htm")):
            # whatever

To build a list of these names, you can use a list comprehension:

htmlfiles = [os.path.join(root, name)
             for root, dirs, files in os.walk(path)
             for name in files
             if name.endswith((".html", ".htm"))]

Custom date format with jQuery validation plugin

Jon, you have some syntax errors, see below, this worked for me.

  <script type="text/javascript">
$(document).ready(function () {

  $.validator.addMethod(
      "australianDate",
      function (value, element) {
        // put your own logic here, this is just a (crappy) example 
        return value.match(/^\d\d?\/\d\d?\/\d\d\d\d$/);
      },
      "Please enter a date in the format dd/mm/yyyy"
    );

  $('#testForm').validate({
    rules: {
      "myDate": {
        australianDate: true
      }
    }
  });

});             

Location of Django logs and errors

Logs are set in your settings.py file. A new, default project, looks like this:

# A sample logging configuration. The only tangible logging
# performed by this configuration is to send an email to
# the site admins on every HTTP 500 error when DEBUG=False.
# See http://docs.djangoproject.com/en/dev/topics/logging for
# more details on how to customize your logging configuration.
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'filters': {
        'require_debug_false': {
            '()': 'django.utils.log.RequireDebugFalse'
        }
    },
    'handlers': {
        'mail_admins': {
            'level': 'ERROR',
            'filters': ['require_debug_false'],
            'class': 'django.utils.log.AdminEmailHandler'
        }
    },
    'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
    }
}

By default, these don't create log files. If you want those, you need to add a filename parameter to your handlers

    'applogfile': {
        'level':'DEBUG',
        'class':'logging.handlers.RotatingFileHandler',
        'filename': os.path.join(DJANGO_ROOT, 'APPNAME.log'),
        'maxBytes': 1024*1024*15, # 15MB
        'backupCount': 10,
    },

This will set up a rotating log that can get 15 MB in size and keep 10 historical versions.

In the loggers section from above, you need to add applogfile to the handlers for your application

'loggers': {
        'django.request': {
            'handlers': ['mail_admins'],
            'level': 'ERROR',
            'propagate': True,
        },
        'APPNAME': {
            'handlers': ['applogfile',],
            'level': 'DEBUG',
        },
    }

This example will put your logs in your Django root in a file named APPNAME.log

Know relationships between all the tables of database in SQL Server

My solution is based on @marc_s solution, i just concatenated columns in cases that a constraint is based on more than one column:

SELECT
   FK.[name] AS ForeignKeyConstraintName
  ,SCHEMA_NAME(FT.schema_id) + '.' + FT.[name] AS ForeignTable
  ,STUFF(ForeignColumns.ForeignColumns, 1, 2, '') AS ForeignColumns
  ,SCHEMA_NAME(RT.schema_id) + '.' + RT.[name] AS ReferencedTable
  ,STUFF(ReferencedColumns.ReferencedColumns, 1, 2, '') AS ReferencedColumns
FROM
  sys.foreign_keys FK
  INNER JOIN sys.tables FT
  ON FT.object_id = FK.parent_object_id
  INNER JOIN sys.tables RT
  ON RT.object_id = FK.referenced_object_id
  CROSS APPLY
  (
    SELECT
      ', ' + iFC.[name] AS [text()]
    FROM
      sys.foreign_key_columns iFKC
      INNER JOIN sys.columns iFC
      ON iFC.object_id = iFKC.parent_object_id
        AND iFC.column_id = iFKC.parent_column_id
    WHERE
      iFKC.constraint_object_id = FK.object_id
    ORDER BY
      iFC.[name]
    FOR XML PATH('')
  ) ForeignColumns (ForeignColumns)
  CROSS APPLY
  (
    SELECT
      ', ' + iRC.[name]AS [text()]
    FROM
      sys.foreign_key_columns iFKC
      INNER JOIN sys.columns iRC
      ON iRC.object_id = iFKC.referenced_object_id
        AND iRC.column_id = iFKC.referenced_column_id
    WHERE
      iFKC.constraint_object_id = FK.object_id
    ORDER BY
      iRC.[name]
    FOR XML PATH('')
  ) ReferencedColumns (ReferencedColumns)

How to delete stuff printed to console by System.out.println()?

System.out is a PrintStream, and in itself does not provide any way to modify what gets output. Depending on what is backing that object, you may or may not be able to modify it. For example, if you are redirecting System.out to a log file, you may be able to modify that file after the fact. If it's going straight to a console, the text will disappear once it reaches the top of the console's buffer, but there's no way to mess with it programmatically.

I'm not sure exactly what you're hoping to accomplish, but you may want to consider creating a proxy PrintStream to filter messages as they get output, instead of trying to remove them after the fact.

Returning pointer from a function

It is not allocating memory at assignment of value 12 to integer pointer. Therefore it crashes, because it's not finding any memory.

You can try this:

#include<stdio.h>
#include<stdlib.h>
int *fun();

int main()
{
    int *ptr;
    ptr=fun();
    printf("\n\t\t%d\n",*ptr);
}

int *fun()
{
    int ptr;
    ptr=12;
    return(&ptr);
}

Deserialize JSON array(or list) in C#

I was having the similar issue and solved by understanding the Classes in asp.net C#

I want to read following JSON string :

[
    {
        "resultList": [
            {
                "channelType": "",
                "duration": "2:29:30",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1204,
                "language": "Hindi",
                "name": "The Great Target",
                "productId": 1204,
                "productMasterId": 1203,
                "productMasterName": "The Great Target",
                "productName": "The Great Target",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2005",
                "showGoodName": "Movies ",
                "views": 8333
            },
            {
                "channelType": "",
                "duration": "2:30:30",
                "episodeno": 0,
                "genre": "Romance",
                "genreList": [
                    "Romance"
                ],
                "genres": [
                    {
                        "personName": "Romance"
                    }
                ],
                "id": 1144,
                "language": "Hindi",
                "name": "Mere Sapnon Ki Rani",
                "productId": 1144,
                "productMasterId": 1143,
                "productMasterName": "Mere Sapnon Ki Rani",
                "productName": "Mere Sapnon Ki Rani",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "1997",
                "showGoodName": "Movies ",
                "views": 6482
            },
            {
                "channelType": "",
                "duration": "2:34:07",
                "episodeno": 0,
                "genre": "Drama",
                "genreList": [
                    "Drama"
                ],
                "genres": [
                    {
                        "personName": "Drama"
                    }
                ],
                "id": 1520,
                "language": "Telugu",
                "name": "Satyameva Jayathe",
                "productId": 1520,
                "productMasterId": 1519,
                "productMasterName": "Satyameva Jayathe",
                "productName": "Satyameva Jayathe",
                "productTypeId": 1,
                "productTypeName": "Movie",
                "rating": 3,
                "releaseyear": "2004",
                "showGoodName": "Movies ",
                "views": 9910
            }
        ],
        "resultSize": 1171,
        "pageIndex": "1"
    }
]

My asp.net c# code looks like following

First, Class3.cs page created in APP_Code folder of Web application

using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Text;
using System.IO;
using System.Web.Script.Serialization;
using System.Collections.Generic;

/// <summary>
/// Summary description for Class3
/// </summary>
public class Class3
{

    public List<ListWrapper_Main> ResultList_Main { get; set; }

    public class ListWrapper_Main
    {
        public List<ListWrapper> ResultList { get; set; }

        public string resultSize { get; set; }
        public string pageIndex { get; set; }
    }

    public class ListWrapper
    {
        public string channelType { get; set; }
        public string duration { get; set; }
        public int episodeno { get; set; }
        public string genre { get; set; }
        public string[] genreList { get; set; }
        public List<genres_cls> genres { get; set; }
        public int id { get; set; }
        public string imageUrl { get; set; }
        //public string imageurl { get; set; }
        public string language { get; set; }
        public string name { get; set; }
        public int productId { get; set; }
        public int productMasterId { get; set; }
        public string productMasterName { get; set; }
        public string productName { get; set; }
        public int productTypeId { get; set; }
        public string productTypeName { get; set; }
        public decimal rating { get; set; }
        public string releaseYear { get; set; }
        //public string releaseyear { get; set; }
        public string showGoodName { get; set; }
        public string views { get; set; }
    }
    public class genres_cls
    {
        public string personName { get; set; }
    }

}

Then, Browser page that reads the string/JSON string listed above and displays/Deserialize the JSON objects and displays the data

JavaScriptSerializer ser = new JavaScriptSerializer();


        string final_sb = sb.ToString();

        List<Class3.ListWrapper_Main> movieInfos = ser.Deserialize<List<Class3.ListWrapper_Main>>(final_sb.ToString());

        foreach (var itemdetail in movieInfos)
        {

            foreach (var itemdetail2 in itemdetail.ResultList)
            {
                Response.Write("channelType=" + itemdetail2.channelType + "<br/>");
                Response.Write("duration=" + itemdetail2.duration + "<br/>");
                Response.Write("episodeno=" + itemdetail2.episodeno + "<br/>");
                Response.Write("genre=" + itemdetail2.genre + "<br/>");

                string[] genreList_arr = itemdetail2.genreList;
                for (int i = 0; i < genreList_arr.Length; i++)
                    Response.Write("genreList1=" + genreList_arr[i].ToString() + "<br>");

                foreach (var genres1 in itemdetail2.genres)
                {
                    Response.Write("genres1=" + genres1.personName + "<br>");
                }

                Response.Write("id=" + itemdetail2.id + "<br/>");
                Response.Write("imageUrl=" + itemdetail2.imageUrl + "<br/>");
                //Response.Write("imageurl=" + itemdetail2.imageurl + "<br/>");
                Response.Write("language=" + itemdetail2.language + "<br/>");
                Response.Write("name=" + itemdetail2.name + "<br/>");
                Response.Write("productId=" + itemdetail2.productId + "<br/>");
                Response.Write("productMasterId=" + itemdetail2.productMasterId + "<br/>");
                Response.Write("productMasterName=" + itemdetail2.productMasterName + "<br/>");
                Response.Write("productName=" + itemdetail2.productName + "<br/>");
                Response.Write("productTypeId=" + itemdetail2.productTypeId + "<br/>");
                Response.Write("productTypeName=" + itemdetail2.productTypeName + "<br/>");
                Response.Write("rating=" + itemdetail2.rating + "<br/>");
                Response.Write("releaseYear=" + itemdetail2.releaseYear + "<br/>");
                //Response.Write("releaseyear=" + itemdetail2.releaseyear + "<br/>");
                Response.Write("showGoodName=" + itemdetail2.showGoodName + "<br/>");
                Response.Write("views=" + itemdetail2.views + "<br/><br>");
                //Response.Write("resultSize" + itemdetail2.resultSize + "<br/>");
                //  Response.Write("pageIndex" + itemdetail2.pageIndex + "<br/>");


            }



            Response.Write("resultSize=" + itemdetail.resultSize + "<br/><br>");
            Response.Write("pageIndex=" + itemdetail.pageIndex + "<br/><br>");

        }

'sb' is the actual string, i.e. JSON string of data mentioned very first on top of this reply

This is basically - web application asp.net c# code....

N joy...

How do I delay a function call for 5 seconds?

You can use plain javascript, this will call your_func once, after 5 seconds:

setTimeout(function() { your_func(); }, 5000);

If your function has no parameters and no explicit receiver you can call directly setTimeout(func, 5000)

There is also a plugin I've used once. It has oneTime and everyTime methods.

How do I calculate someone's age based on a DateTime type birthday?

I think this problem can be solved with an easier way like this-

The class can be like-

using System;

namespace TSA
{
    class BirthDay
    {
        double ageDay;
        public BirthDay(int day, int month, int year)
        {
            DateTime birthDate = new DateTime(year, month, day);
            ageDay = (birthDate - DateTime.Now).TotalDays; //DateTime.UtcNow
        }

        internal int GetAgeYear()
        {
            return (int)Math.Truncate(ageDay / 365);
        }

        internal int GetAgeMonth()
        {
            return (int)Math.Truncate((ageDay % 365) / 30);
        }
    }
}

And calls can be like-

BirthDay b = new BirthDay(1,12,1990);
int year = b.GetAgeYear();
int month = b.GetAgeMonth();

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

How to get a product's image in Magento?

You can try to replace $this-> by Mage:: in some cases. You need to convert to string.

In my case i'm using DirectResize extension (direct link), so my code is like this:

(string)Mage::helper('catalog/image')->init($_product, 'image')->directResize(150,150,3)

The ratio options (3rd param) are :

  • none proportional. The image will be resized at the Width and Height values.
  • proportional, based on the Width value 2
  • proportional, based on the Height value 3
  • proportional for the new image can fit in the Width and the Height values. 4
  • proportional. The new image will cover an area with the Width and the Height values.

Update: other info and versions here


The common way, without plugin would be:

(string)Mage::helper('catalog/image')->init($_product, 'image')->resize(150)

You can replace 'image' with 'small_image' or 'thumbnail'.

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

Using batch processing will result in less overhead. See the following link for examples: http://www.tutorialspoint.com/jdbc/jdbc-batch-processing.htm

Using grep to search for a string that has a dot in it

There are so many answers here suggesting to escape the dot with \. but I have been running into this issue over and over again: \. gives me the same result as .

However, these two expressions work for me:

$ grep -r 0\\.49 *

And:

$ grep -r 0[.]49 *

I'm using a "normal" bash shell on Ubuntu and Archlinux.

Edit, or, according to comments:

$ grep -r '0\.49' *

Note, the single-quotes doing the difference here.

Inserting the iframe into react component

You can use property dangerouslySetInnerHTML, like this

_x000D_
_x000D_
const Component = React.createClass({_x000D_
  iframe: function () {_x000D_
    return {_x000D_
      __html: this.props.iframe_x000D_
    }_x000D_
  },_x000D_
_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <div dangerouslySetInnerHTML={ this.iframe() } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"></div>
_x000D_
_x000D_
_x000D_

also, you can copy all attributes from the string(based on the question, you get iframe as a string from a server) which contains <iframe> tag and pass it to new <iframe> tag, like that

_x000D_
_x000D_
/**_x000D_
 * getAttrs_x000D_
 * returns all attributes from TAG string_x000D_
 * @return Object_x000D_
 */_x000D_
const getAttrs = (iframeTag) => {_x000D_
  var doc = document.createElement('div');_x000D_
  doc.innerHTML = iframeTag;_x000D_
_x000D_
  const iframe = doc.getElementsByTagName('iframe')[0];_x000D_
  return [].slice_x000D_
    .call(iframe.attributes)_x000D_
    .reduce((attrs, element) => {_x000D_
      attrs[element.name] = element.value;_x000D_
      return attrs;_x000D_
    }, {});_x000D_
}_x000D_
_x000D_
const Component = React.createClass({_x000D_
  render: function() {_x000D_
    return (_x000D_
      <div>_x000D_
        <iframe {...getAttrs(this.props.iframe) } />_x000D_
      </div>_x000D_
    );_x000D_
  }_x000D_
});_x000D_
_x000D_
const iframe = '<iframe src="https://www.example.com/show?data..." width="540" height="450"></iframe>'; _x000D_
_x000D_
ReactDOM.render(_x000D_
  <Component iframe={iframe} />,_x000D_
  document.getElementById('container')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<div id="container"><div>
_x000D_
_x000D_
_x000D_

Center align with table-cell

This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.

DEMO

here's the gist of the demo

.container{

  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;

}

html

<div class="container">
  <div class='content'> //you can size this anyway you want
    put anything you want here,
  </div>
</div>

enter image description here

Increasing the timeout value in a WCF service

Under the Tools menu in Visual Studio 2008 (or 2005 if you have the right WCF stuff installed) there is an options called 'WCF Service Configuration Editor'.

From there you can change the binding options for both the client and the services, one of these options will be for time-outs.

CSS3 transition on click using pure CSS

Voila!

_x000D_
_x000D_
div {_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
  font-weight: bold;_x000D_
  width: 48px;_x000D_
  height: 48px;  _x000D_
  transform: rotate(360deg);_x000D_
  transition: transform 0.5s;_x000D_
}_x000D_
_x000D_
div:active {_x000D_
  transform: rotate(0deg);_x000D_
  transition:  0s;_x000D_
}
_x000D_
<div></div>
_x000D_
_x000D_
_x000D_

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

Unsorted vector:

if (std::find(v.begin(), v.end(),value)!=v.end())
    ...

Sorted vector:

if (std::binary_search(v.begin(), v.end(), value)
   ...

P.S. may need to include <algorithm> header

Regular Expression Match to test for a valid year

In my case I wanted to match a string which ends with a year (4 digits) like this for example:

Oct 2020
Nov 2020
Dec 2020
Jan 2021

It'll return true with this one:

var sheetName = 'Jan 2021';
var yearRegex = new RegExp("\b\d{4}$");
var isMonthSheet = yearRegex.test(sheetName);
Logger.log('isMonthSheet = ' + isMonthSheet);

The code above is used in Apps Script.

Here's the link to test the Regex above: https://regex101.com/r/SzYQLN/1

How to get the selected row values of DevExpress XtraGrid?

I found the solution as follows:

private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
{
    TBGRNo.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "GRNo").ToString();
    TBSName.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "SName").ToString();
    TBFName.Text = gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "FName").ToString();            
}

enter image description here

Check if any type of files exist in a directory using BATCH script

A roll your own function.

Supports recursion or not with the 2nd switch.

Also, allow names of files with ; which the accepted answer fails to address although a great answer, this will get over that issue.

The idea was taken from https://ss64.com/nt/empty.html

Notes within code.

@echo off
title %~nx0
setlocal EnableDelayedExpansion
set dir=C:\Users\%username%\Desktop
title Echos folders and files in root directory...
call :FOLDER_FILE_CNT dir TRUE
echo !dir!
echo/ & pause & cls
::
:: FOLDER_FILE_CNT function by Ste
::
:: First Written:               2020.01.26
:: Posted on the thread here:   https://stackoverflow.com/q/10813943/8262102
:: Based on:                    https://ss64.com/nt/empty.html
::
:: Notes are that !%~1! will expand to the returned variable.
:: Syntax call: call :FOLDER_FILE_CNT "<path>" <BOOLEAN>
:: "<path>"   = Your path wrapped in quotes.
:: <BOOLEAN>  = Count files in sub directories (TRUE) or not (FALSE).
:: Returns a variable with a value of:
:: FALSE      = if directory doesn't exist.
:: 0-inf      = if there are files within the directory.
::
:FOLDER_FILE_CNT
if "%~1"=="" (
  echo Use this syntax: & echo call :FOLDER_FILE_CNT "<path>" ^<BOOLEAN^> & echo/ & goto :eof
  ) else if not "%~1"=="" (
  set count=0 & set msg= & set dirExists=
  if not exist "!%~1!" (set msg=FALSE)
  if exist "!%~1!" (
   if {%~2}=={TRUE} (
    >nul 2>nul dir /a-d /s "!%~1!\*" && (for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b /s') do (set /a count+=1)) || (set /a count+=0)
    set msg=!count!
    )
   if {%~2}=={FALSE} (
    for /f "delims=;" %%A in ('dir "!%~1!" /a-d /b') do (set /a count+=1)
    set msg=!count!
    )
   )
  )
  set "%~1=!msg!" & goto :eof
  )

Multi-dimensional arraylist or list in C#?

you just make a list of lists like so:

List<List<string>> results = new List<List<string>>();

and then it's just a matter of using the functionality you want

results.Add(new List<string>()); //adds a new list to your list of lists
results[0].Add("this is a string"); //adds a string to the first list
results[0][0]; //gets the first string in your first list

How to include the reference of DocumentFormat.OpenXml.dll on Mono2.10?

select DocumentFormat.OpenXml under references , view it's properties, and set the Copy Local option to True so that it copies it to the output folder. That worked for me.

Setting state on componentDidMount()

According to the React Documentation it's perfectly OK to call setState() from within the componentDidMount() function.

It will cause render() to be called twice, which is less efficient than only calling it once, but other than that it's perfectly fine.

You can find the documentation here:

https://reactjs.org/docs/react-component.html#componentdidmount

Here is the excerpt from the documentation:

You may call setState() immediately in componentDidMount(). It will trigger an extra rendering, but it will happen before the browser updates the screen. This guarantees that even though the render() will be called twice in this case, the user won’t see the intermediate state. Use this pattern with caution because it often causes performance issues...

Hiding elements in responsive layout?

Bootstrap 4.x answer

hidden-* classes are removed from Bootstrap 4 beta onward.

If you want to show on medium and up use the d-* classes, e.g.:

<div class="d-none d-md-block">This will show in medium and up</div>

If you want to show only in small and below use this:

<div class="d-block d-md-none"> This will show only in below medium form factors</div>

Screen size and class chart

| Screen Size        | Class                          |
|--------------------|--------------------------------|
| Hidden on all      | .d-none                        |
| Hidden only on xs  | .d-none .d-sm-block            |
| Hidden only on sm  | .d-sm-none .d-md-block         |
| Hidden only on md  | .d-md-none .d-lg-block         |
| Hidden only on lg  | .d-lg-none .d-xl-block         |
| Hidden only on xl  | .d-xl-none                     |
| Visible on all     | .d-block                       |
| Visible only on xs | .d-block .d-sm-none            |
| Visible only on sm | .d-none .d-sm-block .d-md-none |
| Visible only on md | .d-none .d-md-block .d-lg-none |
| Visible only on lg | .d-none .d-lg-block .d-xl-none |
| Visible only on xl | .d-none .d-xl-block            |

Rather than using explicit .visible-* classes, you make an element visible by simply not hiding it at that screen size. You can combine one .d-*-none class with one .d-*-block class to show an element only on a given interval of screen sizes (e.g. .d-none.d-md-block.d-xl-none shows the element only on medium and large devices).

Documentation

When should I use GET or POST method? What's the difference between them?

GET and POST are HTTP methods which can achieve similar goals

GET is basically for just getting (retrieving) data, A GET should not have a body, so aside from cookies, the only place to pass info is in the URL and URLs are limited in length , GET is less secure compared to POST because data sent is part of the URL

Never use GET when sending passwords, credit card or other sensitive information!, Data is visible to everyone in the URL, Can be cached data . GET is harmless when we are reloading or calling back button, it will be book marked, parameters remain in browser history, only ASCII characters allowed.

POST may involve anything, like storing or updating data, or ordering a product, or sending e-mail. POST method has a body.

POST method is secured for passing sensitive and confidential information to server it will not visible in query parameters in URL and parameters are not saved in browser history. There are no restrictions on data length. When we are reloading the browser should alert the user that the data are about to be re-submitted. POST method cannot be bookmarked

Rails: How can I set default values in ActiveRecord?

The after_initialize callback pattern can be improved by simply doing the following

after_initialize :some_method_goes_here, :if => :new_record?

This has a non-trivial benefit if your init code needs to deal with associations, as the following code triggers a subtle n+1 if you read the initial record without including the associated.

class Account

  has_one :config
  after_initialize :init_config

  def init_config
    self.config ||= build_config
  end

end

Get the date (a day before current time) in Bash

You could do a simple calculation, pimped with an regex, if the chosen date format is 'YYYYMM':

echo $(($(date +"%Y%m") - 1)) | sed -e 's/99$/12/'

In January of 2020 it will return 201912 ;-) But, it's only a workaround, when date does not have calculation options and other dateinterpreter options (e.g. using perl) not available ;-)

Dealing with float precision in Javascript

Tackling this task, I'd first find the number of decimal places in x, then round y accordingly. I'd use:

y.toFixed(x.toString().split(".")[1].length);

It should convert x to a string, split it over the decimal point, find the length of the right part, and then y.toFixed(length) should round y based on that length.

How to use FormData for AJAX file upload?

Actually The documentation shows that you can use XMLHttpRequest().send() to simply send multiform data in case jquery sucks

how to get bounding box for div element in jquery

As this is specifically tagged for jQuery -

$("#myElement")[0].getBoundingClientRect();

or

$("#myElement").get(0).getBoundingClientRect();

(These are functionally identical, in some older browsers .get() was slightly faster)

Note that if you try to get the values via jQuery calls then it will not take into account any css transform values, which can give unexpected results...

Note 2: In jQuery 3.0 it has changed to using the proper getBoundingClientRect() calls for its own dimension calls (see the jQuery Core 3.0 Upgrade Guide) - which means that the other jQuery answers will finally always be correct - but only when using the new jQuery version - hence why it's called a breaking change...

How to Use Sockets in JavaScript\HTML?

I think it is important to mention, now that this question is over 1 year old, that Socket.IO has since come out and seems to be the primary way to work with sockets in the browser now; it is also compatible with Node.js as far as I know.

How to use BigInteger?

BigInteger is immutable. The javadocs states that add() "[r]eturns a BigInteger whose value is (this + val)." Therefore, you can't change sum, you need to reassign the result of the add method to sum variable.

sum = sum.add(BigInteger.valueOf(i));

Navigation bar show/hide

SWIFT CODE: This works fully for iOS 3.2 and later.

  override func viewDidAppear(animated: Bool) {
    super.viewDidAppear(animated)

    let tapGesture = UITapGestureRecognizer(target: self, action: "hideNavBarOntap")let tapGesture = UITapGestureRecognizer(target: self, action: "hideNavBarOntap")
    tapGesture.delegate = self
    self.view.addGestureRecognizer(tapGesture)

then write

func hideNavBarOntap() {
    if(self.navigationController?.navigationBar.hidden == false) {
        self.navigationController?.setNavigationBarHidden(true, animated: true) // hide nav bar is not hidden
    } else if(self.navigationController?.navigationBar.hidden == true) {
        self.navigationController?.setNavigationBarHidden(false, animated: true) // show nav bar
    }
}

How Do I Replace/Change The Heading Text Inside <h3></h3>, Using jquery?

Give an id to h3 like this:

<h3 id="headertag">Featured Offers</h3>

and in the javascript function do this :

document.getElementById("headertag").innerHTML = "Public Offers";

HTML favicon won't show on google chrome

These are the locations where browsers store the Temporary data in Linux:

Note: you can see hidden files in File Manager using Ctrl + H

for Terminal use the command ls -la

Chromium

~/.cache/chromium/[profile]/Cache/

Google Chrome

~/.cache/google-chrome/[profile]/Cache/

Also, Chromium and Google Chrome store some additional cache at

~/.config/chromium/[profile]/Application Cache/Cache/ 

and

~/.config/google-chrome/[profile]/Application Cache/Cache/

and generally here:

/tmp/

so to apply new FAVICON or try to show it up is to clean them

make sure u are inside each of these directories use the command:

rm -rf *

Showing ValueError: shapes (1,3) and (1,3) not aligned: 3 (dim 1) != 1 (dim 0)

Unlike standard arithmetic, which desires matching dimensions, dot products require that the dimensions are one of:

  • (X..., A, B) dot (Y..., B, C) -> (X..., Y..., A, C), where ... means "0 or more different values
  • (B,) dot (B, C) -> (C,)
  • (A, B) dot (B,) -> (A,)
  • (B,) dot (B,) -> ()

Your problem is that you are using np.matrix, which is totally unnecessary in your code - the main purpose of np.matrix is to translate a * b into np.dot(a, b). As a general rule, np.matrix is probably not a good choice.

Is there an API to get bank transaction and bank balance?

I use GNU Cash and it uses Open Financial Exchange (ofx) http://www.ofx.net/ to download complete transactions and balances from each account of each bank.

Let me emphasize that again, you get a huge list of transactions with OFX into the GNU Cash. Depending on the account type these transactions can be very detailed description of your transactions (purchases+paycheques), investments, interests, etc.

In my case, even though I have Chase debit card I had to choose Chase Credit to make it work. But Chase wants you to enable this OFX feature by logging into your online banking and enable Quicken/MS Money/etc. somewhere in your profile or preferences. Don't call Chase customer support because they know nothing about it.

This service for OFX and GNU Cash is free. I have heard that they charge $10 a month for other platforms.

OFX can download transactions from 348 banks so far. http://www.ofxhome.com/index.php/home/directory

Actualy, OFX also supports making bill payments, stop a check, intrabank and interbank transfers etc. It is quite extensive. See it here: http://ofx.net/AboutOFX/ServicesSupported.aspx

How do I render a shadow?

You have to give elevation prop to View

<View elevation={5} style={styles.container}>
   <Text>Hello World !</Text>
 </View>

styles can be added like this:

 const styles = StyleSheet.create({

     container:{
        padding:20,
        backgroundColor:'#d9d9d9',
        shadowColor: "#000000",
        shadowOpacity: 0.8,
        shadowRadius: 2,
        shadowOffset: {
          height: 1,
          width: 1
        }
       },
   })

Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

I had a similar issue where I also continuously got the same error. I tried many things like changing the listener port number, turning off the firewall etc. Finally I was able to resolve the issue by changing listener.ora file. I changed the following line:

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

to

(ADDRESS = (PROTOCOL = TCP)(HOST = hostname)(PORT = 1521)) 

I also added an entry in the /etc/hosts file.

you can use Oracle net manager to change the above line in listener.ora file. See Oracle Net Services Administrator's Guide for more information on how to do it using net manager.

Also you can use the service name (database_name.domain_name) instead of SID while making the connnection.

I Hope it helps.

How can I set the opacity or transparency of a Panel in WinForms?

Yes, opacity can only work on top-level windows. It uses a hardware feature of the video adapter, that doesn't support child windows, like Panel. The only top-level Control derived class in Winforms is Form.

Several of the 'pure' Winform controls, the ones that do their own painting instead of letting a native Windows control do the job, do however support a transparent BackColor. Panel is one of them. It uses a trick, it asks the Parent to draw itself to produce the background pixels. One side-effect of this trick is that overlapping controls doesn't work, you only see the parent pixels, not the overlapped controls.

This sample form shows it at work:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        this.BackColor = Color.White;
        panel1.BackColor = Color.FromArgb(25, Color.Black);
    }
    protected override void OnPaint(PaintEventArgs e) {
        e.Graphics.DrawLine(Pens.Yellow, 0, 0, 100, 100);
    }
}

If that's not good enough then you need to consider stacking forms on top of each other. Like this.

Notable perhaps is that this restriction is lifted in Windows 8. It no longer uses the video adapter overlay feature and DWM (aka Aero) cannot be turned off anymore. Which makes opacity/transparency on child windows easy to implement. Relying on this is of course future-music for a while to come. Windows 7 will be the next XP :)

How to dynamic filter options of <select > with jQuery?

using Aaron's answer, this can be the short & easiest solution:

function filterSelectList(selectListId, filterId)
{
    var filter = $("#" + filterId).val().toUpperCase();

    $("#" + selectListId + " option").each(function(i){
       if ($(this).text.toUpperCase().includes(filter))
           $(this).css("display", "block");
       else
           $(this).css("display", "none");
    });
};

Run a PostgreSQL .sql file using command line arguments

Of course, you will get a fatal error for authenticating, because you do not include a user name...

Try this one, it is OK for me :)

psql -U username -d myDataBase -a -f myInsertFile

If the database is remote, use the same command with host

psql -h host -U username -d myDataBase -a -f myInsertFile

How to fix corrupt HDFS FIles

You can use

  hdfs fsck /

to determine which files are having problems. Look through the output for missing or corrupt blocks (ignore under-replicated blocks for now). This command is really verbose especially on a large HDFS filesystem so I normally get down to the meaningful output with

  hdfs fsck / | egrep -v '^\.+$' | grep -v eplica

which ignores lines with nothing but dots and lines talking about replication.

Once you find a file that is corrupt

  hdfs fsck /path/to/corrupt/file -locations -blocks -files

Use that output to determine where blocks might live. If the file is larger than your block size it might have multiple blocks.

You can use the reported block numbers to go around to the datanodes and the namenode logs searching for the machine or machines on which the blocks lived. Try looking for filesystem errors on those machines. Missing mount points, datanode not running, file system reformatted/reprovisioned. If you can find a problem in that way and bring the block back online that file will be healthy again.

Lather rinse and repeat until all files are healthy or you exhaust all alternatives looking for the blocks.

Once you determine what happened and you cannot recover any more blocks, just use the

  hdfs fs -rm /path/to/file/with/permanently/missing/blocks

command to get your HDFS filesystem back to healthy so you can start tracking new errors as they occur.

Remove everything after a certain character

You can also use the split() function. This seems to be the easiest one that comes to my mind :).

url.split('?')[0]

jsFiddle Demo

One advantage is this method will work even if there is no ? in the string - it will return the whole string.

Get response from PHP file using AJAX

in your PHP file, when you echo your data use json_encode (http://php.net/manual/en/function.json-encode.php)

e.g.

<?php
//plum or data...
$output = array("data","plum");

echo json_encode($output);

?>

in your javascript code, when your ajax completes the json encoded response data can be turned into an js array like this:

 $.ajax({
                type: "POST",
                url: "process.php",
                data: somedata;
                success function(json_data){
                    var data_array = $.parseJSON(json_data);

                    //access your data like this:
                    var plum_or_whatever = data_array['output'];.
                    //continue from here...
                }
            });

Google OAuth 2 authorization - Error: redirect_uri_mismatch

My problem was that I had http://localhost:3000/ in the address bar and had http://127.0.0.1:3000/ in the console.developers.google.com

enter image description here

enter image description here

Div show/hide media query

It sounds like you may be wanting to access the viewport of the device. You can do this by inserting this meta tag in your header.

<meta name="viewport" content="width=device-width, initial-scale=1.0">

http://www.w3schools.com/css/css_rwd_viewport.asp

C#: How do you edit items and subitems in a listview?

private void listView1_MouseDown(object sender, MouseEventArgs e)
{
    li = listView1.GetItemAt(e.X, e.Y);
    X = e.X;
    Y = e.Y;
}

private void listView1_MouseUp(object sender, MouseEventArgs e)
{
    int nStart = X;
    int spos = 0;
    int epos = listView1.Columns[1].Width;
    for (int i = 0; i < listView1.Columns.Count; i++)
    {
        if (nStart > spos && nStart < epos)
        {
            subItemSelected = i;
            break;
        }

        spos = epos;
        epos += listView1.Columns[i].Width;
    }
    li.SubItems[subItemSelected].Text = "9";
}

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

Initializing data.frames()

> df <- data.frame(matrix(ncol = 300, nrow = 100))
> dim(df)
[1] 100 300

Find value in an array

This answer is for everyone that realizes the accepted answer does not address the question as it currently written.

The question asks how to find a value in an array. The accepted answer shows how to check whether a value exists in an array.

There is already an example using index, so I am providing an example using the select method.

1.9.3-p327 :012 > x = [1,2,3,4,5]
  => [1, 2, 3, 4, 5] 
1.9.3-p327 :013 > x.select {|y| y == 1}
  => [1]

Formatting html email for Outlook

To be able to give you specific help, you's have to explain what particular parts specifically "get messed up", or perhaps offer a screenshot. It also helps to know what version of Outlook you encounter the problem in.

Either way, CampaignMonitor.com's CSS guide has often helped me out debugging email client inconsistencies.

From that guide you can see several things just won't work well or at all in Outlook, here are some highlights of the more important ones:

  • Various types of more sophisticated selectors, e.g. E:first-child, E:hover, E > F (Child combinator), E + F (Adjacent sibling combinator), E ~ F (General sibling combinator). This unfortunately means resorting to workarounds like inline styles.
  • Some font properties, e.g. white-space won't work.
  • The background-image property won't work.
  • There are several issues with the Box Model properties, most importantly height, width, and the max- versions are either not usable or have bugs for certain elements.
  • Positioning and Display issues (e.g. display, floats and position are all out).

In short: combining CSS and Outlook can be a pain. Be prepared to use many ugly workarounds.

PS. In your specific case, there are two minor issues in your html that may cause you odd behavior. There's "align=top" where you probably meant to use vertical-align. Also: cell-padding for tds doesn't exist.

Java converting Image to BufferedImage

If you use Kotlin, you can add an extension method to Image in the same manner Sri Harsha Chilakapati suggests.

fun Image.toBufferedImage(): BufferedImage {
    if (this is BufferedImage) {
        return this
    }
    val bufferedImage = BufferedImage(this.getWidth(null), this.getHeight(null), BufferedImage.TYPE_INT_ARGB)

    val graphics2D = bufferedImage.createGraphics()
    graphics2D.drawImage(this, 0, 0, null)
    graphics2D.dispose()

    return bufferedImage
}

And use it like this:

myImage.toBufferedImage()

How can I post an array of string to ASP.NET MVC Controller without a form?

I modified my response to include the code for a test app I did.

Update: I have updated the jQuery to set the 'traditional' setting to true so this will work again (per @DustinDavis' answer).

First the javascript:

function test()
{
    var stringArray = new Array();
    stringArray[0] = "item1";
    stringArray[1] = "item2";
    stringArray[2] = "item3";
    var postData = { values: stringArray };

    $.ajax({
        type: "POST",
        url: "/Home/SaveList",
        data: postData,
        success: function(data){
            alert(data.Result);
        },
        dataType: "json",
        traditional: true
    });
}

And here's the code in my controller class:

public JsonResult SaveList(List<String> values)
{
    return Json(new { Result = String.Format("Fist item in list: '{0}'", values[0]) });
}

When I call that javascript function, I get an alert saying "First item in list: 'item1'". Hope this helps!

Safe String to BigDecimal conversion

Please try this its working for me

BigDecimal bd ;
String value = "2000.00";

bd = new BigDecimal(value);
BigDecimal currency = bd;

Auto-scaling input[type=text] to width of value?

You can do this the easy way by setting the size attribute to the length of the input contents:

function resizeInput() {
    $(this).attr('size', $(this).val().length);
}

$('input[type="text"]')
    // event handler
    .keyup(resizeInput)
    // resize on page load
    .each(resizeInput);

See: http://jsfiddle.net/nrabinowitz/NvynC/

This seems to add some padding on the right that I suspect is browser dependent. If you wanted it to be really tight to the input, you could use a technique like the one I describe in this related answer, using jQuery to calculate the pixel size of your text.

What is the difference between int, Int16, Int32 and Int64?

  1. int and int32 are one and the same (32-bit integer)
  2. int16 is short int (2 bytes or 16-bits)
  3. int64 is the long datatype (8 bytes or 64-bits)

How to download file from database/folder using php

butangDonload.php

$file = "Bang.png"; //Let say If I put the file name Bang.png
$_SESSION['name']=$file;    

Try this,

<?php

$name=$_SESSION['name'];
download($name);

function download($name){
$file = $nama_fail;
?>

javascript function wait until another function to finish

In my opinion, deferreds/promises (as you have mentionned) is the way to go, rather than using timeouts.

Here is an example I have just written to demonstrate how you could do it using deferreds/promises.

Take some time to play around with deferreds. Once you really understand them, it becomes very easy to perform asynchronous tasks.

Hope this helps!

$(function(){
    function1().done(function(){
        // function1 is done, we can now call function2
        console.log('function1 is done!');

        function2().done(function(){
            //function2 is done
            console.log('function2 is done!');
        });
    });
});

function function1(){
    var dfrd1 = $.Deferred();
    var dfrd2= $.Deferred();

    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function1 is done!');
        dfrd1.resolve();
    }, 1000);

    setTimeout(function(){
        // doing more async stuff
        console.log('task 2 in function1 is done!');
        dfrd2.resolve();
    }, 750);

    return $.when(dfrd1, dfrd2).done(function(){
        console.log('both tasks in function1 are done');
        // Both asyncs tasks are done
    }).promise();
}

function function2(){
    var dfrd1 = $.Deferred();
    setTimeout(function(){
        // doing async stuff
        console.log('task 1 in function2 is done!');
        dfrd1.resolve();
    }, 2000);
    return dfrd1.promise();
}

Find position of a node using xpath

If you ever upgrade to XPath 2.0, note that it provides function index-of, it solves problem this way:

index-of(//b, //b[.='tsr'])

Where:

  • 1st parameter is sequence for searching
  • 2nd is what to search

Endless loop in C/C++

It is very subjective. I write this:

while(true) {} //in C++

Because its intent is very much clear and it is also readable: you look at it and you know infinite loop is intended.

One might say for(;;) is also clear. But I would argue that because of its convoluted syntax, this option requires extra knowledge to reach the conclusion that it is an infinite loop, hence it is relatively less clear. I would even say there are more number of programmers who don't know what for(;;) does (even if they know usual for loop), but almost all programmers who knows while loop would immediately figure out what while(true) does.

To me, writing for(;;) to mean infinite loop, is like writing while() to mean infinite loop — while the former works, the latter does NOT. In the former case, empty condition turns out to be true implicitly, but in the latter case, it is an error! I personally didn't like it.

Now while(1) is also there in the competition. I would ask: why while(1)? Why not while(2), while(3) or while(0.1)? Well, whatever you write, you actually mean while(true) — if so, then why not write it instead?

In C (if I ever write), I would probably write this:

while(1) {} //in C

While while(2), while(3) and while(0.1) would equally make sense. But just to be conformant with other C programmers, I would write while(1), because lots of C programmers write this and I find no reason to deviate from the norm.

How to replace multiple white spaces with one white space

string cleanedString = System.Text.RegularExpressions.Regex.Replace(dirtyString,@"\s+"," ");

How to embed a Google Drive folder in a website

Embedding a Google Drive directory in an IFRAME

Google Drive folders can be embedded and displayed in list and grid views (in which all you can do is click a file or folder to open it on a new tab). To do so, simply replace FOLDER-ID with your own in:

List view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#list" style="width:100%; height:600px; border:0;"></iframe>

or without specifying a mode, since list mode is the default:

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID" style="width:100%; height:600px; border:0;"></iframe>

Grid view

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Obtaining your folder id

The id is the hash (alphanumeric gibberish) after folders/ in the URL of the folder. You can see the URL in the address bar of your browser when you open the Drive folder. For example, in:

https://drive.google.com/drive/folders/0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2 

The Folder ID is 0B1iqp0kGPjWsNDg5NWFlZjEtN2IwZC00NmZiLWE3MjktYTE2ZjZjNTZiMDY2.

Folder with G Suite/Google Apps domain

If your folder is part of a Google Apps domain, you can add the domain to the URL to alleviate the permission problems (detailed further ahead):

<iframe src="https://drive.google.com/a/MY.DOMAIN.COM/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Just replace MY.DOMAIN.COM and FOLDER-ID with your own.

Caveat with folders requiring permission

This technique works best for folders with public access. Folders that are shared only with certain Google accounts can cause trouble when you embed them this way, depending on which Google accounts are active on the user's browser:

  1. If the user has not logged in to any Google account, then nothing appears in the frame.
  2. If the user is logged onto an account without authorisation to access the folder, the frame will contain the message You need permission, with some buttons to Request access or Switch accounts, but if you click on this last, the frame blanks out.
  3. If the user logs into an account without proper permissions, and later adds the authorised account, on loading the embedded Drive Google will resort to the first active account, and the user will see You need permission, unless...
  4. If the URL contains a Google Suite domain, and the user is logged into that domain's account, the embedded view will work, even if the user logged to another account first.

The blank frames are because Google forbids embedding its login page in an IFRAME (presumably to prevent account stealing), via the X-Frame-Options header, which if set to SAMEORIGIN will cause any well-behaved browser to refuse to load the page if it's not in the same domain (v.g. drive.google.com). You can see this in the developer console of your browser.

TL;DR

To get a list or grid view of a Drive folder (in which all you can do is click a file or folder to open it on a new tab), use:

<iframe src="https://drive.google.com/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

or alternatively, for a Google Suite/Apps Drive:

<iframe src="https://drive.google.com/a/MY.DOMAIN.COM/embeddedfolderview?id=FOLDER-ID#grid" style="width:100%; height:600px; border:0;"></iframe>

Replace MY.DOMAIN.COM and FOLDER-ID with your own; remove #grid to get a detailed file list.

For private folders, have your users log to the correct account before loading the page with the embedded folder; if the folder is in a Google Apps domain, you can add the domain to the URL. Else, they must log into the authorised account before any other.

(this answer is an edit of Mori's, but it was rejected as it changed his intent, somehow)

PHP ini file_get_contents external url

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://www.your_external_website.com");
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
curl_close($ch);

is best for http url, But how to open https url help me

C# - Simplest way to remove first occurrence of a substring from another string

int index = sourceString.IndexOf(removeString);
string cleanPath = (index < 0)
    ? sourceString
    : sourceString.Remove(index, removeString.Length);

jQuery - Detect value change on hidden input field

So this is way late, but I've discovered an answer, in case it becomes useful to anyone who comes across this thread.

Changes in value to hidden elements don't automatically fire the .change() event. So, wherever it is that you're setting that value, you also have to tell jQuery to trigger it.

function setUserID(myValue) {
     $('#userid').val(myValue)
                 .trigger('change');
}

Once that's the case,

$('#userid').change(function(){
      //fire your ajax call  
})

should work as expected.

Calling startActivity() from outside of an Activity?

Android Doc says -

FLAG_ACTIVITY_NEW_TASK requirement is now enforced

With Android 9, you cannot start an activity from a non-activity context unless you pass the intent flag FLAG_ACTIVITY_NEW_TASK. If you attempt to start an activity without passing this flag, the activity does not start, and the system prints a message to the log.

Note: The flag requirement has always been the intended behavior, and was enforced on versions lower than Android 7.0 (API level 24). A bug in Android 7.0 prevented the flag requirement from being enforced.

That means for (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) it is mandatory to add Intent.FLAG_ACTIVITY_NEW_TASK while calling startActivity() from outside of an Activity context.

So it is better to add flag for all the versions -

...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...

How to close a Java Swing application from the code

If I understand you correctly you want to close the application even if the user did not click on the close button. You will need to register WindowEvents maybe with addWindowListener() or enableEvents() whichever suits your needs better.

You can then invoke the event with a call to processWindowEvent(). Here is a sample code that will create a JFrame, wait 5 seconds and close the JFrame without user interaction.

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class ClosingFrame extends JFrame implements WindowListener{

public ClosingFrame(){
    super("A Frame");
    setSize(400, 400);
            //in case the user closes the window
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            setVisible(true);
            //enables Window Events on this Component
            this.addWindowListener(this);

            //start a timer
    Thread t = new Timer();
            t.start();
    }

public void windowOpened(WindowEvent e){}
public void windowClosing(WindowEvent e){}

    //the event that we are interested in
public void windowClosed(WindowEvent e){
    System.exit(0);
}

public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}

    //a simple timer 
    class Timer extends Thread{
           int time = 10;
           public void run(){
     while(time-- > 0){
       System.out.println("Still Waiting:" + time);
               try{
                 sleep(500);                     
               }catch(InterruptedException e){}
             }
             System.out.println("About to close");
    //close the frame
            ClosingFrame.this.processWindowEvent(
                 new WindowEvent(
                       ClosingFrame.this, WindowEvent.WINDOW_CLOSED));
           }
    }

    //instantiate the Frame
public static void main(String args[]){
          new ClosingFrame();
    }

}

As you can see, the processWindowEvent() method causes the WindowClosed event to be fired where you have an oportunity to do some clean up code if you require before closing the application.

How do you connect to a MySQL database using Oracle SQL Developer?

Under Tools > Preferences > Databases there is a third party JDBC driver path that must be setup. Once the driver path is setup a separate 'MySQL' tab should appear on the New Connections dialog.

Note: This is the same jdbc connector that is available as a JAR download from the MySQL website.

Show empty string when date field is 1/1/1900

Use this inside of query, no need to create extra variables.

CASE WHEN CreatedDate = '19000101' THEN '' WHEN CreatedDate =
'18000101' THEN ''  ELSE CONVERT(CHAR(10), CreatedDate, 120) + ' ' +
CONVERT(CHAR(8), CreatedDate, 108) END as 'Created Date'

Works like a charm.

Export MySQL database using PHP only

I would Suggest that you do the folllowing,

_x000D_
_x000D_
<?php_x000D_
_x000D_
$con = mysqli_connect('HostName', 'UserName', 'Password', 'DatabaseName');_x000D_
_x000D_
_x000D_
$tables = array();_x000D_
_x000D_
$result = mysqli_query($con,"SHOW TABLES");_x000D_
while ($row = mysqli_fetch_row($result)) {_x000D_
 $tables[] = $row[0];_x000D_
}_x000D_
_x000D_
$return = '';_x000D_
_x000D_
foreach ($tables as $table) {_x000D_
 $result = mysqli_query($con, "SELECT * FROM ".$table);_x000D_
 $num_fields = mysqli_num_fields($result);_x000D_
_x000D_
 $return .= 'DROP TABLE '.$table.';';_x000D_
 $row2 = mysqli_fetch_row(mysqli_query($con, 'SHOW CREATE TABLE '.$table));_x000D_
 $return .= "\n\n".$row2[1].";\n\n";_x000D_
_x000D_
 for ($i=0; $i < $num_fields; $i++) { _x000D_
  while ($row = mysqli_fetch_row($result)) {_x000D_
   $return .= 'INSERT INTO '.$table.' VALUES(';_x000D_
   for ($j=0; $j < $num_fields; $j++) { _x000D_
    $row[$j] = addslashes($row[$j]);_x000D_
    if (isset($row[$j])) {_x000D_
     $return .= '"'.$row[$j].'"';} else { $return .= '""';}_x000D_
     if($j<$num_fields-1){ $return .= ','; }_x000D_
    }_x000D_
    $return .= ");\n";_x000D_
   }_x000D_
  }_x000D_
  $return .= "\n\n\n";_x000D_
 _x000D_
}_x000D_
_x000D_
_x000D_
$handle = fopen('backup.sql', 'w+');_x000D_
fwrite($handle, $return);_x000D_
fclose($handle);_x000D_
echo "success";_x000D_
_x000D_
_x000D_
?>
_x000D_
_x000D_
_x000D_

upd. fixed error in code, added space before VALUES in line $return .= 'INSERT INTO '.$table.'VALUES(';

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

You can also use extremely small numbers for your radius'.

<corners 
  android:bottomRightRadius="0.1dp" android:bottomLeftRadius="2dp" 
 android:topLeftRadius="2dp" android:topRightRadius="0.1dp" />

Create directories using make file

given that you're a newbie, I'd say don't try to do this yet. it's definitely possible, but will needlessly complicate your Makefile. stick to the simple ways until you're more comfortable with make.

that said, one way to build in a directory different from the source directory is VPATH; i prefer pattern rules

Argument Exception "Item with Same Key has already been added"

Clear the dictionary before adding any items to it. I don't know how a dictionary of one object affects another's during assignment but I got the error after creating another object with the same key,value pairs.

NB: If you are going to add items in a loop just make sure you clear the dictionary before entering the loop.

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.

Nginx sites-enabled, sites-available: Cannot create soft-link between config files in Ubuntu 12.04

You need to start by understanding that the target of a symlink is a pathname. And it can be absolute or relative to the directory which contains the symlink

Assuming you have foo.conf in sites-available

Try

cd sites-enabled
sudo ln -s ../sites-available/foo.conf .
ls -l

Now you will have a symlink in sites-enabled called foo.conf which has a target ../sites-available/foo.conf

Just to be clear, the normal configuration for Apache is that the config files for potential sites live in sites-available and the symlinks for the enabled sites live in sites-enabled, pointing at targets in sites-available. That doesn't quite seem to be the case the way you describe your setup, but that is not your primary problem.

If you want a symlink to ALWAYS point at the same file, regardless of the where the symlink is located, then the target should be the full path.

ln -s /etc/apache2/sites-available/foo.conf mysimlink-whatever.conf

Here is (line 1 of) the output of my ls -l /etc/apache2/sites-enabled:

lrwxrwxrwx 1 root root  26 Jun 24 21:06 000-default -> ../sites-available/default

See how the target of the symlink is relative to the directory that contains the symlink (it starts with ".." meaning go up one directory).

Hardlinks are totally different because the target of a hardlink is not a directory entry but a filing system Inode.

Visual Studio window which shows list of methods

Microsoft doesn't feel like implementing this useful tool, but if by chance you can have Visual Assist, you have it in VAssistX > Tools > VA Outline. The plugin is not free though.

How to keep a VMWare VM's clock in sync?

VMware experiences a lot of clock drift. This Google search for 'vmware clock drift' links to several articles.

The first hit may be the most useful for you: http://www.fjc.net/linux/linux-and-vmware-related-issues/linux-2-6-kernels-and-vmware-clock-drift-issues

jQuery hasAttr checking to see if there is an attribute on an element

How about just $(this).is("[name]")?

The [attr] syntax is the CSS selector for an element with an attribute attr, and .is() checks if the element it is called on matches the given CSS selector.

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

How to reference image resources in XAML?

If you've got an image in the Icons folder of your project and its build action is "Resource", you can refer to it like this:

<Image Source="/Icons/play_small.png" />

That's the simplest way to do it. This is the only way I could figure doing it purely from the resource standpoint and no project files:

var resourceManager = new ResourceManager(typeof (Resources));
var bitmap = resourceManager.GetObject("Search") as System.Drawing.Bitmap;

var memoryStream = new MemoryStream();
bitmap.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Bmp);
memoryStream.Position = 0;

var bitmapImage = new BitmapImage();
bitmapImage.BeginInit();
bitmapImage.StreamSource = memoryStream;
bitmapImage.EndInit();

this.image1.Source = bitmapImage;