Programs & Examples On #Hateoas

HATEOAS is an acronym for Hypermedia As The Engine of Application State. Its usage makes your RESTful APIs self discoverable and makes them Level 3 RMM compliant.

Best way to handle list.index(might-not-exist) in python?

The dict type has a get function, where if the key doesn't exist in the dictionary, the 2nd argument to get is the value that it should return. Similarly there is setdefault, which returns the value in the dict if the key exists, otherwise it sets the value according to your default parameter and then returns your default parameter.

You could extend the list type to have a getindexdefault method.

class SuperDuperList(list):
    def getindexdefault(self, elem, default):
        try:
            thing_index = self.index(elem)
            return thing_index
        except ValueError:
            return default

Which could then be used like:

mylist = SuperDuperList([0,1,2])
index = mylist.getindexdefault( 'asdf', -1 )

How to save an HTML5 Canvas as an image on a server?

Here is an example of how to achieve what you need:

  1. Draw something (taken from canvas tutorial)

_x000D_
_x000D_
<canvas id="myCanvas" width="578" height="200"></canvas>
<script>
  var canvas = document.getElementById('myCanvas');
  var context = canvas.getContext('2d');

  // begin custom shape
  context.beginPath();
  context.moveTo(170, 80);
  context.bezierCurveTo(130, 100, 130, 150, 230, 150);
  context.bezierCurveTo(250, 180, 320, 180, 340, 150);
  context.bezierCurveTo(420, 150, 420, 120, 390, 100);
  context.bezierCurveTo(430, 40, 370, 30, 340, 50);
  context.bezierCurveTo(320, 5, 250, 20, 250, 50);
  context.bezierCurveTo(200, 5, 150, 20, 170, 80);

  // complete custom shape
  context.closePath();
  context.lineWidth = 5;
  context.fillStyle = '#8ED6FF';
  context.fill();
  context.strokeStyle = 'blue';
  context.stroke();
</script>
_x000D_
_x000D_
_x000D_

  1. Convert canvas image to URL format (base64)

    var dataURL = canvas.toDataURL();

  2. Send it to your server via Ajax

_x000D_
_x000D_
    $.ajax({
      type: "POST",
      url: "script.php",
      data: { 
         imgBase64: dataURL
      }
    }).done(function(o) {
      console.log('saved'); 
      // If you want the file to be visible in the browser 
      // - please modify the callback in javascript. All you
      // need is to return the url to the file, you just saved 
      // and than put the image in your browser.
    });
_x000D_
_x000D_
_x000D_

  1. Save base64 on your server as an image (here is how to do this in PHP, the same ideas is in every language. Server side in PHP can be found here):

How to delete zero components in a vector in Matlab?

You could use sparse(a), which would return

(1,2) 1

(1,4) 3

This allows you to keep the information about where your non-zero entries used to be.

How to check whether an array is empty using PHP?

An empty array is falsey in PHP, so you don't even need to use empty() as others have suggested.

<?php
$playerList = array();
if (!$playerList) {
    echo "No players";
} else {
    echo "Explode stuff...";
}
// Output is: No players

PHP's empty() determines if a variable doesn't exist or has a falsey value (like array(), 0, null, false, etc).

In most cases you just want to check !$emptyVar. Use empty($emptyVar) if the variable might not have been set AND you don't wont to trigger an E_NOTICE; IMO this is generally a bad idea.

Exporting functions from a DLL with dllexport

I think _naked might get what you want, but it also prevents the compiler from generating the stack management code for the function. extern "C" causes C style name decoration. Remove that and that should get rid of your _'s. The linker doesn't add the underscores, the compiler does. stdcall causes the argument stack size to be appended.

For more, see: http://en.wikipedia.org/wiki/X86_calling_conventions http://www.codeproject.com/KB/cpp/calling_conventions_demystified.aspx

The bigger question is why do you want to do that? What's wrong with the mangled names?

EOL conversion in notepad ++

I open files "directly" from WinSCP which opens the files in Notepad++ I had a php files on my linux server which always opened in Mac format no matter what I did :-(

If I downloaded the file and then opened it from local (windows) it was open as Dos/Windows....hmmm

The solution was to EOL-convert the local file to "UNIX/OSX Format", save it and then upload it.

Now when I open the file directly from the server it's open as "Dos/Windows" :-)

How to escape % in String.Format?

Here's an option if you need to escape multiple %'s in a string with some already escaped.

(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])

To sanitise the message before passing it to String.format, you can use the following

Pattern p = Pattern.compile("(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])");
Matcher m1 = p.matcher(log);

StringBuffer buf = new StringBuffer();
while (m1.find())
    m1.appendReplacement(buf, log.substring(m1.start(), m1.start(2)) + "%%" + log.substring(m1.end(2), m1.end()));

// Return the sanitised message
String escapedString = m1.appendTail(buf).toString();

This works with any number of formatting characters, so it will replace % with %%, %%% with %%%%, %%%%% with %%%%%% etc.

It will leave any already escaped characters alone (e.g. %%, %%%% etc.)

invalid target release: 1.7

This probably works for a lot of things but it's not enough for Maven and certainly not for the maven compiler plugin.

Check Mike's answer to his own question here: stackoverflow question 24705877

This solved the issue for me both command line AND within eclipse.

Also, @LinGao answer to stackoverflow question 2503658 and the use of the $JAVACMD variable might help but I haven't tested it myself.

How to uninstall pip on OSX?

In my case I ran the following command and it worked (not that I was expecting it to):

sudo pip uninstall pip

Which resulted in:

Uninstalling pip-6.1.1:
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/DESCRIPTION.rst
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/METADATA
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/RECORD
  <and all the other stuff>
  ...

  /usr/local/bin/pip
  /usr/local/bin/pip2
  /usr/local/bin/pip2.7
Proceed (y/n)? y
  Successfully uninstalled pip-6.1.1

Finding the id of a parent div using Jquery

JQUery has a .parents() method for moving up the DOM tree you can start there.

If you're interested in doing this a more semantic way I don't think using the REL attribute on a button is the best way to semantically define "this is the answer" in your code. I'd recommend something along these lines:

<p id="question1">
    <label for="input1">Volume =</label> 
    <input type="text" name="userInput1" id="userInput1" />
    <button type="button">Check answer</button>
    <input type="hidden" id="answer1" name="answer1" value="3.93e-6" />
</p>

and

$("button").click(function () {
    var correctAnswer = $(this).parent().siblings("input[type=hidden]").val();
    var userAnswer = $(this).parent().siblings("input[type=text]").val();
    validate(userAnswer, correctAnswer);
    $("#messages").html(feedback);
});

Not quite sure how your validate and feedback are working, but you get the idea.

System.IO.FileNotFoundException: Could not load file or assembly 'X' or one of its dependencies when deploying the application

... Could not load file or assembly 'X' or one of its dependencies ...

Most likely it fails to load another dependency.

you could try to check the dependencies with a dependency walker.

I.e: https://www.dependencywalker.com/

Also check your build configuration (x86 / 64)

Edit: I also had this problem once when I was copying dlls in zip from a "untrusted" network share. The file was locked by Windows and the FileNotFoundException was raised.

See here: Detected DLLs that are from the internet and "blocked" by CASPOL

How can I use Guzzle to send a POST request in JSON?

The simple and basic way (guzzle6):

$client = new Client([
    'headers' => [ 'Content-Type' => 'application/json' ]
]);

$response = $client->post('http://api.com/CheckItOutNow',
    ['body' => json_encode(
        [
            'hello' => 'World'
        ]
    )]
);

To get the response status code and the content of the body I did this:

echo '<pre>' . var_export($response->getStatusCode(), true) . '</pre>';
echo '<pre>' . var_export($response->getBody()->getContents(), true) . '</pre>';

HorizontalScrollView within ScrollView Touch Handling

Thank you Joel for giving me a clue on how to resolve this problem.

I have simplified the code(without need for a GestureDetector) to achieve the same effect:

public class VerticalScrollView extends ScrollView {
    private float xDistance, yDistance, lastX, lastY;

    public VerticalScrollView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                xDistance = yDistance = 0f;
                lastX = ev.getX();
                lastY = ev.getY();
                break;
            case MotionEvent.ACTION_MOVE:
                final float curX = ev.getX();
                final float curY = ev.getY();
                xDistance += Math.abs(curX - lastX);
                yDistance += Math.abs(curY - lastY);
                lastX = curX;
                lastY = curY;
                if(xDistance > yDistance)
                    return false;
        }

        return super.onInterceptTouchEvent(ev);
    }
}

Start/Stop and Restart Jenkins service on Windows

Step 01: You need to add jenkins for environment variables, Then you can use jenkins commands

Step 02: Go to "C:\Program Files (x86)\Jenkins" with admin prompt

Step 03: Choose your option: jenkins.exe stop / jenkins.exe start / jenkins.exe restart

How to properly stop the Thread in Java?

In the IndexProcessor class you need a way of setting a flag which informs the thread that it will need to terminate, similar to the variable run that you have used just in the class scope.

When you wish to stop the thread, you set this flag and call join() on the thread and wait for it to finish.

Make sure that the flag is thread safe by using a volatile variable or by using getter and setter methods which are synchronised with the variable being used as the flag.

public class IndexProcessor implements Runnable {

    private static final Logger LOGGER = LoggerFactory.getLogger(IndexProcessor.class);
    private volatile boolean running = true;

    public void terminate() {
        running = false;
    }

    @Override
    public void run() {
        while (running) {
            try {
                LOGGER.debug("Sleeping...");
                Thread.sleep((long) 15000);

                LOGGER.debug("Processing");
            } catch (InterruptedException e) {
                LOGGER.error("Exception", e);
                running = false;
            }
        }

    }
}

Then in SearchEngineContextListener:

public class SearchEngineContextListener implements ServletContextListener {

    private static final Logger LOGGER = LoggerFactory.getLogger(SearchEngineContextListener.class);

    private Thread thread = null;
    private IndexProcessor runnable = null;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        runnable = new IndexProcessor();
        thread = new Thread(runnable);
        LOGGER.debug("Starting thread: " + thread);
        thread.start();
        LOGGER.debug("Background process successfully started.");
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        LOGGER.debug("Stopping thread: " + thread);
        if (thread != null) {
            runnable.terminate();
            thread.join();
            LOGGER.debug("Thread successfully stopped.");
        }
    }
}

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

For Saturday and Sunday You can do something like this

             $('#orderdate').datepicker({
                               daysOfWeekDisabled: [0,6]
                 });

Replace substring with another substring C++

std::string replace(const std::string & in
                  , const std::string & from
                  , const std::string & to){
  if(from.size() == 0 ) return in;
  std::string out = "";
  std::string tmp = "";
  for(int i = 0, ii = -1; i < in.size(); ++i) {
    // change ii
    if     ( ii <  0 &&  from[0] == in[i] )  {
      ii  = 0;
      tmp = from[0]; 
    } else if( ii >= 0 && ii < from.size()-1 )  {
      ii ++ ;
      tmp = tmp + in[i];
      if(from[ii] == in[i]) {
      } else {
        out = out + tmp;
        tmp = "";
        ii = -1;
      }
    } else {
      out = out + in[i];
    }
    if( tmp == from ) {
      out = out + to;
      tmp = "";
      ii = -1;
    }
  }
  return out;
};

Facebook Open Graph not clearing cache

I was having this issue too. The scraper shows the right information, but the share url was still populated with old data.

The way I got around this was to use the feed method, instead of share, and then populate the data manually (which isn't exposed with the share method)

Something like this:

shareToFB = () => {
    window.FB.ui({
    method: 'feed',
    link: `signup.yourdomain.com/?referrer=${this.props.subscriber.sid}`,
    name: 'THIS WILL OVERRIDE OG:TITLE TAG',
    description: 'THIS WILL OVERRIDE OG:DESCRIPTION TAG',
    caption: 'THIS WILL OVERRIDE THE OG:URL TAG'
  });
};

Right way to split an std::string into a vector<string>

If the string has both spaces and commas you can use the string class function

found_index = myString.find_first_of(delims_str, begin_index) 

in a loop. Checking for != npos and inserting into a vector. If you prefer old school you can also use C's

strtok() 

method.

What is the convention in JSON for empty vs. null?

"JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types."

"The JSON empty concept applies for arrays and objects...Data object does not have a concept of empty lists. Hence, no action is taken on the data object for those properties."

Here is my source.

enumerate() for dictionary in python

The first column of output is the index of each item in enumm and the second one is its keys. If you want to iterate your dictionary then use .items():

for k, v in enumm.items():
    print(k, v)

And the output should look like:

0 1
1 2
2 3
4 4 
5 5
6 6
7 7

Python: Append item to list N times

Itertools repeat combined with list extend.

from itertools import repeat
l = []
l.extend(repeat(x, 100))

Round to 2 decimal places

BigDecimal a = new BigDecimal("12345.0789");
a = a.divide(new BigDecimal("1"), 2, BigDecimal.ROUND_HALF_UP);
//Also check other rounding modes
System.out.println("a >> "+a.toPlainString()); //Returns 12345.08

How to prevent SIGPIPEs (or handle them properly)

Or should I just catch the SIGPIPE with a handler and ignore it?

I believe that is right on. You want to know when the other end has closed their descriptor and that's what SIGPIPE tells you.

Sam

Customize list item bullets using CSS

If you wrap your <li> content in a <span> or other tag, you may change the font size of the <li>, which will change the size of the bullet, then reset the content of the <li> to its original size. You may use em units to resize the <li> bullet proportionally.

For example:

<ul>
    <li><span>First item</span></li>
    <li><span>Second item</span></li>
</ul>

Then CSS:

li {
    list-style-type: disc;
    font-size: 0.8em;
}

li * {
    font-size: initial;
}

A more complex example:

<!DOCTYPE html>
<html lang="en">
<head>
    <title>List Item Bullet Size</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <style>
ul.disc li {
    list-style-type: disc;
    font-size: 1.5em;
}

ul.square li {
    list-style-type: square;
    font-size: 0.8em;
}

li * {
    font-size: initial;
}
    </style>
</head>
<body>

<h1>First</h1>
<ul class="disc">
    <li><span>First item</span></li>
    <li><span>Second item</span></li>
</ul>

<h1>Second</h1>
<ul class="square">
    <li><span>First item</span></li>
    <li><span>Second item</span></li>
</ul>

</body>
</html>

Results in:

Result of markup

Running Python from Atom

The script package does exactly what you're looking for: https://atom.io/packages/script

The package's documentation also contains the key mappings, which you can easily customize.

Android Push Notifications: Icon not displaying in notification, white square shown instead

If you are using Google Cloud Messaging, then this issue will not be solved by simply changing your icon. For example, this will not work:

 Notification notification  = new Notification.Builder(this)
                .setContentTitle(title)
                .setContentText(text)
                .setSmallIcon(R.drawable.ic_notification)
                .setContentIntent(pIntent)
                .setDefaults(Notification.DEFAULT_SOUND|Notification.DEFAULT_LIGHTS|Notification.DEFAULT_VIBRATE)
                .setAutoCancel(true)
                .build();

Even if ic_notification is transparant and white. It must be also defined in the Manifest meta data, like so:

  <meta-data android:name="com.google.firebase.messaging.default_notification_icon"

            android:resource="@drawable/ic_notification" />

Meta-data goes under the application tag, for reference.

How do I disable log messages from the Requests library?

I found out how to configure requests's logging level, it's done via the standard logging module. I decided to configure it to not log messages unless they are at least warnings:

import logging

logging.getLogger("requests").setLevel(logging.WARNING)

If you wish to apply this setting for the urllib3 library (typically used by requests) too, add the following:

logging.getLogger("urllib3").setLevel(logging.WARNING)

Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?

We can give a default value for the timestamp to avoid this problem.

This post gives a detailed workaround: http://gusiev.com/2009/04/update-and-create-timestamps-with-mysql/

create table test_table( 
id integer not null auto_increment primary key, 
stamp_created timestamp default '0000-00-00 00:00:00', 
stamp_updated timestamp default now() on update now() 
);

Note that it is necessary to enter nulls into both columns during "insert":

mysql> insert into test_table(stamp_created, stamp_updated) values(null, null); 
Query OK, 1 row affected (0.06 sec)
mysql> select * from t5; 
+----+---------------------+---------------------+ 
| id | stamp_created       | stamp_updated       |
+----+---------------------+---------------------+
|  2 | 2009-04-30 09:44:35 | 2009-04-30 09:44:35 |
+----+---------------------+---------------------+
2 rows in set (0.00 sec)  
mysql> update test_table set id = 3 where id = 2; 
Query OK, 1 row affected (0.05 sec) Rows matched: 1  Changed: 1  Warnings: 0  
mysql> select * from test_table;
+----+---------------------+---------------------+
| id | stamp_created       | stamp_updated       | 
+----+---------------------+---------------------+ 
|  3 | 2009-04-30 09:44:35 | 2009-04-30 09:46:59 | 
+----+---------------------+---------------------+ 
2 rows in set (0.00 sec) 

JavaScript Infinitely Looping slideshow with delays?

You are calling setTimeout() ten times in a row, so they all expire almost at the same time. What you actually want is this:

window.onload = function start() {
    slide(10);
}
function slide(repeats) {
    if (repeats > 0) {
        document.getElementById('container').style.marginLeft='-600px';
        document.getElementById('container').style.marginLeft='-1200px';
        document.getElementById('container').style.marginLeft='-1800px';
        document.getElementById('container').style.marginLeft='0px';
        window.setTimeout(
          function(){
            slide(repeats - 1)
          },
          3000
        );
    }
}

This will call slide(10), which will then set the 3-second timeout to call slide(9), which will set timeout to call slide(8), etc. When slide(0) is called, no more timeouts will be set up.

Rails formatting date

Use

Model.created_at.strftime("%FT%T")

where,

%F - The ISO 8601 date format (%Y-%m-%d)
%T - 24-hour time (%H:%M:%S)

Following are some of the frequently used useful list of Date and Time formats that you could specify in strftime method:

Date (Year, Month, Day):
  %Y - Year with century (can be negative, 4 digits at least)
          -0001, 0000, 1995, 2009, 14292, etc.
  %C - year / 100 (round down.  20 in 2009)
  %y - year % 100 (00..99)

  %m - Month of the year, zero-padded (01..12)
          %_m  blank-padded ( 1..12)
          %-m  no-padded (1..12)
  %B - The full month name (``January'')
          %^B  uppercased (``JANUARY'')
  %b - The abbreviated month name (``Jan'')
          %^b  uppercased (``JAN'')
  %h - Equivalent to %b

  %d - Day of the month, zero-padded (01..31)
          %-d  no-padded (1..31)
  %e - Day of the month, blank-padded ( 1..31)

  %j - Day of the year (001..366)

Time (Hour, Minute, Second, Subsecond):
  %H - Hour of the day, 24-hour clock, zero-padded (00..23)
  %k - Hour of the day, 24-hour clock, blank-padded ( 0..23)
  %I - Hour of the day, 12-hour clock, zero-padded (01..12)
  %l - Hour of the day, 12-hour clock, blank-padded ( 1..12)
  %P - Meridian indicator, lowercase (``am'' or ``pm'')
  %p - Meridian indicator, uppercase (``AM'' or ``PM'')

  %M - Minute of the hour (00..59)

  %S - Second of the minute (00..59)

  %L - Millisecond of the second (000..999)
  %N - Fractional seconds digits, default is 9 digits (nanosecond)
          %3N  millisecond (3 digits)
          %6N  microsecond (6 digits)
          %9N  nanosecond (9 digits)
          %12N picosecond (12 digits)

For the complete list of formats for strftime method please visit APIDock

Where can I get a virtual machine online?

You can get free Virtual Machine and many more things online for 3 months provided by Microsoft Azure. I guess you need VPN for learning purpose. For that it would suffice.

Refer http://www.windowsazure.com/en-us/pricing/free-trial/

How can I change default dialog button text color in android 5

The simpliest solution is:

dialog.show(); //Only after .show() was called
dialog.getButton(AlertDialog.BUTTON_NEGATIVE).setTextColor(neededColor);
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setTextColor(neededColor);

Crystal Reports 13 And Asp.Net 3.5

I have same problem. I solved install this setup. (I use vs 2015 (4.6))

How to SUM two fields within an SQL query

If you want to add two columns together, all you have to do is add them. Then you will get the sum of those two columns for each row returned by the query.

What your code is doing is adding the two columns together and then getting a sum of the sums. That will work, but it might not be what you are attempting to accomplish.

Regex pattern including all special characters

That's because your pattern contains a .-^ which is all characters between and including . and ^, which included digits and several other characters as shown below:

enter image description here

If by special characters, you mean punctuation and symbols use:

[\p{P}\p{S}]

which contains all unicode punctuation and symbols.

Angular.js: set element height on page load

My solution if your ng-grid depend of element parent(div, layout) :

directive

myapp.directive('sizeelement', function ($window) {
return{
    scope:true,
    priority: 0,
    link: function (scope, element) {
        scope.$watch(function(){return $(element).height(); }, function(newValue, oldValue) {
            scope.height=$(element).height();
        });
    }}
})

sample html

<div class="portlet  box grey" style="height: 100%" sizeelement>
    <div class="portlet-title">
        <h4><i class="icon-list"></i>Articles</h4>
    </div>
    <div class="portlet-body" style="height:{{height-34}}px">
        <div class="gridStyle" ng-grid="gridOrderLine" ="min-height: 250px;"></div>
    </div>
</div>

height-34 : 34 is fix height of my title div, you can fix other height.

It is easy directive but it work fine.

<strong> vs. font-weight:bold & <em> vs. font-style:italic

<strong> and <em> - unlike <b> and <i> - have clear purpose for web browsers for the blind.

A blind person doesn't browse the web visually, but by sound such as text readers. <strong> and <em>, in addition to encouraging something to be bold or italic, also convey loudness or stressing syllables respectively (OH MY! & Ooooooh Myyyyyyy!). Audio-only browsers are unpredictable when it comes to <b> and <i>... they may make them loud or stress them or they may not... you never can be sure unless you use <strong> and <em>.

How to make a query with group_concat in sql server

This can also be achieved using the Scalar-Valued Function in MSSQL 2008
Declare your function as following,

CREATE FUNCTION [dbo].[FunctionName]
(@MaskId INT)
RETURNS Varchar(500) 
AS
BEGIN

    DECLARE @SchoolName varchar(500)                        

    SELECT @SchoolName =ISNULL(@SchoolName ,'')+ MD.maskdetail +', ' 
    FROM maskdetails MD WITH (NOLOCK)       
    AND MD.MaskId=@MaskId

    RETURN @SchoolName

END

And then your final query will be like

SELECT m.maskid,m.maskname,m.schoolid,s.schoolname,
(SELECT [dbo].[FunctionName](m.maskid)) 'maskdetail'
FROM tblmask m JOIN school s on s.id = m.schoolid 
ORDER BY m.maskname ;

Note: You may have to change the function, as I don't know the complete table structure.

Passing two command parameters using a WPF binding

If your values are static, you can use x:Array:

<Button Command="{Binding MyCommand}">10
  <Button.CommandParameter>
    <x:Array Type="system:Object">
       <system:String>Y</system:String>
       <system:Double>10</system:Double>
    </x:Array>
  </Button.CommandParameter>
</Button>

Running a shell script through Cygwin on Windows

The existing answers all seem to run this script in a DOS console window.

This may be acceptable, but for example means that colour codes (changing text colour) don't work but instead get printed out as they are:

there is no item "[032mGroovy[0m"

I found this solution some time ago, so I'm not sure whether mintty.exe is a standard Cygwin utility or whether you have to run the setup program to get it, but I run like this:

D:\apps\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico  bash.exe .\myShellScript.sh

... this causes the script to run in a Cygwin BASH console instead of a Windows DOS console.

Set opacity of background image without affecting child elements

I found a pretty good and simple tutorial about this issue. I think it works great (and though it supports IE, I just tell my clients to use other browsers):

CSS background transparency without affecting child elements, through RGBa and filters

From there you can add gradient support, etc.

PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

You have to change the mamp Mysql Database port into 8889.

Installing Google Protocol Buffers on mac

There should be better ways but what I did today was:

  1. Download from https://github.com/protocolbuffers/protobuf/releases (protoc-3.14.0-osx-x86_64.zip at this moment)

  2. Unzip (double click the zip file)

  3. Here, I added a symbolic link

ln -s ~/Downloads/protoc-3.14.0-osx-x86_64/bin/protoc /usr/local/bin/protoc
  1. Check if works
protoc --version

Psql list all tables

To see the public tables you can do

list tables

\dt

list table, view, and access privileges

\dp or \z

or just the table names

select table_name from information_schema.tables where table_schema = 'public';

RegisterStartupScript from code behind not working when Update Panel is used

You need to use ScriptManager.RegisterStartupScript for Ajax.

protected void ButtonPP_Click(object sender, EventArgs e) {     if (radioBtnACO.SelectedIndex < 0)     {         string csname1 = "PopupScript";          var cstext1 = new StringBuilder();         cstext1.Append("alert('Please Select Criteria!')");          ScriptManager.RegisterStartupScript(this, GetType(), csname1,             cstext1.ToString(), true);     } } 

How to exit an if clause

For what was actually asked, my approach is to put those ifs inside a one-looped loop

while (True):
    if (some_condition):
        ...
        if (condition_a):
            # do something
            # and then exit the outer if block
            break
        ...
        if (condition_b):
            # do something
            # and then exit the outer if block
            break
        # more code here
    # make sure it is looped once
    break

Test it:

conditions = [True,False]
some_condition = True

for condition_a in conditions:
    for condition_b in conditions:
        print("\n")
        print("with condition_a", condition_a)
        print("with condition_b", condition_b)
        while (True):
            if (some_condition):
                print("checkpoint 1")
                if (condition_a):
                    # do something
                    # and then exit the outer if block
                    print("checkpoint 2")
                    break
                print ("checkpoint 3")
                if (condition_b):
                    # do something
                    # and then exit the outer if block
                    print("checkpoint 4")
                    break
                print ("checkpoint 5")
                # more code here
            # make sure it is looped once
            break

What is the correct format to use for Date/Time in an XML file

What does the DTD have to say?

If the XML file is for communicating with other existing software (e.g., SOAP), then check that software for what it expects.

If the XML file is for serialisation or communication with non-existing software (e.g., the one you're writing), you can define it. In which case, I'd suggest something that is both easy to parse in your language(s) of choice, and easy to read for humans. e.g., if your language (whether VB.NET or C#.NET or whatever) allows you to parse ISO dates (YYYY-MM-DD) easily, that's the one I'd suggest.

How do I target only Internet Explorer 10 for certain situations like Internet Explorer-specific CSS or Internet Explorer-specific JavaScript code?

I use this script - it's antiquated, but effective in targeting a separate Internet Explorer 10 style sheet or JavaScript file that is included only if the browser is Internet Explorer 10, the same way you would with conditional comments. No jQuery or other plugin is required.

<script>
    /*@cc_on
      @if (@_jscript_version == 10)
          document.write(' <link type= "text/css" rel="stylesheet" href="your-ie10-styles.css" />');
      @end
    @*/
</script >

How to make a new line or tab in <string> XML (eclipse/android)?

  • Include this line in your layout xmlns:tools="http://schemas.android.com/tools"
  • Now , use \n for new line and \t for space like tab.
  • Example :

    for \n : android:text="Welcome back ! \nPlease login to your account agilanbu"

    for \t : android:text="Welcome back ! \tPlease login to your account agilanbu"

Clicking HTML 5 Video element to play, pause video, breaks play button

The simplest form is to use the onclick listener:

<video height="auto" controls="controls" preload="none" onclick="this.play()">
 <source type="video/mp4" src="vid.mp4">
</video>

No jQuery or complicated Javascript code needed.

Play/Pause can be done with onclick="this.paused ? this.play() : this.pause();".

SQL order string as number

I was looking also a sorting fields that has letter prefix. Here is what i found out the solution. This might help who is looking for the same solution.

Field Values:

FL01,FL02,FL03,FL04,FL05,...FL100,...FL123456789

select SUBSTRING(field,3,9) as field from table order by SUBSTRING(field,3,10)*1 desc

SUBSTRING(field,3,9) i put 9 because 9 is way enough for me to hold max 9 digits integer values.

So the result will be 123456789 123456788 123456787 ... 100 99 ... 2 1

How to set a value for a span using jQuery

You can use this:

$("#submittername").html(submitter_name);

When or Why to use a "SET DEFINE OFF" in Oracle Database

By default, SQL Plus treats '&' as a special character that begins a substitution string. This can cause problems when running scripts that happen to include '&' for other reasons:

SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');
Enter value for spencers: 
old   1: insert into customers (customer_name) values ('Marks & Spencers Ltd')
new   1: insert into customers (customer_name) values ('Marks  Ltd')

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks  Ltd

If you know your script includes (or may include) data containing '&' characters, and you do not want the substitution behaviour as above, then use set define off to switch off the behaviour while running the script:

SQL> set define off
SQL> insert into customers (customer_name) values ('Marks & Spencers Ltd');

1 row created.

SQL> select customer_name from customers;

CUSTOMER_NAME
------------------------------
Marks & Spencers Ltd

You might want to add set define on at the end of the script to restore the default behaviour.

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

Good to see someone's chimed in about Lucene - because I've no idea about that.

Sphinx, on the other hand, I know quite well, so let's see if I can be of some help.

  • Result relevance ranking is the default. You can set up your own sorting should you wish, and give specific fields higher weightings.
  • Indexing speed is super-fast, because it talks directly to the database. Any slowness will come from complex SQL queries and un-indexed foreign keys and other such problems. I've never noticed any slowness in searching either.
  • I'm a Rails guy, so I've no idea how easy it is to implement with Django. There is a Python API that comes with the Sphinx source though.
  • The search service daemon (searchd) is pretty low on memory usage - and you can set limits on how much memory the indexer process uses too.
  • Scalability is where my knowledge is more sketchy - but it's easy enough to copy index files to multiple machines and run several searchd daemons. The general impression I get from others though is that it's pretty damn good under high load, so scaling it out across multiple machines isn't something that needs to be dealt with.
  • There's no support for 'did-you-mean', etc - although these can be done with other tools easily enough. Sphinx does stem words though using dictionaries, so 'driving' and 'drive' (for example) would be considered the same in searches.
  • Sphinx doesn't allow partial index updates for field data though. The common approach to this is to maintain a delta index with all the recent changes, and re-index this after every change (and those new results appear within a second or two). Because of the small amount of data, this can take a matter of seconds. You will still need to re-index the main dataset regularly though (although how regularly depends on the volatility of your data - every day? every hour?). The fast indexing speeds keep this all pretty painless though.

I've no idea how applicable to your situation this is, but Evan Weaver compared a few of the common Rails search options (Sphinx, Ferret (a port of Lucene for Ruby) and Solr), running some benchmarks. Could be useful, I guess.

I've not plumbed the depths of MySQL's full-text search, but I know it doesn't compete speed-wise nor feature-wise with Sphinx, Lucene or Solr.

how to update spyder on anaconda

To expand on juanpa.arrivillaga's comment:

If you want to update Spyder in the root environment, then conda update spyder works for me.

If you want to update Spyder for a virtual environment you have created (e.g., for a different version of Python), then conda update -n $ENV_NAME spyder where $ENV_NAME is your environment name.

EDIT: In case conda update spyder isn't working, this post indicates you might need to run conda update anaconda before updating spyder. Also note that you can specify an exact spyder version if you want.

Getting the textarea value of a ckeditor textarea with javascript

Well. You asked about get value from textarea but in your example you are using a input. Anyways, here we go:

$("#CampaignTitle").bind("keyup", function()
{
    $("#titleBar").text($(this).val());
});

If you really wanted a textarea change your input type text to this

<textarea id="CampaignTitle"></textarea>

Hope it helps.

How do you post data with a link

You cannot make POST HTTP Requests by <a href="some_script.php">some_script</a>

Just open your house.php, find in it where you have $house = $_POST['houseVar'] and change it to:

isset($_POST['houseVar']) ? $house = $_POST['houseVar'] : $house = $_GET['houseVar']

And in the streeview.php make links like that:

<a href="house.php?houseVar=$houseNum"></a>

Or something else. I just don't know your files and what inside it.

Resizing UITableView to fit content

You can try Out this Custom AGTableView

To Set a TableView Height Constraint Using storyboard or programmatically. (This class automatically fetch a height constraint and set content view height to yourtableview height).

class AGTableView: UITableView {

    fileprivate var heightConstraint: NSLayoutConstraint!

    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        self.associateConstraints()
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        self.associateConstraints()
    }

    override open func layoutSubviews() {
        super.layoutSubviews()

        if self.heightConstraint != nil {
            self.heightConstraint.constant = self.contentSize.height
        }
        else{
            self.sizeToFit()
            print("Set a heightConstraint to Resizing UITableView to fit content")
        }
    }

    func associateConstraints() {
        // iterate through height constraints and identify

        for constraint: NSLayoutConstraint in constraints {
            if constraint.firstAttribute == .height {
                if constraint.relation == .equal {
                    heightConstraint = constraint
                }
            }
        }
    }
}

Note If any problem to set a Height then yourTableView.layoutSubviews().

SQL Server 2008 - Case / If statements in SELECT Clause

Simple CASE expression:

CASE input_expression 
     WHEN when_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

Searched CASE expression:

CASE
     WHEN Boolean_expression THEN result_expression [ ...n ] 
     [ ELSE else_result_expression ] 
END

Reference: http://msdn.microsoft.com/en-us/library/ms181765.aspx

Angular and Typescript: Can't find names - Error: cannot find name

I was able to fix this by installing the typings module.

npm install -g typings
typings install

(Using ng 2.0.0-rc.1)

Find a file in python

os.walk is the answer, this will find the first match:

import os

def find(name, path):
    for root, dirs, files in os.walk(path):
        if name in files:
            return os.path.join(root, name)

And this will find all matches:

def find_all(name, path):
    result = []
    for root, dirs, files in os.walk(path):
        if name in files:
            result.append(os.path.join(root, name))
    return result

And this will match a pattern:

import os, fnmatch
def find(pattern, path):
    result = []
    for root, dirs, files in os.walk(path):
        for name in files:
            if fnmatch.fnmatch(name, pattern):
                result.append(os.path.join(root, name))
    return result

find('*.txt', '/path/to/dir')

How to set layout_weight attribute dynamically from code?

If layoutparams is already defined (in XML or dynamically), Here's a one liner:

((LinearLayout.LayoutParams) mView.getLayoutParams()).weight = 1;

Replacing backslashes with forward slashes with str_replace() in php

Single quoted php string variable works.

$str = 'http://www.domain.com/data/images\flags/en.gif';
$str = str_replace('\\', '/', $str);

Ctrl+click doesn't work in Eclipse Juno

I'm having the same issue in Eclipse Luna in my Ubuntu VM, but I just tried to Ctrl+click on a method and it worked (even though my mouse cursor didn't change to a pointer).

C# how to create a Guid value?

There are two ways

var guid = Guid.NewGuid();

or

var guid = Guid.NewGuid().ToString();

both use the Guid class, the first creates a Guid Object, the second a Guid string.

SQL Query for Logins

Select * From Master..SysUsers Where IsSqlUser = 1

python NameError: global name '__file__' is not defined

I had the same problem with PyInstaller and Py2exe so I came across the resolution on the FAQ from cx-freeze.

When using your script from the console or as an application, the functions hereunder will deliver you the "execution path", not the "actual file path":

print(os.getcwd())
print(sys.argv[0])
print(os.path.dirname(os.path.realpath('__file__')))

Source:
http://cx-freeze.readthedocs.org/en/latest/faq.html

Your old line (initial question):

def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

Substitute your line of code with the following snippet.

def find_data_file(filename):
    if getattr(sys, 'frozen', False):
        # The application is frozen
        datadir = os.path.dirname(sys.executable)
    else:
        # The application is not frozen
        # Change this bit to match where you store your data files:
        datadir = os.path.dirname(__file__)

    return os.path.join(datadir, filename)

With the above code you could add your application to the path of your os, you could execute it anywhere without the problem that your app is unable to find it's data/configuration files.

Tested with python:

  • 3.3.4
  • 2.7.13

Transpose a matrix in Python

Is there a prize for being lazy and using the transpose function of NumPy arrays? ;)

import numpy as np

a = np.array([(1,2,3), (4,5,6)])

b = a.transpose()

LaTeX: Prevent line break in a span of text

Use \nolinebreak

\nolinebreak[number]

The \nolinebreak command prevents LaTeX from breaking the current line at the point of the command. With the optional argument, number, you can convert the \nolinebreak command from a demand to a request. The number must be a number from 0 to 4. The higher the number, the more insistent the request is.

Source: http://www.personal.ceu.hu/tex/breaking.htm#nolinebreak

How to use onResume()?

Most of the previous answers do a good job explaining how, why, and when to use onResume() but I would like to add something about re-creating your Activity.

I want to know if I want to restart the activity at the end of exectuion of an other what method is executed onCreate() or onResume()

The answer is onCreate() However, when deciding to actually re-create it, you should ask yourself how much of the Activity needs to be re-created. If it is data in an adapter, say for a list, then you can call notifyDataChanged() on the adapter to repopulate the adapter and not have to redraw everything.

Also, if you just need to update certain views but not all then it may be more efficient to call invalidate() on the view(s) that need updated. This will only redraw those views and possibly allow your application to run more smoothly. I hope this can help you.

Escaping Strings in JavaScript

A variation of the function provided by Paolo Bergantino that works directly on String:

String.prototype.addSlashes = function() 
{ 
   //no need to do (str+'') anymore because 'this' can only be a string
   return this.replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
} 

By adding the code above in your library you will be able to do:

var test = "hello single ' double \" and slash \\ yippie";
alert(test.addSlashes());

EDIT:

Following suggestions in the comments, whoever is concerned about conflicts amongst JavaScript libraries can add the following code:

if(!String.prototype.addSlashes)
{
   String.prototype.addSlashes = function()... 
}
else
   alert("Warning: String.addSlashes has already been declared elsewhere.");

The best way to remove duplicate values from NSMutableArray in Objective-C?

Yes, using NSSet is a sensible approach.

To add to Jim Puls' answer, here's an alternative approach to stripping duplicates while retaining order:

// Initialise a new, empty mutable array 
NSMutableArray *unique = [NSMutableArray array];

for (id obj in originalArray) {
    if (![unique containsObject:obj]) {
        [unique addObject:obj];
    }
}

It's essentially the same approach as Jim's but copies unique items to a fresh mutable array rather than deleting duplicates from the original. This makes it slightly more memory efficient in the case of a large array with lots of duplicates (no need to make a copy of the entire array), and is in my opinion a little more readable.

Note that in either case, checking to see if an item is already included in the target array (using containsObject: in my example, or indexOfObject:inRange: in Jim's) doesn't scale well for large arrays. Those checks run in O(N) time, meaning that if you double the size of the original array then each check will take twice as long to run. Since you're doing the check for each object in the array, you'll also be running more of those more expensive checks. The overall algorithm (both mine and Jim's) runs in O(N2) time, which gets expensive quickly as the original array grows.

To get that down to O(N) time you could use a NSMutableSet to store a record of items already added to the new array, since NSSet lookups are O(1) rather than O(N). In other words, checking to see whether an element is a member of an NSSet takes the same time regardless of how many elements are in the set.

Code using this approach would look something like this:

NSMutableArray *unique = [NSMutableArray array];
NSMutableSet *seen = [NSMutableSet set];

for (id obj in originalArray) {
    if (![seen containsObject:obj]) {
        [unique addObject:obj];
        [seen addObject:obj];
    }
}

This still seems a little wasteful though; we're still generating a new array when the question made clear that the original array is mutable, so we should be able to de-dupe it in place and save some memory. Something like this:

NSMutableSet *seen = [NSMutableSet set];
NSUInteger i = 0;

while (i < [originalArray count]) {
    id obj = [originalArray objectAtIndex:i];

    if ([seen containsObject:obj]) {
        [originalArray removeObjectAtIndex:i];
        // NB: we *don't* increment i here; since
        // we've removed the object previously at
        // index i, [originalArray objectAtIndex:i]
        // now points to the next object in the array.
    } else {
        [seen addObject:obj];
        i++;
    }
}

UPDATE: Yuri Niyazov pointed out that my last answer actually runs in O(N2) because removeObjectAtIndex: probably runs in O(N) time.

(He says "probably" because we don't know for sure how it's implemented; but one possible implementation is that after deleting the object at index X the method then loops through every element from index X+1 to the last object in the array, moving them to the previous index. If that's the case then that is indeed O(N) performance.)

So, what to do? It depends on the situation. If you've got a large array and you're only expecting a small number of duplicates then the in-place de-duplication will work just fine and save you having to build up a duplicate array. If you've got an array where you're expecting lots of duplicates then building up a separate, de-duped array is probably the best approach. The take-away here is that big-O notation only describes the characteristics of an algorithm, it won't tell you definitively which is best for any given circumstance.

Is std::vector copying the objects with a push_back?

std::vector always makes a copy of whatever is being stored in the vector.

If you are keeping a vector of pointers, then it will make a copy of the pointer, but not the instance being to which the pointer is pointing. If you are dealing with large objects, you can (and probably should) always use a vector of pointers. Often, using a vector of smart pointers of an appropriate type is good for safety purposes, since handling object lifetime and memory management can be tricky otherwise.

Should I check in folder "node_modules" to Git when creating a Node.js app on Heroku?

Instead of checking in folder node_modules, make a package.json file for your application.

The package.json file specifies the dependencies of your application. Heroku can then tell npm to install all of those dependencies. The tutorial you linked to contains a section on package.json files.

Is it a good practice to use an empty URL for a HTML form's action attribute? (action="")

I use to do not specify action attribute at all. It is actually how my framework is designed all pages get submitted back exact to same address. But today I discovered problem. Sometimes I borrow action attribute value to make some background call (I guess some people name them AJAX). So I found that IE keeps action attribute value as empty if action attribute wasn't specified. It is a bit odd in my understanding, since if no action attribute specified, the JavaScript counterpart has to be at least undefined. Anyway, my point is before you choose best practice you need to understand more context, like will you use the attribute in JavaScript or not.

How to view AndroidManifest.xml from APK file?

The file needs to be decompiled (or deodex'd not sure which one). But here's another way to do it:

-Download free Tickle My Android tool on XDA: https://forum.xda-developers.com/showthread.php?t=1633333https://forum.xda-developers.com/showthread.php?t=1633333
-Unzip
-Copy APK into \_WorkArea1\_in\ folder
-Open "Tickle My Android.exe"
-Theming Menu
-Decompile Files->Any key to continue (ignore warning)
-Decompile Files->1->[Enter]->y[Enter]
-Wait for it to decompile in new window... Done when new window closes
-Decompiled/viewable files will be here: \_WorkArea3\_working\[App]\

Global variables in c#.net

You can create a variable with an application scope

How to solve COM Exception Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG))?

go to the directory of .Net framework and register their the respective dll with Regsvr32.exe white space dll path.

How to run test cases in a specified file?

There are two ways. The easy one is to use the -run flag and provide a pattern matching names of the tests you want to run.

Example:

$ go test -run NameOfTest

See the docs for more info.

The other way is to name the specific file, containing the tests you want to run:

$ go test foo_test.go

But there's a catch. This works well if:

  • foo.go is in package foo.
  • foo_test.go is in package foo_test and imports 'foo'.

If foo_test.go and foo.go are the same package (a common case) then you must name all other files required to build foo_test. In this example it would be:

$ go test foo_test.go foo.go

I'd recommend to use the -run pattern. Or, where/when possible, always run all package tests.

Close Window from ViewModel

You can pass the window to your ViewModel using the CommandParameter. See my Example below.

I've implemented an CloseWindow Method which takes a Windows as parameter and closes it. The window is passed to the ViewModel via CommandParameter. Note that you need to define an x:Name for the window which should be close. In my XAML Window i call this method via Command and pass the window itself as a parameter to the ViewModel using CommandParameter.

Command="{Binding CloseWindowCommand, Mode=OneWay}" 
CommandParameter="{Binding ElementName=TestWindow}"

ViewModel

public RelayCommand<Window> CloseWindowCommand { get; private set; }

public MainViewModel()
{
    this.CloseWindowCommand = new RelayCommand<Window>(this.CloseWindow);
}

private void CloseWindow(Window window)
{
    if (window != null)
    {
       window.Close();
    }
}

View

<Window x:Class="ClientLibTestTool.ErrorView"
        x:Name="TestWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:localization="clr-namespace:ClientLibTestTool.ViewLanguages"
        DataContext="{Binding Main, Source={StaticResource Locator}}"
        Title="{x:Static localization:localization.HeaderErrorView}"
        Height="600" Width="800"
        ResizeMode="NoResize"
        WindowStartupLocation="CenterScreen">
    <Grid> 
        <Button Content="{x:Static localization:localization.ButtonClose}" 
                Height="30" 
                Width="100" 
                Margin="0,0,10,10" 
                IsCancel="True" 
                VerticalAlignment="Bottom" 
                HorizontalAlignment="Right" 
                Command="{Binding CloseWindowCommand, Mode=OneWay}" 
                CommandParameter="{Binding ElementName=TestWindow}"/>
    </Grid>
</Window>

Note that i'm using the MVVM light framework, but the principal applies to every wpf application.

This solution violates of the MVVM pattern, because the view-model shouldn't know anything about the UI Implementation. If you want to strictly follow the MVVM programming paradigm you have to abstract the type of the view with an interface.

MVVM conform solution (Former EDIT2)

the user Crono mentions a valid point in the comment section:

Passing the Window object to the view model breaks the MVVM pattern IMHO, because it forces your vm to know what it's being viewed in.

You can fix this by introducing an interface containing a close method.

Interface:

public interface ICloseable
{
    void Close();
}

Your refactored ViewModel will look like this:

ViewModel

public RelayCommand<ICloseable> CloseWindowCommand { get; private set; }

public MainViewModel()
{
    this.CloseWindowCommand = new RelayCommand<IClosable>(this.CloseWindow);
}

private void CloseWindow(ICloseable window)
{
    if (window != null)
    {
        window.Close();
    }
}

You have to reference and implement the ICloseable interface in your view

View (Code behind)

public partial class MainWindow : Window, ICloseable
{
    public MainWindow()
    {
        InitializeComponent();
    }
}

Answer to the original question: (former EDIT1)

Your Login Button (Added CommandParameter):

<Button Name="btnLogin" IsDefault="True" Content="Login" Command="{Binding ShowLoginCommand}" CommandParameter="{Binding ElementName=LoginWindow}"/>

Your code:

 public RelayCommand<Window> CloseWindowCommand { get; private set; } // the <Window> is important for your solution!

 public MainViewModel() 
 {
     //initialize the CloseWindowCommand. Again, mind the <Window>
     //you don't have to do this in your constructor but it is good practice, thought
     this.CloseWindowCommand = new RelayCommand<Window>(this.CloseWindow);
 }

 public bool CheckLogin(Window loginWindow) //Added loginWindow Parameter
 {
    var user = context.Users.Where(i => i.Username == this.Username).SingleOrDefault();

    if (user == null)
    {
        MessageBox.Show("Unable to Login, incorrect credentials.");
        return false;
    }
    else if (this.Username == user.Username || this.Password.ToString() == user.Password)
    {
        MessageBox.Show("Welcome "+ user.Username + ", you have successfully logged in.");
        this.CloseWindow(loginWindow); //Added call to CloseWindow Method
        return true;
    }
    else
    {
        MessageBox.Show("Unable to Login, incorrect credentials.");
        return false;
    }
 }

 //Added CloseWindow Method
 private void CloseWindow(Window window)
 {
     if (window != null)
     {
         window.Close();
     }
 }

Print a list of space-separated elements in Python 3

You can apply the list as separate arguments:

print(*L)

and let print() take care of converting each element to a string. You can, as always, control the separator by setting the sep keyword argument:

>>> L = [1, 2, 3, 4, 5]
>>> print(*L)
1 2 3 4 5
>>> print(*L, sep=', ')
1, 2, 3, 4, 5
>>> print(*L, sep=' -> ')
1 -> 2 -> 3 -> 4 -> 5

Unless you need the joined string for something else, this is the easiest method. Otherwise, use str.join():

joined_string = ' '.join([str(v) for v in L])
print(joined_string)
# do other things with joined_string

Note that this requires manual conversion to strings for any non-string values in L!

Trying to pull files from my Github repository: "refusing to merge unrelated histories"

git checkout master
git merge origin/master --allow-unrelated-histories

Resolve conflict, then

git add -A .
git commit -m "Upload"
git push

Binding a list in @RequestParam

It wasn't obvious to me that although you can accept a Collection as a request param, but on the consumer side you still have to pass in the collection items as comma separated values.

For example if the server side api looks like this:

@PostMapping("/post-topics")
public void handleSubscriptions(@RequestParam("topics") Collection<String> topicStrings) {

    topicStrings.forEach(topic -> System.out.println(topic));
}

Directly passing in a collection to the RestTemplate as a RequestParam like below will result in data corruption

public void subscribeToTopics() {

    List<String> topics = Arrays.asList("first-topic", "second-topic", "third-topic");

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.postForEntity(
            "http://localhost:8088/post-topics?topics={topics}",
            null,
            ResponseEntity.class,
            topics);
}

Instead you can use

public void subscribeToTopics() {

    List<String> topicStrings = Arrays.asList("first-topic", "second-topic", "third-topic");
    String topics = String.join(",",topicStrings);

    RestTemplate restTemplate = new RestTemplate();
    restTemplate.postForEntity(
            "http://localhost:8088/post-topics?topics={topics}",
            null,
            ResponseEntity.class,
            topics);
}

The complete example can be found here, hope it saves someone the headache :)

How can I change the value of the elements in a vector?

You can access the values in a vector just as you access any other array.

for (int i = 0; i < v.size(); i++)
{         
  v[i] -= 1;         
} 

HTML Text with tags to formatted text in an Excel cell

I know this thread is ancient, but after assigning the innerHTML, ExecWB worked for me:

_x000D_
_x000D_
.ExecWB 17, 0_x000D_
'Select all contents in browser_x000D_
.ExecWB 12, 2_x000D_
'Copy them
_x000D_
_x000D_
_x000D_

And then just paste the contents into Excel. Since these methods are prone to runtime errors, but work fine after one or two tries in debug mode, you might have to tell Excel to try again if it runs into an error. I solved this by adding this error handler to the sub, and it works fine:

_x000D_
_x000D_
Sub ApplyHTML()_x000D_
  On Error GoTo ErrorHandler_x000D_
    ..._x000D_
  Exit Sub_x000D_
_x000D_
ErrorHandler:_x000D_
    Resume _x000D_
    'I.e. re-run the line of code that caused the error_x000D_
Exit Sub_x000D_
     _x000D_
End Sub
_x000D_
_x000D_
_x000D_

How can I copy the content of a branch to a new local branch?

git checkout old_branch
git branch new_branch

This will give you a new branch "new_branch" with the same state as "old_branch".

This command can be combined to the following:

git checkout -b new_branch old_branch

Find unused code

I have come across AXTools CODESMART..Try that once. Use code analyzer in reviews section.It will list dead local and global functions along with other issues.

SQL query to get the deadlocks in SQL SERVER 2008

You can use a deadlock graph and gather the information you require from the log file.

The only other way I could suggest is digging through the information by using EXEC SP_LOCK (Soon to be deprecated), EXEC SP_WHO2 or the sys.dm_tran_locks table.

SELECT  L.request_session_id AS SPID, 
    DB_NAME(L.resource_database_id) AS DatabaseName,
    O.Name AS LockedObjectName, 
    P.object_id AS LockedObjectId, 
    L.resource_type AS LockedResource, 
    L.request_mode AS LockType,
    ST.text AS SqlStatementText,        
    ES.login_name AS LoginName,
    ES.host_name AS HostName,
    TST.is_user_transaction as IsUserTransaction,
    AT.name as TransactionName,
    CN.auth_scheme as AuthenticationMethod
FROM    sys.dm_tran_locks L
    JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
    JOIN sys.objects O ON O.object_id = P.object_id
    JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
    JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
    JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
    JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
    CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
WHERE   resource_database_id = db_id()
ORDER BY L.request_session_id

http://www.sqlmag.com/article/sql-server-profiler/gathering-deadlock-information-with-deadlock-graph

http://weblogs.sqlteam.com/mladenp/archive/2008/04/29/SQL-Server-2005-Get-full-information-about-transaction-locks.aspx

Bind a function to Twitter Bootstrap Modal Close

$(document.body).on('hidden.bs.modal', function () {
    $('#myModal').removeData('bs.modal')
});

Convert LocalDateTime to LocalDateTime in UTC

Try this using this method.

convert your LocalDateTime to ZonedDateTime by using the of method and pass system default time zone or you can use ZoneId of your zone like ZoneId.of("Australia/Sydney");

LocalDateTime convertToUtc(LocalDateTime dateTime) {
  ZonedDateTime dateTimeInMyZone = ZonedDateTime.
                                        of(dateTime, ZoneId.systemDefault());

  return dateTimeInMyZone
                  .withZoneSameInstant(ZoneOffset.UTC)
                  .toLocalDateTime();
  
}

To convert back to your zone local date time use:

LocalDateTime convertFromUtc(LocalDateTime utcDateTime){
    return ZonedDateTime.
            of(utcDateTime, ZoneId.of("UTC"))
            .toOffsetDateTime()
            .atZoneSameInstant(ZoneId.systemDefault())
            .toLocalDateTime();
}

"SDK Platform Tools component is missing!"

Installing Android SDKs is done via the "Android SDK and AVD Manager"... there's a shortcut on Eclipse's "Window" menu, or you can run the .exe from the root of your existing Android SDK installation.

Yes I think installing the 2.3 SDK will fix your problem... you can install older SDKs at the same time. The important thing is that the structure of the SDK changed in 2.3 with some tools (such as ADB) moving from sdkroot\tools to sdkroot\platform-tools. Quite possibly the very latest ADT plugin isn't massively backwards-compatible re that change.

command/usr/bin/codesign failed with exit code 1- code sign error

I recently had this issue and all above solutions didn't work for me.

The reason why it works on your simulator but not real devices is probably related to your Development Certificate.

So I revoked my certificate on Apple Developer Portal and request a new one on my computer. Here are the steps:

  1. Goto Apple Developer Portal and revoke your old (not working) development certificate. revoke
  2. Add iOS App Development Certificate add
  3. Follow the step on from Apple
  4. Download the newly generated certificate and add it (double click) to your Keychain download
  5. Make sure it is in your XCode Accounts accounts

Then it works!

Hope it helps!

CSS rotation cross browser with jquery.animate()

jQuery transit will probably make your life easier if you are dealing with CSS3 animations through jQuery.

EDIT March 2014 (because my advice has constantly been up and down voted since I posted it)

Let me explain why I was initially hinting towards the plugin above:

Updating the DOM on each step (i.e. $.animate ) is not ideal in terms of performance. It works, but will most probably be slower than pure CSS3 transitions or CSS3 animations.

This is mainly because the browser gets a chance to think ahead if you indicate what the transition is going to look like from start to end.

To do so, you can for example create a CSS class for each state of the transition and only use jQuery to toggle the animation state.

This is generally quite neat as you can tweak you animations alongside the rest of your CSS instead of mixing it up with your business logic:

// initial state
.eye {
   -webkit-transform: rotate(45deg);
   -moz-transform: rotate(45deg);
   transform: rotate(45deg);
   // etc.

   // transition settings
   -webkit-transition: -webkit-transform 1s linear 0.2s;
   -moz-transition: -moz-transform 1s linear 0.2s;
   transition: transform 1s linear 0.2s;
   // etc.
}

// open state    
.eye.open {

   transform: rotate(90deg);
}

// Javascript
$('.eye').on('click', function () { $(this).addClass('open'); });

If any of the transform parameters is dynamic you can of course use the style attribute instead:

$('.eye').on('click', function () { 
    $(this).css({ 
        -webkit-transition: '-webkit-transform 1s ease-in',
        -moz-transition: '-moz-transform 1s ease-in',
        // ...

        // note that jQuery will vendor prefix the transform property automatically
        transform: 'rotate(' + (Math.random()*45+45).toFixed(3) + 'deg)'
    }); 
});

A lot more detailed information on CSS3 transitions on MDN.

HOWEVER There are a few other things to keep in mind and all this can get a bit tricky if you have complex animations, chaining etc. and jQuery Transit just does all the tricky bits under the hood:

$('.eye').transit({ rotate: '90deg'}); // easy huh ?

How to exit an Android app programmatically?

If you are using EventBus (or really any other pub/sub library) in your application to communicate between activities you can send them an explicit event:

final public class KillItWithFireEvent
{
    public KillItWithFireEvent() {}

    public static void send()
    {
        EventBus.getDefault().post(new KillItWithFireEvent());
    }
}

The only downside of this is you need all activities to listen to this event to call their own finish(). For this you can easily create shim activity classes through inheritance which just listen to this event and let subclasses implement everything else, then make sure all your activities inherit from this extra layer. The kill listeners could even add some extra functionality through overrides, like avoiding death on certain particular situations.

How to save an image to localStorage and display it on the next page?

I wrote a little 2,2kb library of saving image in localStorage JQueryImageCaching Usage:

<img data-src="path/to/image">
<script>
    $('img').imageCaching();
</script>

How do I remove diacritics (accents) from a string in .NET?

THIS IS THE VB VERSION (Works with GREEK) :

Imports System.Text

Imports System.Globalization

Public Function RemoveDiacritics(ByVal s As String)
    Dim normalizedString As String
    Dim stringBuilder As New StringBuilder
    normalizedString = s.Normalize(NormalizationForm.FormD)
    Dim i As Integer
    Dim c As Char
    For i = 0 To normalizedString.Length - 1
        c = normalizedString(i)
        If CharUnicodeInfo.GetUnicodeCategory(c) <> UnicodeCategory.NonSpacingMark Then
            stringBuilder.Append(c)
        End If
    Next
    Return stringBuilder.ToString()
End Function

What is size_t in C?

To go into why size_t needed to exist and how we got here:

In pragmatic terms, size_t and ptrdiff_t are guaranteed to be 64 bits wide on a 64-bit implementation, 32 bits wide on a 32-bit implementation, and so on. They could not force any existing type to mean that, on every compiler, without breaking legacy code.

A size_t or ptrdiff_t is not necessarily the same as an intptr_t or uintptr_t. They were different on certain architectures that were still in use when size_t and ptrdiff_t were added to the Standard in the late ’80s, and becoming obsolete when C99 added many new types but not gone yet (such as 16-bit Windows). The x86 in 16-bit protected mode had a segmented memory where the largest possible array or structure could be only 65,536 bytes in size, but a far pointer needed to be 32 bits wide, wider than the registers. On those, intptr_t would have been 32 bits wide but size_t and ptrdiff_t could be 16 bits wide and fit in a register. And who knew what kind of operating system might be written in the future? In theory, the i386 architecture offers a 32-bit segmentation model with 48-bit pointers that no operating system has ever actually used.

The type of a memory offset could not be long because far too much legacy code assumes that long is exactly 32 bits wide. This assumption was even built into the UNIX and Windows APIs. Unfortunately, a lot of other legacy code also assumed that a long is wide enough to hold a pointer, a file offset, the number of seconds that have elapsed since 1970, and so on. POSIX now provides a standardized way to force the latter assumption to be true instead of the former, but neither is a portable assumption to make.

It couldn’t be int because only a tiny handful of compilers in the ’90s made int 64 bits wide. Then they really got weird by keeping long 32 bits wide. The next revision of the Standard declared it illegal for int to be wider than long, but int is still 32 bits wide on most 64-bit systems.

It couldn’t be long long int, which anyway was added later, since that was created to be at least 64 bits wide even on 32-bit systems.

So, a new type was needed. Even if it weren’t, all those other types meant something other than an offset within an array or object. And if there was one lesson from the fiasco of 32-to-64-bit migration, it was to be specific about what properties a type needed to have, and not use one that meant different things in different programs.

How does Facebook Sharer select Images and other metadata when sharing my URL?

Old way, no longer works:

<link rel="image_src" href="http://yoururl/yourimage"/>

Reported new way, also does not work:

<meta property="og:image" content="http://yoururl/yourimage"/>

It randomly worked off and on during the first day I implemented it, hasn't worked at all since.

The Facebook linter page, a utility that inspects your page, reports that everything is correct and does display the thumbnail I selected... just that the share.php page itself doesn't seem to be functioning. Has to be a bug over at Facebook, one they apparently don't care to fix as every bug report regarding this issue I've seen in their system all say resolved or fixed.

Using jQuery to build table rows from AJAX response(json)

Try this (DEMO link updated):

success: function (response) {
        var trHTML = '';
        $.each(response, function (i, item) {
            trHTML += '<tr><td>' + item.rank + '</td><td>' + item.content + '</td><td>' + item.UID + '</td></tr>';
        });
        $('#records_table').append(trHTML);
    }

Fiddle DEMO WITH AJAX

Bootstrap 4, how to make a col have a height of 100%?

I solved this like this:

    <section className="container-fluid">
            <div className="row justify-content-center">

                <article className="d-flex flex-column justify-content-center align-items-center vh-100">
                        <!-- content -->
                </article>

            </div>
    </section>

How do I set a value in CKEditor with Javascript?

Sets the editor data. The data must be provided in the raw format (HTML). CKEDITOR.instances.editor1.setData( 'Put your Data.' ); refer this page

ps1 cannot be loaded because running scripts is disabled on this system

Run this code in your powershell or cmd

Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass

Functional, Declarative, and Imperative Programming

I think that your taxonomy is incorrect. There are two opposite types imperative and declarative. Functional is just a subtype of declarative. BTW, wikipedia states the same fact.

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

Take a look at this WPF metro-styled window with optional glowing borders.

This is a stand-alone application using no other libraries than Microsoft.Windows.Shell (included) to create metro-styled windows with optional glowing borders.

Supports Windows all the way back to XP (.NET4).

Get the element triggering an onclick event in jquery?

You can pass the inline handler the this keyword, obtaining the element which fired the event.

like,

onclick="confirmSubmit(this);"

Regular expression: find spaces (tabs/space) but not newlines

Note: For those dealing with CJK text (Chinese, Japanese, and Korean), the double-byte space (Unicode \u3000) is not included in \s for any implementation I've tried so far (Perl, .NET, PCRE, Python). You'll need to either normalize your strings first (such as by replacing all \u3000 with \u0020), or you'll have to use a character set that includes this codepoint in addition to whatever other whitespace you're targeting, such as [ \t\u3000].

If you're using Perl or PCRE, you have the option of using the \h shorthand for horizontal whitespace, which appears to include the single-byte space, double-byte space, and tab, among others. See the Match whitespace but not newlines (Perl) thread for more detail.

However, this \h shorthand has not been implemented for .NET and C#, as best I've been able to tell.

What is the main difference between Collection and Collections in Java?

Are you asking about the Collections class versus the classes which implement the Collection interface?

If so, the Collections class is a utility class having static methods for doing operations on objects of classes which implement the Collection interface. For example, Collections has methods for finding the max element in a Collection.

The Collection interface defines methods common to structures which hold other objects. List and Set are subinterfaces of Collection, and ArrayList and HashSet are examples of concrete collections.

How to restart a single container with docker-compose

The other answers to restarting a single node are on target, docker-compose restart worker. That will bounce that container, but not include any changes, even if you rebuilt it separately. You can manually stop, rm, create, and start, but there are much easier methods.

If you've updated your code, you can do the build and reload in a single step with:

docker-compose up --detach --build

That will first rebuild your images from any changed code, which is fast if there are no changes since the cache is reused. And then it only replaces the changed containers. If your downloaded images are stale, you can precede the above command with:

docker-compose pull

To download any changed images first (the containers won't be restarted until you run a command like the up above). Doing an initial stop is unnecessary.

And to only do this for a single service, follow the up or pull command with the services you want to specify, e.g.:

docker-compose up --detach --build worker

Here's a quick example of the first option, the Dockerfile is structured to keep the frequently changing parts of the code near the end. In fact the requirements are pulled in separately for the pip install since that file rarely changes. And since the nginx and redis containers were up-to-date, they weren't restarted. Total time for the entire process was under 6 seconds:

$ time docker-compose -f docker-compose.nginx-proxy.yml up --detach --build
Building counter
Step 1 : FROM python:2.7-alpine
 ---> fc479af56697
Step 2 : WORKDIR /app
 ---> Using cache
 ---> d04d0d6d98f1
Step 3 : ADD requirements.txt /app/requirements.txt
 ---> Using cache
 ---> 9c4e311f3f0c
Step 4 : RUN pip install -r requirements.txt
 ---> Using cache
 ---> 85b878795479
Step 5 : ADD . /app
 ---> 63e3d4e6b539
Removing intermediate container 9af53c35d8fe
Step 6 : EXPOSE 80
 ---> Running in a5b3d3f80cd4
 ---> 4ce3750610a9
Removing intermediate container a5b3d3f80cd4
Step 7 : CMD gunicorn app:app -b 0.0.0.0:80 --log-file - --access-logfile - --workers 4 --keep-alive 0
 ---> Running in 0d69957bda4c
 ---> d41ff1635cb7
Removing intermediate container 0d69957bda4c
Successfully built d41ff1635cb7
counter_nginx_1 is up-to-date
counter_redis_1 is up-to-date
Recreating counter_counter_1

real    0m5.959s
user    0m0.508s
sys     0m0.076s

Running Java Program from Command Line Linux

What is the package name of your class? If there is no package name, then most likely the solution is:

java -cp FileManagement Main

Extracting specific selected columns to new DataFrame as a copy

There is a way of doing this and it actually looks similar to R

new = old[['A', 'C', 'D']].copy()

Here you are just selecting the columns you want from the original data frame and creating a variable for those. If you want to modify the new dataframe at all you'll probably want to use .copy() to avoid a SettingWithCopyWarning.

An alternative method is to use filter which will create a copy by default:

new = old.filter(['A','B','D'], axis=1)

Finally, depending on the number of columns in your original dataframe, it might be more succinct to express this using a drop (this will also create a copy by default):

new = old.drop('B', axis=1)

Why AVD Manager options are not showing in Android Studio

I found it from the icon. Please see the device icon.

enter image description here

Parse date string and change format

@codeling and @user1767754 : The following two lines will work. I saw no one posted the complete solution for the example problem that was asked. Hopefully this is enough explanation.

import datetime

x = datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y")
print(x)

Output:

15/02/2010

Java String encoding (UTF-8)

How is this different from the following?

This line of code here:

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

constructs a new String object (i.e. a copy of oldString), while this line of code:

String newString = oldString;

declares a new variable of type java.lang.String and initializes it to refer to the same String object as the variable oldString.

Is there any scenario in which the two lines will have different outputs?

Absolutely:

String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true

vs.

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
 // isSameInstance == false (in most cases)    
boolean isSameInstance = newString == oldString;

a_horse_with_no_name (see comment) is right of course. The equivalent of

String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));

is

String newString = new String(oldString);

minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.

How do I ZIP a file in C#, using no 3rd-party APIs?

Based off Simon McKenzie's answer to this question, I'd suggest using a pair of methods like this:

    public static void ZipFolder(string sourceFolder, string zipFile)
    {
        if (!System.IO.Directory.Exists(sourceFolder))
            throw new ArgumentException("sourceDirectory");

        byte[] zipHeader = new byte[] { 80, 75, 5, 6, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };

        using (System.IO.FileStream fs = System.IO.File.Create(zipFile))
        {
            fs.Write(zipHeader, 0, zipHeader.Length);
        }

        dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
        dynamic source = shellApplication.NameSpace(sourceFolder);
        dynamic destination = shellApplication.NameSpace(zipFile);

        destination.CopyHere(source.Items(), 20);
    }

    public static void UnzipFile(string zipFile, string targetFolder)
    {
        if (!System.IO.Directory.Exists(targetFolder))
            System.IO.Directory.CreateDirectory(targetFolder);

        dynamic shellApplication = Activator.CreateInstance(Type.GetTypeFromProgID("Shell.Application"));
        dynamic compressedFolderContents = shellApplication.NameSpace(zipFile).Items;
        dynamic destinationFolder = shellApplication.NameSpace(targetFolder);

        destinationFolder.CopyHere(compressedFolderContents);
    }
}

React passing parameter via onclick event using ES6 syntax

TL;DR:

Don't bind function (nor use arrow functions) inside render method. See official recommendations.

https://reactjs.org/docs/faq-functions.html


So, there's an accepted answer and a couple more that points the same. And also there are some comments preventing people from using bind within the render method, and also avoiding arrow functions there for the same reason (those functions will be created once again and again on each render). But there's no example, so I'm writing one.

Basically, you have to bind your functions in the constructor.

class Actions extends Component {

    static propTypes = {
        entity_id: PropTypes.number,
        contact_id: PropTypes.number,
        onReplace: PropTypes.func.isRequired,
        onTransfer: PropTypes.func.isRequired
    }

    constructor() {
        super();
        this.onReplace = this.onReplace.bind(this);
        this.onTransfer = this.onTransfer.bind(this);
    }

    onReplace() {
        this.props.onReplace(this.props.entity_id, this.props.contact_id);
    }

    onTransfer() {
        this.props.onTransfer(this.props.entity_id, this.props.contact_id);
    }

    render() {
        return (
            <div className="actions">
                <button className="btn btn-circle btn-icon-only btn-default"
                    onClick={this.onReplace}
                    title="Replace">
                        <i className="fa fa-refresh"></i>
                </button>
                <button className="btn btn-circle btn-icon-only btn-default"
                    onClick={this.onTransfer}
                    title="Transfer">
                    <i className="fa fa-share"></i>
                </button>                                 
            </div>
        )
    }
}

export default Actions

Key lines are:

constructor

this.onReplace = this.onReplace.bind(this);

method

onReplace() {
    this.props.onReplace(this.props.entity_id, this.props.contact_id);
}

render

onClick={this.onReplace}

Error 1053 the service did not respond to the start or control request in a timely fashion

In my case the problem was missing version of .net framework.

My service used

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>

But .net Framework version of server was 4, so by changing 4.5 to 4 the problem fixed:

<startup>
  <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.0" />
</startup>

A completely free agile software process tool

One possibility would be to use a Google Drawing, part of Google Drive, if you want a more visual and easy-to-edit option. You can create the cards by grouping a color-filled rectangle and one or more text fields together. Being a sufficiently free-form online vector drawing program, it doesn't really limit your possibilities like if you use a more dedicated solution.

The only real downsides are that you have to first create the building blocks from the beginning, and don't get numerical statistics like with a more structured tool.

How to access the php.ini file in godaddy shared hosting linux

Follow below if you use godaddy shared hosting.. its very simple: we need to access root folder of the server via ftp, create a "php5.ini" named file under public_html folder... and then add 3 stupid lines... also "php5" because I'm using php5.4 for 1 of my client. you can check your version via control panel and search php version. Adding a new file with php5.ini will not hamper anything on server end, but it will only overwrite whatever we are commanding it to do.

steps are simple: go to file manager.. click on public_html.. a new window will appear.. Click on "+"sign and create a new file in the name: "php5.ini" ... click ok/save. Now right click on that newly created php5.ini file and click on edit... a new window will appear... copy paste these below lines & click on save and close the window.

memory_limit = 128M

upload_max_filesize = 60M

max_input_vars = 5000

Is it possible to display my iPhone on my computer monitor?

Release notes iOS 3.2 (External Display Support) and iOS 4.0 (Inherited Improvements) mentions that it should be possible to connect external displays to iOS 4.0 devices.
But you still have to jailbreak if you would mirror your iPhone screen...
Related SO Question with updates

How do I install Eclipse Marketplace in Eclipse Classic?

With Eclipse 3.7 Indigo, I found the link at http://www.eclipse.org/mpc/ which told me the download location and plugin was http://download.eclipse.org/mpc/indigo/ Which made the "Eclipse Marketplace Client" available in my Software updates after I added that address as a repository. Didn't seem to be in the core list on a fresh install.

android studio 0.4.2: Gradle project sync failed error

Today I ran into the same error, however, i was using Android Studio 1.0.2. What i did tot fix the problem was that i started a project with minimum SDK 4.4 (API 19) so when i checked the version i noticed that at File->ProjectStructure->app i found Android 5 as a compile SDK Version. I changed that back to 4.4.

How can I install Apache Ant on Mac OS X?

For MacOS Maveriks (10.9 and perhaps later versions too), Apache Ant does not come bundled with the operating system and so must be installed manually. You can use brew to easily install ant. Simply execute the following command in a terminal window to install brew:

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

It's a medium sized download which took me 10min to download and install. Just follow the process which involves installing various components. If you already have brew installed, make sure it's up to date by executing:

brew update

Once installed you can simply type:

brew install ant

Ant is now installed and available through the "ant" command in the terminal.

To test the installation, just type "ant -version" into a terminal window. You should get the following output:

Apache Ant(TM) version X.X.X compiled on MONTH DAY YEAR

Source: Error executing command 'ant' on Mac OS X 10.9 Mavericks when building for Android with PhoneGap/Cordova

If you are getting errors installing Brew, try uninstalling first using the command:

rm -rf /usr/local/Cellar /usr/local/.git && brew cleanup

Thanks to OrangeDog and other users for providing additional information.

How to schedule a task to run when shutting down windows

Execute gpedit.msc (local Policies)

Computer Configuration -> Windows settings -> Scripts -> Shutdown -> Properties -> Add

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

Copy all the lines to clipboard

If you're using Vim in visual mode, the standard cut and paste keys also apply, at least with Windows.

  • CTRLA means "Mark the entire file.
  • CTRLC means "Copy the selection.
  • ESC means "De-select, so your next key press doesn't replace the entire file :-)

Under Ubuntu terminal (Gnome) at least, the standard copy also works (CTRLSHIFTC, although there doesn't appear to be a standard keyboard shortcut for select all (other than ALTE followed by A).

Get img thumbnails from Vimeo?

UPDATE: This solution stopped working as of Dec 2018.

I was looking for the same thing and it looks like most answers here are outdated due to Vimeo API v2 being deprecated.

my php 2¢:

$vidID     = 12345 // Vimeo Video ID
$tnLink = json_decode(file_get_contents('https://vimeo.com/api/oembed.json?url=https%3A//vimeo.com/' . $vidID))->thumbnail_url;

with the above you will get the link to Vimeo default thumbnail image.

If you want to use different size image, you can add something like:

$tnLink = substr($tnLink, strrpos($tnLink, '/') + 1);
$tnLink = substr($tnLink, 0, strrpos($tnLink, '_')); // You now have the thumbnail ID, which is different from Video ID

// And you can use it with link to one of the sizes of crunched by Vimeo thumbnail image, for example:
$tnLink = 'https://i.vimeocdn.com/filter/overlay?src0=https%3A%2F%2Fi.vimeocdn.com%2Fvideo%2F' . $tnLink    . '_1280x720.jpg&src1=https%3A%2F%2Ff.vimeocdn.com%2Fimages_v6%2Fshare%2Fplay_icon_overlay.png';

How to undo the last commit in git

Try simply to reset last commit using --soft flag

git reset --soft HEAD~1

Note :

For Windows, wrap the HEAD parts in quotes like git reset --soft "HEAD~1"

javascript compare strings without being case sensitive

Another method using a regular expression (this is more correct than Zachary's answer):

var string1 = 'someText',
    string2 = 'SometexT',
    regex = new RegExp('^' + string1 + '$', 'i');

if (regex.test(string2)) {
    return true;
}

RegExp.test() will return true or false.

Also, adding the '^' (signifying the start of the string) to the beginning and '$' (signifying the end of the string) to the end make sure that your regular expression will match only if 'sometext' is the only text in stringToTest. If you're looking for text that contains the regular expression, it's ok to leave those off.

It might just be easier to use the string.toLowerCase() method.

So... regular expressions are powerful, but you should only use them if you understand how they work. Unexpected things can happen when you use something you don't understand.

There are tons of regular expression 'tutorials', but most appear to be trying to push a certain product. Here's what looks like a decent tutorial... granted, it's written for using php, but otherwise, it appears to be a nice beginner's tutorial: http://weblogtoolscollection.com/regex/regex.php

This appears to be a good tool to test regular expressions: http://gskinner.com/RegExr/

Negation in Python

try instead:

if not os.path.exists(pathName):
    do this

How to get first character of a string in SQL?

Select First two Character in selected Field with Left(string,Number of Char in int)

SELECT LEFT(FName, 2) AS FirstName FROM dbo.NameMaster

Creating an empty list in Python

I use [].

  1. It's faster because the list notation is a short circuit.
  2. Creating a list with items should look about the same as creating a list without, why should there be a difference?

What do raw.githubusercontent.com URLs represent?

raw.githubusercontent.com/username/repo-name/branch-name/path

Replace username with the username of the user that created the repo.

Replace repo-name with the name of the repo.

Replace branch-name with the name of the branch.

Replace path with the path to the file.

To reverse to go to GitHub.com:

GitHub.com/username/repo-name/directory-path/blob/branch-name/filename

Peak memory usage of a linux/unix process

On Linux:

Use /usr/bin/time -v <program> <args> and look for "Maximum resident set size".

(Not to be confused with the Bash time built-in command! So use the full path, /usr/bin/time)

For example:

> /usr/bin/time -v ./myapp
        User time (seconds): 0.00
        . . .
        Maximum resident set size (kbytes): 2792
        . . .

On BSD, MacOS:

Use /usr/bin/time -l <program> <args>, looking for "maximum resident set size":

>/usr/bin/time -l ./myapp
        0.01 real         0.00 user         0.00 sys
      1440  maximum resident set size
      . . .

How can I create a link to a local file on a locally-run web page?

I've a way and work like this:

<'a href="FOLDER_PATH" target="_explorer.exe">Link Text<'/a>

UDP vs TCP, how much faster is it?

It is meaningless to talk about TCP or UDP without taking the network condition into account. If the network between the two point have a very high quality, UDP is absolutely faster than TCP, but in some other case such as the GPRS network, TCP may been faster and more reliability than UDP.

MySql Error: 1364 Field 'display_name' doesn't have default value

I also faced that problem and there are two ways to solve this in laravel.

  1. first one is you can set the default value as null. I will show you an example:

    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('gender');
            $table->string('slug');
            $table->string('pic')->nullable();
            $table->string('email')->unique();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
        });
    }
    

as the above example, you can set nullable() for that feature. then when you are inserting data MySQL set the default value as null.

  1. second one is in your model set your input field in protected $fillable field. as example:

    protected $fillable = [
        'name', 'email', 'password', 'slug', 'gender','pic'
    ];
    

I think the second one is fine than the first one and also you can set nullable feature as well as fillable in the same time without a problem.

How do I make a file:// hyperlink that works in both IE and Firefox?

just use

file:///

works in IE, Firefox and Chrome as far as I can tell.

see http://msdn.microsoft.com/en-us/library/aa767731(VS.85).aspx for more info

Running PowerShell as another user, and launching a script

In windows server 2012 or 2016 you can search for Windows PowerShell and then "Pin to Start". After this you will see "Run as different user" option on a right click on the start page tiles.

Is there a link to the "latest" jQuery library on Google APIs?

http://lab.abhinayrathore.com/jquery_cdn/ is a page where you can find links to the latest versions of jQuery, jQuery UI and Themes for Google and Microsoft CDN's.

This page automatically updates with the latest links from the CDN.

Item frequency count in Python

I happened to work on some Spark exercise, here is my solution.

tokens = ['quick', 'brown', 'fox', 'jumps', 'lazy', 'dog']

print {n: float(tokens.count(n))/float(len(tokens)) for n in tokens}

**#output of the above **

{'brown': 0.16666666666666666, 'lazy': 0.16666666666666666, 'jumps': 0.16666666666666666, 'fox': 0.16666666666666666, 'dog': 0.16666666666666666, 'quick': 0.16666666666666666}

Objective-C: Calling selectors with multiple arguments

Your method signature makes no sense, are you sure it isn't a typo? I'm not clear how it's even compiling, though perhaps you're getting warnings that you're ignoring?

How many parameters do you expect this method to take?

How to select all and copy in vim?

In normal mode:

gg"+yG

In ex mode:

:%y+

How to handle configuration in Go

have a look at gonfig

// load
config, _ := gonfig.FromJson(myJsonFile)
// read with defaults
host, _ := config.GetString("service/host", "localhost")
port, _ := config.GetInt("service/port", 80)
test, _ := config.GetBool("service/testing", false)
rate, _ := config.GetFloat("service/rate", 0.0)
// parse section into target structure
config.GetAs("service/template", &template)

HtmlEncode from Class Library

If you are using C#3 a good tip is to create an extension method to make this even simpler. Just create a static method (preferably in a static class) like so:

public static class Extensions
{
    public static string HtmlEncode(this string s)
    {
        return HttpUtility.HtmlEncode(s);
    }
}

You can then do neat stuff like this:

string encoded = "<div>I need encoding</div>".HtmlEncode();

Failed to Connect to MySQL at localhost:3306 with user root

Go to >system preferences >mysql >initialize database

-Change password -Click use legacy password -Click start sql server

it should work now

What does "async: false" do in jQuery.ajax()?

One use case is to make an ajax call before the user closes the window or leaves the page. This would be like deleting some temporary records in the database before the user can navigate to another site or closes the browser.

 $(window).unload(
        function(){
            $.ajax({
            url: 'your url',
            global: false,
            type: 'POST',
            data: {},
            async: false, //blocks window close
            success: function() {}
        });
    });

Docker Networking - nginx: [emerg] host not found in upstream

There is a possibility to use "volumes_from" as a workaround until depends_on feature (discussed below) is introduced. All you have to do is change your docker-compose file as below:

nginx:
  image: nginx
  ports:
    - "42080:80"
  volumes:
    - ./config/docker/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
  volumes_from:
    - php

php:
  build: config/docker/php
  ports:
    - "42022:22"
  volumes:
    - .:/var/www/html
  env_file: config/docker/php/.env.development

mongo:
  image: mongo
  ports:
    - "42017:27017"
  volumes:
    - /var/mongodata/wa-api:/data/db
  command: --smallfiles

One big caveat in the above approach is that the volumes of php are exposed to nginx, which is not desired. But at the moment this is one docker specific workaround that could be used.

depends_on feature This probably would be a futuristic answer. Because the functionality is not yet implemented in Docker (as of 1.9)

There is a proposal to introduce "depends_on" in the new networking feature introduced by Docker. But there is a long running debate about the same @ https://github.com/docker/compose/issues/374 Hence, once it is implemented, the feature depends_on could be used to order the container start-up, but at the moment, you would have to resort to one of the following:

  1. make nginx retry until the php server is up - I would prefer this one
  2. use volums_from workaround as described above - I would avoid using this, because of the volume leakage into unnecessary containers.

Wait 5 seconds before executing next line

Here's a solution using the new async/await syntax.

Be sure to check browser support as this is a language feature introduced with ECMAScript 6.

Utility function:

const delay = ms => new Promise(res => setTimeout(res, ms));

Usage:

const yourFunction = async () => {
  await delay(5000);
  console.log("Waited 5s");

  await delay(5000);
  console.log("Waited an additional 5s");
};

The advantage of this approach is that it makes your code look and behave like synchronous code.

apply drop shadow to border-top only?

.item .content{
    width: 94.1%;
    background: #2d2d2d;
    padding: 3%;
    border-top: solid 1px #000;
    position: relative;
}
.item .content:before{
      content: "";
      display: block;
      position: absolute;
      top: 0px;
      left: 0;
      width: 100%;
      height: 1px;
      -webkit-box-shadow: 0px 1px 13px rgba(255,255,255,1);
      -moz-box-shadow: 0px 1px 13px rgba(255,255,255,1);
      box-shadow: 0px 1px 13px rgba(255,255,255,1);
      z-index: 100;
}

I am like using something like it for it.

How do you add PostgreSQL Driver as a dependency in Maven?

Depending on your PostgreSQL version you would need to add the postgresql driver to your pom.xml file.

For PostgreSQL 9.1 this would be:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>9.1-901-1.jdbc4</version>
        </dependency>
    </dependencies>
</project>

You can get the code for the dependency (as well as any other dependency) from maven's central repository

If you are using postgresql 9.2+:

<project xmlns="http://maven.apache.org/POM/4.0.0"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <name>Your project name.</name>
    <dependencies>
        <dependency>
            <groupId>org.postgresql</groupId>
            <artifactId>postgresql</artifactId>
            <version>42.2.1</version>
        </dependency>
    </dependencies>
</project>

You can check the latest versions and dependency snippets from:

Enter key pressed event handler

For those who struggle at capturing Enter key on TextBox or other input control, if your Form has AcceptButton defined, you will not be able to use KeyDown event to capture Enter.

What you should do is to catch the Enter key at form level. Add this code to the form:

protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
    if ((this.ActiveControl == myTextBox) && (keyData == Keys.Return))
    {
        //do something
        return true;
    }
    else
    {
        return base.ProcessCmdKey(ref msg, keyData);
    }
}

How to save and load cookies using Python + Selenium WebDriver

Just a slight modification for the code written by Roel Van de Paar, as all credit goes to him. I am using this in Windows and it is working perfectly, both for setting and adding cookies:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--user-data-dir=chrome-data")
driver = webdriver.Chrome('chromedriver.exe',options=chrome_options)
driver.get('https://web.whatsapp.com')  # Already authenticated
time.sleep(30)

How to insert table values from one database to another database?

Mostly we need this type of query in migration script

INSERT INTO  db1.table1(col1,col2,col3,col4)
SELECT col5,col6,col7,col8
  FROM db1.table2

In this query column count must be same in both table

Vue js error: Component template should contain exactly one root element

Note This answer only applies to version 2.x of Vue. Version 3 has lifted this restriction.

You have two root elements in your template.

<div class="form-group">
  ...
</div>
<div class="col-md-6">
  ...
</div>

And you need one.

<div>
    <div class="form-group">
      ...
    </div>

    <div class="col-md-6">
      ...
    </div>
</div>

Essentially in Vue you must have only one root element in your templates.

Why would one omit the close tag?

In addition to everything that's been said already, I'm going to throw in another reason that was a huge pain for us to debug.

Apache 2.4.6 with PHP 5.4 actually segmentation faults on our production machines when there's empty space behind the closing php tag. I just wasted hours until I finally narrowed down the bug with strace.

Here is the error that Apache throws:

[core:notice] [pid 7842] AH00052: child pid 10218 exit signal Segmentation fault (11)

How to convert local time string to UTC?

For getting around day-light saving, etc.

None of the above answers particularly helped me. The code below works for GMT.

def get_utc_from_local(date_time, local_tz=None):
    assert date_time.__class__.__name__ == 'datetime'
    if local_tz is None:
        local_tz = pytz.timezone(settings.TIME_ZONE) # Django eg, "Europe/London"
    local_time = local_tz.normalize(local_tz.localize(date_time))
    return local_time.astimezone(pytz.utc)

import pytz
from datetime import datetime

summer_11_am = datetime(2011, 7, 1, 11)
get_utc_from_local(summer_11_am)
>>>datetime.datetime(2011, 7, 1, 10, 0, tzinfo=<UTC>)

winter_11_am = datetime(2011, 11, 11, 11)
get_utc_from_local(winter_11_am)
>>>datetime.datetime(2011, 11, 11, 11, 0, tzinfo=<UTC>)

How to refer environment variable in POM.xml?

You can use <properties> tag to define a custom variable and ${variable} pattern to use it

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <!-- define -->
    <properties>
        <property.name>1.0</property.name>
    </properties>

    <!-- using -->
    <version>${property.name}</version>

</project>

How to insert &nbsp; in XSLT

Try to use

<xsl:text>&#160;</xsl:text>

But it depends on XSLT processor you are using: the XSLT spec does not require XSLT processors to convert it into "&nbsp;".

Order data frame rows according to vector with specific order

We can adjust the factor levels based on target and use it in arrange

library(dplyr)
df %>% arrange(factor(name, levels = target))

#  name value
#1    b  TRUE
#2    c FALSE
#3    a  TRUE
#4    d FALSE

Or order it and use it in slice

df %>% slice(order(factor(name, levels = target)))

Access Control Origin Header error using Axios in React Web throwing error in Chrome

!!! I had a similar problem and I found that in my case the withCredentials: true in the request was activating the CORS check while issuing the same in the header would avoid the check:

https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSMIssingAllowCredentials

do not use withCredentials: true but set 'Access-Control-Allow-Credentials':true in the headers

How do I turn off the mysql password validation?

For mysql 8.0 the command to disable password validation component is:

UNINSTALL COMPONENT 'file://component_validate_password';

To install it back again, the command is:

INSTALL COMPONENT 'file://component_validate_password';

If you just want to change the policy of password validation plugin:

SET GLOBAL validate_password.policy = 0;   // For LOW
SET GLOBAL validate_password.policy = 1;   // For MEDIUM
SET GLOBAL validate_password.policy = 2;   // For HIGH

Eclipse add Tomcat 7 blank server name

I had same issue before: the server name was not appearing in server while configuring with eclipse

I tried all the solutions which are provided over here, but they didn't work for me.

I resolved it, by simply following these simple tips

Step1: Windows --> Preferences --> Server --> Run time Environments --> Add --> select the tomcat version which was unavailable before --> next --> browse the location of your server with same version

Step2: go to servers and select your server version --> next --> Finish

Issue resolved!!! :)

Parsing arguments to a Java command line program

Simple code for command line in java:

class CMDLineArgument
{
    public static void main(String args[])
    {
        String name=args[0];
        System.out.println(name);
    }
}

Scrollable Menu with Bootstrap - Menu expanding its container when it should not

You can use the built-in CSS class pre-scrollable in bootstrap 3 inside the span element of the dropdown and it works immediately without implementing custom css.

 <ul class="dropdown-menu pre-scrollable">
                <li>item 1 </li>
                <li>item 2 </li>

 </ul>

Python3 integer division

Try this:

a = 1
b = 2
int_div  = a // b

Replace contents of factor column in R dataframe

A more general solution that works with all the data frame at once and where you don't have to add new factors levels is:

data.mtx <- as.matrix(data.df)
data.mtx[which(data.mtx == "old.value.to.replace")] <- "new.value"
data.df <- as.data.frame(data.mtx)

A nice feature of this code is that you can assign as many values as you have in your original data frame at once, not only one "new.value", and the new values can be random values. Thus you can create a complete new random data frame with the same size as the original.

How to calculate DATE Difference in PostgreSQL?

This is how I usually do it. A simple number of days perspective of B minus A.

DATE_PART('day', MAX(joindate) - MIN(joindate)) as date_diff

C# string reference type?

If we have to answer the question: String is a reference type and it behaves as a reference. We pass a parameter that holds a reference to, not the actual string. The problem is in the function:

public static void TestI(string test)
{
    test = "after passing";
}

The parameter test holds a reference to the string but it is a copy. We have two variables pointing to the string. And because any operations with strings actually create a new object, we make our local copy to point to the new string. But the original test variable is not changed.

The suggested solutions to put ref in the function declaration and in the invocation work because we will not pass the value of the test variable but will pass just a reference to it. Thus any changes inside the function will reflect the original variable.

I want to repeat at the end: String is a reference type but since its immutable the line test = "after passing"; actually creates a new object and our copy of the variable test is changed to point to the new string.

Can a for loop increment/decrement by more than one?

for (var i = 0; i < 10; i = i + 2) {
    // code here
}?

Get the Application Context In Fragment In Android?

In Kotlin we can get application context in fragment using this

requireActivity().application

How to delete duplicate rows in SQL Server?

I like CTEs and ROW_NUMBER as the two combined allow us to see which rows are deleted (or updated), therefore just change the DELETE FROM CTE... to SELECT * FROM CTE:

WITH CTE AS(
   SELECT [col1], [col2], [col3], [col4], [col5], [col6], [col7],
       RN = ROW_NUMBER()OVER(PARTITION BY col1 ORDER BY col1)
   FROM dbo.Table1
)
DELETE FROM CTE WHERE RN > 1

DEMO (result is different; I assume that it's due to a typo on your part)

COL1    COL2    COL3    COL4    COL5    COL6    COL7
john    1        1       1       1       1       1
sally   2        2       2       2       2       2

This example determines duplicates by a single column col1 because of the PARTITION BY col1. If you want to include multiple columns simply add them to the PARTITION BY:

ROW_NUMBER()OVER(PARTITION BY Col1, Col2, ... ORDER BY OrderColumn)

Create a Bitmap/Drawable from file path

Well, using the static Drawable.createFromPath(String pathName) seems a bit more straightforward to me than decoding it yourself... :-)

If your mImg is a simple ImageView, you don't even need it, use mImg.setImageUri(Uri uri) directly.

What is the iBeacon Bluetooth Profile

If the reason you ask this question is because you want to use Core Bluetooth to advertise as an iBeacon rather than using the standard API, you can easily do so by advertising an NSDictionary such as:

{
    kCBAdvDataAppleBeaconKey = <a7c4c5fa a8dd4ba1 b9a8a240 584f02d3 00040fa0 c5>;
}

See this answer for more information.

How to get multiline input from user

In Python 3.x the raw_input() of Python 2.x has been replaced by input() function. However in both the cases you cannot input multi-line strings, for that purpose you would need to get input from the user line by line and then .join() them using \n, or you can also take various lines and concatenate them using + operator separated by \n

To get multi-line input from the user you can go like:

no_of_lines = 5
lines = ""
for i in xrange(no_of_lines):
    lines+=input()+"\n"

print(lines)

Or

lines = []
while True:
    line = input()
    if line:
        lines.append(line)
    else:
        break
text = '\n'.join(lines)

Error resolving template "index", template might not exist or might not be accessible by any of the configured Template Resolvers

It May be due to some exceptions like (Parsing NUMERIC to String or vise versa).

Please verify cell values either are null or do handle Exception and see.

Best, Shahid

How can I create a Windows .exe (standalone executable) using Java/Eclipse?

Typical Java programs compile into .jar files, which can be executed like .exe files provided the target machine has Java installed and that Java is in its PATH. From Eclipse you use the Export menu item from the File menu.

Postgres "psql not recognized as an internal or external command"

I had your issue and got it working again (on windows 7).

My setup had actually worked at first. I installed postgres and then set up the system PATH variables with C:\Program Files\PostgreSQL\9.6\bin; C:\Program Files\PostgreSQL\9.6\lib. The psql keyword in the command line gave no errors.

I deleted the PATH variables above one at a time to test if they were both really needed. Psql continued to work after I deleted the lib path, but stopped working after I deleted the bin path. When I returned bin, it still didn't work, and the same with lib. I closed and reopened the command line between tries, and checked the path. The problem lingered even though the path was identical to how it had been when working. I re-pasted it.

I uninstalled and reinstalled postgres. The problem lingered. It finally worked after I deleted the spaces between the "; C:..." in the paths and re-saved.

Not sure if it was really the spaces that were the culprit. Maybe the environment variables just needed to be altered and refreshed after the install.

I'm also still not sure if both lib and bin paths are needed since there seems to be some kind of lingering memory for old path configurations. I don't want to test it again though.

How can I use jQuery to make an input readonly?

Given -

<input name="foo" type="text" value="foo" readonly />

this works - (jquery 1.7.1)

$('input[name="foo"]').prop('readonly', true);

tested with readonly and readOnly - both worked.

Jackson - How to process (deserialize) nested JSON?

Your data is problematic in that you have inner wrapper objects in your array. Presumably your Vendor object is designed to handle id, name, company_id, but each of those multiple objects are also wrapped in an object with a single property vendor.

I'm assuming that you're using the Jackson Data Binding model.

If so then there are two things to consider:

The first is using a special Jackson config property. Jackson - since 1.9 I believe, this may not be available if you're using an old version of Jackson - provides UNWRAP_ROOT_VALUE. It's designed for cases where your results are wrapped in a top-level single-property object that you want to discard.

So, play around with:

objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true);

The second is using wrapper objects. Even after discarding the outer wrapper object you still have the problem of your Vendor objects being wrapped in a single-property object. Use a wrapper to get around this:

class VendorWrapper
{
    Vendor vendor;

    // gettors, settors for vendor if you need them
}

Similarly, instead of using UNWRAP_ROOT_VALUES, you could also define a wrapper class to handle the outer object. Assuming that you have correct Vendor, VendorWrapper object, you can define:

class VendorsWrapper
{
    List<VendorWrapper> vendors = new ArrayList<VendorWrapper>();

    // gettors, settors for vendors if you need them
}

// in your deserialization code:
ObjectMapper mapper = new ObjectMapper();
JsonNode rootNode = mapper.readValue(jsonInput, VendorsWrapper.class); 

The object tree for VendorsWrapper is analogous to your JSON:

VendorsWrapper:
    vendors:
    [
        VendorWrapper
            vendor: Vendor,
        VendorWrapper:
            vendor: Vendor,
        ...
    ]

Finally, you might use the Jackson Tree Model to parse this into JsonNodes, discarding the outer node, and for each JsonNode in the ArrayNode, calling:

mapper.readValue(node.get("vendor").getTextValue(), Vendor.class);

That might result in less code, but it seems no less clumsy than using two wrappers.

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

I guess it would be best to fix the database startup script itself. But as a work around, you can add that line to /etc/rc.local, which is executed about last in init phase.

jQuery.inArray(), how to use it right?

inArray returns the index of the element in the array. If the element was not found, -1 will be returned else index of element.

if(jQuery.inArray("element", myarray) === -1) {
    console.log("Not exists in array");
} else {
    console.log("Exists in array");
}

How to delete columns in numpy.array

This creates another array without those columns:

  b = a.compress(logical_not(z), axis=1)

Activating Anaconda Environment in VsCode

If Anaconda is your default Python install then it just works if you install the Microsoft Python extension.

The following should work regardless of Python editor or if you need to point to a specific install:

In settings.json edit python.path with something like

"python.pythonPath": "C:\\Anaconda3\\envs\\py34\\python.exe"

Instructions to edit settings.json

Mock HttpContext.Current in Test Init Method

Below Test Init will also do the job.

[TestInitialize]
public void TestInit()
{
  HttpContext.Current = new HttpContext(new HttpRequest(null, "http://tempuri.org", null), new HttpResponse(null));
  YourControllerToBeTestedController = GetYourToBeTestedController();
}

How can I implement the Iterable interface?

First off:

public class ProfileCollection implements Iterable<Profile> {

Second:

return m_Profiles.get(m_ActiveProfile);

Malformed String ValueError ast.literal_eval() with String representation of Tuple

ast.literal_eval (located in ast.py) parses the tree with ast.parse first, then it evaluates the code with quite an ugly recursive function, interpreting the parse tree elements and replacing them with their literal equivalents. Unfortunately the code is not at all expandable, so to add Decimal to the code you need to copy all the code and start over.

For a slightly easier approach, you can use ast.parse module to parse the expression, and then the ast.NodeVisitor or ast.NodeTransformer to ensure that there is no unwanted syntax or unwanted variable accesses. Then compile with compile and eval to get the result.

The code is a bit different from literal_eval in that this code actually uses eval, but in my opinion is simpler to understand and one does not need to dig too deep into AST trees. It specifically only allows some syntax, explicitly forbidding for example lambdas, attribute accesses (foo.__dict__ is very evil), or accesses to any names that are not deemed safe. It parses your expression fine, and as an extra I also added Num (float and integer), list and dictionary literals.

Also, works the same on 2.7 and 3.3

import ast
import decimal

source = "(Decimal('11.66985'), Decimal('1e-8'),"\
    "(1,), (1,2,3), 1.2, [1,2,3], {1:2})"

tree = ast.parse(source, mode='eval')

# using the NodeTransformer, you can also modify the nodes in the tree,
# however in this example NodeVisitor could do as we are raising exceptions
# only.
class Transformer(ast.NodeTransformer):
    ALLOWED_NAMES = set(['Decimal', 'None', 'False', 'True'])
    ALLOWED_NODE_TYPES = set([
        'Expression', # a top node for an expression
        'Tuple',      # makes a tuple
        'Call',       # a function call (hint, Decimal())
        'Name',       # an identifier...
        'Load',       # loads a value of a variable with given identifier
        'Str',        # a string literal

        'Num',        # allow numbers too
        'List',       # and list literals
        'Dict',       # and dicts...
    ])

    def visit_Name(self, node):
        if not node.id in self.ALLOWED_NAMES:
            raise RuntimeError("Name access to %s is not allowed" % node.id)

        # traverse to child nodes
        return self.generic_visit(node)

    def generic_visit(self, node):
        nodetype = type(node).__name__
        if nodetype not in self.ALLOWED_NODE_TYPES:
            raise RuntimeError("Invalid expression: %s not allowed" % nodetype)

        return ast.NodeTransformer.generic_visit(self, node)


transformer = Transformer()

# raises RuntimeError on invalid code
transformer.visit(tree)

# compile the ast into a code object
clause = compile(tree, '<AST>', 'eval')

# make the globals contain only the Decimal class,
# and eval the compiled object
result = eval(clause, dict(Decimal=decimal.Decimal))

print(result)

Android Studio: Default project directory

File -> Other Settings -> Default settings... -> Terminal --> Project setting --> Start Directory --> ("Browse or Set Your Project Directory Path")

Now Close current Project and Start New Project Then Let Your eyes see Project Location

What exactly does the .join() method do?

To expand a bit more on what others are saying, if you wanted to use join to simply concatenate your two strings, you would do this:

strid = repr(595)
print ''.join([array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring(), strid])

PHP foreach loop through multidimensional array

If you mean the first and last entry of the array when talking about a.first and a.last, it goes like this:

foreach ($arr_nav as $inner_array) {
    echo reset($inner_array); //apple, orange, pear
    echo end($inner_array); //My Apple, View All Oranges, A Pear
}

arrays in PHP have an internal pointer which you can manipulate with reset, next, end. Retrieving keys/values works with key and current, but using each might be better in many cases..

Invalid configuration object. Webpack has been initialised using a configuration object that does not match the API schema

This error occurs me when I use path.resolve(), to set up 'entry' and 'output' settings. entry: path.resolve(__dirname + '/app.jsx'). Just try entry: __dirname + '/app.jsx'

Oracle 11g SQL to get unique values in one column of a multi-column query

I'd use the RANK() function in a subselect and then just pull the row where rank = 1.

select person, language
from
( 
    select person, language, rank() over(order by language) as rank
    from table A
    group by person, language
)
where rank = 1

Add MIME mapping in web.config for IIS Express

If anybody encounters this with errors like Error: cannot add duplicate collection entry of type ‘mimeMap’ with unique key attribute and/or other scripts stop working when doing this fix, it might help to remove it first like this:

<staticContent>
  <remove fileExtension=".woff" />
  <mimeMap fileExtension=".woff" mimeType="application/font-woff" />
</staticContent>

At least that solved my problem

How to do a redirect to another route with react-router?

For the simple answer, you can use Link component from react-router, instead of button. There is ways to change the route in JS, but seems you don't need that here.

<span className="input-group-btn">
  <Link to="/login" />Click to login</Link>
</span>

To do it programmatically in 1.0.x, you do like this, inside your clickHandler function:

this.history.pushState(null, 'login');

Taken from upgrade doc here

You should have this.history placed on your route handler component by react-router. If it child component beneath that mentioned in routes definition, you may need pass that down further

Invalid default value for 'dateAdded'

I solved mine by changing DATE to DATETIME

Run MySQLDump without Locking Tables

If you use the Percona XtraDB Cluster - I found that adding --skip-add-locks
to the mysqldump command Allows the Percona XtraDB Cluster to run the dump file without an issue about LOCK TABLES commands in the dump file.

Sometimes adding a WCF Service Reference generates an empty reference.cs

I also had the issue of broken service references when working with project references on both sides (the service project and the project having a reference to the service). If the the .dll of the referenced project for example is called "Contoso.Development.Common", but the projects name is simply shortened to "Common", also project references to this project are named just "Common". The service however expects a reference to "Contoso.Development.Common" for resolving classes (if this option is activated in the service reference options).

So with explorer I opened the folder of the project which is referencing the service and the "Common"-project. There I editet the VS project file (.csproj) with notepad. Search for the name of the refernced project (which is "Common.csproj" in this example) and you will quickly find the configuration entry representing the project reference.

I changed

<ProjectReference Include="..\Common\Common.csproj"> <Project>{C90AAD45-6857-4F83-BD1D-4772ED50D44C}</Project> <Name>Common</Name> </ProjectReference>

to

<ProjectReference Include="..\Common\Common.csproj"> <Project>{C90AAD45-6857-4F83-BD1D-4772ED50D44C}</Project> <Name>Contoso.Development.Common</Name> </ProjectReference>

The important thing is to change the name of the reference to the name of the dll the referenced project has as output.

Then switch back to VS. There you will be asked to reload the project since it has been modified outside of VS. Click the reload button.

After doing so adding und updating the service reference worked just as expected.

Hope this also helps someone else.

Regards MH