Programs & Examples On #Filter var

This is a PHP function to filter variables based on various filter flags. Returns FALSE on failure otherwise filtered data is returned.

Can Windows' built-in ZIP compression be scripted?

There are both zip and unzip executables (as well as a boat load of other useful applications) in the UnxUtils package available on SourceForge (http://sourceforge.net/projects/unxutils). Copy them to a location in your PATH, such as 'c:\windows', and you will be able to include them in your scripts.

This is not the perfect solution (or the one you asked for) but a decent work-a-round.

How to show git log history (i.e., all the related commits) for a sub directory of a git repo?

The other answers only show the changed files.

git log -p DIR is very useful, if you need the full diff of all changed files in a specific subdirectory.

Example: Show all detailed changes in a specific version range

git log -p 8a5fb..HEAD -- A B

commit 62ad8c5d
Author: Scott Tiger
Date:   Mon Nov 27 14:25:29 2017 +0100

    My comment

...
@@ -216,6 +216,10 @@ public class MyClass {

+  Added
-  Deleted

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

How could I use requests in asyncio?

DISCLAMER: Following code creates different threads for each function.

This might be useful for some of the cases as it is simpler to use. But know that it is not async but gives illusion of async using multiple threads, even though decorator suggests that.

To make any function non blocking, simply copy the decorator and decorate any function with a callback function as parameter. The callback function will receive the data returned from the function.

import asyncio
import requests


def run_async(callback):
    def inner(func):
        def wrapper(*args, **kwargs):
            def __exec():
                out = func(*args, **kwargs)
                callback(out)
                return out

            return asyncio.get_event_loop().run_in_executor(None, __exec)

        return wrapper

    return inner


def _callback(*args):
    print(args)


# Must provide a callback function, callback func will be executed after the func completes execution !!
@run_async(_callback)
def get(url):
    return requests.get(url)


get("https://google.com")
print("Non blocking code ran !!")

Hide scroll bar, but while still being able to scroll

I just wanted to share a combined snippet for hiding the scrollbar that I use when developing. It is a collection of several snippets found on the Internet that works for me:

.container {
    overflow-x: scroll; /* For horiz. scroll, otherwise overflow-y: scroll; */

    -ms-overflow-style: none;
    overflow: -moz-scrollbars-none;
    scrollbar-width: none;
}


.container::-webkit-scrollbar {
    display: none;  /* Safari and Chrome */
}

Reverse each individual word of "Hello World" string with Java

You need to do this on each word after you split into an array of words.

public String reverse(String word) {
    char[] chs = word.toCharArray();

    int i=0, j=chs.length-1;
    while (i < j) {
        // swap chs[i] and chs[j]
        char t = chs[i];
        chs[i] = chs[j];
        chs[j] = t;
       i++; j--;
    }
    return String.valueOf(chs);
}

Docker-compose: node_modules not present in a volume after npm install succeeds

UPDATE: Use the solution provided by @FrederikNS.

I encountered the same problem. When the folder /worker is mounted to the container - all of it's content will be syncronized (so the node_modules folder will disappear if you don't have it locally.)

Due to incompatible npm packages based on OS, I could not just install the modules locally - then launch the container, so..

My solution to this, was to wrap the source in a src folder, then link node_modules into that folder, using this index.js file. So, the index.js file is now the starting point of my application.

When I run the container, I mounted the /app/src folder to my local src folder.

So the container folder looks something like this:

/app
  /node_modules
  /src
    /node_modules -> ../node_modules
    /app.js
  /index.js

It is ugly, but it works..

Jquery to get SelectedText from dropdown

The problem could be on this line:

            var selectedText2 = $("#SelectedCountryId:selected").text();

It's looking for the item with id of SelectedCountryId that is selected, where you really want the option that's selected under SelectedCountryId, so try:

$('#SelectedCountryId option:selected').text()

How to break lines in PowerShell?

If you are using just code like this below, you must put just a grave accent at the end of line `.

docker run -d --name rabbitmq `
           -p 5672:5672 `
           -p 15672:15672 `
           --restart=always `
           --hostname rabbitmq-master `
           -v c:\docker\rabbitmq\data:/var/lib/rabbitmq `
           rabbitmq:latest

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case i used directive, but hadn't imported it in my module.ts file. Import fixed it.

Python: import cx_Oracle ImportError: No module named cx_Oracle error is thown

To access Oracle from python you need (additionally) the cx_Oracle module. The module must be located either in the system python path or you have to set the PYTHONPATH appropriate.

facebook Uncaught OAuthException: An active access token must be used to query information about the current user

So I had the same issue, but it was because I was saving the access token but not using it. It could be because I'm super sleepy because of due dates, or maybe I just didn't think about it! But in case anyone else is in the same situation:

When I log in the user I save the access token:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$accessToken = $facebook->getAccessToken();
//save the access token for later

Now when I make requests to facebook I just do something like this:

$facebook = new Facebook(array(
    'appId' => <insert the app id you get from facebook here>,
    'secret' => <insert the app secret you get from facebook here>
));

$facebook->setAccessToken($accessToken);
$facebook->api(... insert own code here ...)

Is there a limit on how much JSON can hold?

The maximum length of JSON strings. The default is 2097152 characters, which is equivalent to 4 MB of Unicode string data.

Refer below URL

https://docs.microsoft.com/en-us/dotnet/api/system.web.script.serialization.javascriptserializer.maxjsonlength?view=netframework-4.7.2

Counter increment in Bash loop not working

COUNTER=1
while [ Your != "done" ]
do
     echo " $COUNTER "
     COUNTER=$[$COUNTER +1]
done

TESTED BASH: Centos, SuSE, RH

Load image from resources

Try this for WPF

StreamResourceInfo sri = Application.GetResourceStream(new Uri("pack://application:,,,/WpfGifImage001;Component/Images/Progess_Green.gif"));
picBox1.Image = System.Drawing.Image.FromStream(sri.Stream);

Get min and max value in PHP Array

It is interesting to note that both the solutions above use extra storage in form of arrays (first one two of them and second one uses one array) and then you find min and max using "extra storage" array. While that may be acceptable in real programming world (who gives a two bit about "extra" storage?) it would have got you a "C" in programming 101.

The problem of finding min and max can easily be solved with just two extra memory slots

$first = intval($input[0]['Weight']);
$min = $first ;
$max = $first ;

foreach($input as $data) {
    $weight = intval($data['Weight']);

    if($weight <= $min ) {
        $min =  $weight ;
    }

    if($weight > $max ) {
        $max =  $weight ;
    }

}

echo " min = $min and max = $max \n " ;

How to set aliases in the Git Bash for Windows?

  • Go to: C:\Users\ [youruserdirectory] \bash_profile

  • In your bash_profile file type - alias desk='cd " [DIRECTORY LOCATION] "'

  • Refresh your User directory where the bash_profile file exists then reopen your CMD or Git Bash window

Type in desk to see if you get to the Desktop location or the location you want in the "DIRECTORY LOCATION" area above

Note: [ desk ] can be what ever name that you choose and should get you to the location you want to get to when typed in the CMD window.

Select the top N values by group

Since dplyr 1.0.0, the slice_max()/slice_min() functions were implemented:

mtcars %>%
 group_by(cyl) %>%
 slice_max(mpg, n = 2, with_ties = FALSE)

    mpg   cyl  disp    hp  drat    wt  qsec    vs    am  gear  carb
  <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl> <dbl>
1  33.9     4  71.1    65  4.22  1.84  19.9     1     1     4     1
2  32.4     4  78.7    66  4.08  2.2   19.5     1     1     4     1
3  21.4     6 258     110  3.08  3.22  19.4     1     0     3     1
4  21       6 160     110  3.9   2.62  16.5     0     1     4     4
5  19.2     8 400     175  3.08  3.84  17.0     0     0     3     2
6  18.7     8 360     175  3.15  3.44  17.0     0     0     3     2

The documentation on with_ties parameter:

Should ties be kept together? The default, TRUE, may return more rows than you request. Use FALSE to ignore ties, and return the first n rows.

Javascript communication between browser tabs/windows

Below window(w1) opens another window(w2). Any window can send/receive message to/from another window. So we should ideally verify that the message originated from the window(w2) we opened.

In w1

var w2 = window.open("abc.do");
window.addEventListener("message", function(event){
    console.log(event.data);
});

In w2(abc.do)

window.opener.postMessage("Hi! I'm w2", "*");

Find where python is installed (if it isn't default dir)

If you are using wiindows OS (I am using windows 10 ) just type

where python   

in command prompt ( cmd )

It will show you the directory where you have installed .

J2ME/Android/BlackBerry - driving directions, route between two locations

J2ME Map Route Provider

maps.google.com has a navigation service which can provide you route information in KML format.

To get kml file we need to form url with start and destination locations:

public static String getUrl(double fromLat, double fromLon,
                            double toLat, double toLon) {// connect to map web service
    StringBuffer urlString = new StringBuffer();
    urlString.append("http://maps.google.com/maps?f=d&hl=en");
    urlString.append("&saddr=");// from
    urlString.append(Double.toString(fromLat));
    urlString.append(",");
    urlString.append(Double.toString(fromLon));
    urlString.append("&daddr=");// to
    urlString.append(Double.toString(toLat));
    urlString.append(",");
    urlString.append(Double.toString(toLon));
    urlString.append("&ie=UTF8&0&om=0&output=kml");
    return urlString.toString();
}

Next you will need to parse xml (implemented with SAXParser) and fill data structures:

public class Point {
    String mName;
    String mDescription;
    String mIconUrl;
    double mLatitude;
    double mLongitude;
}

public class Road {
    public String mName;
    public String mDescription;
    public int mColor;
    public int mWidth;
    public double[][] mRoute = new double[][] {};
    public Point[] mPoints = new Point[] {};
}

Network connection is implemented in different ways on Android and Blackberry, so you will have to first form url:

 public static String getUrl(double fromLat, double fromLon,
     double toLat, double toLon)

then create connection with this url and get InputStream.
Then pass this InputStream and get parsed data structure:

 public static Road getRoute(InputStream is) 

Full source code RoadProvider.java

BlackBerry

class MapPathScreen extends MainScreen {
    MapControl map;
    Road mRoad = new Road();
    public MapPathScreen() {
        double fromLat = 49.85, fromLon = 24.016667;
        double toLat = 50.45, toLon = 30.523333;
        String url = RoadProvider.getUrl(fromLat, fromLon, toLat, toLon);
        InputStream is = getConnection(url);
        mRoad = RoadProvider.getRoute(is);
        map = new MapControl();
        add(new LabelField(mRoad.mName));
        add(new LabelField(mRoad.mDescription));
        add(map);
    }
    protected void onUiEngineAttached(boolean attached) {
        super.onUiEngineAttached(attached);
        if (attached) {
            map.drawPath(mRoad);
        }
    }
    private InputStream getConnection(String url) {
        HttpConnection urlConnection = null;
        InputStream is = null;
        try {
            urlConnection = (HttpConnection) Connector.open(url);
            urlConnection.setRequestMethod("GET");
            is = urlConnection.openInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
}

See full code on J2MEMapRouteBlackBerryEx on Google Code

Android

Android G1 screenshot

public class MapRouteActivity extends MapActivity {
    LinearLayout linearLayout;
    MapView mapView;
    private Road mRoad;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        mapView = (MapView) findViewById(R.id.mapview);
        mapView.setBuiltInZoomControls(true);
        new Thread() {
            @Override
            public void run() {
                double fromLat = 49.85, fromLon = 24.016667;
                double toLat = 50.45, toLon = 30.523333;
                String url = RoadProvider
                        .getUrl(fromLat, fromLon, toLat, toLon);
                InputStream is = getConnection(url);
                mRoad = RoadProvider.getRoute(is);
                mHandler.sendEmptyMessage(0);
            }
        }.start();
    }

    Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            TextView textView = (TextView) findViewById(R.id.description);
            textView.setText(mRoad.mName + " " + mRoad.mDescription);
            MapOverlay mapOverlay = new MapOverlay(mRoad, mapView);
            List<Overlay> listOfOverlays = mapView.getOverlays();
            listOfOverlays.clear();
            listOfOverlays.add(mapOverlay);
            mapView.invalidate();
        };
    };

    private InputStream getConnection(String url) {
        InputStream is = null;
        try {
            URLConnection conn = new URL(url).openConnection();
            is = conn.getInputStream();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return is;
    }
    @Override
    protected boolean isRouteDisplayed() {
        return false;
    }
}

See full code on J2MEMapRouteAndroidEx on Google Code

Using css transform property in jQuery

I started using the 'prefix-free' Script available at http://leaverou.github.io/prefixfree so I don't have to take care about the vendor prefixes. It neatly takes care of setting the correct vendor prefix behind the scenes for you. Plus a jQuery Plugin is available as well so one can still use jQuery's .css() method without code changes, so the suggested line in combination with prefix-free would be all you need:

$('.user-text').css('transform', 'scale(' + ui.value + ')');

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

I had this problem and I solved the following:

  1. open IIS
  2. Select the Backend Site

    enter image description here

  3. in features view: open Handler Mapping

enter image description here

  1. in the Handler Mapping window, Find WebDAV

enter image description here

  1. in Edit Module Mapping, open Request Restrictions

enter image description here

  1. enter image description here

Uploading/Displaying Images in MVC 4

        <input type="file" id="picfile" name="picf" />
       <input type="text" id="txtName" style="width: 144px;" />
 $("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;

                    var file = document.getElementById("picfile").files[0];
                    formData.append("FileUpload", file);
                    formData.append("Name", Name);

$.ajax({
                    type: "POST",
                    url: '/Category_Subcategory/Save_Category',
                    data: formData,
                    dataType: 'json',
                    contentType: false,
                    processData: false,
                    success: function (msg) {

                                 alert(msg);

                    },
                    error: function (error) {
                        alert("errror");
                    }
                });

});

 [HttpPost]
    public ActionResult Save_Category()
    {
      string Name=Request.Form[1]; 
      if (Request.Files.Count > 0)
        {
            HttpPostedFileBase file = Request.Files[0];
         }


    }

What is the location of mysql client ".my.cnf" in XAMPP for Windows?

Go to control panel ? services, look for MySQL and right click choose properties. If there, in “path to EXE file”, there is a parameter like

--defaults-file="X:\path\to\my.ini"

this is the file the server actually uses (independent of what mysql --help prints).

creating charts with angularjs

The ZingChart library has an AngularJS directive that was built in-house. Features include:

  • Full access to the entire ZingChart library (all charts, maps, and features)
  • Takes advantage of Angular's 2-way data binding, making data and chart elements easy to update
  • Support from the development team

    ...
    $scope.myJson = {
    type : 'line',
       series : [
          { values : [54,23,34,23,43] },{ values : [10,15,16,20,40] }
       ]
    };
    ...
    
    <zingchart id="myChart" zc-json="myJson" zc-height=500 zc-width=600></zingchart>
    

There is a full demo with code examples available.

Django DB Settings 'Improperly Configured' Error

in my own case in django 1.10.1 running on python2.7.11, I was trying to start the server using django-admin runserver instead of manage.py runserver in my project directory.

Check if string contains a value in array

$owned_urls= array('website1.com', 'website2.com', 'website3.com');
    $string = 'my domain name is website3.com';
    for($i=0; $i < count($owned_urls); $i++)
    {
        if(strpos($string,$owned_urls[$i]) != false)
            echo 'Found';
    }   

linux script to kill java process

if there are multiple java processes and you wish to kill them with one command try the below command

kill -9 $(ps -ef | pgrep -f "java")

replace "java" with any process string identifier , to kill anything else.

pip install from git repo branch

For windows & pycharm setup:

If you are using pycharm and If you want to use pip3 install git+https://github.com/...

  • firstly, you should download git from https://git-scm.com/downloads
  • then restart pycharm
  • and you can use pycharm terminal to install what you want

enter image description here

No operator matches the given name and argument type(s). You might need to add explicit type casts. -- Netbeans, Postgresql 8.4 and Glassfish

If you are using Primefaces, you should insert inside the the .xhtml file so it converts correctly to java integer. For example:

<p:selectCheckboxMenu 
    id="frameSelect"
    widgetVar="frameSelectBox"
    filter="true"
    filterMatchMode="contains"
    label="#{messages['frame']}"
    value="#{platform.frameBean.selectedFramesTypesList}"
    converter="javax.faces.Integer">
    <f:selectItems
        value="#{platform.frameBean.framesTypesList}"
        var="area"
        itemLabel="#{area}"
        itemValue="#{area}" />
</p:selectCheckboxMenu>

PHP write file from input to txt

Your form should look like this :

<form action="myprocessingscript.php" method="POST">
    <input name="field1" type="text" />
    <input name="field2" type="text" />
    <input type="submit" name="submit" value="Save Data">
</form>

and the PHP

<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
    $data = $_POST['field1'] . '-' . $_POST['field2'] . "\r\n";
    $ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
    if($ret === false) {
        die('There was an error writing this file');
    }
    else {
        echo "$ret bytes written to file";
    }
}
else {
   die('no post data to process');
}

I wrote to /tmp/mydata.txt because this way I know exactly where it is. using data.txt writes to that file in the current working directory which I know nothing of in your example.

file_put_contents opens, writes and closes files for you. Don't mess with it.

Further reading: file_put_contents

Multiple modals overlay

Try adding the following to your JS on bootply

$('#myModal2').on('show.bs.modal', function () {  
$('#myModal').css('z-index', 1030); })

$('#myModal2').on('hidden.bs.modal', function () {  
$('#myModal').css('z-index', 1040); })

Explanation:

After playing around with the attributes(using Chrome's dev tool), I have realized that any z-index value below 1031 will put things behind the backdrop.

So by using bootstrap's modal event handles I set the z-index to 1030. If #myModal2 is shown and set the z-index back to 1040 if #myModal2 is hidden.

Demo

how to add super privileges to mysql database?

just the query phpmyadmin prints after granting super user. hope help someone with console:

ON $.$ TO-> $=* doesnt show when you put two with a dot between them.

REVOKE ALL PRIVILEGES ON . FROM 'usr'@'localhost'; GRANT ALL PRIVILEGES ON . TO 'usr'@'localhost' REQUIRE NONE WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

and the reverse one, removing grant:

REVOKE ALL PRIVILEGES ON . FROM 'dos007'@'localhost'; REVOKE GRANT OPTION ON . FROM 'dos007'@'localhost'; GRANT ALL PRIVILEGES ON . TO 'dos007'@'localhost' REQUIRE NONE WITH MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0;

checked on vagrant should be working in any mysql

How do I manually configure a DataSource in Java?

use MYSQL as Example: 1) use database connection pools: for Example: Apache Commons DBCP , also, you need basicDataSource jar package in your classpath

@Bean
public BasicDataSource dataSource() {
    BasicDataSource ds = new BasicDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/gene");
    ds.setUsername("root");
    ds.setPassword("root");
    return ds;
}

2)use JDBC-based Driver it is usually used if you don't consider connection pool:

@Bean
public DataSource dataSource(){
    DriverManagerDataSource ds = new DriverManagerDataSource();
    ds.setDriverClassName("com.mysql.jdbc.Driver");
    ds.setUrl("jdbc:mysql://localhost:3306/gene");
    ds.setUsername("root");
    ds.setPassword("root");
    return ds;
}

Passing parameter via url to sql server reporting service

Try changing "Reports" to "ReportServer" in your url

How to convert an int value to string in Go?

Converting int64:

n := int64(32)
str := strconv.FormatInt(n, 10)

fmt.Println(str)
// Prints "32"

Get environment value in controller

You can not access the environment variable like this.

Inside the .env file you write

IMAP_HOSTNAME_TEST=imap.gmail.com  // I am okay with this

Next, inside the config folder there is a file, mail.php. You may use this file to code. As you are working with mail functionality. You might use another file as well.

return [

//..... other declarations
'imap_hostname_test' => env('IMAP_HOSTNAME_TEST'),
// You are hiding the value inside the configuration as well

];

You can call the variable from a controller using 'config(. Whatever file you are using inside config folder. You need to use that file name (without extension) + '.' + 'variable name' + ')'. In the current case you can call the variable as follows.

$hostname = config('mail.imap_hostname_test');

Since you declare the variable inside mail.php and the variable name is imap_hostname_test, you need to call it like this. If you declare this variable inside app.php then you should call

$hostname = config('app.imap_hostname_test');

How to pass arguments to a Button command in Tkinter?

button = Tk.Button(master=frame, text='press', command=lambda: action(someNumber))

I believe should fix this

How to play a local video with Swift?

Sure you can use Swift!

1. Adding the video file

Add the video (lets call it video.m4v) to your Xcode project

2. Checking your video is into the Bundle

Open the Project Navigator cmd + 1

Then select your project root > your Target > Build Phases > Copy Bundle Resources.

Your video MUST be here. If it's not, then you should add it using the plus button

enter image description here

3. Code

Open your View Controller and write this code.

import UIKit
import AVKit
import AVFoundation

class ViewController: UIViewController {

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        playVideo()
    }

    private func playVideo() {
        guard let path = Bundle.main.path(forResource: "video", ofType:"m4v") else {
            debugPrint("video.m4v not found")
            return
        }
        let player = AVPlayer(url: URL(fileURLWithPath: path))
        let playerController = AVPlayerViewController()
        playerController.player = player
        present(playerController, animated: true) {
            player.play()
        }
    }
}

Why does this "Slow network detected..." log appear in Chrome?

Goto chrome://flags/#enable-webfonts-intervention-v2 and set it to disabled

It’s due to a bug in Chrome with their latest API for ‘network speed’. Hope it will be fixed in the next version

Understanding REST: Verbs, error codes, and authentication

1. You've got the right idea about how to design your resources, IMHO. I wouldn't change a thing.

2. Rather than trying to extend HTTP with more verbs, consider what your proposed verbs can be reduced to in terms of the basic HTTP methods and resources. For example, instead of an activate_login verb, you could set up resources like: /api/users/1/login/active which is a simple boolean. To activate a login, just PUT a document there that says 'true' or 1 or whatever. To deactivate, PUT a document there that is empty or says 0 or false.

Similarly, to change or set passwords, just do PUTs to /api/users/1/password.

Whenever you need to add something (like a credit) think in terms of POSTs. For example, you could do a POST to a resource like /api/users/1/credits with a body containing the number of credits to add. A PUT on the same resource could be used to overwrite the value rather than add. A POST with a negative number in the body would subtract, and so on.

3. I'd strongly advise against extending the basic HTTP status codes. If you can't find one that matches your situation exactly, pick the closest one and put the error details in the response body. Also, remember that HTTP headers are extensible; your application can define all the custom headers that you like. One application that I worked on, for example, could return a 404 Not Found under multiple circumstances. Rather than making the client parse the response body for the reason, we just added a new header, X-Status-Extended, which contained our proprietary status code extensions. So you might see a response like:

HTTP/1.1 404 Not Found    
X-Status-Extended: 404.3 More Specific Error Here

That way a HTTP client like a web browser will still know what to do with the regular 404 code, and a more sophisticated HTTP client can choose to look at the X-Status-Extended header for more specific information.

4. For authentication, I recommend using HTTP authentication if you can. But IMHO there's nothing wrong with using cookie-based authentication if that's easier for you.

I want to remove double quotes from a String

var expressionWithoutQuotes = '';
for(var i =0; i<length;i++){
    if(expressionDiv.charAt(i) != '"'){
        expressionWithoutQuotes += expressionDiv.charAt(i);
    }
}

This may work for you.

How to create nonexistent subdirectories recursively using Bash?

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

+-- main
¦   +-- resources
¦   +-- scala
¦       +-- com
¦           +-- company
+-- test
    +-- resources
    +-- scala
        +-- com
            +-- company

The example was taken from this link for creating SBT directory structure

How to rotate portrait/landscape Android emulator?

Officially it's Ctrl+F11 & Ctrl+F12 or KEYPAD 7 & KEYPAD 9.

In practise it's a bit quirky.

  1. Specifically it's Left Ctrl+F11 and Left Ctrl+F12 to switch to previous orientation and next orientation respectively.

  2. You have to release Ctrl before you can rotate again.

  3. KEYPAD 7 and KEYPAD 9 only work with Num Lock OFF (so they're acting as Home & PageUp rather than 7 & 9).

  4. The only orientations are vertically upright and rotated one quarter-turn anti-clockwise.

Maybe a bit too much info for such a simple question, but it drove me half-mad finding this out.

Note: This was tested on Android SDK R16 and a very old keyboard, modern keyboards may behave differently.

How to do joins in LINQ on multiple fields in single join

Using the join operator you can only perform equijoins. Other types of joins can be constructed using other operators. I'm not sure whether the exact join you are trying to do would be easier using these methods or by changing the where clause. Documentation on the join clause can be found here. MSDN has an article on join operations with multiple links to examples of other joins, as well.

JQuery html() vs. innerHTML

To answer your question:

.html() will just call .innerHTML after doing some checks for nodeTypes and stuff. It also uses a try/catch block where it tries to use innerHTML first and if that fails, it'll fallback gracefully to jQuery's .empty() + append()

How do you use bcrypt for hashing passwords in PHP?


Edit: 2013.01.15 - If your server will support it, use martinstoeckli's solution instead.


Everyone wants to make this more complicated than it is. The crypt() function does most of the work.

function blowfishCrypt($password,$cost)
{
    $chars='./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $salt=sprintf('$2y$%02d$',$cost);
//For PHP < PHP 5.3.7 use this instead
//    $salt=sprintf('$2a$%02d$',$cost);
    //Create a 22 character salt -edit- 2013.01.15 - replaced rand with mt_rand
    mt_srand();
    for($i=0;$i<22;$i++) $salt.=$chars[mt_rand(0,63)];
    return crypt($password,$salt);
}

Example:

$hash=blowfishCrypt('password',10); //This creates the hash
$hash=blowfishCrypt('password',12); //This creates a more secure hash
if(crypt('password',$hash)==$hash){ /*ok*/ } //This checks a password

I know it should be obvious, but please don't use 'password' as your password.

Get child Node of another Node, given node name

Check if the Node is a Dom Element, cast, and call getElementsByTagName()

Node doc = docs.item(i);
if(doc instanceof Element) {
    Element docElement = (Element)doc;
    ...
    cell = doc.getElementsByTagName("aoo").item(0);
}

Getting binary (base64) data from HTML5 Canvas (readAsBinaryString)

Short answer:

const base64Canvas = canvas.toDataURL("image/jpeg").split(';base64,')[1];

Hash function for a string

-- The way to go these days --

Use SipHash. For your own protection.

-- Old and Dangerous --

unsigned int RSHash(const std::string& str)
{
    unsigned int b    = 378551;
    unsigned int a    = 63689;
    unsigned int hash = 0;

    for(std::size_t i = 0; i < str.length(); i++)
    {
        hash = hash * a + str[i];
        a    = a * b;
    }

    return (hash & 0x7FFFFFFF);
 }

 unsigned int JSHash(const std::string& str)
 {
      unsigned int hash = 1315423911;

      for(std::size_t i = 0; i < str.length(); i++)
      {
          hash ^= ((hash << 5) + str[i] + (hash >> 2));
      }

      return (hash & 0x7FFFFFFF);
 }

Ask google for "general purpose hash function"

Add to python path mac os x

Setting the $PYTHONPATH environment variable does not seem to affect the Spyder IDE's iPython terminals on a Mac. However, Spyder's application menu contains a "PYTHONPATH manager." Adding my path here solved my problem. The "PYTHONPATH manager" is also persistent across application restarts.

This is specific to a Mac, because setting the PYTHONPATH environment variable on my Windows PC gives the expected behavior (modules are found) without using the PYTHONPATH manager in Spyder.

Why does this SQL code give error 1066 (Not unique table/alias: 'user')?

    SELECT art.* , sec.section.title, cat.title, use1.name, use2.name as modifiedby
FROM article art
INNER JOIN section sec ON art.section_id = sec.section.id
INNER JOIN category cat ON art.category_id = cat.id
INNER JOIN user use1 ON art.author_id = use1.id
LEFT JOIN user use2 ON art.modified_by = use2.id
WHERE art.id = '1';

Hope This Might Help

What is the difference between char array and char pointer in C?

As far as I can remember, an array is actually a group of pointers. For example

p[1]== *(&p+1)

is a true statement

Directing print output to a .txt file

Another method without having to update your Python code at all, would be to redirect via the console.

Basically, have your Python script print() as usual, then call the script from the command line and use command line redirection. Like this:

$ python ./myscript.py > output.txt

Your output.txt file will now contain all output from your Python script.

Edit:
To address the comment; for Windows, change the forward-slash to a backslash.
(i.e. .\myscript.py)

JS jQuery - check if value is in array

Alternate solution of the values check

//Duplicate Title Entry 
    $.each(ar , function (i, val) {
        if ( jQuery("input:first").val()== val) alert('VALUE FOUND'+Valuecheck);
  });

How to conclude your merge of a file?

Note and update:

Since Git1.7.4 (January 2011), you have git merge --abort, synonymous to "git reset --merge" when a merge is in progress.

But if you want to complete the merge, while somehow nothing remains to be added, then a crude rm -rf .git/MERGE* can be enough for Git to forget about the current merge.

How to read large text file on windows?

I just used less on top of Cygwin to read a 3GB file, though I ended up using grep to find what I needed in it.

(less is more, but better.)

See this answer for more details on less: https://stackoverflow.com/a/1343576/1005039

org.apache.catalina.core.StandardContext startInternal SEVERE: Error listenerStart

For Intellij Idea sometime localhost.log file generated at different location. For e.g. you can find it at homedirectory\ .IntelliJIdea14\system\tomcat.

IF you are using spring then start ur server in debug mode and put debug point in catch block of org.springframework.context.support.AbstractApplicationContext's refresh() method. If bean creation fails you would be able to see the exception.

Android REST client, Sample?

There is another library with much cleaner API and type-safe data. https://github.com/kodart/Httpzoid

Here is a simple usage example

Http http = HttpFactory.create(context);
http.post("http://example.com/users")
    .data(new User("John"))
    .execute();

Or more complex with callbacks

Http http = HttpFactory.create(context);
http.post("http://example.com/users")
    .data(new User("John"))
    .handler(new ResponseHandler<Void>() {
        @Override
        public void success(Void ignore, HttpResponse response) {
        }

        @Override
        public void error(String message, HttpResponse response) {
        }

        @Override
        public void failure(NetworkError error) {
        }

        @Override
        public void complete() {
        }
    }).execute();

It is fresh new, but looks very promising.

SQL Server: Is it possible to insert into two tables at the same time?

Before being able to do a multitable insert in Oracle, you could use a trick involving an insert into a view that had an INSTEAD OF trigger defined on it to perform the inserts. Can this be done in SQL Server?

What online brokers offer APIs?

Only related with currency trading (Forex), but many Forex brokers are offering MetaTrader which let you code in MQL. The main problem with it (aside that it's limited to Forex) is that you've to code in MQL which might not be your preferred language.

Difference between SET autocommit=1 and START TRANSACTION in mysql (Have I missed something?)

Being aware of the transaction (autocommit, explicit and implicit) handling for your database can save you from having to restore data from a backup.

Transactions control data manipulation statement(s) to ensure they are atomic. Being "atomic" means the transaction either occurs, or it does not. The only way to signal the completion of the transaction to database is by using either a COMMIT or ROLLBACK statement (per ANSI-92, which sadly did not include syntax for creating/beginning a transaction so it is vendor specific). COMMIT applies the changes (if any) made within the transaction. ROLLBACK disregards whatever actions took place within the transaction - highly desirable when an UPDATE/DELETE statement does something unintended.

Typically individual DML (Insert, Update, Delete) statements are performed in an autocommit transaction - they are committed as soon as the statement successfully completes. Which means there's no opportunity to roll back the database to the state prior to the statement having been run in cases like yours. When something goes wrong, the only restoration option available is to reconstruct the data from a backup (providing one exists). In MySQL, autocommit is on by default for InnoDB - MyISAM doesn't support transactions. It can be disabled by using:

SET autocommit = 0

An explicit transaction is when statement(s) are wrapped within an explicitly defined transaction code block - for MySQL, that's START TRANSACTION. It also requires an explicitly made COMMIT or ROLLBACK statement at the end of the transaction. Nested transactions is beyond the scope of this topic.

Implicit transactions are slightly different from explicit ones. Implicit transactions do not require explicity defining a transaction. However, like explicit transactions they require a COMMIT or ROLLBACK statement to be supplied.

Conclusion

Explicit transactions are the most ideal solution - they require a statement, COMMIT or ROLLBACK, to finalize the transaction, and what is happening is clearly stated for others to read should there be a need. Implicit transactions are OK if working with the database interactively, but COMMIT statements should only be specified once results have been tested & thoroughly determined to be valid.

That means you should use:

SET autocommit = 0;

START TRANSACTION;
  UPDATE ...;

...and only use COMMIT; when the results are correct.

That said, UPDATE and DELETE statements typically only return the number of rows affected, not specific details. Convert such statements into SELECT statements & review the results to ensure correctness prior to attempting the UPDATE/DELETE statement.

Addendum

DDL (Data Definition Language) statements are automatically committed - they do not require a COMMIT statement. IE: Table, index, stored procedure, database, and view creation or alteration statements.

On design patterns: When should I use the singleton?

A practical example of a singleton can be found in Test::Builder, the class which backs just about every modern Perl testing module. The Test::Builder singleton stores and brokers the state and history of the test process (historical test results, counts the number of tests run) as well as things like where the test output is going. These are all necessary to coordinate multiple testing modules, written by different authors, to work together in a single test script.

The history of Test::Builder's singleton is educational. Calling new() always gives you the same object. First, all the data was stored as class variables with nothing in the object itself. This worked until I wanted to test Test::Builder with itself. Then I needed two Test::Builder objects, one setup as a dummy, to capture and test its behavior and output, and one to be the real test object. At that point Test::Builder was refactored into a real object. The singleton object was stored as class data, and new() would always return it. create() was added to make a fresh object and enable testing.

Currently, users are wanting to change some behaviors of Test::Builder in their own module, but leave others alone, while the test history remains in common across all testing modules. What's happening now is the monolithic Test::Builder object is being broken down into smaller pieces (history, output, format...) with a Test::Builder instance collecting them together. Now Test::Builder no longer has to be a singleton. Its components, like history, can be. This pushes the inflexible necessity of a singleton down a level. It gives more flexibility to the user to mix-and-match pieces. The smaller singleton objects can now just store data, with their containing objects deciding how to use it. It even allows a non-Test::Builder class to play along by using the Test::Builder history and output singletons.

Seems to be there's a push and pull between coordination of data and flexibility of behavior which can be mitigated by putting the singleton around just shared data with the smallest amount of behavior as possible to ensure data integrity.

Convert a number into a Roman Numeral in javaScript

_x000D_
_x000D_
function convertToRoman(num) {_x000D_
    var arr = [];_x000D_
    for (var i = 0; i < num.toString().length; i++) {_x000D_
        arr.push(Number(num.toString().substr(i, 1)));_x000D_
    }_x000D_
    var romanArr = [_x000D_
        ["I", "II", "III", "IV", "V", "VI", "VII", "VIII", "IX"],_x000D_
        ["X", "XX", "XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"],_x000D_
        ["C", "CC", "CCC", "CD", "D", "DC", "DCC", "DCCC", "CM"],_x000D_
        ["M"]_x000D_
    ];_x000D_
    var roman = arr.reverse().map(function (val, i) {_x000D_
        if (val === 0) {_x000D_
            return "";_x000D_
        }_x000D_
        if (i === 3) {_x000D_
            var r = "";_x000D_
            for (var j = 0; j < val; j++) {_x000D_
                r += romanArr[i][0];_x000D_
            }_x000D_
            return r;_x000D_
        } else {_x000D_
            return romanArr[i][val - 1];_x000D_
        }_x000D_
    });_x000D_
    console.log(roman.reverse().join(""));_x000D_
    return roman.join("");_x000D_
}_x000D_
_x000D_
_x000D_
convertToRoman(10);
_x000D_
_x000D_
_x000D_

Convert a hexadecimal string to an integer efficiently in C?

This currently only works with lower case but its super easy to make it work with both.

cout << "\nEnter a hexadecimal number: ";
cin >> hexNumber;
orighex = hexNumber;

strlength = hexNumber.length();

for (i=0;i<strlength;i++)
{
    hexa = hexNumber.substr(i,1);
    if ((hexa>="0") && (hexa<="9"))
    {
        //cout << "This is a numerical value.\n";
    }
    else
    {
        //cout << "This is a alpabetical value.\n";
        if (hexa=="a"){hexa="10";}
        else if (hexa=="b"){hexa="11";}
        else if (hexa=="c"){hexa="12";}
        else if (hexa=="d"){hexa="13";}
        else if (hexa=="e"){hexa="14";}
        else if (hexa=="f"){hexa="15";}
        else{cout << "INVALID ENTRY! ANSWER WONT BE CORRECT\n";}
    }
    //convert from string to integer

    hx = atoi(hexa.c_str());
    finalhex = finalhex + (hx*pow(16.0,strlength-i-1));
}
cout << "The hexadecimal number: " << orighex << " is " << finalhex << " in decimal.\n";

Can IntelliJ IDEA encapsulate all of the functionality of WebStorm and PHPStorm through plugins?

Definitely a great question. I've noted this also as a sub question of the choice for versions within IDEa that this link may help to address...

http://www.jetbrains.com/idea/features/editions_comparison_matrix.html

it as well potentially possesses a ground work for looking at your other IDE choices and the options they provide.

I'm thinking WebStorm is best for JavaScript and Git repo management, meaning the HTML5 CSS Cordova kinds of stacks, which is really where (I believe along with others) the future lies and energies should be focused now... but ya it depends on your needs, etc.

Anyway this tells that story too... http://www.jetbrains.com/products.html

How to search for a part of a word with ElasticSearch

Nevermind.

I had to look at the Lucene documentation. Seems I can use wildcards! :-)

curl http://localhost:9200/my_idx/my_type/_search?q=*Doe*

does the trick!

How to stop creating .DS_Store on Mac?

Please install http://asepsis.binaryage.com/ and then reboot your mac.

ASEPSIS redirect all .DS_Store on your mac to /usr/local/.dscage

After that, You could delete recursively all .DS_Store from your mac.

find ~ -name ".DS_Store" -delete
or
find <your path> -name ".DS_Store" -delete

You should repeat procedure after each Mac major update.

Output to the same line overwriting previous output?

If all you want to do is change a single line, use \r. \r means carriage return. It's effect is solely to put the caret back at the start of the current line. It does not erase anything. Similarly, \b can be used to go one character backward. (some terminals may not support all those features)

import sys

def process(data):
    size_str = os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!'
    sys.stdout.write('%s\r' % size_str)
    sys.stdout.flush()
    file.write(data)

How do I install opencv using pip?

Everybody struggles initially while installing opencv. Opencv requires lot of dependencies in back-end. The best way to start with opencv is, install it in virtual environment. I suggest you to first install python anaconda distribution and create virtual environment using it. Then inside virtual environment using conda install command you can easily install opencv. I feel this is the most safe and easy approach to install opencv. The following command work for me, you can try the same.

conda install -c menpo opencv3 

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

You could try to reinstall the ca-certificates package, or explicitly allow the certificate in question as described here.

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

i solved this problem by removing space between quotes and command value inside of array ,this is happened because container exited after started and no executable command present which to be run inside of container.

['sh', '-c', 'echo Hello Kubernetes! && sleep 3600']

Count multiple columns with group by in one query

It's hard to know how to help you without understanding the context / structure of your data, but I believe this might help you:

SELECT 
     SUM(CASE WHEN column1 IS NOT NULL THEN 1 ELSE 0 END) AS column1_count
    ,SUM(CASE WHEN column2 IS NOT NULL THEN 1 ELSE 0 END) AS column2_count
    ,SUM(CASE WHEN column3 IS NOT NULL THEN 1 ELSE 0 END) AS column3_count
FROM table

Change directory command in Docker?

You can run a script, or a more complex parameter to the RUN. Here is an example from a Dockerfile I've downloaded to look at previously:

RUN cd /opt && unzip treeio.zip && mv treeio-master treeio && \
    rm -f treeio.zip && cd treeio && pip install -r requirements.pip

Because of the use of '&&', it will only get to the final 'pip install' command if all the previous commands have succeeded.

In fact, since every RUN creates a new commit & (currently) an AUFS layer, if you have too many commands in the Dockerfile, you will use up the limits, so merging the RUNs (when the file is stable) can be a very useful thing to do.

Limiting the number of characters per line with CSS

If you use CSS to select a monospace font, the problem of varying character length is easily solved.

Configure hibernate to connect to database via JNDI Datasource

I was getting the same error in my IBM Websphere with c3p0 jar files. I have Oracle 10g database. I simply added the oraclejdbc.jar files in the Application server JVM in IBM Classpath using Websphere Console and the error was resolved.

The oraclejdbc.jar should be set with your C3P0 jar files in your Server Class path whatever it be tomcat, glassfish of IBM.

How to get line count of a large file cheaply in Python?

I believe that a memory mapped file will be the fastest solution. I tried four functions: the function posted by the OP (opcount); a simple iteration over the lines in the file (simplecount); readline with a memory-mapped filed (mmap) (mapcount); and the buffer read solution offered by Mykola Kharechko (bufcount).

I ran each function five times, and calculated the average run-time for a 1.2 million-line text file.

Windows XP, Python 2.5, 2GB RAM, 2 GHz AMD processor

Here are my results:

mapcount : 0.465599966049
simplecount : 0.756399965286
bufcount : 0.546800041199
opcount : 0.718600034714

Edit: numbers for Python 2.6:

mapcount : 0.471799945831
simplecount : 0.634400033951
bufcount : 0.468800067902
opcount : 0.602999973297

So the buffer read strategy seems to be the fastest for Windows/Python 2.6

Here is the code:

from __future__ import with_statement
import time
import mmap
import random
from collections import defaultdict

def mapcount(filename):
    f = open(filename, "r+")
    buf = mmap.mmap(f.fileno(), 0)
    lines = 0
    readline = buf.readline
    while readline():
        lines += 1
    return lines

def simplecount(filename):
    lines = 0
    for line in open(filename):
        lines += 1
    return lines

def bufcount(filename):
    f = open(filename)                  
    lines = 0
    buf_size = 1024 * 1024
    read_f = f.read # loop optimization

    buf = read_f(buf_size)
    while buf:
        lines += buf.count('\n')
        buf = read_f(buf_size)

    return lines

def opcount(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1


counts = defaultdict(list)

for i in range(5):
    for func in [mapcount, simplecount, bufcount, opcount]:
        start_time = time.time()
        assert func("big_file.txt") == 1209138
        counts[func].append(time.time() - start_time)

for key, vals in counts.items():
    print key.__name__, ":", sum(vals) / float(len(vals))

How to use Select2 with JSON via Ajax request?

Here you have an example

$("#profiles-thread").select2({
    minimumInputLength: 2,
    tags: [],
    ajax: {
        url: URL,
        dataType: 'json',
        type: "GET",
        quietMillis: 50,
        data: function (term) {
            return {
                term: term
            };
        },
        results: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.completeName,
                        slug: item.slug,
                        id: item.id
                    }
                })
            };
        }
    }
});

It's quite easy

What is declarative programming?

Since I wrote my prior answer, I have formulated a new definition of the declarative property which is quoted below. I have also defined imperative programming as the dual property.

This definition is superior to the one I provided in my prior answer, because it is succinct and it is more general. But it may be more difficult to grok, because the implication of the incompleteness theorems applicable to programming and life in general are difficult for humans to wrap their mind around.

The quoted explanation of the definition discusses the role pure functional programming plays in declarative programming.

Declarative vs. Imperative

The declarative property is weird, obtuse, and difficult to capture in a technically precise definition that remains general and not ambiguous, because it is a naive notion that we can declare the meaning (a.k.a semantics) of the program without incurring unintended side effects. There is an inherent tension between expression of meaning and avoidance of unintended effects, and this tension actually derives from the incompleteness theorems of programming and our universe.

It is oversimplification, technically imprecise, and often ambiguous to define declarative as what to do and imperative as how to do. An ambiguous case is the “what” is the “how” in a program that outputs a program— a compiler.

Evidently the unbounded recursion that makes a language Turing complete, is also analogously in the semantics— not only in the syntactical structure of evaluation (a.k.a. operational semantics). This is logically an example analogous to Gödel's theorem— “any complete system of axioms is also inconsistent”. Ponder the contradictory weirdness of that quote! It is also an example that demonstrates how the expression of semantics does not have a provable bound, thus we can't prove2 that a program (and analogously its semantics) halt a.k.a. the Halting theorem.

The incompleteness theorems derive from the fundamental nature of our universe, which as stated in the Second Law of Thermodynamics is “the entropy (a.k.a. the # of independent possibilities) is trending to maximum forever”. The coding and design of a program is never finished— it's alive!— because it attempts to address a real world need, and the semantics of the real world are always changing and trending to more possibilities. Humans never stop discovering new things (including errors in programs ;-).

To precisely and technically capture this aforementioned desired notion within this weird universe that has no edge (ponder that! there is no “outside” of our universe), requires a terse but deceptively-not-simple definition which will sound incorrect until it is explained deeply.

Definition:


The declarative property is where there can exist only one possible set of statements that can express each specific modular semantic.

The imperative property3 is the dual, where semantics are inconsistent under composition and/or can be expressed with variations of sets of statements.


This definition of declarative is distinctively local in semantic scope, meaning that it requires that a modular semantic maintain its consistent meaning regardless where and how it's instantiated and employed in global scope. Thus each declarative modular semantic should be intrinsically orthogonal to all possible others— and not an impossible (due to incompleteness theorems) global algorithm or model for witnessing consistency, which is also the point of “More Is Not Always Better” by Robert Harper, Professor of Computer Science at Carnegie Mellon University, one of the designers of Standard ML.

Examples of these modular declarative semantics include category theory functors e.g. the Applicative, nominal typing, namespaces, named fields, and w.r.t. to operational level of semantics then pure functional programming.

Thus well designed declarative languages can more clearly express meaning, albeit with some loss of generality in what can be expressed, yet a gain in what can be expressed with intrinsic consistency.

An example of the aforementioned definition is the set of formulas in the cells of a spreadsheet program— which are not expected to give the same meaning when moved to different column and row cells, i.e. cell identifiers changed. The cell identifiers are part of and not superfluous to the intended meaning. So each spreadsheet result is unique w.r.t. to the cell identifiers in a set of formulas. The consistent modular semantic in this case is use of cell identifiers as the input and output of pure functions for cells formulas (see below).

Hyper Text Markup Language a.k.a. HTML— the language for static web pages— is an example of a highly (but not perfectly3) declarative language that (at least before HTML 5) had no capability to express dynamic behavior. HTML is perhaps the easiest language to learn. For dynamic behavior, an imperative scripting language such as JavaScript was usually combined with HTML. HTML without JavaScript fits the declarative definition because each nominal type (i.e. the tags) maintains its consistent meaning under composition within the rules of the syntax.

A competing definition for declarative is the commutative and idempotent properties of the semantic statements, i.e. that statements can be reordered and duplicated without changing the meaning. For example, statements assigning values to named fields can be reordered and duplicated without changed the meaning of the program, if those names are modular w.r.t. to any implied order. Names sometimes imply an order, e.g. cell identifiers include their column and row position— moving a total on spreadsheet changes its meaning. Otherwise, these properties implicitly require global consistency of semantics. It is generally impossible to design the semantics of statements so they remain consistent if randomly ordered or duplicated, because order and duplication are intrinsic to semantics. For example, the statements “Foo exists” (or construction) and “Foo does not exist” (and destruction). If one considers random inconsistency endemical of the intended semantics, then one accepts this definition as general enough for the declarative property. In essence this definition is vacuous as a generalized definition because it attempts to make consistency orthogonal to semantics, i.e. to defy the fact that the universe of semantics is dynamically unbounded and can't be captured in a global coherence paradigm.

Requiring the commutative and idempotent properties for the (structural evaluation order of the) lower-level operational semantics converts operational semantics to a declarative localized modular semantic, e.g. pure functional programming (including recursion instead of imperative loops). Then the operational order of the implementation details do not impact (i.e. spread globally into) the consistency of the higher-level semantics. For example, the order of evaluation of (and theoretically also the duplication of) the spreadsheet formulas doesn't matter because the outputs are not copied to the inputs until after all outputs have been computed, i.e. analogous to pure functions.

C, Java, C++, C#, PHP, and JavaScript aren't particularly declarative. Copute's syntax and Python's syntax are more declaratively coupled to intended results, i.e. consistent syntactical semantics that eliminate the extraneous so one can readily comprehend code after they've forgotten it. Copute and Haskell enforce determinism of the operational semantics and encourage “don't repeat yourself” (DRY), because they only allow the pure functional paradigm.


2 Even where we can prove the semantics of a program, e.g. with the language Coq, this is limited to the semantics that are expressed in the typing, and typing can never capture all of the semantics of a program— not even for languages that are not Turing complete, e.g. with HTML+CSS it is possible to express inconsistent combinations which thus have undefined semantics.

3 Many explanations incorrectly claim that only imperative programming has syntactically ordered statements. I clarified this confusion between imperative and functional programming. For example, the order of HTML statements does not reduce the consistency of their meaning.


Edit: I posted the following comment to Robert Harper's blog:

in functional programming ... the range of variation of a variable is a type

Depending on how one distinguishes functional from imperative programming, your ‘assignable’ in an imperative program also may have a type placing a bound on its variability.

The only non-muddled definition I currently appreciate for functional programming is a) functions as first-class objects and types, b) preference for recursion over loops, and/or c) pure functions— i.e. those functions which do not impact the desired semantics of the program when memoized (thus perfectly pure functional programming doesn't exist in a general purpose denotational semantics due to impacts of operational semantics, e.g. memory allocation).

The idempotent property of a pure function means the function call on its variables can be substituted by its value, which is not generally the case for the arguments of an imperative procedure. Pure functions seem to be declarative w.r.t. to the uncomposed state transitions between the input and result types.

But the composition of pure functions does not maintain any such consistency, because it is possible to model a side-effect (global state) imperative process in a pure functional programming language, e.g. Haskell's IOMonad and moreover it is entirely impossible to prevent doing such in any Turing complete pure functional programming language.

As I wrote in 2012 which seems to the similar consensus of comments in your recent blog, that declarative programming is an attempt to capture the notion that the intended semantics are never opaque. Examples of opaque semantics are dependence on order, dependence on erasure of higher-level semantics at the operational semantics layer (e.g. casts are not conversions and reified generics limit higher-level semantics), and dependence on variable values which can not be checked (proved correct) by the programming language.

Thus I have concluded that only non-Turing complete languages can be declarative.

Thus one unambiguous and distinct attribute of a declarative language could be that its output can be proven to obey some enumerable set of generative rules. For example, for any specific HTML program (ignoring differences in the ways interpreters diverge) that is not scripted (i.e. is not Turing complete) then its output variability can be enumerable. Or more succinctly an HTML program is a pure function of its variability. Ditto a spreadsheet program is a pure function of its input variables.

So it seems to me that declarative languages are the antithesis of unbounded recursion, i.e. per Gödel's second incompleteness theorem self-referential theorems can't be proven.

Lesie Lamport wrote a fairytale about how Euclid might have worked around Gödel's incompleteness theorems applied to math proofs in the programming language context by to congruence between types and logic (Curry-Howard correspondence, etc).

In Subversion can I be a user other than my login name?

Most of the answers seem to be for svn+ssh, or don't seem to work for us.

For http access, the easiest way to log out an SVN user from the command line is:

rm ~/.subversion/auth/svn.simple/*

Hat tip: http://www.yolinux.com/TUTORIALS/Subversion.html

Why does the 'int' object is not callable error occur when using the sum() function?

You probably redefined your "sum" function to be an integer data type. So it is rightly telling you that an integer is not something you can pass a range.

To fix this, restart your interpreter.

Python 2.7.3 (default, Apr 20 2012, 22:44:07) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> data1 = range(0, 1000, 3)
>>> data2 = range(0, 1000, 5)
>>> data3 = list(set(data1 + data2)) # makes new list without duplicates
>>> total = sum(data3) # calculate sum of data3 list's elements
>>> print total
233168

If you shadow the sum builtin, you can get the error you are seeing

>>> sum = 0
>>> total = sum(data3) # calculate sum of data3 list's elements
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

Also, note that sum will work fine on the set there is no need to convert it to a list

simple HTTP server in Java using only Java SE API

Try this https://github.com/devashish234073/Java-Socket-Http-Server/blob/master/README.md

This API has creates an HTTP server using sockets.

  1. It gets a request from the browser as text
  2. Parses it to retrieve URL info, method, attributes, etc.
  3. Creates dynamic response using the URL mapping defined
  4. Sends the response to the browser.

For example the here's how the constructor in the Response.java class converts a raw response into an http response:

public Response(String resp){
    Date date = new Date();
    String start = "HTTP/1.1 200 OK\r\n";
    String header = "Date: "+date.toString()+"\r\n";
    header+= "Content-Type: text/html\r\n";
    header+= "Content-length: "+resp.length()+"\r\n";
    header+="\r\n";
    this.resp=start+header+resp;
}

Reading images in python

you can try to use cv2 like this

import cv2

image= cv2.imread('image page')

cv2.imshow('image', image)

cv2.waitKey(0)

cv2.destroyAllWindows()

How to install a package inside virtualenv?

Well i don't have an appropriate reason regarding why this behavior occurs but then i just found a small work around

Inside the VirtualEnvironment

pip install -Iv package_name==version_number

now this will install the version in your virtual environment

Additionally you can check inside the virtual environment with this

pip install yolk
yolk -l

This shall give you the details of all the installed packages in both the locations(system and virtualenv)

While some might say its not appropriate to use --system-site-packages (it may be true), but what if you have already done a lot of stuffs inside your virtualenv? Now you dont want to redo everything from the scratch.

You may use this as a hack and be careful from the next time :)

How to get pandas.DataFrame columns containing specific dtype

To get the column names from pandas dataframe in python3- Here I am creating a data frame from a fileName.csv file

>>> import pandas as pd
>>> df = pd.read_csv('fileName.csv')
>>> columnNames = list(df.head(0)) 
>>> print(columnNames)

www-data permissions?

As stated in an article by Slicehost:

User setup

So let's start by adding the main user to the Apache user group:

sudo usermod -a -G www-data demo

That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.

You will need to log out and log back in again to enable the group change.

Check the groups now:

groups
...
# demo www-data

So now I am a member of two groups: My own (demo) and the Apache group (www-data).

Folder setup

Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).

Let's set that up:

sudo chgrp -R www-data /home/demo/public_html

As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.

If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.

Setgid

Good so far, but remember the command we just gave only affects existing folders. What about anything new?

We can set the ownership so anything new is also in the 'www-data' group.

The first command will change the permissions for the public_html directory to include the "setgid" bit:

sudo chmod 2750 /home/demo/public_html

That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.

If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:

sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads

The permissions only need to be set once as new files will automatically be assigned the correct ownership.

How to print VARCHAR(MAX) using Print Statement?

create procedure dbo.PrintMax @text nvarchar(max)
as
begin
    declare @i int, @newline nchar(2), @print varchar(max); 
    set @newline = nchar(13) + nchar(10);
    select @i = charindex(@newline, @text);
    while (@i > 0)
    begin
        select @print = substring(@text,0,@i);
        while (len(@print) > 8000)
        begin
            print substring(@print,0,8000);
            select @print = substring(@print,8000,len(@print));
        end
        print @print;
        select @text = substring(@text,@i+2,len(@text));
        select @i = charindex(@newline, @text);
    end
    print @text;
end

Is there a portable way to get the current username in Python?

Using only standard python libs:

from os import environ,getcwd
getUser = lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"]
user = getUser()

Works on Windows (if you are on drive C), Mac or Linux

Alternatively, you could remove one line with an immediate invocation:

from os import environ,getcwd
user = (lambda: environ["USERNAME"] if "C:" in getcwd() else environ["USER"])()

React - uncaught TypeError: Cannot read property 'setState' of undefined

You have to bind your methods with 'this' (default object). So whatever your function may be just bind that in the constructor.

constructor(props) {
    super(props);
    this.state = { checked:false };

    this.handleChecked = this.handleChecked.bind(this);
}

handleChecked(){
    this.setState({
        checked: !(this.state.checked)
    })
}

render(){
    var msg;

    if(this.state.checked){
        msg = 'checked'
    }
    else{
        msg = 'not checked'
    }

    return (
        <div>               
            <input type='checkbox' defaultChecked = {this.state.checked} onChange = {this.handleChecked} />
            <h3>This is {msg}</h3>
        </div>
    );

In-place type conversion of a NumPy array

a = np.subtract(a, 0., dtype=np.float32)

UIImage resize (Scale proportion)

This change worked for me:

// The size returned by CGImageGetWidth(imgRef) & CGImageGetHeight(imgRef) is incorrect as it doesn't respect the image orientation!
// CGImageRef imgRef = [image CGImage];
// CGFloat width = CGImageGetWidth(imgRef);
// CGFloat height = CGImageGetHeight(imgRef);
//
// This returns the actual width and height of the photo (and hence solves the problem
CGFloat width = image.size.width; 
CGFloat height = image.size.height;
CGRect bounds = CGRectMake(0, 0, width, height);

Combine two tables that have no common fields

Select 
DISTINCT  t1.col,t2col
From table1 t1, table2 t2

OR

Select 
DISTINCT  t1.col,t2col
From table1 t1 
cross JOIN  table2 t2

if its hug data , its take long time ..

Pass object to javascript function

Answering normajeans' question about setting default value. Create a defaults object with same properties and merge with the arguments object

If using ES6:

    function yourFunction(args){
        let defaults = {opt1: true, opt2: 'something'};
        let params = {...defaults, ...args}; // right-most object overwrites 
        console.log(params.opt1);
    }

Older Browsers using Object.assign(target, source):

    function yourFunction(args){
        var defaults = {opt1: true, opt2: 'something'};
        var params = Object.assign(defaults, args) // args overwrites as it is source
        console.log(params.opt1);
    }

Hiding the scroll bar on an HTML page

I think I found a workaround for you guys if you're still interested. This is my first week, but it worked for me...

<div class="contentScroller">
    <div class="content">
    </div>
</div>

.contentScroller {overflow-y: auto; visibility: hidden;}
.content {visibility: visible;}

Check mySQL version on Mac 10.8.5

To check your MySQL version on your mac, navigate to the directory where you installed it (default is usr/local/mysql/bin) and issue this command:

./mysql --version

Alternatively, to avoid needing to navigate to that specific dir to run the command, add its location to your path ($PATH). There's more than one way to add a dir to your $PATH (with explanations on stackoverflow and other places on how to do so), such as adding it to your ./bash_profile.

After adding the mysql bin dir to your $PATH, verify it's there by executing:

echo $PATH

Thereafter you can check your mysql version from anywhere by running (note no "./"):

mysql --version

Setting Access-Control-Allow-Origin in ASP.Net MVC - simplest possible method

For plain ASP.NET MVC Controllers

Create a new attribute

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
        base.OnActionExecuting(filterContext);
    }
}

Tag your action:

[AllowCrossSiteJson]
public ActionResult YourMethod()
{
    return Json("Works better?");
}

For ASP.NET Web API

using System;
using System.Web.Http.Filters;

public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        if (actionExecutedContext.Response != null)
            actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");

        base.OnActionExecuted(actionExecutedContext);
    }
}

Tag a whole API controller:

[AllowCrossSiteJson]
public class ValuesController : ApiController
{

Or individual API calls:

[AllowCrossSiteJson]
public IEnumerable<PartViewModel> Get()
{
    ...
}

For Internet Explorer <= v9

IE <= 9 doesn't support CORS. I've written a javascript that will automatically route those requests through a proxy. It's all 100% transparent (you just have to include my proxy and the script).

Download it using nuget corsproxy and follow the included instructions.

Blog post | Source code

File being used by another process after using File.Create()

I think I know the reason for this exception. You might be running this code snippet in multiple threads.

How to simplify a null-safe compareTo() implementation?

One of the simple way of using NullSafe Comparator is to use Spring implementation of it, below is one of the simple example to refer :

public int compare(Object o1, Object o2) {
        ValidationMessage m1 = (ValidationMessage) o1;
        ValidationMessage m2 = (ValidationMessage) o2;
        int c;
        if (m1.getTimestamp() == m2.getTimestamp()) {
            c = NullSafeComparator.NULLS_HIGH.compare(m1.getProperty(), m2.getProperty());
            if (c == 0) {
                c = m1.getSeverity().compareTo(m2.getSeverity());
                if (c == 0) {
                    c = m1.getMessage().compareTo(m2.getMessage());
                }
            }
        }
        else {
            c = (m1.getTimestamp() > m2.getTimestamp()) ? -1 : 1;
        }
        return c;
    }

Where is the Postgresql config file: 'postgresql.conf' on Windows?

On my machine:

C:\Program Files (x86)\OpenERP 6.1-20121026-233219\PostgreSQL\data

Win32Exception (0x80004005): The wait operation timed out

The problem you are having is the query command is taking too long. I believe that the default timeout for a query to execute is 15 seconds. You need to set the CommandTimeout (in seconds) so that it is long enough for the command to complete its execution. The "CommandTimeout" is different than the "Connection Timeout" in your connection string and must be set for each command.

In your sql Selecting Event, use the command:

e.Command.CommandTimeout = 60

for example:

Protected Sub SqlDataSource1_Selecting(sender As Object, e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs)
    e.Command.CommandTimeout = 60
End Sub

How to select rows where column value IS NOT NULL using CodeIgniter's ActiveRecord?

And just to give you yet another option, you can use NOT ISNULL(archived) as your WHERE filter.

How to disable registration new users in Laravel

Laravel 5.7 introduced the following functionality:

Auth::routes(['register' => false]);

The currently possible options here are:

Auth::routes([
  'register' => false, // Registration Routes...
  'reset' => false, // Password Reset Routes...
  'verify' => false, // Email Verification Routes...
]);

For older Laravel versions just override showRegistrationForm() and register() methods in

  • AuthController for Laravel 5.0 - 5.4
  • Auth/RegisterController.php for Laravel 5.5
public function showRegistrationForm()
{
    return redirect('login');
}

public function register()
{

}

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

You need to use html helper, and you don't need to provide date format in model class. e.x :

@Html.TextBoxFor(m => m.ResgistrationhaseDate, "{0:dd/MM/yyyy}")

UITableView set to static cells. Is it possible to hide some of the cells programmatically?

In > Swift 2.2, I've combined few answers here.

Make an outlet from storyboard to link to your staticCell.

@IBOutlet weak var updateStaticCell: UITableViewCell!

override func viewDidLoad() {
    ...
    updateStaticCell.hidden = true
}

override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
    if indexPath.row == 0 {
        return 0
    } else {
        return super.tableView(tableView, heightForRowAtIndexPath: indexPath)
    }
}

I want to hide my first cell so I set the height to 0 as described above.

Reading rows from a CSV file in Python

Reading it columnwise is harder?

Anyway this reads the line and stores the values in a list:

for line in open("csvfile.csv"):
    csv_row = line.split() #returns a list ["1","50","60"]

Modern solution:

# pip install pandas
import pandas as pd 
df = pd.read_table("csvfile.csv", sep=" ")

How do I run a batch script from within a batch script?

If you wish to open the batch file in another window, use start. This way, you can basically run two scripts at the same time. In other words, you don't have to wait for the script you just called to finish. All examples below work:

start batch.bat
start call batch.bat
start cmd /c batch.bat

If you want to wait for the script to finish, try start /w call batch.bat, but the batch.bat has to end with exit.

How do I pass a class as a parameter in Java?

As you said GWT does not support reflection. You should use deferred binding instead of reflection, or third party library such as gwt-ent for reflection suppport at gwt layer.

Displaying Windows command prompt output and redirecting it to a file

Another variation is to split the pipe, and then re-direct the output as you like.

    @echo off
    for /f "tokens=1,* delims=:" %%P in ('findstr /n "^"') do (
      echo(%%Q
      echo(%%Q>&3
    )
    @exit/b %errorlevel%

Save the above to a .bat file. It splits text output on filestream 1 to filestream 3 also, which you can redirect as needed. In my examples below, I called the above script splitPipe.bat ...

    dir | splitPipe.bat  1>con  2>&1  3>my_stdout.log

    splitPipe.bat 2>nul < somefile.txt

PHP Fatal error: Cannot redeclare class

You must use require_once() function.

Android Webview - Webpage should fit the device screen

here's an updated version, not using deprecated methods, based upon @danh32's answer:

protected int getScale(Double contentWidth) {
    if(this.getActivity() != null) {
        DisplayMetrics displaymetrics = new DisplayMetrics();
        this.getActivity().getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
        Double val = displaymetrics.widthPixels / contentWidth * 100d;
        return val.intValue();
    } else {
        return 100;
    }
}

to be used alike:

int initialScale = this.getScale(420d);
this.mWebView.setInitialScale(initialScale);

How to kill a child process by the parent process?

In the parent process, fork()'s return value is the process ID of the child process. Stuff that value away somewhere for when you need to terminate the child process. fork() returns zero(0) in the child process.

When you need to terminate the child process, use the kill(2) function with the process ID returned by fork(), and the signal you wish to deliver (e.g. SIGTERM).

Remember to call wait() on the child process to prevent any lingering zombies.

Check if a key is down?

$('#mytextbox').keydown(function (e) {
            if (e.keyCode == 13) {
                if (e.altKey) {
                    alert("alt is pressed");
                }
            }
 });

if you press alt + enter, you will see the alert.

Check a radio button with javascript

Do not mix CSS/JQuery syntax (# for identifier) with native JS.

Native JS solution:

document.getElementById("_1234").checked = true;

JQuery solution:

$("#_1234").prop("checked", true);

Docker - Cannot remove dead container

In my case, I had to remove it with

rm -r /var/lib/docker/containers/<container-id>/

and it worked. Maybe that's how you solve it in docker version ~19. My docker version was 19.03.12,

how to configure lombok in eclipse luna

I have met with the exact same problem. And it turns out that the configuration file generated by gradle asks for java1.7.
While my system has java1.8 installed.

After modifying the compiler compliance level to 1.8. All things are working as expected.

What's the difference between Invoke() and BeginInvoke()

Do you mean Delegate.Invoke/BeginInvoke or Control.Invoke/BeginInvoke?

  • Delegate.Invoke: Executes synchronously, on the same thread.
  • Delegate.BeginInvoke: Executes asynchronously, on a threadpool thread.
  • Control.Invoke: Executes on the UI thread, but calling thread waits for completion before continuing.
  • Control.BeginInvoke: Executes on the UI thread, and calling thread doesn't wait for completion.

Tim's answer mentions when you might want to use BeginInvoke - although it was mostly geared towards Delegate.BeginInvoke, I suspect.

For Windows Forms apps, I would suggest that you should usually use BeginInvoke. That way you don't need to worry about deadlock, for example - but you need to understand that the UI may not have been updated by the time you next look at it! In particular, you shouldn't modify data which the UI thread might be about to use for display purposes. For example, if you have a Person with FirstName and LastName properties, and you did:

person.FirstName = "Kevin"; // person is a shared reference
person.LastName = "Spacey";
control.BeginInvoke(UpdateName);
person.FirstName = "Keyser";
person.LastName = "Soze";

Then the UI may well end up displaying "Keyser Spacey". (There's an outside chance it could display "Kevin Soze" but only through the weirdness of the memory model.)

Unless you have this sort of issue, however, Control.BeginInvoke is easier to get right, and will avoid your background thread from having to wait for no good reason. Note that the Windows Forms team has guaranteed that you can use Control.BeginInvoke in a "fire and forget" manner - i.e. without ever calling EndInvoke. This is not true of async calls in general: normally every BeginXXX should have a corresponding EndXXX call, usually in the callback.

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

This is a common issue when attempting to 'bubble' up data from a chain of stored procedures. A restriction in SQL Server is you can only have one INSERT-EXEC active at a time. I recommend looking at How to Share Data Between Stored Procedures which is a very thorough article on patterns to work around this type of problem.

For example a work around could be to turn Sp3 into a Table-valued function.

How do you add an action to a button programmatically in xcode

 UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
[button addTarget:self 
       action:@selector(aMethod1:)
forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"Show View" forState:UIControlStateNormal];
button.frame = CGRectMake(80.0, 210.0, 160.0, 40.0);
[view addSubview:button];   

JQuery datepicker language

Maybe you don't have a language file:

Language files are here: https://github.com/jquery/jquery-ui/tree/master/ui/i18n

A new localization should be created in a separate JavaScript file named ui.datepicker-.js. Within a document.ready event it should add a new entry into the $.datepicker.regional array, indexed by the language code, with the following attributes:

http://api.jqueryui.com/datepicker/

How to create a CPU spike with a bash command

I use stress for this kind of thing, you can tell it how many cores to max out.. it allows for stressing memory and disk as well.

Example to stress 2 cores for 60 seconds

stress --cpu 2 --timeout 60

What is the difference between field, variable, attribute, and property in Java POJOs?

Variables are comprised of fields and non-fields.

Fields can be either:

  1. Static fields or
  2. non-static fields also called instantiations e.g. x = F()

Non-fields can be either:

  1. local variables, the analog of fields but inside a methods rather than outside all of them, or
  2. parameters e.g. y in x = f(y)

In conclusion, the key distinction between variables is whether they are fields or non-fields, meaning whether they are inside a methods or outside all methods.

Basic Example (excuse me for my syntax, I am just a beginner)

Class {    
    //fields    

    method1 {              
         //non-fields    

    }    
}

How to install 2 Anacondas (Python 2 and 3) on Mac OS

There is no need to install Anaconda again. Conda, the package manager for Anaconda, fully supports separated environments. The easiest way to create an environment for Python 2.7 is to do

conda create -n python2 python=2.7 anaconda

This will create an environment named python2 that contains the Python 2.7 version of Anaconda. You can activate this environment with

source activate python2

This will put that environment (typically ~/anaconda/envs/python2) in front in your PATH, so that when you type python at the terminal it will load the Python from that environment.

If you don't want all of Anaconda, you can replace anaconda in the command above with whatever packages you want. You can use conda to install packages in that environment later, either by using the -n python2 flag to conda, or by activating the environment.

How do I install Maven with Yum?

Maven is packaged for Fedora since mid 2014, so it is now pretty easy. Just type

sudo dnf install maven

Now test the installation, just run maven in a random directory

mvn

And it will fail, because you did not specify a goal, e.g. mvn package

[INFO] Scanning for projects...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 0.102 s
[INFO] Finished at: 2017-11-14T13:45:00+01:00
[INFO] Final Memory: 8M/176M
[INFO] ------------------------------------------------------------------------
[ERROR] No goals have been specified for this build

[...]

Uncaught SyntaxError: Unexpected token u in JSON at position 0

I had this issue for 2 days, let me show you how I fixed it.

This was how the code looked when I was getting the error:

request.onload = function() {
    // This is where we begin accessing the Json
    let data = JSON.parse(this.response);
    console.log(data)
}

This is what I changed to get the result I wanted:

request.onload = function() {
    // This is where we begin accessing the Json
    let data = JSON.parse(this.responseText);
    console.log(data)
}

So all I really did was change this.response to this.responseText.

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

Create a method similar to String.format() of Java

StringJoin=(s, r=[])=>{
  r.map((v,i)=>{
    s = s.replace('%'+(i+1),v)
  })
return s
}

use

console.log(StringJoin('I can %1 a %2',['create','method'])) //output: 'I can create a method'

What does a "Cannot find symbol" or "Cannot resolve symbol" error mean?

I too was getting this error. (for which I googled and I was directed to this page)

Problem: I was calling a static method defined in the class of a project A from a class defined in another project B. I was getting the following error:

error: cannot find symbol

Solution: I resolved this by first building the project where the method is defined then the project where the method was being called from.

How to give a Linux user sudo access?

Edit /etc/sudoers file either manually or using the visudo application. Remember: System reads /etc/sudoers file from top to the bottom, so you could overwrite a particular setting by putting the next one below. So to be on the safe side - define your access setting at the bottom.

How do I select the parent form based on which submit button is clicked?

You can select the form like this:

$("#submit").click(function(){
    var form = $(this).parents('form:first');
    ...
});

However, it is generally better to attach the event to the submit event of the form itself, as it will trigger even when submitting by pressing the enter key from one of the fields:

$('form#myform1').submit(function(e){
     e.preventDefault(); //Prevent the normal submission action
     var form = this;
     // ... Handle form submission
});

To select fields inside the form, use the form context. For example:

$("input[name='somename']",form).val();

Oracle SQL : timestamps in where clause

to_timestamp()

You need to use to_timestamp() to convert your string to a proper timestamp value:

to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

to_date()

If your column is of type DATE (which also supports seconds), you need to use to_date()

to_date('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')

Example

To get this into a where condition use the following:

select * 
from TableA 
where startdate >= to_timestamp('12-01-2012 21:24:00', 'dd-mm-yyyy hh24:mi:ss')
  and startdate <= to_timestamp('12-01-2012 21:25:33', 'dd-mm-yyyy hh24:mi:ss')

Note

You never need to use to_timestamp() on a column that is of type timestamp.

button image as form input submit button?

<div class="container-fluid login-container">
    <div class="row">
        <form (ngSubmit)="login('da')">
            <div class="col-md-4">
                    <div class="login-text">
                        Login
                    </div>
                    <div class="form-signin">
                            <input type="text" class="form-control" placeholder="Email" required>
                            <input type="password" class="form-control" placeholder="Password" required>
                    </div>
            </div>
            <div class="col-md-4">
                <div class="login-go-div">
                    <input type="image" src="../../../assets/images/svg/login-go-initial.svg" class="login-go"
                         onmouseover="this.src='../../../assets/images/svg/login-go.svg'"
                         onmouseout="this.src='../../../assets/images/svg/login-go-initial.svg'"/>
                </div>
            </div>
        </form>
    </div>
</div>

This is the working code for it.

How to show/hide JPanels in a JFrame?

If you want to hide panel on button click, write below code in JButton Action. I assume you want to hide jpanel1.

jpanel1.setVisible(false);

Short form for Java if statement

The way to do it is with ternary operator:

name = city.getName() == null ? city.getName() : "N/A"

However, I believe you have a typo in your code above, and you mean to say:

if (city.getName() != null) ...

good postgresql client for windows?

do you mean something like pgAdmin for administration?

Oracle copy data to another table

Creating a table and copying the data in a single command:

create table T_NEW as
  select * from T;

* This will not copy PKs, FKs, Triggers, etc.

Can't compare naive and aware datetime.now() <= challenge.datetime_end

By default, the datetime object is naive in Python, so you need to make both of them either naive or aware datetime objects. This can be done using:

import datetime
import pytz

utc=pytz.UTC

challenge.datetime_start = utc.localize(challenge.datetime_start) 
challenge.datetime_end = utc.localize(challenge.datetime_end) 
# now both the datetime objects are aware, and you can compare them

Note: This would raise a ValueError if tzinfo is already set. If you are not sure about that, just use

start_time = challenge.datetime_start.replace(tzinfo=utc)
end_time = challenge.datetime_end.replace(tzinfo=utc)

BTW, you could format a UNIX timestamp in datetime.datetime object with timezone info as following

d = datetime.datetime.utcfromtimestamp(int(unix_timestamp))
d_with_tz = datetime.datetime(
    year=d.year,
    month=d.month,
    day=d.day,
    hour=d.hour,
    minute=d.minute,
    second=d.second,
    tzinfo=pytz.UTC)

What does "to stub" mean in programming?

In this context, the word "stub" is used in place of "mock", but for the sake of clarity and precision, the author should have used "mock", because "mock" is a sort of stub, but for testing. To avoid further confusion, we need to define what a stub is.

In the general context, a stub is a piece of program (typically a function or an object) that encapsulates the complexity of invoking another program (usually located on another machine, VM, or process - but not always, it can also be a local object). Because the actual program to invoke is usually not located on the same memory space, invoking it requires many operations such as addressing, performing the actual remote invocation, marshalling/serializing the data/arguments to be passed (and same with the potential result), maybe even dealing with authentication/security, and so on. Note that in some contexts, stubs are also called proxies (such as dynamic proxies in Java).

A mock is a very specific and restrictive kind of stub, because a mock is a replacement of another function or object for testing. In practice we often use mocks as local programs (functions or objects) to replace a remote program in the test environment. In any case, the mock may simulate the actual behaviour of the replaced program in a restricted context.

Most famous kinds of stubs are obviously for distributed programming, when needing to invoke remote procedures (RPC) or remote objects (RMI, CORBA). Most distributed programming frameworks/libraries automate the generation of stubs so that you don't have to write them manually. Stubs can be generated from an interface definition, written with IDL for instance (but you can also use any language to define interfaces).

Typically, in RPC, RMI, CORBA, and so on, one distinguishes client-side stubs, which mostly take care of marshaling/serializing the arguments and performing the remote invocation, and server-side stubs, which mostly take care of unmarshaling/deserializing the arguments and actually execute the remote function/method. Obviously, client stubs are located on the client side, while sever stubs (often called skeletons) are located on the server side.

Writing good efficient and generic stubs becomes quite challenging when dealing with object references. Most distributed object frameworks such as RMI and CORBA deal with distributed objects references, but that's something most programmers avoid in REST environments for instance. Typically, in REST environments, JavaScript programmers make simple stub functions to encapsulate the AJAX invocations (object serialization being supported by JSON.parse and JSON.stringify). The Swagger Codegen project provides an extensive support for automatically generating REST stubs in various languages.

How to split a data frame?

If you want to split by values in one of the columns, you can use lapply. For instance, to split ChickWeight into a separate dataset for each chick:

data(ChickWeight)
lapply(unique(ChickWeight$Chick), function(x) ChickWeight[ChickWeight$Chick == x,])

Convert an array into an ArrayList

This will give you a list.

List<Card> cardsList = Arrays.asList(hand);

If you want an arraylist, you can do

ArrayList<Card> cardsList = new ArrayList<Card>(Arrays.asList(hand));

Checking if a field contains a string

If your regex includes a variable, make sure to escape it.

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

This can be used like this

new RegExp(escapeRegExp(searchString), 'i')

Or in a mongoDb query like this

{ '$regex': escapeRegExp(searchString) }

Posted same comment here

How to switch to new window in Selenium for Python?

window_handles should give you the references to all open windows.

this is what the docu has to say about switching windows.

MySQL timestamp select date range

A compact, flexible method for timestamps without fractional seconds would be:

SELECT * FROM table_name 
WHERE field_name 
BETWEEN UNIX_TIMESTAMP('2010-10-01') AND UNIX_TIMESTAMP('2010-10-31 23:59:59')

If you are using fractional seconds and a recent version of MySQL then you would be better to take the approach of using the >= and < operators as per Wouter's answer.

Here is an example of temporal fields defined with fractional second precision (maximum precision in use):

mysql> create table time_info (t_time time(6), t_datetime datetime(6), t_timestamp timestamp(6), t_short timestamp null);
Query OK, 0 rows affected (0.02 sec)

mysql> insert into time_info set t_time = curtime(6), t_datetime = now(6), t_short = t_datetime;
Query OK, 1 row affected (0.01 sec)

mysql> select * from time_info;
+-----------------+----------------------------+----------------------------+---------------------+
| 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34.378453 | 2016-01-11 22:05:34 |
+-----------------+----------------------------+----------------------------+---------------------+
1 row in set (0.00 sec)

Best practices for catching and re-throwing .NET exceptions

If you throw a new exception with the initial exception you will preserve the initial stack trace too..

try{
} 
catch(Exception ex){
     throw new MoreDescriptiveException("here is what was happening", ex);
}

Python OpenCV2 (cv2) wrapper to get image size?

cv2 uses numpy for manipulating images, so the proper and best way to get the size of an image is using numpy.shape. Assuming you are working with BGR images, here is an example:

>>> import numpy as np
>>> import cv2
>>> img = cv2.imread('foo.jpg')
>>> height, width, channels = img.shape
>>> print height, width, channels
  600 800 3

In case you were working with binary images, img will have two dimensions, and therefore you must change the code to: height, width = img.shape

How make background image on newsletter in outlook?

Powerful tool for "Bulletproof Email Background Images" (VML for Outlook 2007/2010/2013, and HTML/CSS for Outlook 2000/2003, Gmail, Hotmail...)

http://emailbg.net

as an exemple :

    <div style="background-color:#f6f6f6;">
  <!--[if gte mso 9]>
  <v:background xmlns:v="urn:schemas-microsoft-com:vml" fill="t">
    <v:fill type="tile" src="http://i.imgur.com/n8Q6f.png" color="#f6f6f6"/>
  </v:background>
  <![endif]-->
  <table height="100%" width="100%" cellpadding="0" cellspacing="0" border="0">
    <tr>
      <td valign="top" align="left" background="http://i.imgur.com/n8Q6f.png">
      </td>
    </tr>
  </table>
</div>

in order to have the specified background image to Full email body.

This link help to use the Vector Markup Language (VML)

msdn.microsoft.com/en-us/library/bb264137%28v=vs.85%29.aspx

www.w3.org/TR/NOTE-VML#_Toc416858389

java.util.Date and getYear()

        try{ 
int year = Integer.parseInt(new Date().toString().split("-")[0]); 
} 
catch(NumberFormatException e){
}

Much of Date is deprecated.

Change input text border color without changing its height

use this, it won't effect height:

<input type="text" style="border:1px solid #ff0000" />

Filtering a data frame by values in a column

Try this:

subset(studentdata, Drink=='water')

that should do it.

What are sessions? How do they work?

Because HTTP is stateless, in order to associate a request to any other request, you need a way to store user data between HTTP requests.

Cookies or URL parameters ( for ex. like http://example.com/myPage?asd=lol&boo=no ) are both suitable ways to transport data between 2 or more request. However they are not good in case you don't want that data to be readable/editable on client side.

The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented. Or you can use the client as a convenient remote storage, but you would encrypt the data and keep the secret server-side.

Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.

In your specific example, the user id (could be username or another unique ID in your user database) is stored in the session data, server-side, after successful identification. Then for every HTTP request you get from the client, the session id (given by the client) will point you to the correct session data (stored by the server) that contains the authenticated user id - that way your code will know what user it is talking to.

How do I retrieve a textbox value using JQuery?

You need to use the val() function to get the textbox value. text does not exist as a property only as a function and even then its not the correct function to use in this situation.

var from = $("input#fromAddress").val()

val() is the standard function for getting the value of an input.

"Operation must use an updateable query" error in MS Access

You have to remove the IMEX=1 if you want to update. ;)

"IMEX=1; tells the driver to always read "intermixed" (numbers, dates, strings etc) data columns as text. Note that this option might affect excel sheet write access negative." https://www.connectionstrings.com/excel/

Get number of digits with JavaScript

Note : This function will ignore the numbers after the decimal mean dot, If you wanna count with decimal then remove the Math.floor(). Direct to the point check this out!

function digitCount ( num )
{
     return Math.floor( num.toString()).length;
}

 digitCount(2343) ;

// ES5+

 const digitCount2 = num => String( Math.floor( Math.abs(num) ) ).length;

 console.log(digitCount2(3343))

Basically What's going on here. toString() and String() same build-in function for converting digit to string, once we converted then we'll find the length of the string by build-in function length.

Alert: But this function wouldn't work properly for negative number, if you're trying to play with negative number then check this answer Or simple put Math.abs() in it;

Cheer You!

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Suppose I have the following table T:

a   b
--------
1   abc
1   def
1   ghi
2   jkl
2   mno
2   pqr

And I do the following query:

SELECT a, b
FROM T
GROUP BY a

The output should have two rows, one row where a=1 and a second row where a=2.

But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.

This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).

Fixing it might look like this:

SELECT a, MAX(b) AS x
FROM T
GROUP BY a

Now it's clear that you want the following result:

a   x
--------
1   ghi
2   pqr

How can I get new selection in "select" in Angular 2?

In Angular 8 you can simply use "selectionChange" like this:

 <mat-select  [(value)]="selectedData" (selectionChange)="onChange()" >
  <mat-option *ngFor="let i of data" [value]="i.ItemID">
  {{i.ItemName}}
  </mat-option>
 </mat-select>

WCF service maxReceivedMessageSize basicHttpBinding issue

When using HTTPS instead of ON the binding, put it IN the binding with the httpsTransport tag:

    <binding name="MyServiceBinding">
      <security defaultAlgorithmSuite="Basic256Rsa15" 
                authenticationMode="MutualCertificate" requireDerivedKeys="true" 
                securityHeaderLayout="Lax" includeTimestamp="true" 
                messageProtectionOrder="SignBeforeEncrypt" 
                messageSecurityVersion="WSSecurity10WSTrust13WSSecureConversation13WSSecurityPolicy12BasicSecurityProfile10"
                requireSignatureConfirmation="false">
        <localClientSettings detectReplays="true" />
        <localServiceSettings detectReplays="true" />
        <secureConversationBootstrap keyEntropyMode="CombinedEntropy" />
      </security>
      <textMessageEncoding messageVersion="Soap11WSAddressing10">
        <readerQuotas maxDepth="2147483647" maxStringContentLength="2147483647" 
                      maxArrayLength="2147483647" maxBytesPerRead="4096" 
                      maxNameTableCharCount="16384"/>
      </textMessageEncoding>
      <httpsTransport maxReceivedMessageSize="2147483647" 
                      maxBufferSize="2147483647" maxBufferPoolSize="2147483647" 
                      requireClientCertificate="false" />
    </binding>

R: `which` statement with multiple conditions

The && function is not vectorized. You need the & function:

EUR <- PCs[which(PCs$V13 < 9 & PCs$V13 > 3), ]

Get exception description and stack trace which caused an exception, all as a string

If you would like to get the same information given when an exception isn't handled you can do something like this. Do import traceback and then:

try:
    ...
except Exception as e:
    print(traceback.print_tb(e.__traceback__))

I'm using Python 3.7.

Set ImageView width and height programmatically?

The best and easiest way to set a button dynamically is

 Button index=new Button(this);
 int height = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 45, getResources().getDisplayMetrics());             
 int width = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 42, getResources().getDisplayMetrics());

The above height and width are in pixels px. 45 being the height in dp and 42 being the width in dp.

 index.setLayoutParams(new <Parent>.LayoutParams(width, height));

So, for example, if you've placed your button within a TableRow within a TableLayout, you should have it as TableRow.LayoutParams

 index.setLayoutParams(new TableRow.LayoutParams(width, height));

How are people unit testing with Entity Framework 6, should you bother?

I would not unit test code I don't own. What are you testing here, that the MSFT compiler works?

That said, to make this code testable, you almost HAVE to make your data access layer separate from your business logic code. What I do is take all of my EF stuff and put it in a (or multiple) DAO or DAL class which also has a corresponding interface. Then I write my service which will have the DAO or DAL object injected in as a dependency (constructor injection preferably) referenced as the interface. Now the part that needs to be tested (your code) can easily be tested by mocking out the DAO interface and injecting that into your service instance inside your unit test.

//this is testable just inject a mock of IProductDAO during unit testing
public class ProductService : IProductService
{
    private IProductDAO _productDAO;

    public ProductService(IProductDAO productDAO)
    {
        _productDAO = productDAO;
    }

    public List<Product> GetAllProducts()
    {
        return _productDAO.GetAll();
    }

    ...
}

I would consider live Data Access Layers to be part of integration testing, not unit testing. I have seen guys run verifications on how many trips to the database hibernate makes before, but they were on a project that involved billions of records in their datastore and those extra trips really mattered.

How do I make Git use the editor of my choice for commits?

there is a list of commad that you can use but for vs code use this

 git config --global core.editor "code --wait"

this is the link for all editor :https://git-scm.com/book/en/v2/Appendix-C%3A-Git-Commands-Setup-and-Config

PHP file_get_contents() and setting request headers

Actually, upon further reading on the file_get_contents() function:

// Create a stream
$opts = [
    "http" => [
        "method" => "GET",
        "header" => "Accept-language: en\r\n" .
            "Cookie: foo=bar\r\n"
    ]
];

// DOCS: https://www.php.net/manual/en/function.stream-context-create.php
$context = stream_context_create($opts);

// Open the file using the HTTP headers set above
// DOCS: https://www.php.net/manual/en/function.file-get-contents.php
$file = file_get_contents('http://www.example.com/', false, $context);

You may be able to follow this pattern to achieve what you are seeking to, I haven't personally tested this though. (and if it doesn't work, feel free to check out my other answer)

Create a shortcut on Desktop

For Windows Vista/7/8/10, you can create a symlink instead via mklink.

Process.Start("cmd.exe", $"/c mklink {linkName} {applicationPath}");

Alternatively, call CreateSymbolicLink via P/Invoke.

Getting DOM elements by classname

If you wish to get the innerhtml of the class without the zend you could use this:

$dom = new DomDocument();
$dom->load($filePath);
$classname = 'main-article';
$finder = new DomXPath($dom);
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(@class), ' '), ' $classname ')]");
$tmp_dom = new DOMDocument(); 
foreach ($nodes as $node) 
    {
    $tmp_dom->appendChild($tmp_dom->importNode($node,true));
    }
$innerHTML.=trim($tmp_dom->saveHTML()); 
echo $innerHTML;

Difference between StringBuilder and StringBuffer

A String is an immutable object which means the value cannot be changed whereas StringBuffer is mutable.

The StringBuffer is Synchronized hence thread-safe whereas StringBuilder is not and suitable for only single-threaded instances.

How to use Python's "easy_install" on Windows ... it's not so easy

If you are using Anaconda's Python distribution,

you can install it through pip

pip install setuptools

and then execute it as a module

python -m easy_install

How can I apply styles to multiple classes at once?

just seperate the class name with a comma.

.a,.b{
your styles
}

converting list to json format - quick and easy way

I would avoid rolling your own and use either:

System.Web.Script.JavascriptSerializer

or

JSON.net

Both will do an excellent job :)

Set font-weight using Bootstrap classes

Create in your Site.css (or in another place) a new class named for example .font-bold and set it to your element

.font-bold {
  font-weight: bold;
}

What is the Python equivalent of Matlab's tic and toc functions?

You can use tic and toc from ttictoc. Install it with

pip install ttictoc

And just import them in your script as follow

from ttictoc import tic,toc
tic()
# Some code
print(toc())

libpng warning: iCCP: known incorrect sRGB profile

Here is a ridiculously brute force answer:

I modified the gradlew script. Here is my new exec command at the end of the file in the

exec "$JAVACMD" "${JVM_OPTS[@]}" -classpath "$CLASSPATH" org.gradle.wrapper.GradleWrapperMain "$@" **| grep -v "libpng warning:"**

Show data on mouseover of circle

I assume that what you want is a tooltip. The easiest way to do this is to append an svg:title element to each circle, as the browser will take care of showing the tooltip and you don't need the mousehandler. The code would be something like

vis.selectAll("circle")
   .data(datafiltered).enter().append("svg:circle")
   ...
   .append("svg:title")
   .text(function(d) { return d.x; });

If you want fancier tooltips, you could use tipsy for example. See here for an example.

c# - How to get sum of the values from List?

You can use the Sum function, but you'll have to convert the strings to integers, like so:

int total = monValues.Sum(x => Convert.ToInt32(x));

C# Linq Where Date Between 2 Dates

If you have date interval filter condition and you need to select all records which falls partly into this filter range. Assumption: records has ValidFrom and ValidTo property.

DateTime intervalDateFrom = new DateTime(1990, 01, 01);
DateTime intervalDateTo = new DateTime(2000, 01, 01);

var itemsFiltered = allItems.Where(x=> 
    (x.ValidFrom >= intervalDateFrom && x.ValidFrom <= intervalDateTo) ||
    (x.ValidTo >= intervalDateFrom && x.ValidTo <= intervalDateTo) ||
    (intervalDateFrom >= x.ValidFrom && intervalDateFrom <= x.ValidTo) ||
    (intervalDateTo >= x.ValidFrom && intervalDateTo <= x.ValidTo)
);

How to write to error log file in PHP

you can simply use :

error_log("your message");

By default, the message will be send to the php system logger.

Include php files when they are in different folders

You can get to the root from within each site using $_SERVER['DOCUMENT_ROOT']. For testing ONLY you can echo out the path to make sure it's working, if you do it the right way. You NEVER want to show the local server paths for things like includes and requires.

Site 1

echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/';

Includes under site one would be at:

echo $_SERVER['DOCUMENT_ROOT'].'/includes/'; // should be '/main_web_folder/includes/';

Site 2

echo $_SERVER['DOCUMENT_ROOT']; //should be '/main_web_folder/blog/';

The actual code to access includes from site1 inside of site2 you would say:

include($_SERVER['DOCUMENT_ROOT'].'/../includes/file_from_site_1.php');

It will only use the relative path of the file executing the query if you try to access it by excluding the document root and the root slash:

 //(not as fool-proof or non-platform specific)
 include('../includes/file_from_site_1.php');

Included paths have no place in code on the front end (live) of the site anywhere, and should be secured and used in production environments only.

Additionally for URLs on the site itself you can make them relative to the domain. Browsers will automatically fill in the rest because they know which page they are looking at. So instead of:

<a href='http://www.__domain__name__here__.com/contact/'>Contact</a>

You should use:

<a href='/contact/'>Contact</a>

For good SEO you'll want to make sure that the URLs for the blog do not exist in the other domain, otherwise it may be marked as a duplicate site. With that being said you might also want to add a line to your robots.txt file for ONLY site1:

User-agent: *
Disallow: /blog/

Other possibilities:

Look up your IP address and include this snippet of code:

function is_dev(){
  //use the external IP from Google.
  //If you're hosting locally it's 127.0.01 unless you've changed it.
  $ip_address='xxx.xxx.xxx.xxx';

  if ($_SERVER['REMOTE_ADDR']==$ip_address){
     return true;
  } else {
     return false;
  } 
}

if(is_dev()){
    echo $_SERVER['DOCUMENT_ROOT'];       
}

Remember if your ISP changes your IP, as in you have a DCHP Dynamic IP, you'll need to change the IP in that file to see the results. I would put that file in an include, then require it on pages for debugging.

If you're okay with modern methods like using the browser console log you could do this instead and view it in the browser's debugging interface:

if(is_dev()){
    echo "<script>".PHP_EOL;
    echo "console.log('".$_SERVER['DOCUMENT_ROOT']."');".PHP_EOL;
    echo "</script>".PHP_EOL;       
}

Maven does not find JUnit tests to run

In my case we are migration multimodule application to Spring Boot. Unfortunately maven didnt execute all tests anymore in the modules. The naming of the Test Classes didnt change, we are following the naming conventions.

At the end it helped, when I added the dependency surefire-junit47 to the plugin maven-surefire-plugin. But I could not explain, why, it was trial and error:

<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<dependencies>
  <dependency>
    <groupId>org.apache.maven.surefire</groupId>
    <artifactId>surefire-junit47</artifactId>
    <version>${maven-surefire-plugin.version}</version>
  </dependency>
</dependencies>

Symfony2 Setting a default choice field selection

the solution: for type entity use option "data" but value is a object. ie:

$em = $this->getDoctrine()->getEntityManager();

->add('sucursal', 'entity', array
(

    'class' => 'TestGeneralBundle:Sucursal',
    'property'=>'descripcion',
    'label' => 'Sucursal',
    'required' => false,
    'data'=>$em->getReference("TestGeneralBundle:Sucursal",3)           

))

System.Collections.Generic.IEnumerable' does not contain any definition for 'ToList'

In my case, I had copied some code from another project that was using Automapper - took me ages to work that one out. Just had to add automapper nuget package to project.

Npm Error - No matching version found for

Try removing package-lock.json file first

H2 database error: Database may be already in use: "Locked by another process"

If you are running same app into multiple ports where app uses single database (h2), then add AUTO_SERVER=TRUE in the url as follows:

jdbc:h2:file:C:/simple-commerce/price;DB_CLOSE_ON_EXIT=FALSE;AUTO_RECONNECT=TRUE;AUTO_SERVER=TRUE

Package opencv was not found in the pkg-config search path

I installed opencv following the steps on https://docs.opencv.org/trunk/d7/d9f/tutorial_linux_install.html

Except on Step 2, use: cmake -D CMAKE_BUILD_TYPE=Release -D OPENCV_GENERATE_PKGCONFIG=YES -D CMAKE_INSTALL_PREFIX=/path/to/opencv/ ..

Then locate the opencv4.pc file, mine was in opencv/build/unix-install/

Now run: $ export PKG_CONFIG_PATH=/path/to/the/file

AngularJS $watch window resize inside directive

You can listen resize event and fire where some dimension change

directive

(function() {
'use strict';

    angular
    .module('myApp.directives')
    .directive('resize', ['$window', function ($window) {
        return {
            link: link,
            restrict: 'A'
        };

        function link(scope, element, attrs){
            scope.width = $window.innerWidth;
            function onResize(){
                // uncomment for only fire when $window.innerWidth change   
                // if (scope.width !== $window.innerWidth)
                {
                    scope.width = $window.innerWidth;
                    scope.$digest();
                }
            };

            function cleanUp() {
                angular.element($window).off('resize', onResize);
            }

            angular.element($window).on('resize', onResize);
            scope.$on('$destroy', cleanUp);
        }
    }]);
})();

In html

<div class="row" resize> ,
    <div class="col-sm-2 col-xs-6" ng-repeat="v in tag.vod"> 
        <h4 ng-bind="::v.known_as"></h4>
    </div> 
</div> 

Controller :

$scope.$watch('width', function(old, newv){
     console.log(old, newv);
 })

How to use in jQuery :not and hasClass() to get a specific element without a class

You can also use jQuery - is(selector) Method:

var lastOpenSite = $(this).siblings().is(':not(.closedTab)');

Calling a parent window function from an iframe

You can use

window.top

see the following.

<head>
    <script>
    function abc() {
        alert("sss");
    }
    </script>
</head>
<body>
    <iframe id="myFrame">
        <a onclick="window.top.abc();" href="#">Click Me</a>
    </iframe>
</body>

How to cast or convert an unsigned int to int in C?

If an unsigned int and a (signed) int are used in the same expression, the signed int gets implicitly converted to unsigned. This is a rather dangerous feature of the C language, and one you therefore need to be aware of. It may or may not be the cause of your bug. If you want a more detailed answer, you'll have to post some code.

Rename a column in MySQL

From MySQL 5.7 Reference Manual.

Syntax :

ALTER TABLE t1 CHANGE a b DATATYPE;

e.g. : for Customer TABLE having COLUMN customer_name, customer_street, customercity.

And we want to change customercity TO customer_city :

alter table customer change customercity customer_city VARCHAR(225);

What is the C++ function to raise a number to a power?

Use the pow(x,y) function: See Here

Just include math.h and you're all set.

Why is this HTTP request not working on AWS Lambda?

Of course, I was misunderstanding the problem. As AWS themselves put it:

For those encountering nodejs for the first time in Lambda, a common error is forgetting that callbacks execute asynchronously and calling context.done() in the original handler when you really meant to wait for another callback (such as an S3.PUT operation) to complete, forcing the function to terminate with its work incomplete.

I was calling context.done way before any callbacks for the request fired, causing the termination of my function ahead of time.

The working code is this:

var http = require('http');

exports.handler = function(event, context) {
  console.log('start request to ' + event.url)
  http.get(event.url, function(res) {
    console.log("Got response: " + res.statusCode);
    context.succeed();
  }).on('error', function(e) {
    console.log("Got error: " + e.message);
    context.done(null, 'FAILURE');
  });

  console.log('end request to ' + event.url);
}

Update: starting 2017 AWS has deprecated the old Nodejs 0.10 and only the newer 4.3 run-time is now available (old functions should be updated). This runtime introduced some changes to the handler function. The new handler has now 3 parameters.

function(event, context, callback)

Although you will still find the succeed, done and fail on the context parameter, AWS suggest to use the callback function instead or null is returned by default.

callback(new Error('failure')) // to return error
callback(null, 'success msg') // to return ok

Complete documentation can be found at http://docs.aws.amazon.com/lambda/latest/dg/nodejs-prog-model-handler.html

How to convert string to boolean in typescript Angular 4

Boolean("true") will do the work too

Can we rely on String.isEmpty for checking null condition on a String in Java?

No, absolutely not - because if acct is null, it won't even get to isEmpty... it will immediately throw a NullPointerException.

Your test should be:

if (acct != null && !acct.isEmpty())

Note the use of && here, rather than your || in the previous code; also note how in your previous code, your conditions were wrong anyway - even with && you would only have entered the if body if acct was an empty string.

Alternatively, using Guava:

if (!Strings.isNullOrEmpty(acct))

makefile execute another target

Actually you are right: it runs another instance of make. A possible solution would be:

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : clean clearscr all

clearscr:
    clear

By calling make fresh you get first the clean target, then the clearscreen which runs clear and finally all which does the job.

EDIT Aug 4

What happens in the case of parallel builds with make’s -j option? There's a way of fixing the order. From the make manual, section 4.2:

Occasionally, however, you have a situation where you want to impose a specific ordering on the rules to be invoked without forcing the target to be updated if one of those rules is executed. In that case, you want to define order-only prerequisites. Order-only prerequisites can be specified by placing a pipe symbol (|) in the prerequisites list: any prerequisites to the left of the pipe symbol are normal; any prerequisites to the right are order-only: targets : normal-prerequisites | order-only-prerequisites

The normal prerequisites section may of course be empty. Also, you may still declare multiple lines of prerequisites for the same target: they are appended appropriately. Note that if you declare the same file to be both a normal and an order-only prerequisite, the normal prerequisite takes precedence (since they are a strict superset of the behavior of an order-only prerequisite).

Hence the makefile becomes

.PHONY : clearscr fresh clean all

all :
    compile executable

clean :
    rm -f *.o $(EXEC)

fresh : | clean clearscr all

clearscr:
    clear

EDIT Dec 5

It is not a big deal to run more than one makefile instance since each command inside the task will be a sub-shell anyways. But you can have reusable methods using the call function.

log_success = (echo "\x1B[32m>> $1\x1B[39m")
log_error = (>&2 echo "\x1B[31m>> $1\x1B[39m" && exit 1)

install:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  command1  # this line will be a subshell
  command2  # this line will be another subshell
  @command3  # Use `@` to hide the command line
  $(call log_error, "It works, yey!")

uninstall:
  @[ "$(AWS_PROFILE)" ] || $(call log_error, "AWS_PROFILE not set!")
  ....
  $(call log_error, "Nuked!")

How to get annotations of a member variable?

Everybody describes issue with getting annotations, but the problem is in definition of your annotation. You should to add to your annotation definition a @Retention(RetentionPolicy.RUNTIME):

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface MyAnnotation{
    int id();
}

How to call Stored Procedures with EntityFramework?

Based up the OP's original request to be able to called a stored proc like this...

using (Entities context = new Entities())
{
    context.MyStoreadProcedure(Parameters); 
}

Mindless passenger has a project that allows you to call a stored proc from entity frame work like this....

using (testentities te = new testentities())
{
    //-------------------------------------------------------------
    // Simple stored proc
    //-------------------------------------------------------------
    var parms1 = new testone() { inparm = "abcd" };
    var results1 = te.CallStoredProc<testone>(te.testoneproc, parms1);
    var r1 = results1.ToList<TestOneResultSet>();
}

... and I am working on a stored procedure framework (here) which you can call like in one of my test methods shown below...

[TestClass]
public class TenantDataBasedTests : BaseIntegrationTest
{
    [TestMethod]
    public void GetTenantForName_ReturnsOneRecord()
    {
        // ARRANGE
        const int expectedCount = 1;
        const string expectedName = "Me";

        // Build the paraemeters object
        var parameters = new GetTenantForTenantNameParameters
        {
            TenantName = expectedName
        };

        // get an instance of the stored procedure passing the parameters
        var procedure = new GetTenantForTenantNameProcedure(parameters);

        // Initialise the procedure name and schema from procedure attributes
        procedure.InitializeFromAttributes();

        // Add some tenants to context so we have something for the procedure to return!
        AddTenentsToContext(Context);

        // ACT
        // Get the results by calling the stored procedure from the context extention method 
        var results = Context.ExecuteStoredProcedure(procedure);

        // ASSERT
        Assert.AreEqual(expectedCount, results.Count);
    }
}

internal class GetTenantForTenantNameParameters
{
    [Name("TenantName")]
    [Size(100)]
    [ParameterDbType(SqlDbType.VarChar)]
    public string TenantName { get; set; }
}

[Schema("app")]
[Name("Tenant_GetForTenantName")]
internal class GetTenantForTenantNameProcedure
    : StoredProcedureBase<TenantResultRow, GetTenantForTenantNameParameters>
{
    public GetTenantForTenantNameProcedure(
        GetTenantForTenantNameParameters parameters)
        : base(parameters)
    {
    }
}

If either of those two approaches are any good?

Display current time in 12 hour format with AM/PM

SimpleDateFormat formatDate = new SimpleDateFormat("hh:mm:ss a");
  • h is used for AM/PM times (1-12).

  • H is used for 24 hour times (1-24).

  • a is the AM/PM marker

  • m is minute in hour

Note: Two h's will print a leading zero: 01:13 PM. One h will print without the leading zero: 1:13 PM.

Looks like basically everyone beat me to it already, but I digress

PHPDoc type hinting for array of objects?

Netbeans hints:

You get code completion on $users[0]-> and for $this-> for an array of User classes.

/**
 * @var User[]
 */
var $users = array();

You also can see the type of the array in a list of class members when you do completion of $this->...

Why both no-cache and no-store should be used in HTTP response?

If a caching system correctly implements no-store, then you wouldn't need no-cache. But not all do. Additionally, some browsers implement no-cache like it was no-store. Thus, while not strictly required, it's probably safest to include both.