Programs & Examples On #Biological neural network

Biological neural networks (BNNs) provide the inspiration for artificial neural network algorithms (ANNs). Sometimes, it is useful to return to this inspiration in understanding ANNs or coming up with modifications to them. This tag is for questions about how BNNs inform ANNs and related algorithms.

Take a list of numbers and return the average

The input() function returns a string which may contain a "list of numbers". You should have understood that the numbers[2] operation returns the third element of an iterable. A string is an iterable, but an iterable of characters, which isn't what you want - you want to average the numbers in the input string.

So there are two things you have to do before you can get to the averaging shown by garyprice:

  1. convert the input string into something containing just the number strings (you don't want the spaces between the numbers)
  2. convert each number string into an integer

Hint for step 1: you have to split the input string into non-space substrings.

Step 2 (convert string to integer) should be easy to find with google.

HTH

How to move a marker in Google Maps API

<style>
    #frame{
        position: fixed;
        top: 5%;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 6px #B2B2B2;
        display: inline-block;
        padding: 8px 8px;
        width: 98%;
        height: 92%;
        display: none;
        z-index: 1000;
    }
    #map{
        position: fixed;
        display: inline-block;
        width: 99%;
        height: 93%;
        display: none;
        z-index: 1000;
    }

    #loading{
        position: fixed;
        top: 50%;
        left: 50%;
        opacity: 1!important;
        margin-top: -100px;
        margin-left: -150px;
        background-color: #fff;
        border-radius: 5px;
        box-shadow: 0 0 6px #B2B2B2;
        display: inline-block;
        padding: 8px 8px;
        max-width: 66%;
        display: none;
        color: #000;

    }
    #mytitle{
        color: #FFF;
        background-image: linear-gradient(to bottom,#d67631,#d67631);
        //  border-color: rgba(47, 164, 35, 1);
        width: 100%;
        cursor: move;
    }
    #closex{ 
        display: block;
        float:right;
        position:relative;
        top:-10px;
        right: -10px;
        height: 20px;
        cursor: pointer;
    }
    .pointer{
        cursor: pointer !important;
    }

</style> 
<div id="loading">
    <i class="fa fa-circle-o-notch fa-spin fa-2x"></i>
    Loading...
</div>
<div id="frame">
    <div id="headerx"></div>
    <div id="map" >    
    </div>
</div>


<?php
$url = Yii::app()->baseUrl . '/reports/reports/transponderdetails';
?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>

<script>
    function clode() {
        $('#frame').hide();
        $('#frame').html();
    }
    function track(id) {
        $('#loading').show();
        $('#loading').parent().css("opacity", '0.7');


        $.ajax({
            type: "POST",
            url: '<?php echo $url; ?>',
            data: {'id': id},
            success: function(data) {
                $('#frame').show();
                $('#headerx').html(data);
                $('#loading').parents().css("opacity", '1');
                $('#loading').hide();
                var thelat = parseFloat($('#lat').text());
                var long = parseFloat($('#long').text());
                $('#map').show();
                var lat = thelat;
                var lng = long;
                var orlat=thelat;
                var orlong=long;
                //Intialize the Path Array
                var path = new google.maps.MVCArray();
                var service = new google.maps.DirectionsService();


                var myLatLng = new google.maps.LatLng(lat, lng), myOptions = {zoom: 4, center: myLatLng, mapTypeId: google.maps.MapTypeId.ROADMAP};
                var map = new google.maps.Map(document.getElementById('map'), myOptions);
                var poly = new google.maps.Polyline({map: map, strokeColor: '#4986E7'});
                var marker = new google.maps.Marker({position: myLatLng, map: map});

                function initialize() {
                    marker.setMap(map);
                    movepointer(map, marker);
                    var drawingManager = new google.maps.drawing.DrawingManager();
                    drawingManager.setMap(map);
                }

                function movepointer(map, marker) {
                    marker.setPosition(new google.maps.LatLng(lat, lng));
                    map.panTo(new google.maps.LatLng(lat, lng));

                    var src = myLatLng;//start point
                    var des = myLatLng;// should be the destination
                    path.push(src);
                    poly.setPath(path);
                    service.route({
                        origin: src,
                        destination: des,
                        travelMode: google.maps.DirectionsTravelMode.DRIVING
                    }, function(result, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
                            for (var i = 0, len = result.routes[0].overview_path.length; i < len; i++) {
                                path.push(result.routes[0].overview_path[i]);
                            }
                        }
                    });

                }
                ;

                // function()
                setInterval(function() {
                    lat = Math.random() + orlat;
                    lng = Math.random() + orlong;
                    console.log(lat + "-" + lng);
                    myLatLng = new google.maps.LatLng(lat, lng);
                    movepointer(map, marker);

                }, 1000);



            },
            error: function() {
                $('#frame').html('Sorry, no details found');
            },
        });
        return false;
    }
    $(function() {
        $("#frame").draggable();
    });

</script>

How to configure CORS in a Spring Boot + Spring Security application?

Kotlin solution

...
http.cors().configurationSource {
  CorsConfiguration().applyPermitDefaultValues()
}
...

How do I show the value of a #define at compile-time?

In Microsoft C/C++, you can use the built-in _CRT_STRINGIZE() to print constants. Many of my stdafx.h files contain some combination of these:

#pragma message("_MSC_VER      is " _CRT_STRINGIZE(_MSC_VER))
#pragma message("_MFC_VER      is " _CRT_STRINGIZE(_MFC_VER))
#pragma message("_ATL_VER      is " _CRT_STRINGIZE(_ATL_VER))
#pragma message("WINVER        is " _CRT_STRINGIZE(WINVER))
#pragma message("_WIN32_WINNT  is " _CRT_STRINGIZE(_WIN32_WINNT))
#pragma message("_WIN32_IE     is " _CRT_STRINGIZE(_WIN32_IE))
#pragma message("NTDDI_VERSION is " _CRT_STRINGIZE(NTDDI_VERSION)) 

and outputs something like this:

_MSC_VER      is 1915
_MFC_VER      is 0x0E00
_ATL_VER      is 0x0E00
WINVER        is 0x0600
_WIN32_WINNT  is 0x0600
_WIN32_IE     is 0x0700
NTDDI_VERSION is 0x06000000

How can I put a database under git (version control)?

Storing each level of database changes under git versioning control is like pushing your entire database with each commit and restoring your entire database with each pull. If your database is so prone to crucial changes and you cannot afford to loose them, you can just update your pre_commit and post_merge hooks. I did the same with one of my projects and you can find the directions here.

Adding a line break in MySQL INSERT INTO text

You can simply replace all \n with <br/> tag so that when page is displayed then it breaks line.

UPDATE table SET field = REPLACE(field, '\n', '<br/>')

Handler "ExtensionlessUrlHandler-Integrated-4.0" has a bad module "ManagedPipelineHandler" in its module list

Despite following most of the advice on this page, I was still getting problems on Windows Server 2012. Installing .NET Extensibility 4.5 solved it for me:

Add Roles and Features > Server Roles > Web Server (IIS) > Web Server > Application Development > .NET Extensibility 4.5

HAProxy redirecting http to https (ssl)

  acl host-example hdr(host) -i www.example.com

  # for everything not https
  http-request redirect scheme https code 301 unless { ssl_fc }

  # for anything matching acl
  http-request redirect scheme https code 301 if host-example !{ ssl_fc }

Android Button click go to another xml page

There is more than one way to do this.

Here is a good resource straight from Google: http://developer.android.com/training/basics/firstapp/starting-activity.html

At developer.android.com, they have numerous tutorials explaining just about everything you need to know about android. They even provide detailed API for each class.

If that doesn't help, there are NUMEROUS different resources that can help you with this question and other android questions.

How do I check OS with a preprocessor directive?

On MinGW, the _WIN32 define check isn't working. Here's a solution:

#if defined(_WIN32) || defined(__CYGWIN__)
    // Windows (x86 or x64)
    // ...
#elif defined(__linux__)
    // Linux
    // ...
#elif defined(__APPLE__) && defined(__MACH__)
    // Mac OS
    // ...
#elif defined(unix) || defined(__unix__) || defined(__unix)
    // Unix like OS
    // ...
#else
    #error Unknown environment!
#endif

For more information please look: https://sourceforge.net/p/predef/wiki/OperatingSystems/

How to convert md5 string to normal text?

The idea of MD5 is that is a one-way hashing, so it can't be once the original value has been passed through the hashing algorithm (if at all).

You could (potentially) create a database table with a pairing of the original and the MD5 values but I guess that's highly impractical and poses a major security risk.

Differences between strong and weak in Objective-C

strong and weak, these keywords revolves around Object Ownership in Objective-C

What is object ownership ?

Pointer variables imply ownership of the objects that they point to.

  • When a method (or function) has a local variable that points to an object, that variable is said to own the object being pointed to.
  • When an object has an instance variable that points to another object, the object with the pointer is said to own the object being pointed to.

Anytime a pointer variable points to an object, that object has an owner and will stay alive. This is known as a strong reference.

A variable can optionally not take ownership of an object that it points to. A variable that does not take ownership of an object is known as a weak reference.

Have a look for a detailed explanation here Demystifying @property and attributes

Open page in new window without popup blocking

This is the only one that actually worked for me in all the browsers

let newTab = window.open(); newTab.location.href = url;

Limit Get-ChildItem recursion depth

Use this to limit the depth to 2:

Get-ChildItem \*\*\*,\*\*,\*

The way it works is that it returns the children at each depth 2,1 and 0.


Explanation:

This command

Get-ChildItem \*\*\*

returns all items with a depth of two subfolders. Adding \* adds an additional subfolder to search in.

In line with the OP question, to limit a recursive search using get-childitem you are required to specify all the depths that can be searched.

How to download a folder from github?

You can download a file/folder from github

Simply use: svn export <repo>/trunk/<folder>

Ex: svn export https://github.com/lodash/lodash/trunk/docs

Note: You may first list the contents of the folder in terminal using svn ls <repo>/trunk/folder

(yes, that's svn here. apparently in 2016 you still need svn to simply download some github files)

TortoiseSVN Error: "OPTIONS of 'https://...' could not connect to server (...)"

This was driving me nuts and I solved it today. I'm posting in this old thread because I arrived here several times while searching for a solution. I hope it helps someone. For me, I checked svn-settings --> network --> Edit Subversion server file and found that there were some uncommented lines at the end:

http-proxy-host = 
ssl-trust-default-ca = no
http-proxy-username = 
http-proxy-password = 

that differed from my co-workers. Once I comment these, it started working again.

Redirecting to previous page after login? PHP

You should first get user refer page in a variable using $_SERVER['HTTP_REFERER']; in your login page.

LIKE:

<?php 
    session_start();
    $refPage = $_SERVER['HTTP_REFERER']; 
?>

And now when the user clicks to Login then change header location to user refer page

LIKE:

<?php 
if(isset($_POST[login])){
    session_start();
    header('location:' . $refPage);
}
?>

And in this time you should first check that user refers page empty or not because your user can visit direct your login page then your $refPage variable will be empty so after Click to Login page stays here

LIKE:

<?php
if(isset($_POST[login])){
    session_start();
    $refPage = $_SERVER['HTTP_REFERER'];  // get reffer page url
    if(empty($refPage)){ 
        header('location: yourredirectpage'); // if ref page is empty then set default redirect page.
    }else{
        header('location:' . $refPage); // or if ref page in not empty then redirect page to reffer page
    }
}
?>


Or you can use input type hidden where you can set value $_SERVER['HTTP_REFERER'];

LIKE:

<input type="hidden" name="refPage" value="<?php echo $_SERVER['HTTP_REFERER']; ?>">

And when a user clicks to Login then you can get the refPage value and redirect the previous page. And you should also check empty refer page. Because your user can visit direct your login page.


Thank you.

Filter Excel pivot table using VBA

Latest versions of Excel has a new tool called Slicers. Using slicers in VBA is actually more reliable that .CurrentPage (there have been reports of bugs while looping through numerous filter options). Here is a simple example of how you can select a slicer item (remember to deselect all the non-relevant slicer values):

Sub Step_Thru_SlicerItems2()
Dim slItem As SlicerItem
Dim i As Long
Dim searchName as string

Application.ScreenUpdating = False
searchName="Value1"

    For Each slItem In .VisibleSlicerItems
        If slItem.Name <> .SlicerItems(1).Name Then _
            slItem.Selected = False
        Else
            slItem.Selected = True
        End if
    Next slItem
End Sub

There are also services like SmartKato that would help you out with setting up your dashboards or reports and/or fix your code.

Detecting TCP Client Disconnect

"""
tcp_disconnect.py
Echo network data test program in python. This easily translates to C & Java.

A server program might want to confirm that a tcp client is still connected 
before it sends a data. That is, detect if its connected without reading from socket.
This will demonstrate how to detect a TCP client disconnect without reading data.

The method to do this:
1) select on socket as poll (no wait)
2) if no recv data waiting, then client still connected
3) if recv data waiting, the read one char using PEEK flag 
4) if PEEK data len=0, then client has disconnected, otherwise its connected.
Note, the peek flag will read data without removing it from tcp queue.

To see it in action: 0) run this program on one computer 1) from another computer, 
connect via telnet port 12345, 2) type a line of data 3) wait to see it echo, 
4) type another line, 5) disconnect quickly, 6) watch the program will detect the 
disconnect and exit.

John Masinter, 17-Dec-2008
"""

import socket
import time
import select

HOST = ''       # all local interfaces
PORT = 12345    # port to listen

# listen for new TCP connections
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind((HOST, PORT))
s.listen(1)
# accept new conneciton
conn, addr = s.accept()
print 'Connected by', addr
# loop reading/echoing, until client disconnects
try:
    conn.send("Send me data, and I will echo it back after a short delay.\n")
    while 1:
        data = conn.recv(1024)                          # recv all data queued
        if not data: break                              # client disconnected
        time.sleep(3)                                   # simulate time consuming work
        # below will detect if client disconnects during sleep
        r, w, e = select.select([conn], [], [], 0)      # more data waiting?
        print "select: r=%s w=%s e=%s" % (r,w,e)        # debug output to command line
        if r:                                           # yes, data avail to read.
            t = conn.recv(1024, socket.MSG_PEEK)        # read without remove from queue
            print "peek: len=%d, data=%s" % (len(t),t)  # debug output
            if len(t)==0:                               # length of data peeked 0?
                print "Client disconnected."            # client disconnected
                break                                   # quit program
        conn.send("-->"+data)                           # echo only if still connected
finally:
    conn.close()

How to get time difference in minutes in PHP

The answers above are for older versions of PHP. Use the DateTime class to do any date calculations now that PHP 5.3 is the norm. Eg.

$start_date = new DateTime('2007-09-01 04:10:58');
$since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
echo $since_start->days.' days total<br>';
echo $since_start->y.' years<br>';
echo $since_start->m.' months<br>';
echo $since_start->d.' days<br>';
echo $since_start->h.' hours<br>';
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';

$since_start is a DateInterval object. Note that the days property is available (because we used the diff method of the DateTime class to generate the DateInterval object).

The above code will output:

1837 days total
5 years
0 months
10 days
6 hours
14 minutes
2 seconds

To get the total number of minutes:

$minutes = $since_start->days * 24 * 60;
$minutes += $since_start->h * 60;
$minutes += $since_start->i;
echo $minutes.' minutes';

This will output:

2645654 minutes

Which is the actual number of minutes that has passed between the two dates. The DateTime class will take daylight saving (depending on timezone) into account where the "old way" won't. Read the manual about Date and Time http://www.php.net/manual/en/book.datetime.php

The CodeDom provider type "Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider" could not be located

I had a number of projects in the solution and the web project (problem giving this error) was not set as the StartUp project. I set this web project as the StartUp project, and clicked on the menu item "Debug"->"Start Debugging" and it worked. I stopped debugging and then tried it again and now it’s back working. Weird.

How to download files using axios

When response comes with a downloadable file, response headers will be something like

Content-Disposition: "attachment;filename=report.xls"
Content-Type: "application/octet-stream" // or Content-type: "application/vnd.ms-excel"

What you can do is create a separate component, which will contain a hidden iframe.

  import * as React from 'react';

  var MyIframe = React.createClass({

     render: function() {
         return (
           <div style={{display: 'none'}}>
               <iframe src={this.props.iframeSrc} />
           </div>
         );
     }
  });

Now, you can pass the url of the downloadable file as prop to this component, So when this component will receive prop, it will re-render and file will be downloaded.

Edit: You can also use js-file-download module. Link to Github repo

const FileDownload = require('js-file-download');

Axios({
  url: 'http://localhost/downloadFile',
  method: 'GET',
  responseType: 'blob', // Important
}).then((response) => {
    FileDownload(response.data, 'report.csv');
});

Hope this helps :)

Java URL encoding of query string parameters

In android I would use this code:

Uri myUI = Uri.parse ("http://example.com/query").buildUpon().appendQueryParameter("q","random word A3500 bank 24").build();

Where Uri is a android.net.Uri

Text size and different android screen sizes

Everyone can use the below mentioned android library that is the easiest way to make text sizes compatible with almost all devices screens. It actually developed on the basis of new android configuration qualifiers for screen size (introduced in Android 3.2) SmallestWidth swdp.

https://github.com/intuit/sdp

What does a lazy val do?

A lazy val is most easily understood as a "memoized (no-arg) def".

Like a def, a lazy val is not evaluated until it is invoked. But the result is saved so that subsequent invocations return the saved value. The memoized result takes up space in your data structure, like a val.

As others have mentioned, the use cases for a lazy val are to defer expensive computations until they are needed and store their results, and to solve certain circular dependencies between values.

Lazy vals are in fact implemented more or less as memoized defs. You can read about the details of their implementation here:

http://docs.scala-lang.org/sips/pending/improved-lazy-val-initialization.html

how to make a specific text on TextView BOLD

You can add the two strings separately in the builder, one of them is spannedString, the other is a regular one.This way you don`t have to calculate the indexes.

val instructionPress = resources?.getString(R.string.settings_press)

val okText = resources?.getString(R.string.ok)
val spannableString = SpannableString(okText)

val spannableBuilder = SpannableStringBuilder()
spannableBuilder.append(instructionPress)
spannableBuilder.append(spannableString, StyleSpan(Typeface.BOLD), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE)

instructionText.setText(spannableBuilder,TextView.BufferType.SPANNABLE)

iOS 8 Snapshotting a view that has not been rendered results in an empty snapshot

I had this issue when animating some views and the app would go into background mode and come back. I handled it by setting a flag isActive. I set it to NO in

- (void)applicationWillResignActive:(UIApplication *)application

and YES in

- (void)applicationDidBecomeActive:(UIApplication *)application

and animate or not animate my views accordingly. Took care of the issue.

Using braces with dynamic variable names in PHP

I was in a position where I had 6 identical arrays and I needed to pick the right one depending on another variable and then assign values to it. In the case shown here $comp_cat was 'a' so I needed to pick my 'a' array ( I also of course had 'b' to 'f' arrays)

Note that the values for the position of the variable in the array go after the closing brace.

${'comp_cat_'.$comp_cat.'_arr'}[1][0] = "FRED BLOGGS";

${'comp_cat_'.$comp_cat.'_arr'}[1][1] = $file_tidy;

echo 'First array value is '.$comp_cat_a_arr[1][0].' and the second value is .$comp_cat_a_arr[1][1];

What is "loose coupling?" Please provide examples

You can read more about the generic concept of "loose coupling".

In short, it's a description of a relationship between two classes, where each class knows the very least about the other and each class could potentially continue to work just fine whether the other is present or not and without dependency on the particular implementation of the other class.

Ignoring a class property in Entity Framework 4.1 Code First

You can use the NotMapped attribute data annotation to instruct Code-First to exclude a particular property

public class Customer
{
    public int CustomerID { set; get; }
    public string FirstName { set; get; } 
    public string LastName{ set; get; } 
    [NotMapped]
    public int Age { set; get; }
}

[NotMapped] attribute is included in the System.ComponentModel.DataAnnotations namespace.

You can alternatively do this with Fluent API overriding OnModelCreating function in your DBContext class:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
   modelBuilder.Entity<Customer>().Ignore(t => t.LastName);
   base.OnModelCreating(modelBuilder);
}

http://msdn.microsoft.com/en-us/library/hh295847(v=vs.103).aspx

The version I checked is EF 4.3, which is the latest stable version available when you use NuGet.


Edit : SEP 2017

Asp.NET Core(2.0)

Data annotation

If you are using asp.net core (2.0 at the time of this writing), The [NotMapped] attribute can be used on the property level.

public class Customer
{
    public int Id { set; get; }
    public string FirstName { set; get; } 
    public string LastName { set; get; } 
    [NotMapped]
    public int FullName { set; get; }
}

Fluent API

public class SchoolContext : DbContext
{
    public SchoolContext(DbContextOptions<SchoolContext> options) : base(options)
    {
    }
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Customer>().Ignore(t => t.FullName);
        base.OnModelCreating(modelBuilder);
    }
    public DbSet<Customer> Customers { get; set; }
}

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

If you need one single regex, try:

(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*\W)

A short explanation:

(?=.*[a-z])        // use positive look ahead to see if at least one lower case letter exists
(?=.*[A-Z])        // use positive look ahead to see if at least one upper case letter exists
(?=.*\d)           // use positive look ahead to see if at least one digit exists
(?=.*\W])        // use positive look ahead to see if at least one non-word character exists

And I agree with SilentGhost, \W might be a bit broad. I'd replace it with a character set like this: [-+_!@#$%^&*.,?] (feel free to add more of course!)

Error: stray '\240' in program

It appears you have illegal characters in your source. I cannot figure out what character \240 should be but apparently it is around the start of line 10

In the code you posted, the issue does not exist: Live On Coliru

Remove array element based on object property

Iterate through the array, and splice out the ones you don't want. For easier use, iterate backwards so you don't have to take into account the live nature of the array:

for (var i = myArray.length - 1; i >= 0; --i) {
    if (myArray[i].field == "money") {
        myArray.splice(i,1);
    }
}

How to make picturebox transparent?

One fast solution is set image property for image1 and set backgroundimage property to imag2, the only inconvenience is that you have the two images inside the picture box, but you can change background properties to tile, streched, etc. Make sure that backcolor be transparent. Hope this helps

Validating IPv4 addresses with regexp

This is a little longer than some but this is what I use to match IPv4 addresses. Simple with no compromises.

^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$

Encrypt and decrypt a string in C#?

Disclaimer: This solution should only be used for data at rest that is not exposed to the public (for example - a configuration file or DB). Only in this scenario, the quick-and-dirty solution can be considered better than @jbtule's solution, due to lower maintanance.

Original post: I found jbtule's answer a bit complicated for a quick and dirty secured AES string encryption and Brett's answer had a bug with the Initialization Vector being a fixed value making it vulnerable to padding attacks, so I fixed Brett's code and added a random IV that is added to the chipered string, creating a different encrypted value each and every encryption of the same value:

Encryption:

public static string Encrypt(string clearText)
{            
    byte[] clearBytes = Encoding.Unicode.GetBytes(clearText);
    using (Aes encryptor = Aes.Create())
    {
        byte[] IV = new byte[15];
        rand.NextBytes(IV);
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, IV);
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cs.Write(clearBytes, 0, clearBytes.Length);
                cs.Close();
            }
            clearText = Convert.ToBase64String(IV) + Convert.ToBase64String(ms.ToArray());
        }
    }
    return clearText;
}

Decryption:

public static string Decrypt(string cipherText)
{
    byte[] IV = Convert.FromBase64String(cipherText.Substring(0, 20));
    cipherText = cipherText.Substring(20).Replace(" ", "+");
    byte[] cipherBytes = Convert.FromBase64String(cipherText);
    using (Aes encryptor = Aes.Create())
    {
        Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, IV);
        encryptor.Key = pdb.GetBytes(32);
        encryptor.IV = pdb.GetBytes(16);
        using (MemoryStream ms = new MemoryStream())
        {
            using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
            {
                cs.Write(cipherBytes, 0, cipherBytes.Length);
                cs.Close();
            }
            cipherText = Encoding.Unicode.GetString(ms.ToArray());
        }
    }
    return cipherText;
}

Replace EncryptionKey with your key. In my implementation, the key is being saved in the configuration file (web.config\app.config) as you shouldn't save it hard coded. The configuration file should be also encrypted so the key won't be saved as clear text in it.

protected static string _Key = "";
protected static string EncryptionKey
{
    get
    {
        if (String.IsNullOrEmpty(_Key))
        {
            _Key = ConfigurationManager.AppSettings["AESKey"].ToString();
        }

        return _Key;
    }
}

How to install cron

Do you have a Windows machine or a Linux machine?

Under Windows cron is called 'Scheduled Tasks'. It's located in the Control Panel. You can set several scripts to run at specified times in the control panel. Use the wizard to define the scheduled times. Be sure that PHP is callable in your PATH.

Under Linux you can create a crontab for your current user by typing:

crontab -e [username]

If this command fails, it's likely that cron is not installed. If you use a Debian based system (Debian, Ubuntu), try the following commands first:

sudo apt-get update
sudo apt-get install cron

If the command runs properly, a text editor will appear. Now you can add command lines to the crontab file. To run something every five minutes:

*/5 * * * *  /home/user/test.pl

The syntax is basically this:

.---------------- minute (0 - 59) 
|  .------------- hour (0 - 23)
|  |  .---------- day of month (1 - 31)
|  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ... 
|  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7)  OR sun,mon,tue,wed,thu,fri,sat 
|  |  |  |  |
*  *  *  *  *  command to be executed

Read more about it on the following pages: Wikipedia: crontab

Using both Python 2.x and Python 3.x in IPython Notebook

A solution is available that allows me to keep my MacPorts installation by configuring the Ipython kernelspec.

Requirements:

  • MacPorts is installed in the usual /opt directory
  • python 2.7 is installed through macports
  • python 3.4 is installed through macports
  • Ipython is installed for python 2.7
  • Ipython is installed for python 3.4

For python 2.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/2.7/bin
$ sudo ./ipython kernelspec install-self

For python 3.x:

$ cd /opt/local/Library/Frameworks/Python.framework/Versions/3.4/bin
$ sudo ./ipython kernelspec install-self

Now you can open an Ipython notebook and then choose a python 2.x or a python 3.x notebook.

Choose your python!

How to convert java.sql.timestamp to LocalDate (java8) java.time?

You can do:

timeStamp.toLocalDateTime().toLocalDate();

Note that timestamp.toLocalDateTime() will use the Clock.systemDefaultZone() time zone to make the conversion. This may or may not be what you want.

How to escape regular expression special characters using javascript?

Use the backslash to escape a character. For example:

/\\d/

This will match \d instead of a numeric character

return error message with actionResult

You need to return a view which has a friendly error message to the user

catch (Exception ex)
{
   // to do :log error
   return View("Error");
}

You should not be showing the internal details of your exception(like exception stacktrace etc) to the user. You should be logging the relevant information to your error log so that you can go through it and fix the issue.

If your request is an ajax request, You may return a JSON response with a proper status flag which client can evaluate and do further actions

[HttpPost]
public ActionResult Create(CustomerVM model)
{
  try
  {
   //save customer
    return Json(new { status="success",message="customer created"});
  }
  catch(Exception ex)
  {
    //to do: log error
   return Json(new { status="error",message="error creating customer"});
  }
} 

If you want to show the error in the form user submitted, You may use ModelState.AddModelError method along with the Html helper methods like Html.ValidationSummary etc to show the error to the user in the form he submitted.

How to get the current URL within a Django template?

You can get the url without parameters by using {{request.path}} You can get the url with parameters by using {{request.get_full_path}}

Can't install laravel installer via composer

I am using WSL with ubuntu 16.04 LTS version with php 7.3 and laravel 5.7

sudo apt-get install php7.3-zip

Work for me

Open S3 object as a string with Boto3

This isn't in the boto3 documentation. This worked for me:

object.get()["Body"].read()

object being an s3 object: http://boto3.readthedocs.org/en/latest/reference/services/s3.html#object

How do I use HTML as the view engine in Express?

In your apps.js just add

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

Now you can use ejs view engine while keeping your view files as .html

source: http://www.makebetterthings.com/node-js/how-to-use-html-with-express-node-js/

You need to install this two packages:

`npm install ejs --save`
`npm install path --save`

And then import needed packages:

`var path = require('path');`


This way you can save your views as .html instead of .ejs.
Pretty helpful while working with IDEs that support html but dont recognize ejs.

how to set "camera position" for 3d plots using python/matplotlib?

Minimal example varying azim, dist and elev

To add some simple sample images to what was explained at: https://stackoverflow.com/a/12905458/895245

Here is my test program:

#!/usr/bin/env python3

import sys

import matplotlib.pyplot as plt
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np

fig = plt.figure()
ax = fig.gca(projection='3d')

if len(sys.argv) > 1:
    azim = int(sys.argv[1])
else:
    azim = None
if len(sys.argv) > 2:
    dist = int(sys.argv[2])
else:
    dist = None
if len(sys.argv) > 3:
    elev = int(sys.argv[3])
else:
    elev = None

# Make data.
X = np.arange(-5, 6, 1)
Y = np.arange(-5, 6, 1)
X, Y = np.meshgrid(X, Y)
Z = X**2

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, linewidth=0, antialiased=False)

# Labels.
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_zlabel('z')

if azim is not None:
    ax.azim = azim
if dist is not None:
    ax.dist = dist
if elev is not None:
    ax.elev = elev

print('ax.azim = {}'.format(ax.azim))
print('ax.dist = {}'.format(ax.dist))
print('ax.elev = {}'.format(ax.elev))

plt.savefig(
    'main_{}_{}_{}.png'.format(ax.azim, ax.dist, ax.elev),
    format='png',
    bbox_inches='tight'
)

Running it without arguments gives the default values:

ax.azim = -60
ax.dist = 10
ax.elev = 30

main_-60_10_30.png

enter image description here

Vary azim

The azimuth is the rotation around the z axis e.g.:

  • 0 means "looking from +x"
  • 90 means "looking from +y"

main_-60_10_30.png

enter image description here

main_0_10_30.png

enter image description here

main_60_10_30.png

enter image description here

Vary dist

dist seems to be the distance from the center visible point in data coordinates.

main_-60_10_30.png

enter image description here

main_-60_5_30.png

enter image description here

main_-60_20_-30.png

enter image description here

Vary elev

From this we understand that elev is the angle between the eye and the xy plane.

main_-60_10_60.png

enter image description here

main_-60_10_30.png

enter image description here

main_-60_10_0.png

enter image description here

main_-60_10_-30.png

enter image description here

Tested on matpotlib==3.2.2.

How to insert a newline in front of a pattern?

Hmm, just escaped newlines seem to work in more recent versions of sed (I have GNU sed 4.2.1),

dev:~/pg/services/places> echo 'foobar' | sed -r 's/(bar)/\n\1/;'
foo
bar

Extract the last substring from a cell

This works, even when there are middle names:

=MID(A2,FIND(CHAR(1),SUBSTITUTE(A2," ",CHAR(1),LEN(A2)-LEN(SUBSTITUTE(A2," ",""))))+1,LEN(A2))

If you want everything BUT the last name, check out this answer.

If there are trailing spaces in your names, then you may want to remove them by replacing all instances of A2 by TRIM(A2) in the above formula.

Note that it is only by pure chance that your first formula =RIGHT(A2,FIND(" ",A2,1)-1) kind of works for Alistair Stevens. This is because "Alistair" and " Stevens" happen to contain the same number of characters (if you count the leading space in " Stevens").

accessing a variable from another class

You could make the variables public fields:

  public int width;
  public int height;

  DrawFrame() {
    this.width = 400;
    this.height = 400;
  }

You could then access the variables like so:

DrawFrame frame = new DrawFrame();
int theWidth = frame.width;
int theHeight = frame.height;

A better solution, however, would be to make the variables private fields add two accessor methods to your class, keeping the data in the DrawFrame class encapsulated:

 private int width;
 private int height;

 DrawFrame() {
    this.width = 400;
    this.height = 400;
 }

  public int getWidth() {
     return this.width;
  }

  public int getHeight() {
     return this.height;
  }

Then you can get the width/height like so:

  DrawFrame frame = new DrawFrame();
  int theWidth = frame.getWidth();
  int theHeight = frame.getHeight();

I strongly suggest you use the latter method.

Check if an element has event listener on it. No jQuery

There is no JavaScript function to achieve this. However, you could set a boolean value to true when you add the listener, and false when you remove it. Then check against this boolean before potentially adding a duplicate event listener.

Possible duplicate: How to check whether dynamically attached event listener exists or not?

Add / Change parameter of URL and redirect to the new URL

I think something like this would work, upgrading the @Marc code:

//view-all parameter does NOT exist  
$params = $_GET;  
if(!isset($_GET['view-all'])){  
  //Adding view-all parameter  
  $params['view-all'] = 'Yes';  
}  
else{  
  //view-all parameter does exist!  
  $params['view-all'] = ($params['view-all'] == 'Yes' ? 'No' : 'Yes');  
}
$new_url = $_SERVER['PHP_SELF'].'?'.http_build_query($params);

Cannot resolve symbol 'AppCompatActivity'

none of below solved my issue

  • Restart Android
  • File >> Synch Project with Gradle Files
  • Build >> Clean Project
  • Build >> Rebuild Project
  • File >> Invalidate Caches / Restart

Instead, I solved it by updating the version of appcompat & design dependencies to the recent version To do so: go to build.grade (Module:app) >> dependencies section and then hit ALT + ENTER on both appcompat & design dependencies then select the shown version in my case it's 24.2.1 as shown in the picture enter image description here

Java - How to create new Entry (key, value)

Why Map.Entry? I guess something like a key-value pair is fit for the case.

Use java.util.AbstractMap.SimpleImmutableEntry or java.util.AbstractMap.SimpleEntry

How to top, left justify text in a <td> cell that spans multiple rows

try this

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<style>_x000D_
table, th, td {_x000D_
    border: 1px solid black;_x000D_
}_x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<table style="width:50%;">_x000D_
    <tr>_x000D_
      <th>Month</th>_x000D_
      <th>Savings</th>_x000D_
    </tr>_x000D_
    <tr style="height:100px">_x000D_
      <td valign="top">January</td>_x000D_
      <td valign="bottom">$100</td>_x000D_
    </tr>_x000D_
</table>_x000D_
_x000D_
<p><b>Note:</b> The valign attribute is not supported in HTML5. Use CSS instead.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

use valign="top" for td style

Insert if not exists Oracle

We can combine the DUAL and NOT EXISTS to archive your requirement:

INSERT INTO schema.myFoo ( 
    primary_key, value1, value2
) 
SELECT
    'bar', 'baz', 'bat' 
FROM DUAL
WHERE NOT EXISTS (
    SELECT 1 
    FROM schema.myFoo
    WHERE primary_key = 'bar'
);

How to use Git?

I think gitready is a great starting point. I'm using git for a project now and that site pretty much got the ball rolling for me.

MySQL CONCAT returns NULL if any field contain NULL

you can use if statement like below

select CONCAT(if(affiliate_name is null ,'',affiliate_name),'- ',if(model is null ,'',affiliate_name)) as model from devices

Singletons vs. Application Context in Android?

Application is not the same as the Singleton.The reasons are:

  1. Application's method(such as onCreate) is called in the ui thread;
  2. singleton's method can be called in any thread;
  3. In the method "onCreate" of Application,you can instantiate Handler;
  4. If the singleton is executed in none-ui thread,you could not instantiate Handler;
  5. Application has the ability to manage the life cycle of the activities in the app.It has the method "registerActivityLifecycleCallbacks".But the singletons has not the ability.

get data from mysql database to use in javascript

Do you really need to "build" it from javascript or can you simply return the built HTML from PHP and insert it into the DOM?

  1. Send AJAX request to php script
  2. PHP script processes request and builds table
  3. PHP script sends response back to JS in form of encoded HTML
  4. JS takes response and inserts it into the DOM

When should I use Lazy<T>?

From MSDN:

Use an instance of Lazy to defer the creation of a large or resource-intensive object or the execution of a resource-intensive task, particularly when such creation or execution might not occur during the lifetime of the program.

In addition to James Michael Hare's answer, Lazy provides thread-safe initialization of your value. Take a look at LazyThreadSafetyMode enumeration MSDN entry describing various types of thread safety modes for this class.

Executing an EXE file using a PowerShell script

& "C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode

or

[System.Diagnostics.Process]::Start("C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe", "C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode")

UPDATE: sorry I missed "(I invoked the command using the "&" operator)" sentence. I had this problem when I was evaluating the path dynamically. Try Invoke-Expression construction:

Invoke-Expression "& `"C:\Program Files\Automated QA\TestExecute 8\Bin\TestExecute.exe`" C:\temp\TestProject1\TestProject1.pjs /run /exit /SilentMode"

What exactly is the meaning of an API?

Lets say you are developing a game and you want the game user to login their facebook profile(to get your profile information) before playing it,so how your game is going to access facebook? Now here comes the API.Facebook has already written the program(API) for you to do it, you have to just use those programs in your game application.using Facebook-API you can use their services in your application.Here is a good and detailed look on API... http://money.howstuffworks.com/business-communications/how-to-leverage-an-api-for-conferencing1.htm

Convert row to column header for Pandas DataFrame,

This works (pandas v'0.19.2'):

df.rename(columns=df.iloc[0])

How to change the color of a button?

To change the color of button programmatically

Here it is :

Button b1;
//colorAccent is the resource made in the color.xml file , you can change it.
b1.setBackgroundResource(R.color.colorAccent);  

Java: how can I split an ArrayList in multiple small ArrayLists?

You can use the chunk method from Eclipse Collections:

ArrayList<Integer> list = new ArrayList<>(Interval.oneTo(1000));
RichIterable<RichIterable<Integer>> chunks = Iterate.chunk(list, 10);
Verify.assertSize(100, chunks);

A few examples of the chunk method were included in this DZone article as well.

Note: I am a committer for Eclipse Collections.

Get current working directory in a Qt application

Thank you RedX and Kaz for your answers. I don't get why by me it gives the path of the exe. I found an other way to do it :

QString pwd("");
char * PWD;
PWD = getenv ("PWD");
pwd.append(PWD);
cout << "Working directory : " << pwd << flush;

It is less elegant than a single line... but it works for me.

Get user's non-truncated Active Directory groups from command line

Or you could use dsquery and dsget:

dsquery user domainroot -name <userName> | dsget user -memberof

To retrieve group memberships something like this:

Tue 09/10/2013 13:17:41.65
C:\
>dsquery user domainroot -name jqpublic | dsget user -memberof
"CN=Technical Support Staff,OU=Acme,OU=Applications,DC=YourCompany,DC=com"
"CN=Technical Support Staff,OU=Contosa,OU=Applications,DC=YourCompany,DC=com"
"CN=Regional Administrators,OU=Workstation,DC=YourCompany,DC=com"

Although I can't find any evidence that I ever installed this package on my computer, you might need to install the Remote Server Administration Tools for Windows 7.

JPA eager fetch does not join

I had exactly this problem with the exception that the Person class had a embedded key class. My own solution was to join them in the query AND remove

@Fetch(FetchMode.JOIN)

My embedded id class:

@Embeddable
public class MessageRecipientId implements Serializable {

    @ManyToOne(targetEntity = Message.class, fetch = FetchType.LAZY)
    @JoinColumn(name="messageId")
    private Message message;
    private String governmentId;

    public MessageRecipientId() {
    }

    public Message getMessage() {
        return message;
    }

    public void setMessage(Message message) {
        this.message = message;
    }

    public String getGovernmentId() {
        return governmentId;
    }

    public void setGovernmentId(String governmentId) {
        this.governmentId = governmentId;
    }

    public MessageRecipientId(Message message, GovernmentId governmentId) {
        this.message = message;
        this.governmentId = governmentId.getValue();
    }

}

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

Git: Merge a Remote branch locally

You can reference those remote tracking branches ~(listed with git branch -r) with the name of their remote.

You need to fetch the remote branch:

git fetch origin aRemoteBranch

If you want to merge one of those remote branches on your local branch:

git checkout master
git merge origin/aRemoteBranch

Note 1: For a large repo with a long history, you will want to add the --depth=1 option when you use git fetch.

Note 2: These commands also work with other remote repos so you can setup an origin and an upstream if you are working on a fork.

Note 3: user3265569 suggests the following alias in the comments:

From aLocalBranch, run git combine remoteBranch
Alias:

combine = !git fetch origin ${1} && git merge origin/${1}

Opposite scenario: If you want to merge one of your local branch on a remote branch (as opposed to a remote branch to a local one, as shown above), you need to create a new local branch on top of said remote branch first:

git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch

The idea here, is to merge "one of your local branch" (here anotherLocalBranch) to a remote branch (origin/aBranch).
For that, you create first "myBranch" as representing that remote branch: that is the git checkout -b myBranch origin/aBranch part.
And then you can merge anotherLocalBranch to it (to myBranch).

How to supply value to an annotation from a Constant java

You're not supplying it with an array in your example. The following compiles fine:

public @interface SampleAnnotation {
    String[] sampleValues();
}

public class Values {
    public static final String val0 = "A";
    public static final String val1 = "B";

    @SampleAnnotation(sampleValues={ val0, val1 })
    public void foo() {
    }
}

How to change the height of a div dynamically based on another div using css?

In this piece of code the height of left panel will gets adjusted to the height of right panel dynamically...

function resizeDiv() {
var rh=$('.pright').height()+'px'.toString();
$('.pleft').css('height',rh);
}

You can try this here http://jsfiddle.net/SriharshaCR/7q585k1x/9/embedded/result/

How do I access ViewBag from JS

if you are using razor engine template then do the following

in your view write :

<script> var myJsVariable = '@ViewBag.MyVariable' </script>

UPDATE: A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```

<head>
 <script>
   var AppConfig = @Html.Raw(Json.Encode(new {
    baseUrl: Url.Content("~"),
    fbApi: "get it from db",
    awsUrl: "get it from db"
   }));
 </script>
</head>

And you can use it in your JavaScript code as follow:

<script>
  myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
  alert(myProduct.fullUrl);
</script>

Notice: Array to string conversion in

Even simpler:

$get = @mysql_query("SELECT money FROM players WHERE username = '" . $_SESSION['username'] . "'");

note the quotes around username in the $_SESSION reference.

finding the type of an element using jQuery

It is worth noting that @Marius's second answer could be used as pure Javascript solution.

document.getElementById('elementId').tagName

Find files in created between a date range

If you use GNU find, since version 4.3.3 you can do:

find -newerct "1 Aug 2013" ! -newerct "1 Sep 2013" -ls

It will accept any date string accepted by GNU date -d.

You can change the c in -newerct to any of a, B, c, or m for looking at atime/birth/ctime/mtime.

Another example - list files modified between 17:30 and 22:00 on Nov 6 2017:

find -newermt "2017-11-06 17:30:00" ! -newermt "2017-11-06 22:00:00" -ls

Full details from man find:

   -newerXY reference
          Compares the timestamp of the current file with reference.  The reference argument is normally the name of a file (and one of its timestamps  is  used
          for  the  comparison)  but  it may also be a string describing an absolute time.  X and Y are placeholders for other letters, and these letters select
          which time belonging to how reference is used for the comparison.

          a   The access time of the file reference
          B   The birth time of the file reference
          c   The inode status change time of reference
          m   The modification time of the file reference
          t   reference is interpreted directly as a time

          Some combinations are invalid; for example, it is invalid for X to be t.  Some combinations are not implemented on all systems; for example B  is  not
          supported on all systems.  If an invalid or unsupported combination of XY is specified, a fatal error results.  Time specifications are interpreted as
          for the argument to the -d option of GNU date.  If you try to use the birth time of a reference file, and the birth time cannot be determined, a fatal
          error  message  results.   If  you  specify a test which refers to the birth time of files being examined, this test will fail for any files where the
          birth time is unknown.

EOFException - how to handle?

You can use while(in.available() != 0) instead of while(true).

A circular reference was detected while serializing an object of type 'SubSonic.Schema .DatabaseColumn'.

JSON, like xml and various other formats, is a tree-based serialization format. It won't love you if you have circular references in your objects, as the "tree" would be:

root B => child A => parent B => child A => parent B => ...

There are often ways of disabling navigation along a certain path; for example, with XmlSerializer you might mark the parent property as XmlIgnore. I don't know if this is possible with the json serializer in question, nor whether DatabaseColumn has suitable markers (very unlikely, as it would need to reference every serialization API)

Sending JWT token in the headers with Postman

In Postman latest version(7++) may be there is no Bearer field in Authorization So go to Header tab

select key as Authorization and in value write JWT

Find PHP version on windows command line

  1. Open command prompt
  2. Locate directory using cd C:/Xampp/php
  3. Type command php -v

You will get your php version details

How to use multiple @RequestMapping annotations in spring?

From my test (spring 3.0.5), @RequestMapping(value={"", "/"}) - only "/" works, "" does not. However I found out this works: @RequestMapping(value={"/", " * "}), the " * " matches anything, so it will be the default handler in case no others.

how to convert integer to string?

NSArray *myArray = [NSArray arrayWithObjects:[NSNumber numberWithInt:1], [NSNumber numberWithInt:2], [NSNumber numberWithInt:3]];

Update for new Objective-C syntax:

NSArray *myArray = @[@1, @2, @3];

Those two declarations are identical from the compiler's perspective.

if you're just wanting to use an integer in a string for putting into a textbox or something:

int myInteger = 5;
NSString* myNewString = [NSString stringWithFormat:@"%i", myInteger];

When should I use semicolons in SQL Server?

You must use it.

The practice of using a semicolon to terminate statements is standard and in fact is a requirement in several other database platforms. SQL Server requires the semicolon only in particular cases—but in cases where a semicolon is not required, using one doesn’t cause problems. I strongly recommend that you adopt the practice of terminating all statements with a semicolon. Not only will doing this improve the readability of your code, but in some cases it can save you some grief. (When a semicolon is required and is not specified, the error message SQL Server produces is not always very clear.)

And most important:

The SQL Server documentation indicates that not terminating T-SQL statements with a semicolon is a deprecated feature. This means that the long-term goal is to enforce use of the semicolon in a future version of the product. That’s one more reason to get into the habit of terminating all of your statements, even where it’s currently not required.

Source: Microsoft SQL Server 2012 T-SQL Fundamentals by Itzik Ben-Gan.


An example of why you always must use ; are the following two queries (copied from this post):

BEGIN TRY
    BEGIN TRAN
    SELECT 1/0 AS CauseAnException
    COMMIT
END TRY
BEGIN CATCH
    SELECT ERROR_MESSAGE()
    THROW
END CATCH

enter image description here

BEGIN TRY
    BEGIN TRAN
    SELECT 1/0 AS CauseAnException;
    COMMIT
END TRY
BEGIN CATCH
    SELECT ERROR_MESSAGE();
    THROW
END CATCH

enter image description here

Why do I need 'b' to encode a string with Base64?

If the data to be encoded contains "exotic" characters, I think you have to encode in "UTF-8"

encoded = base64.b64encode (bytes('data to be encoded', "utf-8"))

How to import NumPy in the Python shell

On Debian/Ubuntu:

aptitude install python-numpy

On Windows, download the installer:

http://sourceforge.net/projects/numpy/files/NumPy/

On other systems, download the tar.gz and run the following:

$ tar xfz numpy-n.m.tar.gz
$ cd numpy-n.m
$ python setup.py install

how to count length of the JSON array element

First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :

obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

Setting up the Two-tone color:

As described above you can use the color css key except for materials Two-tone theme which seems to be glitchy ;-)

A workaround is described in one of several angular material github issue's by using a custom css filter. This custom filter can be generated here.

E.g.:

Html:

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons|Material+Icons+Outlined|Material+Icons+Round|Material+Icons+Two+Tone|Material+Icons+Sharp">

<i class="material-icons-two-tone red">home</i>

css:

.red {
filter: invert(8%) sepia(94%) saturate(4590%) hue-rotate(358deg) brightness(101%) contrast(112%);
}

Attachments:

Apache HttpClient Android (Gradle)

Working gradle dependency

Try this:

compile 'org.jbundle.util.osgi.wrapped:org.jbundle.util.osgi.wrapped.org.apache.http.client:4.1.2'

MySQL: How to add one day to datetime field in query

If you are able to use NOW() this would be simplest form:

SELECT * FROM `fab_scheduler` WHERE eventdate>=(NOW() - INTERVAL 1 DAY)) AND eventdate<NOW() ORDER BY eventdate DESC;

With MySQL 5.6+ query abowe should do. Depending on sql server, You may be required to use CURRDATE() instead of NOW() - which is alias for DATE(NOW()) and will return only date part of datetime data type;

The performance impact of using instanceof in Java

You're focusing on the wrong thing. The difference between instanceof and any other method for checking the same thing would probably not even be measurable. If performance is critical then Java is probably the wrong language. The major reason being that you can't control when the VM decides it wants to go collect garbage, which can take the CPU to 100% for several seconds in a large program (MagicDraw 10 was great for that). Unless you are in control of every computer this program will run on you can't guarantee which version of JVM it will be on, and many of the older ones had major speed issues. If it's a small app you may be ok with Java, but if you are constantly reading and discarding data then you will notice when the GC kicks in.

How can I put a ListView into a ScrollView without it collapsing?

Before it was not possible. But with the release of new Appcompat libraries and Design libraries, this can be achieved.

You just have to use NestedScrollView https://developer.android.com/reference/android/support/v4/widget/NestedScrollView.html

I am not aware it will work with Listview or not but works with RecyclerView.

Code Snippet:

<android.support.v4.widget.NestedScrollView 
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
    android:layout_width="match_parent"
    android:layout_height="wrap_content" />

</android.support.v4.widget.NestedScrollView>

Xcode 6.1 Missing required architecture X86_64 in file

One other thing to look out for is that XCode is badly handling the library imports, and in many cases the solution is to find the imported file in your project, delete it in Finder or from the command line and add it back again, otherwise it won't get properly updated by XCode. By XCode leaving there the old file you keep running in circles not understanding why it is not compiling, missing the architecture etc.

jQuery - getting custom attribute from selected option

You're adding the event handler to the <select> element.
Therefore, $(this) will be the dropdown itself, not the selected <option>.

You need to find the selected <option>, like this:

var option = $('option:selected', this).attr('mytag');

Invoking modal window in AngularJS Bootstrap UI using JavaScript

OK, so first of all the http://angular-ui.github.io/bootstrap/ has a <modal> directive and the $dialog service and both of those can be used to open modal windows.

The difference is that with the <modal> directive content of a modal is embedded in a hosting template (one that triggers modal window opening). The $dialog service is far more flexible and allow you to load modal's content from a separate file as well as trigger modal windows from any place in AngularJS code (this being a controller, a service or another directive).

Not sure what you mean exactly by "using JavaScript code" but assuming that you mean any place in AngularJS code the $dialog service is probably a way to go.

It is very easy to use and in its simplest form you could just write:

$dialog.dialog({}).open('modalContent.html');  

To illustrate that it can be really triggered by any JavaScript code here is a version that triggers modal with a timer, 3 seconds after a controller was instantiated:

function DialogDemoCtrl($scope, $timeout, $dialog){
  $timeout(function(){
    $dialog.dialog({}).open('modalContent.html');  
  }, 3000);  
}

This can be seen in action in this plunk: http://plnkr.co/edit/u9HHaRlHnko492WDtmRU?p=preview

Finally, here is the full reference documentation to the $dialog service described here: https://github.com/angular-ui/bootstrap/blob/master/src/dialog/README.md

npm WARN package.json: No repository field

In Simple word- package.json of your project has not property of repository you must have to add it,

and you have to add repository in your package.json like below

enter image description here

and Let me explain according to your scenario

you must have to add repository field something like below

  "repository" : {     
     "type" : "git",
      "url" : "http://github.com/npm/express.git" 
   }

Compare every item to every other item in ArrayList

The following code will compare each item with other list of items using contains() method.Length of for loop must be bigger size() of bigger list then only it will compare all the values of both list.

List<String> str = new ArrayList<String>();
str.add("first");
str.add("second");
str.add("third");
List<String> str1 = new ArrayList<String>();
str1.add("first");
str1.add("second");
str1.add("third1");
for (int i = 0; i<str1.size(); i++)
{
System.out.println(str.contains(str1.get(i)));
}

Output is true true false

Using StringWriter for XML Serialization

When serialising an XML document to a .NET string, the encoding must be set to UTF-16. Strings are stored as UTF-16 internally, so this is the only encoding that makes sense. If you want to store data in a different encoding, you use a byte array instead.

SQL Server works on a similar principle; any string passed into an xml column must be encoded as UTF-16. SQL Server will reject any string where the XML declaration does not specify UTF-16. If the XML declaration is not present, then the XML standard requires that it default to UTF-8, so SQL Server will reject that as well.

Bearing this in mind, here are some utility methods for doing the conversion.

public static string Serialize<T>(T value) {

    if(value == null) {
        return null;
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    XmlWriterSettings settings = new XmlWriterSettings()
    {
        Encoding = new UnicodeEncoding(false, false), // no BOM in a .NET string
        Indent = false,
        OmitXmlDeclaration = false
    };

    using(StringWriter textWriter = new StringWriter()) {
        using(XmlWriter xmlWriter = XmlWriter.Create(textWriter, settings)) {
            serializer.Serialize(xmlWriter, value);
        }
        return textWriter.ToString();
    }
}

public static T Deserialize<T>(string xml) {

    if(string.IsNullOrEmpty(xml)) {
        return default(T);
    }

    XmlSerializer serializer = new XmlSerializer(typeof(T));

    XmlReaderSettings settings = new XmlReaderSettings();
    // No settings need modifying here

    using(StringReader textReader = new StringReader(xml)) {
        using(XmlReader xmlReader = XmlReader.Create(textReader, settings)) {
            return (T) serializer.Deserialize(xmlReader);
        }
    }
}

How to make ConstraintLayout work with percentage values?

It may be useful to have a quick reference here.

Placement of views

Use a guideline with app:layout_constraintGuide_percent like this:

<androidx.constraintlayout.widget.Guideline
    android:id="@+id/guideline"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    app:layout_constraintGuide_percent="0.5"/>

And then you can use this guideline as anchor points for other views.

or

Use bias with app:layout_constraintHorizontal_bias and/or app:layout_constraintVertical_bias to modify view location when the available space allows

<Button
    ...
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintHorizontal_bias="0.25"
    ...
    />

Size of views

Another percent based value is height and/or width of elements, with app:layout_constraintHeight_percent and/or app:layout_constraintWidth_percent:

<Button
    ...
    android:layout_width="0dp"
    app:layout_constraintWidth_percent="0.5"
    ...
    />

What is the use of a private static variable in Java?

ThreadLocal variables are typically implemented as private static. In this way, they are not bound to the class and each thread has its own reference to its own "ThreadLocal" object.

In Unix, how do you remove everything in the current directory and below it?

Practice safe computing. Simply go up one level in the hierarchy and don't use a wildcard expression:

cd ..; rm -rf -- <dir-to-remove>

The two dashes -- tell rm that <dir-to-remove> is not a command-line option, even when it begins with a dash.

'Property does not exist on type 'never'

if you're receiving the error in parameter, so keep any or any[] type of input like below

getOptionLabel={(option: any) => option!.name}
 <Autocomplete
    options={tests}
    getOptionLabel={(option: any) => option!.name}
    ....
  />

MySQL Workbench not displaying query results

The problem, as it is described, corresponds exactly to the bug MySQL Bugs: #74147: empty grid result, incompatibiliity with libglib_2.42

The good news is it's almost closed.

A patch is available since today.

EDIT : In Debian Jessie (testing), the problem is solved with the package mysql-workbench 6.2.3+dfsg-6 available since today.

Converting a JS object to an array using jQuery

x = [];
for( var i in myObj ) {
    x[i] = myObj[i];
}

How to echo in PHP, HTML tags

There isn't any need to use echo, sir. Just use the tag <plaintext>:

<plaintext>
    <div>
        <h3><a href="#">First</a></h3>
        <div>Lorem ipsum dolor sit amet.</div>
    </div>

Could not establish secure channel for SSL/TLS with authority '*'

Yes an Untrusted certificate can cause this. Look at the certificate path for the webservice by opening the websservice in a browser and use the browser tools to look at the certificate path. You may need to install one or more intermediate certificates onto the computer calling the webservice. In the browser you may see "Certificate errors" with an option to "Install Certificate" when you investigate further - this could be the certificate you missing.

My particular problem was a Geotrust Geotrust DV SSL CA intermediate certificate missing following an upgrade to their root server in July 2010 https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422

(2020 update deadlink preserved here: https://web.archive.org/web/20140724085537/https://knowledge.geotrust.com/support/knowledge-base/index?page=content&id=AR1422 )

Creating a zero-filled pandas data frame

It's best to do this with numpy in my opinion

import numpy as np
import pandas as pd
d = pd.DataFrame(np.zeros((N_rows, N_cols)))

MIT vs GPL license

IANAL but as I see it....

While you can combine GPL and MIT code, the GPL is tainting. Which means the package as a whole gets the limitations of the GPL. As that is more restrictive you can no longer use it in commercial (or rather closed source) software. Which also means if you have a MIT/BSD/ASL project you will not want to add dependencies to GPL code.

Adding a GPL dependency does not change the license of your code but it will limit what people can do with the artifact of your project. This is also why the ASF does not allow dependencies to GPL code for their projects.

http://www.apache.org/licenses/GPL-compatibility.html

Limiting the number of characters in a string, and chopping off the rest

You can achieve this easily using

    shortString = longString.substring(0, Math.min(s.length(), MAX_LENGTH));

Temporarily switch working copy to a specific Git commit

First, use git log to see the log, pick the commit you want, note down the sha1 hash that is used to identify the commit. Next, run git checkout hash. After you are done, git checkout original_branch. This has the advantage of not moving the HEAD, it simply switches the working copy to a specific commit.

Python 3.6 install win32api?

Information provided by @Gord

As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

pip install pywin32

If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

pip install pywin32==xxx

This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


Probably now undesirable solutions but certainly still valid as of September 2019

There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


EDIT

Since I posted my answer there are other alternatives to downloading the win32api module.

It is now available to download through pip using this command;

pip install pypiwin32

Also it can be installed from this GitHub repository as provided in comments by @Heath

ORA-00907: missing right parenthesis

I would recommend separating out all of the foreign-key constraints from your CREATE TABLE statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.

You can add an FK constraint to a table using SQL like the following:

ALTER TABLE orders ADD CONSTRAINT orders_FK
  FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);

In particular, your formats and library tables both have foreign-key constraints on one another. The two CREATE TABLE statements to create these two tables can never run successfully, as each will only work when the other table has already been created.

Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.

What is the best way to compare 2 folder trees on windows?

You could also execute tree > tree.txt in both folders and then diff both tree.txt files with any file based diff tool (git diff).

Is it possible to force row level locking in SQL Server?

You can't really force the optimizer to do anything, but you can guide it.

UPDATE
Employees WITH (ROWLOCK)
SET Name='Mr Bean'
WHERE Age>93

See - Controlling SQL Server with Locking and Hints

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

Try adding the following middleware to your NodeJS/Express app (I have added some comments for your convenience):

// Add headers
app.use(function (req, res, next) {

    // Website you wish to allow to connect
    res.setHeader('Access-Control-Allow-Origin', 'http://localhost:8888');

    // Request methods you wish to allow
    res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');

    // Request headers you wish to allow
    res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');

    // Set to true if you need the website to include cookies in the requests sent
    // to the API (e.g. in case you use sessions)
    res.setHeader('Access-Control-Allow-Credentials', true);

    // Pass to next layer of middleware
    next();
});

Hope that helps!

continuing execution after an exception is thrown in java

If you throw the exception, the method execution will stop and the exception is thrown to the caller method. throw always interrupt the execution flow of the current method. a try/catch block is something you could write when you call a method that may throw an exception, but throwing an exception just means that method execution is terminated due to an abnormal condition, and the exception notifies the caller method of that condition.

Find this tutorial about exception and how they work - http://docs.oracle.com/javase/tutorial/essential/exceptions/

How to detect installed version of MS-Office?

One way to check for the installed Office version would be to check the InstallRoot registry keys for the Office applications of interest.

For example, if you would like to check whether Word 2007 is installed you should check for the presence of the following Registry key:

HKLM\Software\Microsoft\Office\12.0\Word\InstallRoot::Path

This entry contains the path to the executable.

Replace 12.0 (for Office 2007) with the corresponding version number:

Office 97   -  7.0
Office 98   -  8.0
Office 2000 -  9.0
Office XP   - 10.0
Office 2003 - 11.0
Office 2007 - 12.0
Office 2010 - 14.0 (sic!)
Office 2013 - 15.0
Office 2016 - 16.0
Office 2019 - 16.0 (sic!)

The other applications have similar keys:

HKLM\Software\Microsoft\Office\12.0\Excel\InstallRoot::Path
HKLM\Software\Microsoft\Office\12.0\PowerPoint\InstallRoot::Path

Or you can check the common root path of all applications:

HKLM\Software\Microsoft\Office\12.0\Common\InstallRoot::Path

Another option, without using specific Registry keys would be to query the MSI database using the MSIEnumProducts API as described here.

As an aside, parallel installations of different Office versions are not officially supported by Microsoft. They do somewhat work, but you might get undesired effects and inconsistencies.

Update: Office 2019 and Office 365

As of Office 2019, MSI-based setup are no longer available, Click-To-Run is the only way to deploy Office now. Together with this change towards the regularly updated Office 365, also the major/minor version numbers of Office are no longer updated (at least for the time being). That means that – even for Office 2019 – the value used in Registry keys and the value returned by Application.Version (e.g. in Word) still is 16.0.

For the time being, there is no documented way to distinguish the Office 2016 from Office 2019. A clue might be the file version of the winword.exe; however, this version is also incremented for patched Office 2016 versions (see the comment by @antonio below).

If you need to distinguish somehow between Office versions, e.g. to make sure that a certain feature is present or that a minimum version of Office is installed, probably the best way it to look at the file version of one of the main Office applications:

// Using the file path to winword.exe
// Retrieve the path e.g. from the InstallRoot Registry key
var fileVersionInfo = FileVersionInfo.GetVersionInfo(@"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE");
var version = new Version(fileVersionInfo.FileVersion);

// On a running instance using the `Process` class
var process = Process.GetProcessesByName("winword").First();
string fileVersionInfo = process.MainModule.FileVersionInfo.FileVersion;
var version = Version(fileVersionInfo);

The file version of Office 2019 is 16.0.10730.20102, so if you see anything greater than that you are dealing with Office 2019 or a current Office 365 version.

Load data from txt with pandas

If you don't have an index assigned to the data and you are not sure what the spacing is, you can use to let pandas assign an index and look for multiple spaces.

df = pd.read_csv('filename.txt', delimiter= '\s+', index_col=False)

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

.bashrc: Permission denied

If you can't access the file and your os is any linux distro or mac os x then either of these commands should work:

sudo nano .bashrc

chmod 777 .bashrc 

it is worthless

How to convert an int array to String with toString method in Java

Using the utility I describe here, you can have a more control over the string representation you get for your array.

String[] s = { "hello", "world" };
RichIterable<String> r = RichIterable.from(s);
r.mkString();                 // gives "hello, world"
r.mkString(" | ");            // gives "hello | world"
r.mkString("< ", ", ", " >"); // gives "< hello, world >"

How to determine day of week by passing specific date?

Can use the following code snippet for input like (day = "08", month = "05", year = "2015" and output will be "WEDNESDAY")

Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.DAY_OF_MONTH, Integer.parseInt(day));
calendar.set(Calendar.MONTH, (Integer.parseInt(month)-1));
calendar.set(Calendar.YEAR, Integer.parseInt(year));
String dayOfWeek = calendar.getDisplayName(Calendar.DAY_OF_WEEK, Calendar.LONG, Locale.US).toUpperCase();

Iterate over object keys in node.js

Also remember that you can pass a second argument to the .forEach() function specifying the object to use as the this keyword.

// myOjbect is the object you want to iterate.
// Notice the second argument (secondArg) we passed to .forEach.
Object.keys(myObject).forEach(function(element, key, _array) {
  // element is the name of the key.
  // key is just a numerical value for the array
  // _array is the array of all the keys

  // this keyword = secondArg
  this.foo;
  this.bar();
}, secondArg);

Python NoneType object is not callable (beginner)

You want to pass the function object hi to your loop() function, not the result of a call to hi() (which is None since hi() doesn't return anything).

So try this:

>>> loop(hi, 5)
hi
hi
hi
hi
hi

Perhaps this will help you understand better:

>>> print hi()
hi
None
>>> print hi
<function hi at 0x0000000002422648>

Setting WPF image source in code

This is a bit less code and can be done in a single line.

string packUri = "pack://application:,,,/AssemblyName;component/Images/icon.png";
_image.Source = new ImageSourceConverter().ConvertFromString(packUri) as ImageSource;

Convert to absolute value in Objective-C

Depending on the type of your variable, one of abs(int), labs(long), llabs(long long), imaxabs(intmax_t), fabsf(float), fabs(double), or fabsl(long double).

Those functions are all part of the C standard library, and so are present both in Objective-C and plain C (and are generally available in C++ programs too.)

(Alas, there is no habs(short) function. Or scabs(signed char) for that matter...)


Apple's and GNU's Objective-C headers also include an ABS() macro which is type-agnostic. I don't recommend using ABS() however as it is not guaranteed to be side-effect-safe. For instance, ABS(a++) will have an undefined result.


If you're using C++ or Objective-C++, you can bring in the <cmath> header and use std::abs(), which is templated for all the standard integer and floating-point types.

How to add property to object in PHP >= 5.3 strict mode without generating error

If you want to edit the decoded JSON, try getting it as an associative array instead of an array of objects.

$data = json_decode($json, TRUE);

How to close current tab in a browser window?

Tested successfully in FF 18 and Chrome 24:

Insert in head:

<script>
    function closeWindow() {
        window.open('','_parent','');
        window.close();
    }
</script> 

HTML:

<a href="javascript:closeWindow();">Close Window</a>

Credits go to Marcos J. Drake.

Android Dialog: Removing title bar

I am an Android novice and came across this question trying to get rid of a title bar.

I'm using an activity and displaying it as a dialog. I was poking around with themes and came across a useful bit of default theming.

Here's the code from my AndroidManifest.xml that I was using when the title bar was showing:

<activity
    android:name=".AlertDialog"
    android:theme="@android:style/Theme.Holo.Dialog"

    >

</activity>

Here's the change that got me my desired result:

<activity
    android:name=".AlertDialog"
    android:theme="@android:style/Theme.Holo.Dialog.NoActionBar"

    >

</activity>

As I said, I'm still new to Android, so this may have undesirable side-effects, but it appears to have given me the outcome I wanted, which was just to remove the title bar from the dialog.

How to fire a change event on a HTMLSelectElement if the new value is the same as the old?

JavaScript code:

  • on mousedown event: set selectedIndex property value to -1
  • on change event: handle event

The only drawback is that when the user clicks on the dropdown list, the currently selected item does not appear selected

Where does MySQL store database files on Windows and what are the names of the files?

In Windows 7, the MySQL database is stored at

C:\ProgramData\MySQL\MySQL Server 5.6\data

Note: this is a hidden folder. And my example is for MySQL Server version 5.6; change the folder name based on your version if different.

It comes in handy to know this location because sometimes the MySQL Workbench fails to drop schemas (or import databases). This is mostly due to the presence of files in the db folders that for some reason could not be removed in an earlier process by the Workbench. Remove the files using Windows Explorer and try again (dropping, importing), your problem should be solved.

Hope this helps :)

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

If you are trying to populate a table from a SQL dump, make sure that the table listed in the "INSERT INTO" statements of the dump is the same one you are trying to populate. Opening "MyTable" and importing with a SQL dump will throw exactly that kind of error if the dump is trying to put entries into "MyOtherTable", which may already have entries.

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

successful/fail message pop up box after submit?

You are echoing outside the body tag of your HTML. Put your echos there, and you should be fine.

Also, remove the onclick="alert()" from your submit. This is the cause for your first undefined message.

<?php
  $posted = false;
  if( $_POST ) {
    $posted = true;

    // Database stuff here...
    // $result = mysql_query( ... )
    $result = $_POST['name'] == "danny"; // Dummy result
  }
?>

<html>
  <head></head>
  <body>

  <?php
    if( $posted ) {
      if( $result ) 
        echo "<script type='text/javascript'>alert('submitted successfully!')</script>";
      else
        echo "<script type='text/javascript'>alert('failed!')</script>";
    }
  ?>
    <form action="" method="post">
      Name:<input type="text" id="name" name="name"/>
      <input type="submit" value="submit" name="submit"/>
    </form>
  </body>
</html>

MySql Query Replace NULL with Empty String in Select

Try COALESCE. It returns the first non-NULL value.

SELECT COALESCE(`prereq`, ' ') FROM `test`

sys.stdin.readline() reads without prompt, returning 'nothing in between'

import sys
userinput = sys.stdin.readline()
betAmount = int(userinput)

print betAmount

This works on my system. I checked int('23\n') would result in 23.

Move textfield when keyboard appears swift

I created a Swift 3 protocol to handle the keyboard appearance / disappearance

import UIKit

protocol KeyboardHandler: class {

var bottomConstraint: NSLayoutConstraint! { get set }

    func keyboardWillShow(_ notification: Notification)
    func keyboardWillHide(_ notification: Notification)
    func startObservingKeyboardChanges()
    func stopObservingKeyboardChanges()
}


extension KeyboardHandler where Self: UIViewController {

    func startObservingKeyboardChanges() {

        // NotificationCenter observers
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardWillShow, object: nil, queue: nil) { [weak self] notification in
          self?.keyboardWillShow(notification)
        }

        // Deal with rotations
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil, queue: nil) { [weak self] notification in
          self?.keyboardWillShow(notification)
        }

        // Deal with keyboard change (emoji, numerical, etc.)
        NotificationCenter.default.addObserver(forName: NSNotification.Name.UITextInputCurrentInputModeDidChange, object: nil, queue: nil) { [weak self] notification in
          self?.keyboardWillShow(notification)
        }

        NotificationCenter.default.addObserver(forName: NSNotification.Name.UIKeyboardWillHide, object: nil, queue: nil) { [weak self] notification in
          self?.keyboardWillHide(notification)
        }
    }


    func keyboardWillShow(_ notification: Notification) {

      let verticalPadding: CGFloat = 20 // Padding between the bottom of the view and the top of the keyboard

      guard let value = notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue else { return }
      let keyboardHeight = value.cgRectValue.height

      // Here you could have more complex rules, like checking if the textField currently selected is actually covered by the keyboard, but that's out of this scope.
      self.bottomConstraint.constant = keyboardHeight + verticalPadding

      UIView.animate(withDuration: 0.1, animations: { () -> Void in
          self.view.layoutIfNeeded()
      })
  }


  func keyboardWillHide(_ notification: Notification) {
      self.bottomConstraint.constant = 0

      UIView.animate(withDuration: 0.1, animations: { () -> Void in
          self.view.layoutIfNeeded()
      })
  }


  func stopObservingKeyboardChanges() {
      NotificationCenter.default.removeObserver(self)
  }

}

Then, to implement it in a UIViewController, do the following:

  • let the viewController conform to this protocol :

    class FormMailVC: UIViewControlle, KeyboardHandler {
    
  • start observing keyboard changes in viewWillAppear:

    // MARK: - View controller life cycle
    override func viewWillAppear(_ animated: Bool) {
      super.viewWillAppear(animated)
      startObservingKeyboardChanges()
    }
    
  • stop observing keyboard changes in viewWillDisappear:

    override func viewWillDisappear(_ animated: Bool) {
      super.viewWillDisappear(animated)
      stopObservingKeyboardChanges()
    }
    
  • create an IBOutlet for the bottom constraint from the storyboard:

    // NSLayoutConstraints
    @IBOutlet weak var bottomConstraint: NSLayoutConstraint!
    

    (I recommend having all of your UI embedded inside a "contentView", and linking to this property the bottom constraint from this contentView to the bottom layout guide) Content view bottom constraint

  • change the constraint priority of the top constraint to 250 (low)

Content view top constraint

This is to let the whole content view slide upwards when the keyboard appears. The priority must be lower than any other constraint priority in the subviews, including content hugging priorities / content compression resistance priorities.

  • Make sure that your Autolayout has enough constraints to determine how the contentView should slide up.

You may have to add a "greater than equal" constraint for this: "greater than equal" constraint

And here you go! Without keyboard

With keyboard

PHPmailer sending HTML CODE

just you need to pass true as an argument to IsHTML() function.

CSS transition with visibility not working

Visibility is animatable. Check this blog post about it: http://www.greywyvern.com/?post=337

You can see it here too: https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_animated_properties

Let's say you have a menu that you want to fade-in and fade-out on mouse hover. If you use opacity:0 only, your transparent menu will still be there and it will animate when you hover the invisible area. But if you add visibility:hidden, you can eliminate this problem:

_x000D_
_x000D_
div {_x000D_
    width:100px;_x000D_
    height:20px;_x000D_
}_x000D_
.menu {_x000D_
    visibility:hidden;_x000D_
    opacity:0;_x000D_
    transition:visibility 0.3s linear,opacity 0.3s linear;_x000D_
    _x000D_
    background:#eee;_x000D_
    width:100px;_x000D_
    margin:0;_x000D_
    padding:5px;_x000D_
    list-style:none;_x000D_
}_x000D_
div:hover > .menu {_x000D_
    visibility:visible;_x000D_
    opacity:1;_x000D_
}
_x000D_
<div>_x000D_
  <a href="#">Open Menu</a>_x000D_
  <ul class="menu">_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
    <li><a href="#">Item</a></li>_x000D_
  </ul>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Genymotion Android emulator - adb access?

Just Go To the Genymotion Installation Directory and then in folder tools you will see adb.exe there open command prompt here and run adb commands

How do I update a Linq to SQL dbml file?

To update a table in your .dbml-diagram with, for example, added columns, do this:

  1. Update your SQL Server Explorer window.
  2. Drag the "new" version of your table into the .dbml-diagram (report1 in the picture below).

report1 is the new version of the table

  1. Mark the added columns in the new version of the table, press Ctrl+C to copy the added columns.

copy the added columns

  1. Click the "old" version of your table and press Ctrl+V to paste the added columns into the already present version of the table.

paste the added columns to the old version of the table

jQuery hide and show toggle div with plus and minus icon

this works:

http://jsfiddle.net/UhEut/

CSS:

.show_hide {
    display:none;
}
.plus:after {
    content:" +";
}
.minus:after {
    content:" -";
}

jQuery:

$(document).ready(function(){
  $(".slidingDiv").hide();
  $(".show_hide").addClass("plus").show();
  $('.show_hide').toggle(
      function(){
          $(".slidingDiv").slideDown();
          $(this).addClass("minus");
          $(this).removeClass("plus");
      },
      function(){
          $(".slidingDiv").slideUp();
          $(this).addClass("plus");
          $(this).removeClass("minus");
      }
  );
});

HTML:

<a href="#" class="show_hide">Show/hide</a>

<div class="slidingDiv" style="display: block;">
Check out the updated jQuery plugin for doing this: <a href="http://papermashup.com/jquery-show-hide-plugin/" class="show_hide" target="_blank" style="display: inline;">jQuery Show / Hide Plugin</a>
</div>

in the CSS, instead of content:" +"; You can put an background-image (with background-position:right center; and background-repeat:no-repeat and maybe making the .show_hide displayed as block and give him a width, so that the bg-image is not overlayed by the link-text itself).

CSS3 equivalent to jQuery slideUp and slideDown?

I changed your solution, so that it works in all modern browsers:

css snippet:

-webkit-transition: height 1s ease-in-out;
-moz-transition: height 1s ease-in-out;
-ms-transition: height 1s ease-in-out;
-o-transition: height 1s ease-in-out;
transition: height 1s ease-in-out;

js snippet:

    var clone = $('#this').clone()
                .css({'position':'absolute','visibility':'hidden','height':'auto'})
                .addClass('slideClone')
                .appendTo('body');

    var newHeight = $(".slideClone").height();
    $(".slideClone").remove();
    $('#this').css('height',newHeight + 'px');

here's the full example http://jsfiddle.net/RHPQd/

How to insert DECIMAL into MySQL database

I noticed something else about your coding.... look

INSERT INTO reports_services (id,title,description,cost) VALUES (0, 'test title', 'test decription ', '3.80')

in your "CREATE TABLE" code you have the id set to "AUTO_INCREMENT" which means it's automatically generating a result for that field.... but in your above code you include it as one of the insertions and in the "VALUES" you have a 0 there... idk if that's your way of telling us you left it blank because it's set to AUTO_INC. or if that's the actual code you have... if it's the code you have not only should you not be trying to send data to a field set to generate it automatically, but the RIGHT WAY to do it WRONG would be

'0',

you put

0,

lol....so that might be causing some of the problem... I also just noticed in the code after "test description" you have a space before the '.... that might be throwing something off too.... idk.. I hope this helps n maybe resolves some other problem you might be pulling your hair out about now.... speaking of which.... I need to figure out my problem before I tear all my hair out..... good luck.. :)

UPDATE.....

I almost forgot... if you have the 0 there to show that it's blank... you could be entering "test title" as the id and "test description" as the title then "3.whatever cents" for the description leaving "cost" empty...... which could be why it maxed out because if I'm not mistaking you have it set to NOT NULL.... and you left it null... so it forced something... maybe.... lol

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

I don't think that one is better than the other in general; it depends on how you intend to use it.

  • If you want to store it in a DB column that has a charset/collation that does not support the right single quote character, you may run into storing it as the multi-byte character instead of 7-bit ASCII (&rsquo;).
  • If you are displaying it on an html element that specifies a charset that does not support it, it may not display in either case.
  • If many developers are going to be editing/viewing this file with editors/keyboards that do not support properly typing or displaying the character, you may want to use the entity
  • If you need to convert the file between various character encodings or formats, you may want to use the entity
  • If your HTML code may escape entities improperly, you may want to use the character.

In general I would lean more towards using the character because as you point out it is easier to read and type.

No assembly found containing an OwinStartupAttribute Error

just paste this code <add key="owin:AutomaticAppStartup" value="false" /> in Web.config Not In web.config there is two webconfig so be sure that it will been paste in Web.Config

Message 'src refspec master does not match any' when pushing commits in Git

In my case fastlane match nuke development (which deletes the development certificates and profiles from the git credential store and the Developer Portal) tried to push master but we don't have master. Since we have two different teams we have also 2 different branches. What solved the problem was to call tell match about the correct branch:

fastlane match --git_branch <your_branch> nuke development

Difference between filter and filter_by in SQLAlchemy

filter_by is used for simple queries on the column names using regular kwargs, like

db.users.filter_by(name='Joe')

The same can be accomplished with filter, not using kwargs, but instead using the '==' equality operator, which has been overloaded on the db.users.name object:

db.users.filter(db.users.name=='Joe')

You can also write more powerful queries using filter, such as expressions like:

db.users.filter(or_(db.users.name=='Ryan', db.users.country=='England'))

Reorder bars in geom_bar ggplot2 by value

Your code works fine, except that the barplot is ordered from low to high. When you want to order the bars from high to low, you will have to add a -sign before value:

ggplot(corr.m, aes(x = reorder(miRNA, -value), y = value, fill = variable)) + 
  geom_bar(stat = "identity")

which gives:

enter image description here


Used data:

corr.m <- structure(list(miRNA = structure(c(5L, 2L, 3L, 6L, 1L, 4L), .Label = c("mmu-miR-139-5p", "mmu-miR-1983", "mmu-miR-301a-3p", "mmu-miR-5097", "mmu-miR-532-3p", "mmu-miR-96-5p"), class = "factor"),
                         variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L), .Label = "pos", class = "factor"),
                         value = c(7L, 75L, 70L, 5L, 10L, 47L)),
                    class = "data.frame", row.names = c("1", "2", "3", "4", "5", "6"))

Regex Last occurrence?

Your negative lookahead solution would e.g. be this:

\\(?:.(?!\\))+$

See it here on Regexr

Correct way to use StringBuilder in SQL

You are correct in guessing that the aim of using string builder is not achieved, at least not to its full extent.

However, when the compiler sees the expression "select id1, " + " id2 " + " from " + " table" it emits code which actually creates a StringBuilder behind the scenes and appends to it, so the end result is not that bad afterall.

But of course anyone looking at that code is bound to think that it is kind of retarded.

How do I add a placeholder on a CharField in Django?

For a ModelForm, you can use the Meta class thus:

from django import forms

from .models import MyModel

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'name': forms.TextInput(attrs={'placeholder': 'Name'}),
            'description': forms.Textarea(
                attrs={'placeholder': 'Enter description here'}),
        }

Git list of staged files

The best way to do this is by running the command:

git diff --name-only --cached

When you check the manual you will likely find the following:

--name-only
    Show only names of changed files.

And on the example part of the manual:

git diff --cached
    Changes between the index and your current HEAD.

Combined together you get the changes between the index and your current HEAD and Show only names of changed files.

Update: --staged is also available as an alias for --cached above in more recent git versions.

Batch file script to zip files

This is the correct syntax for archiving individual; folders in a batch as individual zipped files...

for /d %%X in (*) do "c:\Program Files\7-Zip\7z.exe" a -mx "%%X.zip" "%%X\*"

How to use querySelectorAll only for elements that have a specific attribute set?

Extra Tips:

Multiple "nots", input that is NOT hidden and NOT disabled:

:not([type="hidden"]):not([disabled])

Also did you know you can do this:

node.parentNode.querySelectorAll('div');

This is equivelent to jQuery's:

$(node).parent().find('div');

Which will effectively find all divs in "node" and below recursively, HOT DAMN!

What is Bootstrap?

Bootstrap is Open source HTML Framework. which compatible at almost every Browser. Basically Large Screen Browser width is >992px and extra Large 1200px. so by using Bootstrap defined classes we can adjust screen resolution for displaying contents at every screen from small mobiles to Larger Screen. I tried to explain very short. for Example :

<div class="col-sm-3">....</div>
<div class="col-sm-9">....</div>

How do I remove link underlining in my HTML email?

Another way to fool Gmail (for phone numbers): use a ~ instead of a -

404-835-9421 --> 404~835~9421

It'll save you (or less savvy users ;-) the trip down html lane.

I found another way to remove links in outlook that i tested so far. if you create a blank class for example in your css say .blank {} and then do the following to your links for example:

<a href="http://www.link.com/"><span class="blank" style="text-decoration:none !important;">Search</span></a>

this worked for me hopefully it will help someone who is still having trouble taking out the underline of links in outlook. If anyone has a workaround for gmail please could you help me tried everything in this thread nothing is working.

Thanks

C++ Erase vector element by value rather than by position?

Eric Niebler is working on a range-proposal and some of the examples show how to remove certain elements. Removing 8. Does create a new vector.

#include <iostream>
#include <range/v3/all.hpp>

int main(int argc, char const *argv[])
{
    std::vector<int> vi{2,4,6,8,10};
    for (auto& i : vi) {
        std::cout << i << std::endl;
    }
    std::cout << "-----" << std::endl;
    std::vector<int> vim = vi | ranges::view::remove_if([](int i){return i == 8;});
    for (auto& i : vim) {
        std::cout << i << std::endl;
    }
    return 0;
}

outputs

2
4
6
8
10
-----
2
4
6
10

CodeIgniter Select Query

$query= $this->m_general->get('users' , array('id'=> $id ));
echo $query[''];

is ok ;)

How to escape a JSON string containing newline characters using JavaScript?

As per user667073 suggested, except reordering the backslash replacement first, and fixing the quote replacement

escape = function (str) {
  return str
    .replace(/[\\]/g, '\\\\')
    .replace(/[\"]/g, '\\\"')
    .replace(/[\/]/g, '\\/')
    .replace(/[\b]/g, '\\b')
    .replace(/[\f]/g, '\\f')
    .replace(/[\n]/g, '\\n')
    .replace(/[\r]/g, '\\r')
    .replace(/[\t]/g, '\\t');
};

How to find all tables that have foreign keys that reference particular table.column and have values for those foreign keys?

Listing all foreign keys in a db including description

    SELECT  
    i1.CONSTRAINT_NAME, i1.TABLE_NAME,i1.COLUMN_NAME,
    i1.REFERENCED_TABLE_SCHEMA,i1.REFERENCED_TABLE_NAME, i1.REFERENCED_COLUMN_NAME,
    i2.UPDATE_RULE, i2.DELETE_RULE 
    FROM   
    information_schema.KEY_COLUMN_USAGE AS i1  
    INNER JOIN 
    information_schema.REFERENTIAL_CONSTRAINTS AS i2 
    ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME 
    WHERE i1.REFERENCED_TABLE_NAME IS NOT NULL  
    AND  i1.TABLE_SCHEMA  ='db_name';

restricting to a specific column in a table table

AND i1.table_name = 'target_tb_name' AND i1.column_name = 'target_col_name'

Java, reading a file from current directory?

If you know your file will live where your classes are, that directory will be on your classpath. In that case, you can be sure that this solution will solve your problem:

URL path = ClassLoader.getSystemResource("myFile.txt");
if(path==null) {
     //The file was not found, insert error handling here
}
File f = new File(path.toURI());

reader = new BufferedReader(new FileReader(f));

Truncate to three decimals in Python

How about this:

In [1]: '%.3f' % round(1324343032.324325235 * 1000 / 1000,3)
Out[1]: '1324343032.324'

Possible duplicate of round() in Python doesn't seem to be rounding properly

[EDIT]

Given the additional comments I believe you'll want to do:

In : Decimal('%.3f' % (1324343032.324325235 * 1000 / 1000))
Out: Decimal('1324343032.324')

The floating point accuracy isn't going to be what you want:

In : 3.324
Out: 3.3239999999999998

(all examples are with Python 2.6.5)

Printing a java map Map<String, Object> - How?

You may use Map.entrySet() method:

for (Map.Entry entry : objectSet.entrySet())
{
    System.out.println("key: " + entry.getKey() + "; value: " + entry.getValue());
}

Override back button to act like home button

If you want to catch the Back Button have a look at this post on the Android Developer Blog. It covers the easier way to do this in Android 2.0 and the best way to do this for an application that runs on 1.x and 2.0.

However, if your Activity is Stopped it still may be killed depending on memory availability on the device. If you want a process to run with no UI you should create a Service. The documentation says the following about Services:

A service doesn't have a visual user interface, but rather runs in the background for an indefinite period of time. For example, a service might play background music as the user attends to other matters, or it might fetch data over the network or calculate something and provide the result to activities that need it.

These seems appropriate for your requirements.

In HTML5, should the main navigation be inside or outside the <header> element?

It's a little unclear whether you're asking for opinions, eg. "it's common to do xxx" or an actual rule, so I'm going to lean in the direction of rules.

The examples you cite seem based upon the examples in the spec for the nav element. Remember that the spec keeps getting tweaked and the rules are sometimes convoluted, so I'd venture many people might tend to just do what's given rather than interpret. You're showing two separate examples with different behavior, so there's only so much you can read into it. Do either of those sites also have the opposing sub/nav situation, and if so how do they handle it?

Most importantly, though, there's nothing in the spec saying either is the way to do it. One of the goals with HTML5 was to be very clear[this for comparison] about semantics, requirements, etc. so the omission is worth noting. As far as I can see, the examples are independent of each other and equally valid within their own context of layout requirements, etc.

Having the nav's source position be conditional is kind of silly(another red flag). Just pick a method and go with it.

X-UA-Compatible is set to IE=edge, but it still doesn't stop Compatibility Mode

Additionally, X-UA-Compatible must be the first meta tag in the head section

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
</head>

By the way, the correct order or the main head tags are:

<head>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta charset="utf-8">
    <title>Site Title</title>
    <!-- other tags -->
</head>

This way

  1. we set the render engine to use before IExplorer begins to process
  2. the document then we set the encoding to use for all browser
  3. then we print the title, which will be processed with the already defined encoding.

How to write a basic swap function in Java

Java is pass by value. So the swap in the sense you mean is not possible. But you can swap contents of two objects or you do it inline.

Remove Unnamed columns in pandas dataframe

First, find the columns that have 'unnamed', then drop those columns. Note: You should Add inplace = True to the .drop parameters as well.

df.drop(df.columns[df.columns.str.contains('unnamed',case = False)],axis = 1, inplace = True)

How to clear form after submit in Angular 2?

Here is how I do it in Angular 7.3

// you can put this method in a module and reuse it as needed
resetForm(form: FormGroup) {

    form.reset();

    Object.keys(form.controls).forEach(key => {
      form.get(key).setErrors(null) ;
    });
}

There was no need to call form.clearValidators()

Presenting a UIAlertController properly on an iPad using iOS 8

Just add the following code before presenting your action sheet:

if let popoverController = optionMenu.popoverPresentationController {
    popoverController.sourceView = self.view
    popoverController.sourceRect = CGRect(x: self.view.bounds.midX, y: self.view.bounds.midY, width: 0, height: 0)
    popoverController.permittedArrowDirections = []
}

How can I replace non-printable Unicode characters in Java?

my_string.replaceAll("\\p{C}", "?");

See more about Unicode regex. java.util.regexPattern/String.replaceAll supports them.

Overriding !important style

If you want to update / add single style in DOM Element style attribute you can use this function:

function setCssTextStyle(el, style, value) {
  var result = el.style.cssText.match(new RegExp("(?:[;\\s]|^)(" +
      style.replace("-", "\\-") + "\\s*:(.*?)(;|$))")),
    idx;
  if (result) {
    idx = result.index + result[0].indexOf(result[1]);
    el.style.cssText = el.style.cssText.substring(0, idx) +
      style + ": " + value + ";" +
      el.style.cssText.substring(idx + result[1].length);
  } else {
    el.style.cssText += " " + style + ": " + value + ";";
  }
}

style.cssText is supported for all major browsers.

Use case example:

var elem = document.getElementById("elementId");
setCssTextStyle(elem, "margin-top", "10px !important");

Here is link to demo

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

For ENOENT on Windows, https://github.com/nodejs/node-v0.x-archive/issues/2318#issuecomment-249355505 fix it.

e.g. replace spawn('npm', ['-v'], {stdio: 'inherit'}) with:

  • for all node.js version:

    spawn(/^win/.test(process.platform) ? 'npm.cmd' : 'npm', ['-v'], {stdio: 'inherit'})
    
  • for node.js 5.x and later:

    spawn('npm', ['-v'], {stdio: 'inherit', shell: true})
    

How to unpackage and repackage a WAR file

you can update your war from the command line using java commands as mentioned here:

jar -uvf test.war yourclassesdir 

Other useful commands:

Command to unzip/explode the war file

jar -xvf test.war

Command to create the war file

jar -cvf test.war yourclassesdir 

Eg:

jar -cvf test.war *
jar -cvf test.war WEB-INF META-INF

static and extern global variables in C and C++

When you #include a header, it's exactly as if you put the code into the source file itself. In both cases the varGlobal variable is defined in the source so it will work no matter how it's declared.

Also as pointed out in the comments, C++ variables at file scope are not static in scope even though they will be assigned to static storage. If the variable were a class member for example, it would need to be accessible to other compilation units in the program by default and non-class members are no different.

How to set zoom level in google map

What you're looking for are the scales for each zoom level. The numbers are in metres. Use these:

20 : 1128.497220

19 : 2256.994440

18 : 4513.988880

17 : 9027.977761

16 : 18055.955520

15 : 36111.911040

14 : 72223.822090

13 : 144447.644200

12 : 288895.288400

11 : 577790.576700

10 : 1155581.153000

9 : 2311162.307000

8 : 4622324.614000

7 : 9244649.227000

6 : 18489298.450000

5 : 36978596.910000

4 : 73957193.820000

3 : 147914387.600000

2 : 295828775.300000

1 : 591657550.500000

html5 audio player - jquery toggle click play/pause?

Simple Add this Code

        var status = "play"; // Declare global variable

        if (status == 'pause') {
            status='play';                
        } else {
            status = 'pause';     
        }
        $("#audio").trigger(status);    

Cannot ping AWS EC2 instance

Go to the security group of the EC2 instance and edit the inbound rule allow 0.0.0.0/0 for ICMP.

It will work.

document.getelementbyId will return null if element is not defined?

Yes it will return null if it's not present you can try this below in the demo. Both will return true. The first elements exists the second doesn't.

Demo

Html

<div id="xx"></div>

Javascript:

   if (document.getElementById('xx') !=null) 
     console.log('it exists!');

   if (document.getElementById('xxThisisNotAnElementOnThePage') ==null) 
     console.log('does not exist!');

How to clear the cache of nginx?

I had the exact same problem - I was running my nginx in Virtualbox. I did not have caching turned on. But looks like sendfile was set to on in nginx.conf and that was causing the problem. @kolbyjack mentioned it above in the comments.

When I turned off sendfile - it worked fine.

This is because:

Sendfile is used to ‘copy data between one file descriptor and another‘ and apparently has some real trouble when run in a virtual machine environment, or at least when run through Virtualbox. Turning this config off in nginx causes the static file to be served via a different method and your changes will be reflected immediately and without question

It is related to this bug: https://www.virtualbox.org/ticket/12597

Run certain code every n seconds

import threading

def printit():
  threading.Timer(5.0, printit).start()
  print "Hello, World!"

printit()

# continue with the rest of your code

https://docs.python.org/3/library/threading.html#timer-objects

Format datetime in asp.net mvc 4

Client validation issues can occur because of MVC bug (even in MVC 5) in jquery.validate.unobtrusive.min.js which does not accept date/datetime format in any way. Unfortunately you have to solve it manually.

My finally working solution:

$(function () {
    $.validator.methods.date = function (value, element) {
        return this.optional(element) || moment(value, "DD.MM.YYYY", true).isValid();
    }
});

You have to include before:

@Scripts.Render("~/Scripts/jquery-3.1.1.js")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")
@Scripts.Render("~/Scripts/moment.js")

You can install moment.js using:

Install-Package Moment.js

MATLAB - multiple return values from a function?

Change the function that you get one single Result=[array, listp, freep]. So there is only one result to be displayed

Java check to see if a variable has been initialized

Assuming you're interested in whether the variable has been explicitly assigned a value or not, the answer is "not really". There's absolutely no difference between a field (instance variable or class variable) which hasn't been explicitly assigned at all yet, and one which has been assigned its default value - 0, false, null etc.

Now if you know that once assigned, the value will never reassigned a value of null, you can use:

if (box != null) {
    box.removeFromCanvas();
}

(and that also avoids a possible NullPointerException) but you need to be aware that "a field with a value of null" isn't the same as "a field which hasn't been explicitly assigned a value". Null is a perfectly valid variable value (for non-primitive variables, of course). Indeed, you may even want to change the above code to:

if (box != null) {
    box.removeFromCanvas();
    // Forget about the box - we don't want to try to remove it again
    box = null;
}

The difference is also visible for local variables, which can't be read before they've been "definitely assigned" - but one of the values which they can be definitely assigned is null (for reference type variables):

// Won't compile
String x;
System.out.println(x);

// Will compile, prints null
String y = null;
System.out.println(y);

Keep only date part when using pandas.to_datetime

I wanted to be able to change the type for a set of columns in a data frame and then remove the time keeping the day. round(), floor(), ceil() all work

df[date_columns] = df[date_columns].apply(pd.to_datetime)
df[date_columns] = df[date_columns].apply(lambda t: t.dt.floor('d'))

How do I run a Python program?

Python itself comes with an editor that you can access from the IDLE File > New File menu option.

Write the code in that file, save it as [filename].py and then (in that same file editor window) press F5 to execute the code you created in the IDLE Shell window.

Note: it's just been the easiest and most straightforward way for me so far.

What processes are using which ports on unix?

If you want to know all listening ports along with its details: local address, foreign address and state as well as Process ID (PID). You can use following command for it in linux.

 netstat -tulpn

ITextSharp insert text to an existing pdf

In addition to the excellent answers above, the following shows how to add text to each page of a multi-page document:

 using (var reader = new PdfReader(@"C:\Input.pdf"))
 {
    using (var fileStream = new FileStream(@"C:\Output.pdf", FileMode.Create, FileAccess.Write))
    {
       var document = new Document(reader.GetPageSizeWithRotation(1));
       var writer = PdfWriter.GetInstance(document, fileStream);

       document.Open();

       for (var i = 1; i <= reader.NumberOfPages; i++)
       {
          document.NewPage();

          var baseFont = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
          var importedPage = writer.GetImportedPage(reader, i);

          var contentByte = writer.DirectContent;
          contentByte.BeginText();
          contentByte.SetFontAndSize(baseFont, 12);

          var multiLineString = "Hello,\r\nWorld!".Split('\n');

          foreach (var line in multiLineString)
          {
             contentByte.ShowTextAligned(PdfContentByte.ALIGN_LEFT, line, 200, 200, 0);
          }

          contentByte.EndText();
          contentByte.AddTemplate(importedPage, 0, 0);
       }

       document.Close();
       writer.Close();
    }
 }

python pip - install from local dir

All you need to do is run

pip install /opt/mypackage

and pip will search /opt/mypackage for a setup.py, build a wheel, then install it.

The problem with using the -e flag for pip install as suggested in the comments and this answer is that this requires that the original source directory stay in place for as long as you want to use the module. It's great if you're a developer working on the source, but if you're just trying to install a package, it's the wrong choice.

Alternatively, you don't even need to download the repo from Github at all. pip supports installing directly from git repos using a variety of protocols including HTTP, HTTPS, and SSH, among others. See the docs I linked to for examples.

How to replace local branch with remote branch entirely in Git?

The ugly but simpler way: delete your local folder, and clone the remote repository again.

Cannot install Aptana Studio 3.6 on Windows

I had the same problem. I solved by installing NodeJS from this link: http://go.aptana.com/installer_nodejs_windows and Git latest version from https://git-scm.com/downloads.

Finally I was able to run the Aptana installer with no problems.

MYSQL into outfile "access denied" - but my user has "ALL" access.. and the folder is CHMOD 777

I tried all the solutions but it still wasn't sufficient. After some more digging I eventually found I had also to set the 'file_priv' flag, and restart mysql.

To resume :

Grant the privileges :

> GRANT ALL PRIVILEGES
  ON my_database.* 
  to 'my_user'@'localhost';

> GRANT FILE ON *.* TO my_user;

> FLUSH PRIVILEGES; 

Set the flag :

> UPDATE mysql.user SET File_priv = 'Y' WHERE user='my_user' AND host='localhost';

Finally restart the mysql server:

$ sudo service mysql restart

After that, I could write into the secure_file_priv directory. For me it was /var/lib/mysql-files/, but you can check it with the following command :

> SHOW VARIABLES LIKE "secure_file_priv";

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

How to read pdf file and write it to outputStream

You can use PdfBox from Apache which is simple to use and has good performance.

Here is an example of extracting text from a PDF file (you can read more here) :

import java.io.*;
import org.apache.pdfbox.pdmodel.*;
import org.apache.pdfbox.util.*;

public class PDFTest {

 public static void main(String[] args){
 PDDocument pd;
 BufferedWriter wr;
 try {
         File input = new File("C:\\Invoice.pdf");  // The PDF file from where you would like to extract
         File output = new File("C:\\SampleText.txt"); // The text file where you are going to store the extracted data
         pd = PDDocument.load(input);
         System.out.println(pd.getNumberOfPages());
         System.out.println(pd.isEncrypted());
         pd.save("CopyOfInvoice.pdf"); // Creates a copy called "CopyOfInvoice.pdf"
         PDFTextStripper stripper = new PDFTextStripper();
         wr = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(output)));
         stripper.writeText(pd, wr);
         if (pd != null) {
             pd.close();
         }
        // I use close() to flush the stream.
        wr.close();
 } catch (Exception e){
         e.printStackTrace();
        } 
     }
}

UPDATE:

You can get the text using PDFTextStripper:

PDFTextStripper reader = new PDFTextStripper();
String pageText = reader.getText(pd); // PDDocument object created

How do I find the length (or dimensions, size) of a numpy matrix in python?

shape is a property of both numpy ndarray's and matrices.

A.shape

will return a tuple (m, n), where m is the number of rows, and n is the number of columns.

In fact, the numpy matrix object is built on top of the ndarray object, one of numpy's two fundamental objects (along with a universal function object), so it inherits from ndarray

Xcode stuck on Indexing

I had a similar problem, and found that I accidentally defined a class as its own subclass. I got no warning or error for this but the compiling got stuck.

class mainClass : mainClass
{
    ...
}