Programs & Examples On #Project management

PROJECT MANAGEMENT QUESTIONS ARE OFF-TOPIC. Please ask these questions on ProjectManagement.SE - https://pm.stackexchange.com

How different is Scrum practice from Agile Practice?

As mentioned Agile is a set of principles about how a methodology should be implemented to achieve the benefits of embracing change, close co-operation etc. These principles address some of the project management issues found in studies such as the Chaos Report by the Standish group.

Agile methodologies are created by the development and supporting teams to meet the principles. The methodology is made to fit the business and changed as appropriate.

SCRUM is a fixed set of processes to implement an incremental development methodology. Since the processes are fixed and not catered to the teams it cannot really be considered agile in the original sense of focus on individuals rather than processes.

Duplicate and rename Xcode project & associated folders

For anybody else having issues with storyboard crashes after copying your project, head over to Main.storyboard under Identity Inspector.

Next, check that your current module is the correct renamed module and not the old one.

Why use ICollection and not IEnumerable or List<T> on many-many/one-many relationships?

I remember it this way:

  1. IEnumerable has one method GetEnumerator() which allows one to read through the values in a collection but not write to it. Most of the complexity of using the enumerator is taken care of for us by the for each statement in C#. IEnumerable has one property: Current, which returns the current element.

  2. ICollection implements IEnumerable and adds few additional properties the most use of which is Count. The generic version of ICollection implements the Add() and Remove() methods.

  3. IList implements both IEnumerable and ICollection, and add the integer indexing access to items (which is not usually required, as ordering is done in database).

.bashrc at ssh login

If ayman's solution doesn't work, try naming your file .profile instead of .bash_profile. That worked for me.

Rename a file in C#

Take a look at System.IO.File.Move, "move" the file to a new name.

System.IO.File.Move("oldfilename", "newfilename");

How do I abort/cancel TPL Tasks?

To answer Prerak K's question about how to use CancellationTokens when not using an anonymous method in Task.Factory.StartNew(), you pass the CancellationToken as a parameter into the method you're starting with StartNew(), as shown in the MSDN example here.

e.g.

var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;

Task.Factory.StartNew( () => DoSomeWork(1, token), token);

static void DoSomeWork(int taskNum, CancellationToken ct)
{
    // Do work here, checking and acting on ct.IsCancellationRequested where applicable, 

}

Sorting a set of values

From a comment:

I want to sort each set.

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

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

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


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

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

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

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


* See the comments for exceptions.

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

I ran into a very similar problem with the same error message. First, debug some by turning on the Qt Debug printer with the command line command:

export QT_DEBUG_PLUGINS=1

and rerun the application. For me this revealed the following:

"Cannot load library /home/.../miniconda3/lib/python3.7/site-packages/PyQt5/Qt/plugins/platforms/libqxcb.so: (libxkbcommon-x11.so.0: cannot open shared object file: No such file or directory)"

"Cannot load library /home/.../miniconda3/lib/python3.7/site-packages/PyQt5/Qt/plugins/platforms/libqxcb.so: (libxkbcommon-x11.so.0: cannot open shared object file: No such file or directory)"

Indeed, I was missing libxkbcommon-x11.so.0 and libxkbcommon-x11.so.0. Next, check your architecture using dpkg from the linux command line. (For me, the command "arch" gave a different and unhelpful result)

dpkg --print-architecture #result for me: amd64

I then googled "libxkbcommon-x11.so.0 ubuntu 18.04 amd64", and likewise for libxkbcommon-x11.so.0, which yields those packages on packages.ubuntu.com. That told me, in retrospect unsurprisingly, I'm missing packages called libxkbcommon-x11-0 and libxkbcommon0, and that installing those packages will include the needed files, but the dev versions will not. Then the solution:

sudo apt-get update

sudo apt-get install libxkbcommon0

sudo apt-get install libxkbcommon-x11-0

Why in C++ do we use DWORD rather than unsigned int?

DWORD is not a C++ type, it's defined in <windows.h>.

The reason is that DWORD has a specific range and format Windows functions rely on, so if you require that specific range use that type. (Or as they say "When in Rome, do as the Romans do.") For you, that happens to correspond to unsigned int, but that might not always be the case. To be safe, use DWORD when a DWORD is expected, regardless of what it may actually be.

For example, if they ever changed the range or format of unsigned int they could use a different type to underly DWORD to keep the same requirements, and all code using DWORD would be none-the-wiser. (Likewise, they could decide DWORD needs to be unsigned long long, change it, and all code using DWORD would be none-the-wiser.)


Also note unsigned int does not necessary have the range 0 to 4,294,967,295. See here.

Object of custom type as dictionary key

You override __hash__ if you want special hash-semantics, and __cmp__ or __eq__ in order to make your class usable as a key. Objects who compare equal need to have the same hash value.

Python expects __hash__ to return an integer, returning Banana() is not recommended :)

User defined classes have __hash__ by default that calls id(self), as you noted.

There is some extra tips from the documentation.:

Classes which inherit a __hash__() method from a parent class but change the meaning of __cmp__() or __eq__() such that the hash value returned is no longer appropriate (e.g. by switching to a value-based concept of equality instead of the default identity based equality) can explicitly flag themselves as being unhashable by setting __hash__ = None in the class definition. Doing so means that not only will instances of the class raise an appropriate TypeError when a program attempts to retrieve their hash value, but they will also be correctly identified as unhashable when checking isinstance(obj, collections.Hashable) (unlike classes which define their own __hash__() to explicitly raise TypeError).

Understanding SQL Server LOCKS on SELECT queries

At my work, we have a very big system that runs on many PCs at the same time, with very big tables with hundreds of thousands of rows, and sometimes many millions of rows.

When you make a SELECT on a very big table, let's say you want to know every transaction a user has made in the past 10 years, and the primary key of the table is not built in an efficient way, the query might take several minutes to run.

Then, our application might me running on many user's PCs at the same time, accessing the same database. So if someone tries to insert into the table that the other SELECT is reading (in pages that SQL is trying to read), then a LOCK can occur and the two transactions block each other.

We had to add a "NO LOCK" to our SELECT statement, because it was a huge SELECT on a table that is used a lot by a lot of users at the same time and we had LOCKS all the time.

I don't know if my example is clear enough? This is a real life example.

How do you replace all the occurrences of a certain character in a string?

You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:

>>> input_given="join smith 25"
>>> chars="".join([i for i in input_given if not i.isdigit()])
>>> age=input_given.translate(None,chars)
>>> age
'25'
>>> name=input_given.replace(age,"").strip()
>>> name
'join smith'

This would of course fail if there is multiple numbers in the input. a quick check would be:

assert(age in input_given)

and also:

assert(len(name)<len(input_given))

How to resolve "git did not exit cleanly (exit code 128)" error on TortoiseGit?

In my case a folder in my directory named as the git-repository on the server caused the failure.

How to set proper codeigniter base url?

Base URL should be absolute, including the protocol:

$config['base_url'] = "http://".$_SERVER['SERVER_NAME']."/mysite/";

This configuration will work in both localhost and server.

Don't forget to enable on autoload:

$autoload['helper'] = array('url','file');

Then base_url() will output as below

echo base_url('assets/style.css'); //http://yoursite.com/mysite/assets/style.css

What's in an Eclipse .classpath/.project file?

Eclipse is a runtime environment for plugins. Virtually everything you see in Eclipse is the result of plugins installed on Eclipse, rather than Eclipse itself.

The .project file is maintained by the core Eclipse platform, and its goal is to describe the project from a generic, plugin-independent Eclipse view. What's the project's name? what other projects in the workspace does it refer to? What are the builders that are used in order to build the project? (remember, the concept of "build" doesn't pertain specifically to Java projects, but also to other types of projects)

The .classpath file is maintained by Eclipse's JDT feature (feature = set of plugins). JDT holds multiple such "meta" files in the project (see the .settings directory inside the project); the .classpath file is just one of them. Specifically, the .classpath file contains information that the JDT feature needs in order to properly compile the project: the project's source folders (that is, what to compile); the output folders (where to compile to); and classpath entries (such as other projects in the workspace, arbitrary JAR files on the file system, and so forth).

Blindly copying such files from one machine to another may be risky. For example, if arbitrary JAR files are placed on the classpath (that is, JAR files that are located outside the workspace and are referred-to by absolute path naming), the .classpath file is rendered non-portable and must be modified in order to be portable. There are certain best practices that can be followed to guarantee .classpath file portability.

Android - how to make a scrollable constraintlayout?

in scrollview make height and width 0 add Top_toBottomOfand Bottom_toTopOf constraints that's it.

Fatal error: Class 'ZipArchive' not found in

Try to write \ZIPARCHIVE instead of ZIPARCHIVE.

Left/Right float button inside div

You can use justify-content: space-between in .test like so:

_x000D_
_x000D_
.test {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


For those who want to use Bootstrap 4 can use justify-content-between:

_x000D_
_x000D_
div {_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Angular 2 Show and Hide an element

Depending on your needs, *ngIf or [ngClass]="{hide_element: item.hidden}" where CSS class hide_element is { display: none; }

*ngIf can cause issues if you're changing state variables *ngIf is removing, in those cases using CSS display: none; is required.

Connecting an input stream to an outputstream

Use org.apache.commons.io.IOUtils

InputStream inStream = new ...
OutputStream outStream = new ...
IOUtils.copy(inStream, outStream);

or copyLarge for size >2GB

What exactly does numpy.exp() do?

exp(x) = e^x where e= 2.718281(approx)

import numpy as np

ar=np.array([1,2,3])
ar=np.exp(ar)
print ar

outputs:

[ 2.71828183  7.3890561  20.08553692]

How to set app icon for Electron / Atom Shell App

Below is the solution that i have :

mainWindow = new BrowserWindow({width: 800, height: 600,icon: __dirname + '/Bluetooth.ico'});

What is the default value for Guid?

You can use these methods to get an empty guid. The result will be a guid with all it's digits being 0's - "00000000-0000-0000-0000-000000000000".

new Guid()

default(Guid)

Guid.Empty

How to print HTML content on click of a button, but not the page?

Below Code May Be Help You :

<html>
<head>
<script>
function printPage(id)
{
   var html="<html>";
   html+= document.getElementById(id).innerHTML;

   html+="</html>";

   var printWin = window.open('','','left=0,top=0,width=1,height=1,toolbar=0,scrollbars=0,status  =0');
   printWin.document.write(html);
   printWin.document.close();
   printWin.focus();
   printWin.print();
   printWin.close();
}
</script>
</head>
<body>
<div id="block1">
<table border="1" >
</tr>
<th colspan="3">Block 1</th>
</tr>
<tr>
<th>1</th><th>XYZ</th><th>athock</th>
</tr>
</table>

</div>

<div id="block2">
    This is Block 2 content
</div>

<input type="button" value="Print Block 1" onclick="printPage('block1');"></input>
<input type="button" value="Print Block 2" onclick="printPage('block2');"></input>
</body>
</html>

HttpRequest maximum allowable size in tomcat?

The full answer

1. The default (fresh install of tomcat)

When you download tomcat from their official website (of today that's tomcat version 9.0.26), all the apps you installed to tomcat can handle HTTP requests of unlimited size, given that the apps themselves do not have any limits on request size.

However, when you try to upload an app in tomcat's manager app, that app has a default war file limit of 50MB. If you're trying to install Jenkins for example which is 77 MB as ot today, it will fail.

2. Configure tomcat's per port http request size limit

Tomcat itself has size limit for each port, and this is defined in conf\server.xml. This is controlled by maxPostSize attribute of each Connector(port). If this attribute does not exist, which it is by default, there is no limit on the request size.

To add a limit to a specific port, set a byte size for the attribute. For example, the below config for the default 8080 port limits request size to 200 MB. This means that all the apps installed under port 8080 now has the size limit of 200MB

<Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443"
           maxPostSize="209715200" />

3. Configure app level size limit

After passing the port level size limit, you can still configure app level limit. This also means that app level limit should be less than port level limit. The limit can be done through annotation within each servlet, or in the web.xml file. Again, if this is not set at all, there is no limit on request size.

To set limit through java annotation

@WebServlet("/uploadFiles")
@MultipartConfig( fileSizeThreshold = 0, maxFileSize = 209715200, maxRequestSize = 209715200)
public class FileUploadServlet extends HttpServlet {

    public void doPost(HttpServletRequest request, HttpServletResponse response) {
        // ...
    }
}

To set limit through web.xml

<web-app>
  ...
  <servlet>
    ...
    <multipart-config>
      <file-size-threshold>0</file-size-threshold>
      <max-file-size>209715200</max-file-size>
      <max-request-size>209715200</max-request-size>
    </multipart-config>
    ...
  </servlet>
  ...
</web-app>

4. Appendix - If you see file upload size error when trying to install app through Tomcat's Manager app

Tomcat's Manager app (by default localhost:8080/manager) is nothing but a default web app. By default that app has a web.xml configuration of request limit of 50MB. To install (upload) app with size greater than 50MB through this manager app, you have to change the limit. Open the manager app's web.xml file from webapps\manager\WEB-INF\web.xml and follow the above guide to change the size limit and finally restart tomcat.

General error: 1364 Field 'user_id' doesn't have a default value

Here's how I did it:

This is my PostsController

Post::create([

    'title' => request('title'),
    'body' => request('body'),
    'user_id' => auth()->id() 
]);

And this is my Post Model.

protected $fillable = ['title', 'body','user_id'];

And try refreshing the migration if its just on test instance

$ php artisan migrate:refresh

Note: migrate: refresh will delete all the previous posts, users

How to list the contents of a package using YUM?

I don't think you can list the contents of a package using yum, but if you have the .rpm file on your local system (as will most likely be the case for all installed packages), you can use the rpm command to list the contents of that package like so:

rpm -qlp /path/to/fileToList.rpm

If you don't have the package file (.rpm), but you have the package installed, try this:

rpm -ql packageName

plot different color for different categorical levels using matplotlib

I usually do it using Seaborn which is built on top of matplotlib

import seaborn as sns
iris = sns.load_dataset('iris')
sns.scatterplot(x='sepal_length', y='sepal_width',
              hue='species', data=iris); 

How to change status bar color to match app in Lollipop? [Android]

Another way to set the status bar color is through the style.xml.

To do that, create a style.xml file under res/values-v21 folder with this content:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="AppTheme" parent="android:Theme.Material">
        <!--   darker variant for the status bar and contextual app bars -->
        <item name="android:colorPrimaryDark">@color/blue_dark</item>
    </style>
</resources>

Edit: as pointed out in comments, when using AppCompat the code is different. In file res/values/style.xml use instead:

<style name="Theme.MyTheme" parent="Theme.AppCompat.Light">   
    <!-- Set AppCompat’s color theming attrs -->
    <item name="colorPrimary">@color/my_awesome_red</item>
    <item name="colorPrimaryDark">@color/my_awesome_darker_red</item>
    <!-- Other attributes -->
</style>

What bitrate is used for each of the youtube video qualities (360p - 1080p), in regards to flowplayer?

Looking at this official google link: Youtube Live encoder settings, bitrates and resolutions they have this table:

                   240p       360p        480p        720p        1080p
Resolution      426 x 240   640 x 360   854x480     1280x720    1920x1080
Video Bitrates                   
Maximum         700 Kbps    1000 Kbps   2000 Kbps   4000 Kbps   6000 Kbps
Recommended     400 Kbps    750 Kbps    1000 Kbps   2500 Kbps   4500 Kbps
Minimum         300 Kbps    400 Kbps    500 Kbps    1500 Kbps   3000 Kbps

It would appear as though this is the case, although the numbers dont sync up to the google table above:

// the bitrates, video width and file names for this clip
      bitrates: [
        { url: "bbb-800.mp4", width: 480, bitrate: 800 }, //360p video
        { url: "bbb-1200.mp4", width: 720, bitrate: 1200 }, //480p video
        { url: "bbb-1600.mp4", width: 1080, bitrate: 1600 } //720p video
      ],

Is it possible to add dynamically named properties to JavaScript object?

Definitely. Think of it as a dictionary or associative array. You can add to it at any point.

Output to the same line overwriting previous output?

I found that for a simple print statement in python 2.7, just put a comma at the end after your '\r'.

print os.path.getsize(file_name)/1024, 'KB / ', size, 'KB downloaded!\r',

This is shorter than other non-python 3 solutions, but also more difficult to maintain.

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window

If the setTimeout function does not work for you either, then do the following:

//Create an iframe
iframe = $('body').append($('<iframe id="documentToPrint" name="documentToPrint" src="about:blank"/>'));
iframeElement = $('#documentToPrint')[0].contentWindow.document;

//Open the iframe
iframeElement.open();

//Write your content to the iframe
iframeElement.write($("yourContentId").html());

//This is the important bit.
//Wait for the iframe window to load, then print it.
$('#documentToPrint')[0].contentWindow.onload = function () {
    $('#print-document')[0].contentWindow.print();
    $('#print-document').remove();
};
iframeElement.close();

How to copy files across computers using SSH and MAC OS X Terminal

You may also want to look at rsync if you're doing a lot of files.

If you're going to making a lot of changes and want to keep your directories and files in sync, you may want to use a version control system like Subversion or Git. See http://xoa.petdance.com/How_to:_Keep_your_home_directory_in_Subversion

Simple mediaplayer play mp3 from file path?

Here is the code to set up a MediaPlayer to play off of the SD card:

String PATH_TO_FILE = "/sdcard/music.mp3";    
mediaPlayer = new  MediaPlayer();
mediaPlayer.setDataSource(PATH_TO_FILE);
mediaPlayer.prepare();   
mediaPlayer.start()

You can see the full example here. Let me know if you have any problems.

Extract code country from phone number [libphonenumber]

Use a try catch block like below:

try { 

const phoneNumber = this.phoneUtil.parseAndKeepRawInput(value, this.countryCode);

}catch(e){}

Undefined symbols for architecture i386: _OBJC_CLASS_$_SKPSMTPMessage", referenced from: error

Is your framework compiled for armv(x)? It looks to me like it's compiled for i386, which code won't run on an iOS device. Or else it's compiled for armv(x) and you're trying to run it on the simulator, which is i386 code. Make sure, using the build settings Akshay displayed above, that your framework is correctly compiled for the chip you're going to run it on.

C# generic list <T> how to get the type of T?

Given an object which I suspect to be some kind of IList<>, how can I determine of what it's an IList<>?

Here's a reliable solution. My apologies for length - C#'s introspection API makes this suprisingly difficult.

/// <summary>
/// Test if a type implements IList of T, and if so, determine T.
/// </summary>
public static bool TryListOfWhat(Type type, out Type innerType)
{
    Contract.Requires(type != null);

    var interfaceTest = new Func<Type, Type>(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IList<>) ? i.GetGenericArguments().Single() : null);

    innerType = interfaceTest(type);
    if (innerType != null)
    {
        return true;
    }

    foreach (var i in type.GetInterfaces())
    {
        innerType = interfaceTest(i);
        if (innerType != null)
        {
            return true;
        }
    }

    return false;
}

Example usage:

    object value = new ObservableCollection<int>();
Type innerType;
TryListOfWhat(value.GetType(), out innerType).Dump();
innerType.Dump();

Returns

True
typeof(Int32)

How to execute a .bat file from a C# windows form app?

Here is what you are looking for:

Service hangs up at WaitForExit after calling batch file

It's about a question as to why a service can't execute a file, but it shows all the code necessary to do so.

Array of PHP Objects

The best place to find answers to general (and somewhat easy questions) such as this is to read up on PHP docs. Specifically in your case you can read more on objects. You can store stdObject and instantiated objects within an array. In fact, there is a process known as 'hydration' which populates the member variables of an object with values from a database row, then the object is stored in an array (possibly with other objects) and returned to the calling code for access.

-- Edit --

class Car
{
    public $color;
    public $type;
}

$myCar = new Car();
$myCar->color = 'red';
$myCar->type = 'sedan';

$yourCar = new Car();
$yourCar->color = 'blue';
$yourCar->type = 'suv';

$cars = array($myCar, $yourCar);

foreach ($cars as $car) {
    echo 'This car is a ' . $car->color . ' ' . $car->type . "\n";
}

How do I Search/Find and Replace in a standard string?

// Replace all occurrences of searchStr in str with replacer
// Each match is replaced only once to prevent an infinite loop
// The algorithm iterates once over the input and only concatenates 
// to the output, so it should be reasonably efficient
std::string replace(const std::string& str, const std::string& searchStr, 
    const std::string& replacer)
{
    // Prevent an infinite loop if the input is empty
    if (searchStr == "") {
        return str;
    }

    std::string result = "";
    size_t pos = 0;
    size_t pos2 = str.find(searchStr, pos);

    while (pos2 != std::string::npos) {
        result += str.substr(pos, pos2-pos) + replacer;
        pos = pos2 + searchStr.length();
        pos2 = str.find(searchStr, pos);
    }

    result += str.substr(pos, str.length()-pos);
    return result;
}

Multiplying across in a numpy array

I've compared the different options for speed and found that – much to my surprise – all options (except diag) are equally fast. I personally use

A * b[:, None]

(or (A.T * b).T) because it's short.

enter image description here


Code to reproduce the plot:

import numpy
import perfplot


def newaxis(data):
    A, b = data
    return A * b[:, numpy.newaxis]


def none(data):
    A, b = data
    return A * b[:, None]


def double_transpose(data):
    A, b = data
    return (A.T * b).T


def double_transpose_contiguous(data):
    A, b = data
    return numpy.ascontiguousarray((A.T * b).T)


def diag_dot(data):
    A, b = data
    return numpy.dot(numpy.diag(b), A)


def einsum(data):
    A, b = data
    return numpy.einsum("ij,i->ij", A, b)


perfplot.save(
    "p.png",
    setup=lambda n: (numpy.random.rand(n, n), numpy.random.rand(n)),
    kernels=[
        newaxis,
        none,
        double_transpose,
        double_transpose_contiguous,
        diag_dot,
        einsum,
    ],
    n_range=[2 ** k for k in range(13)],
    xlabel="len(A), len(b)",
)

How to make jQuery UI nav menu horizontal?

Just think about the jquery-ui menu as being the verticle dropdown when you hover over a topic on your main horizonal menu. That way, you have a separate jquery ui menu for each topic on your main menu. The horizonal main menu is just a collection of float:left divs wrapped in a mainmenu div. You then use the hover in and hover out to pop up each menu.

$('.mainmenuitem').hover(
    function(){ 
        $(this).addClass('ui-state-focus');
        $(this).addClass('ui-corner-all');
        $(this).addClass('ui-state-hover');
        $(this).addClass('ui-state-active');
        $(this).addClass('mainmenuhighlighted');
        // trigger submenu
        var position=$(this).offset();
        posleft=position.left;
        postop=position.top;
        submenu=$(this).attr('submenu');
        showSubmenu(posleft,postop,submenu);    
    },
    function(){ 
        $(this).removeClass('ui-state-focus');
        $(this).removeClass('ui-corner-all');
        $(this).removeClass('ui-state-hover');
        $(this).removeClass('ui-state-active');
        $(this).removeClass('mainmenuhighlighted');
        // remove submenu
        $('.submenu').hide();
    }
    );

The showSubmenu function is simple - it just positions the submenu and shows it.

function showSubmenu(left,top,submenu){
    var tPosX=left;
    var tPosY=top+28;
    $('#'+submenu).css({left:tPosX, top:tPosY,position:'absolute'});
    $('#'+submenu).show();
}

You then need to make sure the submenu is visible while your cursor is on it and disappears when you leave (this should be in your document.ready function.

$('.submenu').hover(
            function(){ 
                $(this).show();
            },
            function(){ 
                $(this).hide();
            }
            );

Also don't forget to hide your submenus to start with - in the document.ready function

$(".submenu" ).hide();

See the full code here

http://jsfiddle.net/R4nyn/

How to generate List<String> from SQL query?

If you would like to query all columns

List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
    cn.Open();
    MySqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        list_users.Add(new Users(dr));
    }
}
catch { /* error */ }
finally { cn.Close(); }

The User's constructor would do all the "dr.GetString(i)"

Simple file write function in C++

You need to declare the prototype of your writeFile function, before actually using it:

int writeFile( void );

int main( void )
{
   ...

Converting integer to digit list

If you have a string like this: '123456' and you want a list of integers like this: [1,2,3,4,5,6], use this:

>>>s = '123456'    
>>>list1 = [int(i) for i in list(s)]
>>>print(list1)

[1,2,3,4,5,6]

or if you want a list of strings like this: ['1','2','3','4','5','6'], use this:

>>>s = '123456'    
>>>list1 = list(s)
>>>print(list1)

['1','2','3','4','5','6']

Check which element has been clicked with jQuery

Hope this useful for you.

$(document).click(function(e){
    if ($('#news_gallery').on('clicked')) {
        var article = $('#news-article .news-article');
    }  
});

what is the difference between OLE DB and ODBC data sources?

According to ADO: ActiveX Data Objects, a book by Jason T. Roff, published by O'Reilly Media in 2001 (excellent diagram here), he says precisely what MOZILLA said.

(directly from page 7 of that book)

  • ODBC provides access only to relational databases
  • OLE DB provides the following features
    • Access to data regardless of its format or location
    • Full access to ODBC data sources and ODBC drivers

So it would seem that OLE DB interacts with SQL-based datasources THRU the ODBC driver layer.

alt text

I'm not 100% sure this image is correct. The two connections I'm not certain about are ADO.NET thru ADO C-api, and OLE DB thru ODBC to SQL-based data source (because in this diagram the author doesn't put OLE DB's access thru ODBC, which I believe is a mistake).

How can I group data with an Angular filter?

If you need that in js code. You can use injected method of angula-filter lib. Like this.

function controller($scope, $http, groupByFilter) {     

   var groupedData = groupByFilter(originalArray, 'groupPropName');

}

https://github.com/a8m/angular-filter/wiki/Common-Questions#inject-filters

String formatting: % vs. .format vs. string literal

One situation where % may help is when you are formatting regex expressions. For example,

'{type_names} [a-z]{2}'.format(type_names='triangle|square')

raises IndexError. In this situation, you can use:

'%(type_names)s [a-z]{2}' % {'type_names': 'triangle|square'}

This avoids writing the regex as '{type_names} [a-z]{{2}}'. This can be useful when you have two regexes, where one is used alone without format, but the concatenation of both is formatted.

On duplicate key ignore?

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

Query OK, 0 rows affected (0.07 sec)

Android: How to get a custom View's height and width?

Well getheight gets the height, and getwidth gets the width. But you're calling those methods too soon. If you're calling them in oncreate or onresume, the view isn't drawn yet. You have to call it after the view has been drawn.

What exceptions should be thrown for invalid or unexpected parameters in .NET?

Short answer:
Neither

Longer answer:
using Argument*Exception (except in a library that is a product on its on, such as component library) is a smell. Exceptions are to handle exceptional situation, not bugs, and not user's (i.e. API consumer) shortfalls.

Longest answer:
Throwing exceptions for invalid arguments is rude, unless you write a library.
I prefer using assertions, for two (or more) reasons:

  • Assertions don't need to be tested, while throw assertions do, and test against ArgumentNullException looks ridiculous (try it).
  • Assertions better communicate the intended use of the unit, and is closer to being executable documentation than a class behavior specification.
  • You can change behavior of assertion violation. For example in debug compilation a message box is fine, so that your QA will hit you with it right away (you also get your IDE breaking on the line where it happens), while in unit test you can indicate assertion failure as a test failure.

Here is what handling of null exception looks like (being sarcastic, obviously):

try {
    library.Method(null);
}
catch (ArgumentNullException e) {
    // retry with real argument this time
    library.Method(realArgument);
}

Exceptions shall be used when situation is expected but exceptional (things happen that are outside of consumer's control, such as IO failure). Argument*Exception is an indication of a bug and shall be (my opinion) handled with tests and assisted with Debug.Assert

BTW: In this particular case, you could have used Month type, instead of int. C# falls short when it comes to type safety (Aspect# rulez!) but sometimes you can prevent (or catch at compile time) those bugs all together.

And yes, MicroSoft is wrong about that.

Display milliseconds in Excel

Right click on Cell B1 and choose Format Cells. In Custom, put the following in the text box labeled Type:

[h]:mm:ss.000 

To set this in code, you can do something like:

Range("A1").NumberFormat = "[h]:mm:ss.000"

That should give you what you're looking for.

NOTE: Specially formatted fields often require that the column width be wide enough for the entire contents of the formatted text. Otherwise, the text will display as ######.

How to resolve merge conflicts in Git repository?

Gitlense For VS Code

You can try Gitlense for VS Code, They key features are:

3. Easily Resolve Conflicts.

I already like this feature:

enter image description here

2. Current Line Blame.

enter image description here

3. Gutter Blame

enter image description here

4. Status Bar Blame

enter image description here

And there are many features you can check them here.

Detect if user is scrolling

Use an interval to check

You can setup an interval to keep checking if the user has scrolled then do something accordingly.

Borrowing from the great John Resig in his article.

Example:

    let didScroll = false;

    window.onscroll = () => didScroll = true;

    setInterval(() => {
        if ( didScroll ) {
            didScroll = false;
            console.log('Someone scrolled me!')
        }
    }, 250);

See live example

jQuery limit to 2 decimal places

You could use a variable to make the calculation and use toFixed when you set the #diskamountUnit element value:

var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));

You can also do that in one step, in the val method call but IMO the first way is more readable:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));

C# static class constructor

Static constructor called only the first instance of the class created.

like this:

static class YourClass
{
    static YourClass()
    {
        //initialization
    }
}

Code for Greatest Common Divisor in Python

This code calculates the gcd of more than two numbers depending on the choice given by # the user, here user gives the number

numbers = [];
count = input ("HOW MANY NUMBERS YOU WANT TO CALCULATE GCD?\n")
for i in range(0, count):
  number = input("ENTER THE NUMBER : \n")
  numbers.append(number)
numbers_sorted = sorted(numbers)
print  'NUMBERS SORTED IN INCREASING ORDER\n',numbers_sorted
gcd = numbers_sorted[0]

for i in range(1, count):
  divisor = gcd
  dividend = numbers_sorted[i]
  remainder = dividend % divisor
  if remainder == 0 :
  gcd = divisor
  else :
    while not remainder == 0 :
      dividend_one = divisor
      divisor_one = remainder
      remainder = dividend_one % divisor_one
      gcd = divisor_one

print 'GCD OF ' ,count,'NUMBERS IS \n', gcd

Add JsonArray to JsonObject

Your list:

List<MyCustomObject> myCustomObjectList;

Your JSONArray:

// Don't need to loop through it. JSONArray constructor do it for you.
new JSONArray(myCustomObjectList)

Your response:

return new JSONObject().put("yourCustomKey", new JSONArray(myCustomObjectList));

Your post/put http body request would be like this:

    {
        "yourCustomKey: [
           {
               "myCustomObjectProperty": 1
           },
           {
               "myCustomObjectProperty": 2
           }
        ]
    }

How to write a shell script that runs some commands as superuser and some commands not as superuser, without having to babysit it?

If you use this, check man sudo too:

#!/bin/bash

sudo echo "Hi, I'm root"

sudo -u nobody echo "I'm nobody"

sudo -u 1000 touch /test_user

How to access full source of old commit in BitBucket?

  1. The easiest way is to click on that commit and add a tag to that commit. I have included the tag 'last_commit' with this commit

  2. Than go to downloads in the left corner of the side nav in bit bucket. Click on download in the left side

  3. Now click on tags in the nav bar and download the zip from the UI. Find your tag and download the zip

Should I use Vagrant or Docker for creating an isolated environment?

I preface my reply by admitting I have no experience with Docker, other than as an avid observer of what looks to be a really neat solution that's gaining a lot of traction.

I do have a decent amount of experience with Vagrant and can highly recommend it. It's certainly a more heavyweight solution in terms of it being VM based instead of LXC based. However, I've found a decent laptop (8 GB RAM, i5/i7 CPU) has no trouble running a VM using Vagrant/VirtualBox alongside development tooling.

One of the really great things with Vagrant is the integration with Puppet/Chef/shell scripts for automating configuration. If you're using one of these options to configure your production environment, you can create a development environment which is as close to identical as you're going to get, and this is exactly what you want.

The other great thing with Vagrant is that you can version your Vagrantfile along with your application code. This means that everyone else on your team can share this file and you're guaranteed that everyone is working with the same environment configuration.

Interestingly, Vagrant and Docker may actually be complimentary. Vagrant can be extended to support different virtualization providers, and it may be possible that Docker is one such provider which gets support in the near future. See https://github.com/dotcloud/docker/issues/404 for recent discussion on the topic.

Bootstrap 3 - set height of modal window according to screen size

I am using jquery for this. I mad a function to set desired height to the modal(You can change that according to your requirement). Then I used Modal Shown event to call this function. Remember not to use $("#modal").show() rather use $("#modal").modal('show') otherwise shown.bs.modal will not be fired.

That all I have for this scenario.

_x000D_
_x000D_
var offset=250; //You can set offset accordingly based on your UI_x000D_
function AdjustPopup() _x000D_
{_x000D_
    $(".modal-body").css("height","auto");_x000D_
    if ($(".modal-body:visible").height() > ($(window).height() - offset)) _x000D_
    {_x000D_
        $(".modal-body:visible").css("height", ($(window).height() - offset));_x000D_
    }_x000D_
}_x000D_
//Execute the function on every trigger on show() event._x000D_
$(document).ready(function(){_x000D_
$('.modal').on('shown.bs.modal', function (e) {_x000D_
        AdjustPopup();_x000D_
    });_x000D_
});_x000D_
//Remember to show modal like this_x000D_
$("#MyModal").modal('show');
_x000D_
_x000D_
_x000D_

How to get the previous URL in JavaScript?

Those of you using Node.js and Express can set a session cookie that will remember the current page URL, thus allowing you to check the referrer on the next page load. Here's an example that uses the express-session middleware:

//Add me after the express-session middleware    
app.use((req, res, next) => {
    req.session.referrer = req.protocol + '://' + req.get('host') + req.originalUrl;
    next();
});

You can then check for the existance of a referrer cookie like so:

if ( req.session.referrer ) console.log(req.session.referrer);

Do not assume that a referrer cookie always exists with this method as it will not be available on instances where the previous URL was another website, the session was cleaned or was just created (first-time website load).

How to loop through all the properties of a class?

Here's another way to do it, using a LINQ lambda:

C#:

SomeObject.GetType().GetProperties().ToList().ForEach(x => Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, null)}"));

VB.NET:

SomeObject.GetType.GetProperties.ToList.ForEach(Sub(x) Console.WriteLine($"{x.Name} = {x.GetValue(SomeObject, Nothing)}"))

Accessing a local website from another computer inside the local network in IIS 7

do not turn off firewall, Go Control Panel\System and Security\Windows Firewall then Advanced settings then Inbound Rules->From right pan choose New Rule-> Port-> TCP and type in port number 80 then give a name in next window, that's it.

MySQL search and replace some text in a field

 UPDATE table SET field = replace(field, text_needs_to_be_replaced, text_required);

Like for example, if I want to replace all occurrences of John by Mark I will use below,

UPDATE student SET student_name = replace(student_name, 'John', 'Mark');

Flutter - The method was called on null

You should declare your method first in void initState(), so when the first time pages has been loaded, it will init your method first, hope it can help

How to implement 2D vector array?

I'm not exactly sure what the problem is, as your example code has several errors and doesn't really make it clear what you're trying to do. But here's how you add to a specific row of a 2D vector:

// declare 2D vector
vector< vector<int> > myVector;
// make new row (arbitrary example)
vector<int> myRow(1,5);
myVector.push_back(myRow);
// add element to row
myVector[0].push_back(1);

Does this answer your question? If not, could you try to be more specific as to what you are having trouble with?

How to Delete Session Cookie?

Be sure to supply the exact same path as when you set it, i.e.

Setting:

$.cookie('foo','bar', {path: '/'});

Removing:

$.cookie('foo', null, {path: '/'});

Note that

$.cookie('foo', null); 

will NOT work, since it is actually not the same cookie.

Hope that helps. The same goes for the other options in the hash

Seeing if data is normally distributed in R

The Anderson-Darling test is also be useful.

library(nortest)
ad.test(data)

Non-static variable cannot be referenced from a static context

Let's analyze your program first.. In your program, your first method is main(), and keep it in mind it is the static method... Then you declare the local variable for that method (compareCount, low, high, etc..). The scope of this variable is only the declared method, regardless of it being a static or non static method. So you can't use those variables outside that method. This is the basic error u made.

Then we come to next point. You told static is killing you. (It may be killing you but it only gives life to your program!!) First you must understand the basic thing. *Static method calls only the static method and use only the static variable. *Static variable or static method are not dependent on any instance of that class. (i.e. If you change any state of the static variable it will reflect in all objects of the class) *Because of this you call it as a class variable or a class method. And a lot more is there about the "static" keyword. I hope now you get the idea. First change the scope of the variable and declare it as a static (to be able to use it in static methods).

And the advice for you is: you misunderstood the idea of the scope of the variables and static functionalities. Get clear idea about that.

How to copy Java Collections list

To understand why Collections.copy() throws an IndexOutOfBoundsException although you've made the backing array of the destination list large enough (via the size() call on the sourceList), see the answer by Abhay Yadav in this related question: How to copy a java.util.List into another java.util.List

warning: control reaches end of non-void function [-Wreturn-type]

You can also use EXIT_SUCCESS instead of return 0;. The macro EXIT_SUCCESS is actually defined as zero, but makes your program more readable.

How to copy files from 'assets' folder to sdcard?

There are essentially two ways to do this.

First, you can use AssetManager.open and, as described by Rohith Nandakumar and iterate over the inputstream.

Second, you can use AssetManager.openFd, which allows you to use a FileChannel (which has the [transferTo](https://developer.android.com/reference/java/nio/channels/FileChannel.html#transferTo(long, long, java.nio.channels.WritableByteChannel)) and [transferFrom](https://developer.android.com/reference/java/nio/channels/FileChannel.html#transferFrom(java.nio.channels.ReadableByteChannel, long, long)) methods), so you don't have to loop over the input stream yourself.

I will describe the openFd method here.

Compression

First you need to ensure that the file is stored uncompressed. The packaging system may choose to compress any file with an extension that is not marked as noCompress, and compressed files cannot be memory mapped, so you will have to rely on AssetManager.open in that case.

You can add a '.mp3' extension to your file to stop it from being compressed, but the proper solution is to modify your app/build.gradle file and add the following lines (to disable compression of PDF files)

aaptOptions {
    noCompress 'pdf'
}

File packing

Note that the packager can still pack multiple files into one, so you can't just read the whole file the AssetManager gives you. You need to to ask the AssetFileDescriptor which parts you need.

Finding the correct part of the packed file

Once you've ensured your file is stored uncompressed, you can use the AssetManager.openFd method to obtain an AssetFileDescriptor, which can be used to obtain a FileInputStream (unlike AssetManager.open, which returns an InputStream) that contains a FileChannel. It also contains the starting offset (getStartOffset) and size (getLength), which you need to obtain the correct part of the file.

Implementation

An example implementation is given below:

private void copyFileFromAssets(String in_filename, File out_file){
    Log.d("copyFileFromAssets", "Copying file '"+in_filename+"' to '"+out_file.toString()+"'");
    AssetManager assetManager = getApplicationContext().getAssets();
    FileChannel in_chan = null, out_chan = null;
    try {
        AssetFileDescriptor in_afd = assetManager.openFd(in_filename);
        FileInputStream in_stream = in_afd.createInputStream();
        in_chan = in_stream.getChannel();
        Log.d("copyFileFromAssets", "Asset space in file: start = "+in_afd.getStartOffset()+", length = "+in_afd.getLength());
        FileOutputStream out_stream = new FileOutputStream(out_file);
        out_chan = out_stream.getChannel();
        in_chan.transferTo(in_afd.getStartOffset(), in_afd.getLength(), out_chan);
    } catch (IOException ioe){
        Log.w("copyFileFromAssets", "Failed to copy file '"+in_filename+"' to external storage:"+ioe.toString());
    } finally {
        try {
            if (in_chan != null) {
                in_chan.close();
            }
            if (out_chan != null) {
                out_chan.close();
            }
        } catch (IOException ioe){}
    }
}

This answer is based on JPM's answer.

Firestore Getting documents id from collection

I have tried this

return this.db.collection('items').snapshotChanges().pipe(
          map(actions => {       
            return actions.map(a => {
              const data = a.payload.doc.data() as Item;
              data.id = a.payload.doc.id;
              data.$key = a.payload.doc.id;
              return data;
            });
          })
        );

CSS to select/style first word

What you are looking for is a pseudo-element that doesn't exist. There is :first-letter and :first-line, but no :first-word.

You can of course do this with JavaScript. Here's some code I found that does this: http://www.dynamicsitesolutions.com/javascript/first-word-selector/

How do I compare version numbers in Python?

What's wrong with transforming the version string into a tuple and going from there? Seems elegant enough for me

>>> (2,3,1) < (10,1,1)
True
>>> (2,3,1) < (10,1,1,1)
True
>>> (2,3,1,10) < (10,1,1,1)
True
>>> (10,3,1,10) < (10,1,1,1)
False
>>> (10,3,1,10) < (10,4,1,1)
True

@kindall's solution is a quick example of how good the code would look.

How to group dataframe rows into list in pandas groupby

If looking for a unique list while grouping multiple columns this could probably help:

df.groupby('a').agg(lambda x: list(set(x))).reset_index()

How to generate unique IDs for form labels in React?

The id should be placed inside of componentWillMount (update for 2018) constructor, not render. Putting it in render will re-generate new ids unnecessarily.

If you're using underscore or lodash, there is a uniqueId function, so your resulting code should be something like:

constructor(props) {
    super(props);
    this.id = _.uniqueId("prefix-");
}

render() { 
  const id = this.id;
  return (
    <div>
        <input id={id} type="checkbox" />
        <label htmlFor={id}>label</label>
    </div>
  );
}

2019 Hooks update:

import React, { useState } from 'react';
import _uniqueId from 'lodash/uniqueId';

const MyComponent = (props) => {
  // id will be set once when the component initially renders, but never again
  // (unless you assigned and called the second argument of the tuple)
  const [id] = useState(_uniqueId('prefix-'));
  return (
    <div>
      <input id={id} type="checkbox" />
      <label htmlFor={id}>label</label>
    </div>
  );
}

batch to copy files with xcopy

Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)

xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J

Changing element style attribute dynamically using JavaScript

It's almost correct.

Since the - is a javascript operator, you can't really have that in property names. If you were setting, border or something single-worded like that instead, your code would work just fine.

However, the thing you need to remember for padding-top, and for any hyphenated attribute name, is that in javascript, you remove the hyphen, and make the next letter uppercase, so in your case that'd be paddingTop.

There are some other exceptions. JavaScript has some reserved words, so you can't set float like that, for instance. Instead, in some browsers you need to use cssFloat and in others styleFloat. It is for discrepancies like this that it is recommended that you use a framework such as jQuery, that handles browser incompatibilities for you...

How do I convert a string to a double in Python?

>>> x = "2342.34"
>>> float(x)
2342.3400000000001

There you go. Use float (which behaves like and has the same precision as a C,C++, or Java double).

Copy an entire worksheet to a new worksheet in Excel 2010

'Make the excel file that runs the software the active workbook
ThisWorkbook.Activate

'The first sheet used as a temporary place to hold the data 
ThisWorkbook.Worksheets(1).Cells.Copy

'Create a new Excel workbook
Dim NewCaseFile As Workbook
Dim strFileName As String

Set NewCaseFile = Workbooks.Add
With NewCaseFile
    Sheets(1).Select
    Cells(1, 1).Select
End With

ActiveSheet.Paste

How to terminate the script in JavaScript?

If you use any undefined function in the script then script will stop due to "Uncaught ReferenceError". I have tried by following code and first two lines executed.

I think, this is the best way to stop the script. If there's any other way then please comment me. I also want to know another best and simple way. BTW, I didn't get exit or die inbuilt function in Javascript like PHP for terminate the script. If anyone know then please let me know.

alert('Hello');

document.write('Hello User!!!');

die();  //Uncaught ReferenceError: die is not defined

alert('bye');

document.write('Bye User!!!');

Creating a "logical exclusive or" operator in Java

What you're asking for wouldn't make much sense. Unless I'm incorrect you're suggesting that you want to use XOR to perform Logical operations the same way AND and OR do. Your provided code actually shows what I'm reffering to:

public static boolean logicalXOR(boolean x, boolean y) {
    return ( ( x || y ) && ! ( x && y ) );
}

Your function has boolean inputs, and when bitwise XOR is used on booleans the result is the same as the code you've provided. In other words, bitwise XOR is already efficient when comparing individual bits(booleans) or comparing the individual bits in larger values. To put this into context, in terms of binary values any non-zero value is TRUE and only ZERO is false.

So for XOR to be applied the same way Logical AND is applied, you would either only use binary values with just one bit(giving the same result and efficiency) or the binary value would have to be evaluated as a whole instead of per bit. In other words the expression ( 010 ^^ 110 ) = FALSE instead of ( 010 ^^ 110 ) = 100. This would remove most of the semantic meaning from the operation, and represents a logical test you shouldn't be using anyway.

How can I get the Windows last reboot reason

This article explains in detail how to find the reason for last startup/shutdown. In my case, this was due to windows SCCM pushing updates even though I had it disabled locally. Visit the article for full details with pictures. For reference, here are the steps copy/pasted from the website:

  1. Press the Windows + R keys to open the Run dialog, type eventvwr.msc, and press Enter.

  2. If prompted by UAC, then click/tap on Yes (Windows 7/8) or Continue (Vista).

  3. In the left pane of Event Viewer, double click/tap on Windows Logs to expand it, click on System to select it, then right click on System, and click/tap on Filter Current Log.

  4. Do either step 5 or 6 below for what shutdown events you would like to see.

  5. To See the Dates and Times of All User Shut Downs of the Computer

    A) In Event sources, click/tap on the drop down arrow and check the USER32 box.

    B) In the All Event IDs field, type 1074, then click/tap on OK.

    C) This will give you a list of power off (shutdown) and restart Shutdown Type of events at the top of the middle pane in Event Viewer.

    D) You can scroll through these listed events to find the events with power off as the Shutdown Type. You will notice the date and time, and what user was responsible for shutting down the computer per power off event listed.

    E) Go to step 7.

  6. To See the Dates and Times of All Unexpected Shut Downs of the Computer

    A) In the All Event IDs field, type 6008, then click/tap on OK.

    B) This will give you a list of unexpected shutdown events at the top of the middle pane in Event Viewer. You can scroll through these listed events to see the date and time of each one.

Lodash .clone and .cloneDeep behaviors

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

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

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

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

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

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

VSCode cannot find module '@angular/core' or any other modules

I tried a lot of stuff the guys informed here, without success. After, I just realized I was using the Deno Support for VSCode extension. I uninstalled it and a restart was required. After restart the problem was solved.

How to atomically delete keys matching a pattern using Redis

// TODO

You think it's command not make sense bu some times Redis command like DEL not working correct and comes to the rescue of this

redis-cli KEYS "*" | xargs -i redis-cli EXPIRE {} 1 it's life hack

Make an Android button change background on click through XML

To change image by using code

public void onClick(View v) {
   if(v == ButtonName) {
     ButtonName.setImageResource(R.drawable.ImageName);
   }
}

Or, using an XML file:

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:state_pressed="true"
   android:drawable="@drawable/login_selected" /> <!-- pressed -->
  <item android:state_focused="true"
   android:drawable="@drawable/login_mouse_over" /> <!-- focused -->
  <item android:drawable="@drawable/login" /> <!-- default -->
</selector>

In OnClick, just add this code:

ButtonName.setBackgroundDrawable(getResources().getDrawable(R.drawable.ImageName));

Migrating from VMWARE to VirtualBox

Note: I am not sure this will be of any help to you, but you never know.

I found this link:http://www.ubuntugeek.com/howto-convert-vmware-image-to-virtualbox-image.html

ENJOY :-)

Insert if not exists Oracle

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

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

How do files get into the External Dependencies in Visual Studio C++?

To resolve external dependencies within project. below things are important..
1. The compiler should know that where are header '.h' files located in workspace.
2. The linker able to find all specified  all '.lib' files & there names for current project.

So, Developer has to specify external dependencies for Project as below..

1. Select Project in Solution explorer.

2 . Project Properties -> Configuration Properties -> C/C++ -> General
specify all header files in "Additional Include Directories".

3.  Project Properties -> Configuration Properties -> Linker -> General
specify relative path for all lib files in "Additional Library Directories".

enter image description here enter image description here

updating Google play services in Emulator

Running the app on a virtual device with system image, 'Google Play API' instead of 'Google API' will solve your issue smoothly..

  • Virtual devices Nexus 5x and Nexus 5 supports 'Google Play API' image.

  • Google Play API comes with Nougat 7.1.1 and O 8.0.

Just follow the below simple steps and make sure your pc is connected to internet.

  1. Create a new virtual device by selecting Create Virtual Device(left-bottom corner) from Android Virtual Devices Manager.

  2. Select the Hardware 'Nexus 5x' or 'Nexus 5'.

  3. Download the system image 'Nougat' with Google Play or 'O' with Google Play. 'O' is the latest Android 8.0 version.

  4. Click on Next and Finish.

  5. Run your app again on the new virtual device and click on the 'Upgrade now ' option that shows along with the warning message.

  6. You will be directed to the Play Store and you can update your Google Play services easily.

See your app runs smoothly!

  • Note: If you plan to use APIs from Google Play services, you must use the Google APIs System Image.

How do I erase an element from std::vector<> by index?

I suggest to read this since I believe that is what are you looking for.https://en.wikipedia.org/wiki/Erase%E2%80%93remove_idiom

If you use for example

 vec.erase(vec.begin() + 1, vec.begin() + 3);

you will erase n -th element of vector but when you erase second element, all other elements of vector will be shifted and vector sized will be -1. This can be problem if you loop through vector since vector size() is decreasing. If you have problem like this provided link suggested to use existing algorithm in standard C++ library. and "remove" or "remove_if".

Hope that this helped

How do I tell Python to convert integers into words

#This valid till 4 digit number
numbers={1:'one', 2:'two', 3:'three', 4:'four', 5:'five', 6:'six', 7:'seven', 8:'eight', 9:'nine',
10:'ten', 11:'eleven', 12:'twelve', 13:'thirteen', 14:'fourteen', 15:'fifteen', 16:'sixteen',
17:'seventeen', 18:'eighteen', 19:'nineteen', 20:'twenty', 30:'thirty', 40:'forty', 50:'fifty', 
60:'sixty', 70:'seventy', 80:'eighty', 90:'ninety', 100:'hundred', 1000:'thousand'}

def my_fun(num):
    list = []
    num_len = len(str(num)) - 1
    while num_len > 0 and num > 0:
       while num_len > 0 and num > 0:
        if num in numbers and num < 1000:
            list.append(numbers[num])
            num_len = 0
        elif num < 100:
            list.extend([numbers[num - num%10], numbers[num%10]])
            num_len = 0
        else:
            quotent = num//10**num_len # 4567//1000= 4
            num = num % 10**num_len #4567%1000 =567
            if quotent != 0 :
                list.append(numbers[quotent])
                list.append(numbers[10**num_len])
            else:
                list.append(numbers[num])
            num_len -= 1
    return ' '.join(list)

Is there a way to get a list of column names in sqlite?

I use this:

import sqlite3

    db = sqlite3.connect('~/foo.sqlite')
    dbc = db.cursor()
    dbc.execute("PRAGMA table_info('bar')"
    ciao = dbc.fetchall()

    HeaderList=[]
    for i in ciao:
        counter=0
        for a in i:
            counter+=1
            if( counter==2):
                HeaderList.append(a)

print(HeaderList)

Custom UITableViewCell from nib in Swift

Swift 4

Register Nib

override func viewDidLoad() {
    super.viewDidLoad()
    tblMissions.register(UINib(nibName: "MissionCell", bundle: nil), forCellReuseIdentifier: "MissionCell")
}

In TableView DataSource

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
          guard let cell = tableView.dequeueReusableCell(withIdentifier: "MissionCell", for: indexPath) as? MissionCell else { return UITableViewCell() }
          return cell
    }

How to connect to SQL Server from another computer?

If you want to connect to SQL server remotly you need to use a software - like Sql Server Management studio.

The computers doesn't need to be on the same network - but they must be able to connect each other using a communication protocol like tcp/ip, and the server must be set up to support incoming connection of the type you choose.

if you want to connect to another computer (to browse files ?) you use other tools, and not sql server (you can map a drive and access it through there ect...)

To Enable SQL connection using tcp/ip read this article:

For Sql Express: express For Sql 2008: 2008

Make sure you enable access through the machine firewall as well.

You might need to install either SSMS or Toad on the machine your using to connect to the server. both you can download from their's company web site.

What is the most efficient way to store a list in the Django models?

Using one-to-many relation (FK from Friend to parent class) will make your app more scalable (as you can trivially extend the Friend object with additional attributes beyond the simple name). And thus this is the best way

Angular 1 - get current URL parameters

You could inject $routeParams to your controller and access all the params that where used when the route was resolved.

E.g.:

// route was: app.dev/backend/:type/:id

function MyCtrl($scope, $routeParams, $log) {
    // use the params
    $log.info($routeParams.type, $routeParams.id);
};

See angular $routeParams documentation for further information.

Round number to nearest integer

I use and may advise the following solution (python3.6):

y = int(x + (x % (1 if x >= 0 else -1)))

It works fine for half-numbers (positives and negatives) and works even faster than int(round(x)):

round_methods = [lambda x: int(round(x)), 
                 lambda x: int(x + (x % (1 if x >= 0 else -1))),
                 lambda x: np.rint(x).astype(int),
                 lambda x: int(proper_round(x))]

for rm in round_methods:
    %timeit rm(112.5)
Out:
201 ns ± 3.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
159 ns ± 0.646 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
925 ns ± 7.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.18 µs ± 8.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

for rm in round_methods:
    print(rm(112.4), rm(112.5), rm(112.6))
    print(rm(-12.4), rm(-12.5), rm(-12.6))
    print('=' * 11)

Out:
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========

How to center buttons in Twitter Bootstrap 3?

You can do the following. It also avoids buttons overlapping.

<div class="center-block" style="max-width:400px">
  <a href="#" class="btn btn-success">Accept</a>
  <a href="#" class="btn btn-danger"> Reject</a>
</div>

How to edit a text file in my terminal

If you are still inside the vi editor, you might be in a different mode from the one you want. Hit ESC a couple of times (until it rings or flashes) and then "i" to enter INSERT mode or "a" to enter APPEND mode (they are the same, just start before or after current character).

If you are back at the command prompt, make sure you can locate the file, then navigate to that directory and perform the mentioned "vi helloWorld.txt". Once you are in the editor, you'll need to check the vi reference to know how to perform the editions you want (you may want to google "vi reference" or "vi cheat sheet").

Once the edition is done, hit ESC again, then type :wq to save your work or :q! to quit without saving.

For quick reference, here you have a text-based cheat sheet.

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

The latest SDKs (beginning with 2.2, I believe), include TV-Out functionality. With a special cable connected to the iPhone dock connector, a program can send RCA signals representing its current screen contents through the iPhone->RCA cable. If you have a TV Tuner for your computer (i.e. I have an EyeTV Hybrid) with RCA inputs, you can display the screen contents of your iPhone directly in the TV viewer.

Open a facebook link by native Facebook app on iOS

This will open the URL in Safari:

[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"http://www.facebook.com/comments.php?href=http://wombeta.jiffysoftware.com/ViewWOMPrint.aspx?WPID=317"]];

For the iphone, you can launch the Facebook app if installed by using a url starting with fb://

More information can be found here: http://iphonedevtools.com/?p=302 also here: http://wiki.akosma.com/IPhone_URL_Schemes#Facebook

Stolen from the above site:

fb://profile – Open Facebook app to the user’s profile
fb://friends – Open Facebook app to the friends list
fb://notifications – Open Facebook app to the notifications list (NOTE: there appears to be a bug with this URL. The Notifications page opens. However, it’s not possible to navigate to anywhere else in the Facebook app)
fb://feed – Open Facebook app to the News Feed
fb://events – Open Facebook app to the Events page
fb://requests – Open Facebook app to the Requests list
fb://notes - Open Facebook app to the Notes page
fb://albums – Open Facebook app to Photo Albums list

To launch the above URLs:

NSURL *theURL = [NSURL URLWithString:@"fb://<insert function here>"];
[[UIApplication sharedApplication] openURL:theURL];

gpg decryption fails with no secret key error

I have solved this problem, try to use root privileges, such as sudo gpg ... I think that gpg elevated without permissions does not refer to file permissions, but system

How to sort a file in-place

The sort command prints the result of the sorting operation to standard output by default. In order to achieve an "in-place" sort, you can do this:

sort -o file file

This overwrites the input file with the sorted output. The -o switch, used to specify an output, is defined by POSIX, so should be available on all version of sort:

-o Specify the name of an output file to be used instead of the standard output. This file can be the same as one of the input files.

If you are unfortunate enough to have a version of sort without the -o switch (Luis assures me that they exist), you can achieve an "in-place" edit in the standard way:

sort file > tmp && mv tmp file

How to check if a table exists in a given schema

For PostgreSQL 9.3 or less...Or who likes all normalized to text

Three flavors of my old SwissKnife library: relname_exists(anyThing), relname_normalized(anyThing) and relnamechecked_to_array(anyThing). All checks from pg_catalog.pg_class table, and returns standard universal datatypes (boolean, text or text[]).

/**
 * From my old SwissKnife Lib to your SwissKnife. License CC0.
 * Check and normalize to array the free-parameter relation-name.
 * Options: (name); (name,schema), ("schema.name"). Ignores schema2 in ("schema.name",schema2).
 */
CREATE FUNCTION relname_to_array(text,text default NULL) RETURNS text[] AS $f$
     SELECT array[n.nspname::text, c.relname::text]
     FROM   pg_catalog.pg_class c JOIN pg_catalog.pg_namespace n ON n.oid = c.relnamespace,
            regexp_split_to_array($1,'\.') t(x) -- not work with quoted names
     WHERE  CASE
              WHEN COALESCE(x[2],'')>'' THEN n.nspname = x[1]      AND c.relname = x[2]
              WHEN $2 IS NULL THEN           n.nspname = 'public'  AND c.relname = $1
              ELSE                           n.nspname = $2        AND c.relname = $1
            END
$f$ language SQL IMMUTABLE;

CREATE FUNCTION relname_exists(text,text default NULL) RETURNS boolean AS $wrap$
  SELECT EXISTS (SELECT relname_to_array($1,$2))
$wrap$ language SQL IMMUTABLE;

CREATE FUNCTION relname_normalized(text,text default NULL,boolean DEFAULT true) RETURNS text AS $wrap$
  SELECT COALESCE(array_to_string(relname_to_array($1,$2), '.'), CASE WHEN $3 THEN '' ELSE NULL END)
$wrap$ language SQL IMMUTABLE;

How do I set specific environment variables when debugging in Visual Studio?

In Visual Studio for Mac and C# you can use:

Environment.SetEnvironmentVariable("<Variable_name>", "<Value>");

But you will need the following namespace

using System.Collections;

you can check the full list of variables with this:

foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())
            Console.WriteLine("  {0} = {1}", de.Key, de.Value);

Adding data attribute to DOM

Using .data() will only add data to the jQuery object for that element. In order to add the information to the element itself you need to access that element using jQuery's .attr or native .setAttribute

$('div').attr('data-info', 1);
$('div')[0].setAttribute('data-info',1);

In order to access an element with the attribute set, you can simply select based on that attribute as you note in your post ($('div[data-info="1"]')), but when you use .data() you cannot. In order to select based on the .data() setting, you would need to use jQuery's filter function.

jsFiddle Demo

_x000D_
_x000D_
$('div').data('info', 1);_x000D_
//alert($('div').data('info'));//1_x000D_
_x000D_
$('div').filter(function(){_x000D_
   return $(this).data('info') == 1; _x000D_
}).text('222');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div>1</div>
_x000D_
_x000D_
_x000D_

To find first N prime numbers in python

What you want is something like this:

x = int(input("Enter the number:"))
count = 0
num = 2
while count < x:
     if isnumprime(x):
        print(x)
        count += 1
     num += 1

I'll leave it up to you to implement isnumprime() ;) Hint: You only need to test division with all previously found prime numbers.

"message failed to fetch from registry" while trying to install any module

One thing that has worked for me with random npm install errors (where the package that errors out is different under different times (but same environment) is to use this:

npm cache clean

And then repeat the process. Then the process seems to go smoother and the real problem and error message will emerge, where you can fix it and then proceed.

This is based on experience of running npm install of a whole bunch of packages under a pretty bare Ubuntu installation inside a Docker instance. Sometimes there are build/make tools missing from the Ubuntu and the npm errors will not show the real problem until you clean the cache for some reason.

How to get the class of the clicked element?

$("li").click(function(){
    alert($(this).attr("class"));
});

Where does Oracle SQL Developer store connections?

In a simpler way open search window and search for connection.xml gives a right click on that file and select open file/folder location. Once you get that connection.xml try to import it into SQLDeveloper by right clicking to CONNECTIONS.

adding directory to sys.path /PYTHONPATH

You could use:

import os
path = 'the path you want'
os.environ['PATH'] += ':'+path

Java - How to create a custom dialog box?

Well, you essentially create a JDialog, add your text components and make it visible. It might help if you narrow down which specific bit you're having trouble with.

Parsing Query String in node.js

Starting with Node.js 11, the url.parse and other methods of the Legacy URL API were deprecated (only in the documentation, at first) in favour of the standardized WHATWG URL API. The new API does not offer parsing the query string into an object. That can be achieved using tthe querystring.parse method:

// Load modules to create an http server, parse a URL and parse a URL query.
const http = require('http');
const { URL } = require('url');
const { parse: parseQuery } = require('querystring');

// Provide the origin for relative URLs sent to Node.js requests.
const serverOrigin = 'http://localhost:8000';

// Configure our HTTP server to respond to all requests with a greeting.
const server = http.createServer((request, response) => {
  // Parse the request URL. Relative URLs require an origin explicitly.
  const url = new URL(request.url, serverOrigin);
  // Parse the URL query. The leading '?' has to be removed before this.
  const query = parseQuery(url.search.substr(1));
  response.writeHead(200, { 'Content-Type': 'text/plain' });
  response.end(`Hello, ${query.name}!\n`);
});

// Listen on port 8000, IP defaults to 127.0.0.1.
server.listen(8000);

// Print a friendly message on the terminal.
console.log(`Server running at ${serverOrigin}/`);

If you run the script above, you can test the server response like this, for example:

curl -q http://localhost:8000/status?name=ryan
Hello, ryan!

How do I enable Java in Microsoft Edge web browser?

Edge has dropped all support for plugins. This means that Java, ActiveX, Silverlight, and other plugins are no longer supported. For this reason Microsoft has included Internet Explorer 11, which does support these plugins, with non-mobile versions of Windows 10. If you are running Windows 10 and need plugin support Edge is not an option, but IE 11 is.

Print PHP Call Stack

If you want a stack trace which looks very similar to how php formats the exception stack trace than use this function I wrote:

function debug_backtrace_string() {
    $stack = '';
    $i = 1;
    $trace = debug_backtrace();
    unset($trace[0]); //Remove call to this function from stack trace
    foreach($trace as $node) {
        $stack .= "#$i ".$node['file'] ."(" .$node['line']."): "; 
        if(isset($node['class'])) {
            $stack .= $node['class'] . "->"; 
        }
        $stack .= $node['function'] . "()" . PHP_EOL;
        $i++;
    }
    return $stack;
} 

This will return a stack trace formatted like this:

#1 C:\Inetpub\sitename.com\modules\sponsors\class.php(306): filePathCombine()
#2 C:\Inetpub\sitename.com\modules\sponsors\class.php(294): Process->_deleteImageFile()
#3 C:\Inetpub\sitename.com\VPanel\modules\sponsors\class.php(70): Process->_deleteImage()
#4 C:\Inetpub\sitename.com\modules\sponsors\process.php(24): Process->_delete() 

matching query does not exist Error in Django

I also had this problem. It was caused by the development server not deleting the django session after a debug abort in Aptana, with subsequent database deletion. (Meaning the id of a non-existent database record was still present in the session the next time the development server started)

To resolve this during development, I used

request.session.flush()

Enable remote MySQL connection: ERROR 1045 (28000): Access denied for user

if you are using dynamic ip just grant access to 192.168.2.% so now you dont have to worry about granting access to your ip address every time.

Python: Importing urllib.quote

This is how I handle this, without using exceptions.

import sys
if sys.version_info.major > 2:  # Python 3 or later
    from urllib.parse import quote
else:  # Python 2
    from urllib import quote

How to create a cron job using Bash automatically without the interactive editor?

CRON="1 2 3 4 5 /root/bin/backup.sh" 
cat < (crontab -l) |grep -v "${CRON}" < (echo "${CRON}")

add -w parameter to grep exact command, without -w parameter adding the cronjob "testing" cause deletion of cron job "testing123"

script function to add/remove cronjobs. no duplication entries :

cronjob_editor () {         
# usage: cronjob_editor '<interval>' '<command>' <add|remove>

if [[ -z "$1" ]] ;then printf " no interval specified\n" ;fi
if [[ -z "$2" ]] ;then printf " no command specified\n" ;fi
if [[ -z "$3" ]] ;then printf " no action specified\n" ;fi

if [[ "$3" == add ]] ;then
    # add cronjob, no duplication:
    ( crontab -l | grep -v -F -w "$2" ; echo "$1 $2" ) | crontab -
elif [[ "$3" == remove ]] ;then
    # remove cronjob:
    ( crontab -l | grep -v -F -w "$2" ) | crontab -
fi 
} 
cronjob_editor "$1" "$2" "$3"

tested :

$ ./cronjob_editor.sh '*/10 * * * *' 'echo "this is a test" > export_file' add
$ crontab  -l
$ */10 * * * * echo "this is a test" > export_file

How to load GIF image in Swift?

This is working for me

Podfile:

platform :ios, '9.0'
use_frameworks!

target '<Your Target Name>' do
pod 'SwiftGifOrigin', '~> 1.7.0'
end

Usage:

// An animated UIImage
let jeremyGif = UIImage.gif(name: "jeremy")

// A UIImageView with async loading
let imageView = UIImageView()
imageView.loadGif(name: "jeremy")

// A UIImageView with async loading from asset catalog(from iOS9)
let imageView = UIImageView()
imageView.loadGif(asset: "jeremy")

For more information follow this link: https://github.com/swiftgif/SwiftGif

SQL Server Configuration Manager not found

If you don't have any version of SQLServerManagerXX.msc, then you simply do not have it installed. I noticed it does not come with SQL server management studio 2019.

It's available (client-connectivity tools) in the SQL Server Express edition or SQL Server Developer edition which is good for dev/test (non-production) usage.

The mysqli extension is missing. Please check your PHP configuration

This article can help you Configuring PHP with MySQL for Apache 2 or IIS in Windows. Look at the section "Configure PHP and MySQL under Apache 2", point 3:

extension_dir = "c:\php\extensions"      ; FOR PHP 4 ONLY 
extension_dir = "c:\php\ext"             ; FOR PHP 5 ONLY

You must uncomment extension_dir param line and set it to absolute path to the PHP extensions directory.

Reading From A Text File - Batch

Your code "for /f "tokens=* delims=" %%x in (a.txt) do echo %%x" will work on most Windows Operating Systems unless you have modified commands.

So you could instead "cd" into the directory to read from before executing the "for /f" command to follow out the string. For instance if the file "a.txt" is located at C:\documents and settings\%USERNAME%\desktop\a.txt then you'd use the following.

cd "C:\documents and settings\%USERNAME%\desktop"
for /f "tokens=* delims=" %%x in (a.txt) do echo %%x
echo.
echo.
echo.
pause >nul
exit

But since this doesn't work on your computer for x reason there is an easier and more efficient way of doing this. Using the "type" command.

@echo off
color a
cls
cd "C:\documents and settings\%USERNAME%\desktop"
type a.txt
echo.
echo.
pause >nul
exit

Or if you'd like them to select the file from which to write in the batch you could do the following.

@echo off
:A
color a
cls
echo Choose the file that you want to read.
echo.
echo.
tree
echo.
echo.
echo.
set file=
set /p file=File:
cls
echo Reading from %file%
echo.
type %file%
echo.
echo.
echo.
set re=
set /p re=Y/N?:
if %re%==Y goto :A
if %re%==y goto :A
exit

How do I check if a cookie exists?

/// ************************************************ cookie_exists

/// global entry point, export to global namespace

/// <synopsis>
///   cookie_exists ( name );
///
/// <summary>
///   determines if a cookie with name exists
///
/// <param name="name">
///   string containing the name of the cookie to test for 
//    existence
///
/// <returns>
///   true, if the cookie exists; otherwise, false
///
/// <example>
///   if ( cookie_exists ( name ) );
///     {
///     // do something with the existing cookie
///     }
///   else
///     {
///     // cookies does not exist, do something else 
///     }

function cookie_exists ( name )
  {
  var exists = false;

  if ( document.cookie )
    {
    if ( document.cookie.length > 0 )
      {
                                    // trim name
      if ( ( name = name.replace ( /^\s*/, "" ).length > 0 ) )
        {
        var cookies = document.cookie.split ( ";" );
        var name_with_equal = name + "=";

        for ( var i = 0; ( i < cookies.length ); i++ )
          {
                                    // trim cookie
          var cookie = cookies [ i ].replace ( /^\s*/, "" );

          if ( cookie.indexOf ( name_with_equal ) === 0 )
            {
            exists = true;
            break;
            }
          }
        }
      }
    }

  return ( exists );

  } // cookie_exists

CreateProcess error=2, The system cannot find the file specified

My recomendation is to keep the getRuntime().exec because exec uses the ProcessBuilder.

Try

 p=r.exec(new String[] {"winrar", "x", "h:\\myjar.jar", "*.*", "h:\\new"}, null, dir);

Convert the values in a column into row names in an existing data frame

As of 2016 you can also use the tidyverse.

library(tidyverse)
samp %>% remove_rownames %>% column_to_rownames(var="names")

How to get URL of current page in PHP

 $uri = $_SERVER['REQUEST_URI'];

This will give you the requested directory and file name. If you use mod_rewrite, this is extremely useful because it tells you what page the user was looking at.

If you need the actual file name, you might want to try either $_SERVER['PHP_SELF'], the magic constant __FILE__, or $_SERVER['SCRIPT_FILENAME']. The latter 2 give you the complete path (from the root of the server), rather than just the root of your website. They are useful for includes and such.

$_SERVER['PHP_SELF'] gives you the file name relative to the root of the website.

 $relative_path = $_SERVER['PHP_SELF'];
 $complete_path = __FILE__;
 $complete_path = $_SERVER['SCRIPT_FILENAME'];

Common MySQL fields and their appropriate data types

Here are some common datatypes I use (I am not much of a pro though):

| Column           | Data type     | Note
| ---------------- | ------------- | -------------------------------------
| id               | INTEGER       | AUTO_INCREMENT, UNSIGNED                                                          |  
| uuid             | CHAR(36)      | or CHAR(16) binary                                                                |  
| title            | VARCHAR(255)  |                                                                                   |  
| full name        | VARCHAR(70)   |                                                                                   |  
| gender           | TINYINT       | UNSIGNED                                                                          |  
| description      | TINYTEXT      | often may not be enough, use TEXT 
                                     instead          
| post body        | TEXT          |                                                                                   |  
| email            | VARCHAR(255)  |                                                                                   |  
| url              | VARCHAR(2083) | MySQL version < 5.0.3 - use TEXT                                                  |  
| salt             | CHAR(x)       | randomly generated string, usually of 
                                     fixed length (x)    
| digest (md5)     | CHAR(32)      |                                                                                   |  
| phone number     | VARCHAR(20)   |                                                                                   |  
| US zip code      | CHAR(5)       | Use CHAR(10) if you store extended 
                                     codes      
| US/Canada p.code | CHAR(6)       |                                                                                   |  
| file path        | VARCHAR(255)  |                                                                                   |  
| 5-star rating    | DECIMAL(3,2)  | UNSIGNED                                                                          |  
| price            | DECIMAL(10,2) | UNSIGNED                                                                          |  
| date (creation)  | DATE/DATETIME | usually displayed as initial date of 
                                     a post                                       |  
| date (tracking)  | TIMESTAMP     | can be used for tracking changes in a 
                                     post                                        |  
| tags, categories | TINYTEXT      | comma separated values *                                                          |  
| status           | TINYINT(1)    | 1 – published, 0 – unpublished, … You 
                                     can also use ENUM for human-readable 
                                     values
| json data        | JSON          | or LONGTEXT       

How to return only 1 row if multiple duplicate rows and still return rows that are not duplicates?

Try this if you want to display one of duplicate rows based on RequestID and CreatedDate and show the latest HistoryStatus.

with t as (select row_number()over(partition by RequestID,CreatedDate order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t a where  rnum in (SELECT Max(rnum) FROM t GROUP BY RequestID,CreatedDate having t.RequestID=a.RequestID)

or if you want to select one of duplicate rows considering CreatedDate only and show the latest HistoryStatus then try the query below.

with t as (select row_number()over(partition by CreatedDate order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t  where  rnum = (SELECT Max(rnum) FROM t)

Or if you want to select one of duplicate rows considering Request ID only and show the latest HistoryStatus then use the query below

with t as (select row_number()over(partition by RequestID order by RequestID) as rnum,* from tbltmp)
Select RequestID,CreatedDate,HistoryStatus from t a where  rnum in (SELECT Max(rnum) FROM t GROUP BY RequestID,CreatedDate having t.RequestID=a.RequestID)

All the above queries I have written in sql server 2005.

Insert PHP code In WordPress Page and Post

WordPress does not execute PHP in post/page content by default unless it has a shortcode.

The quickest and easiest way to do this is to use a plugin that allows you to run PHP embedded in post content.

There are two other "quick and easy" ways to accomplish it without a plugin:

  • Make it a shortcode (put it in functions.php and have it echo the country name) which is very easy - see here: Shortcode API at WP Codex

  • Put it in a template file - make a custom template for that page based on your default page template and add the PHP into the template file rather than the post content: Custom Page Templates

Where can I read the Console output in Visual Studio 2015

My problem was that I needed to Reset Window Layout.

Reset Window Layout

How to display a jpg file in Python?

Don't forget to include

import Image

In order to show it use this :

Image.open('pathToFile').show()

'if' in prolog?

Prolog program actually is big condition for "if" with "then" which prints "Goal is reached" and "else" which prints "No sloutions was found". A, Bmeans "A is true and B is true", most of prolog systems will not try to satisfy "B" if "A" is not reachable (i.e. X=3, write('X is 3'),nl will print 'X is 3' when X=3, and will do nothing if X=2).

In SQL how to compare date values?

You could add the time component

WHERE mydate<='2008-11-25 23:59:59'

but that might fail on DST switchover dates if mydate is '2008-11-25 24:59:59', so it's probably safest to grab everything before the next date:

WHERE mydate < '2008-11-26 00:00:00'

Getting all documents from one collection in Firestore

You could get the whole collection as an object, rather than array like this:

async getMarker() {
    const snapshot = await firebase.firestore().collection('events').get()
    const collection = {};
    snapshot.forEach(doc => {
        collection[doc.id] = doc.data();
    });
    return collection;
}

That would give you a better representation of what's in firestore. Nothing wrong with an array, just another option.

Creating java date object from year,month,day

That's my favorite way prior to Java 8:

Date date = new GregorianCalendar(year, month - 1, day).getTime();

I'd say this is a cleaner approach than:

calendar.set(year, month - 1, day, 0, 0);

How do I write a RGB color value in JavaScript?

try:

parent.childNodes[1].style.color = "rgb(155, 102, 102)"; 

Or

parent.childNodes[1].style.color = "#"+(155).toString(16)+(102).toString(16)+(102).toString(16);

What is the difference between T(n) and O(n)?

Using limits

Let's consider f(n) > 0 and g(n) > 0 for all n. It's ok to consider this, because the fastest real algorithm has at least one operation and completes its execution after the start. This will simplify the calculus, because we can use the value (f(n)) instead of the absolute value (|f(n)|).

  1. f(n) = O(g(n))

    General:

              f(n)     
    0 = lim -------- < 8
        n?8   g(n)
    

    For g(n) = n:

              f(n)     
    0 = lim -------- < 8
        n?8    n
    

    Examples:

        Expression               Value of the limit
    ------------------------------------------------
    n        = O(n)                      1
    1/2*n    = O(n)                     1/2
    2*n      = O(n)                      2
    n+log(n) = O(n)                      1
    n        = O(n*log(n))               0
    n        = O(n²)                     0
    n        = O(nn)                     0
    

    Counterexamples:

        Expression                Value of the limit
    -------------------------------------------------
    n        ? O(log(n))                 8
    1/2*n    ? O(sqrt(n))                8
    2*n      ? O(1)                      8
    n+log(n) ? O(log(n))                 8
    
  2. f(n) = T(g(n))

    General:

              f(n)     
    0 < lim -------- < 8
        n?8   g(n)
    

    For g(n) = n:

              f(n)     
    0 < lim -------- < 8
        n?8    n
    

    Examples:

        Expression               Value of the limit
    ------------------------------------------------
    n        = T(n)                      1
    1/2*n    = T(n)                     1/2
    2*n      = T(n)                      2
    n+log(n) = T(n)                      1
    

    Counterexamples:

        Expression                Value of the limit
    -------------------------------------------------
    n        ? T(log(n))                 8
    1/2*n    ? T(sqrt(n))                8
    2*n      ? T(1)                      8
    n+log(n) ? T(log(n))                 8
    n        ? T(n*log(n))               0
    n        ? T(n²)                     0
    n        ? T(nn)                     0
    

How do I create and read a value from cookie?

A simple read

var getCookie = function (name) {
    var valueStart = document.cookie.indexOf(name + "=") + name.length + 1;
    var valueEnd = document.cookie.indexOf(";", valueStart); 
    return document.cookie.slice(valueStart, valueEnd)
}

How can I check if a value is of type Integer?

if (x % 1 == 0)
    // x is an integer

Here x is a numeric primitive: short, int, long, float or double

remove borders around html input

use this i hope this help ful to you... border:none !important; background-color:transparent;

try this

<div id="generic_search"><input type="search" onkeypress="return runScript(event)" /></div>
<button type="button" id="generic_search_button" /></button>

how do I insert a column at a specific column index in pandas?

Here is a very simple answer to this(only one line).

You can do that after you added the 'n' column into your df as follows.

import pandas as pd
df = pd.DataFrame({'l':['a','b','c','d'], 'v':[1,2,1,2]})
df['n'] = 0

df
    l   v   n
0   a   1   0
1   b   2   0
2   c   1   0
3   d   2   0

# here you can add the below code and it should work.
df = df[list('nlv')]
df

    n   l   v
0   0   a   1
1   0   b   2
2   0   c   1
3   0   d   2



However, if you have words in your columns names instead of letters. It should include two brackets around your column names. 

import pandas as pd
df = pd.DataFrame({'Upper':['a','b','c','d'], 'Lower':[1,2,1,2]})
df['Net'] = 0
df['Mid'] = 2
df['Zsore'] = 2

df

    Upper   Lower   Net Mid Zsore
0   a       1       0   2   2
1   b       2       0   2   2
2   c       1       0   2   2
3   d       2       0   2   2

# here you can add below line and it should work 
df = df[list(('Mid','Upper', 'Lower', 'Net','Zsore'))]
df

   Mid  Upper   Lower   Net Zsore
0   2   a       1       0   2
1   2   b       2       0   2
2   2   c       1       0   2
3   2   d       2       0   2

MAX function in where clause mysql

We can't reference the result of an aggregate function (for example MAX() ) in a WHERE clause of the same SELECT.

The normative pattern for solving this type of problem is to use an inline view, something like this:

SELECT t.firstName
     , t.Lastname
     , t.id
  FROM mytable t
  JOIN ( SELECT MAX(mx.id) AS max_id
           FROM mytable mx
       ) m
    ON m.max_id = t.id

This is just one way to get the specified result. There are several other approaches to get the same result, and some of those can be much less efficient than others. Other answers demonstrate this approach:

 WHERE t.id = (SELECT MAX(id) FROM ... )

Sometimes, the simplest approach is to use an ORDER BY with a LIMIT. (Note that this syntax is specific to MySQL)

SELECT t.firstName
     , t.Lastname
     , t.id
  FROM mytable t
 ORDER BY t.id DESC
 LIMIT 1

Note that this will return only one row; so if there is more than one row with the same id value, then this won't return all of them. (The first query will return ALL the rows that have the same id value.)

This approach can be extended to get more than one row, you could get the five rows that have the highest id values by changing it to LIMIT 5.

Note that performance of this approach is particularly dependent on a suitable index being available (i.e. with id as the PRIMARY KEY or as the leading column in another index.) A suitable index will improve performance of queries using all of these approaches.

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

You have to add empty option to solve it,

I also can give you one more solution but its up to you that is fine for you or not Because User select default option after selecting other options than jsFunction will be called twice.

<select onChange="jsFunction()" id="selectOpt">
    <option value="1" onclick="jsFunction()">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
</select>

function jsFunction(){
  var myselect = document.getElementById("selectOpt");
  alert(myselect.options[myselect.selectedIndex].value);
}

ggplot geom_text font size control

Here are a few options for changing text / label sizes

library(ggplot2)

# Example data using mtcars

a <- aggregate(mpg ~ vs + am , mtcars, function(i) round(mean(i)))

p <- ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
            geom_bar(stat="identity",position="dodge") + 
            geom_text(data = a, aes(label = mpg), 
                            position = position_dodge(width=0.9),  size=20)

The size in the geom_text changes the size of the geom_text labels.

p <- p + theme(axis.text = element_text(size = 15)) # changes axis labels

p <- p + theme(axis.title = element_text(size = 25)) # change axis titles

p <- p + theme(text = element_text(size = 10)) # this will change all text size 
                                                             # (except geom_text)


For this And why size of 10 in geom_text() is different from that in theme(text=element_text()) ?

Yes, they are different. I did a quick manual check and they appear to be in the ratio of ~ (14/5) for geom_text sizes to theme sizes.

So a horrible fix for uniform sizes is to scale by this ratio

geom.text.size = 7
theme.size = (14/5) * geom.text.size

ggplot(mtcars, aes(factor(vs), y=mpg, fill=factor(am))) + 
  geom_bar(stat="identity",position="dodge") + 
  geom_text(data = a, aes(label = mpg), 
            position = position_dodge(width=0.9),  size=geom.text.size) + 
  theme(axis.text = element_text(size = theme.size, colour="black")) 

This of course doesn't explain why? and is a pita (and i assume there is a more sensible way to do this)

How to redirect user's browser URL to a different page in Nodejs?

OP: "I would love if there were a way to do it where I didn't have to know the host address..."

response.writeHead(301, {
  Location: "http" + (request.socket.encrypted ? "s" : "") + "://" + 
    request.headers.host + newRoom
});
response.end();

jQuery: Best practice to populate drop down?

I found this to be working from jquery site

$.getJSON( "/Admin/GetFolderList/", function( data ) {
  var options = $("#dropdownID");
  $.each( data, function(key, val) {
    options.append(new Option(key, val));
  });
});

Sending SMS from PHP

PHP by itself has no SMS module or functions and doesn't allow you to send SMS.

SMS ( Short Messaging System) is a GSM technology an you need a GSM provider that will provide this service for you and may have an PHP API implementation for it.

Usually people in telecom business use Asterisk to handle calls and sms programming.

jquery function setInterval

This is because you are executing the function not referencing it. You should do:

  setInterval(swapImages,1000);

Localhost : 404 not found

you need to stop that service running on this port .check service running on specific port by "netstat -ano".then in window search type services.exe and search that process and stop that process .to change port of that process check this http://seankilleen.com/2012/11/how-to-stop-sql-server-reporting-services-from-using-port-80-on-your-server-field-notes/

How do I use a C# Class Library in a project?

Add a reference to it in your project and a using clause at the top of the CS file where you want to use it.

Adding a reference:

  1. In Visual Studio, click Project, and then Add Reference.
  2. Click the Browse tab and locate the DLL you want to add a reference to.
    NOTE: Apparently using Browse is bad form if the DLL you want to use is in the same project. Instead, right-click the Project and then click Add Reference, then select the appropriate class from the Project tab:
    enter image description here
  3. Click OK.

Adding a using clause:

Add "using [namespace];" to the CS file where you want to reference your library. So, if the library you want to reference has a namespace called MyLibrary, add the following to the CS file:

using MyLibrary;

How to get UTC+0 date in Java 8?

In Java8 you use the new Time API, and convert an Instant in to a ZonedDateTime Using the UTC TimeZone

Alter SQL table - allow NULL column value

The following MySQL statement should modify your column to accept NULLs.

ALTER TABLE `MyTable`
ALTER COLUMN `Col3` varchar(20) DEFAULT NULL

In bootstrap how to add borders to rows without adding up?

Here is one solution:

div.row { 
  border: 1px solid;
  border-bottom: 0px;
}
.container div.row:last-child {
  border-bottom: 1px solid;
}

I'm not 100% its the most effiecent, but it works :D

http://jsfiddle.net/aaronmallen/7cb3Y/2/

QByteArray to QString

You can use:

QString::fromStdString(byteArray.toStdString())

How can I create an object based on an interface file definition in TypeScript?

If you want an empty object of an interface, you can do just:

var modal = <IModal>{};

The advantage of using interfaces in lieu of classes for structuring data is that if you don't have any methods on the class, it will show in compiled JS as an empty method. Example:

class TestClass {
    a: number;
    b: string;
    c: boolean;
}

compiles into

var TestClass = (function () {
    function TestClass() {
    }
    return TestClass;
})();

which carries no value. Interfaces, on the other hand, don't show up in JS at all while still providing the benefits of data structuring and type checking.

Regex matching in a Bash if statement

Or you might be looking at this question because you happened to make a silly typo like I did and have the =~ reversed to ~=

text-align:center won't work with form <label> tag (?)

This is because label is an inline element, and is therefore only as big as the text it contains.

The possible is to display your label as a block element like this:

#formItem label {
    display: block;
    text-align: center;
    line-height: 150%;
    font-size: .85em;
}

However, if you want to use the label on the same line with other elements, you either need to set display: inline-block; and give it an explicit width (which doesn't work on most browsers), or you need to wrap it inside a div and do the alignment in the div.

Choosing a file in Python with simple Dialog

With EasyGui:

import easygui
print(easygui.fileopenbox())

To install:

pip install easygui

Demo:

import easygui
easygui.egdemo()

Disable PHP in directory (including all sub-directories) with .htaccess

If you're using mod_php, you could put (either in a .htaccess in /USERS or in your httpd.conf for the USERS directory)

RemoveHandler .php

or

RemoveType .php

(depending on whether PHP is enabled using AddHandler or AddType)

PHP files run from another directory will be still able to include files in /USERS (assuming that there is no open_basedir restriction), because this does not go through Apache. If a php file is accessed using apache it will be serverd as plain text.

Edit

Lance Rushing's solution of just denying access to the files is probably better

How can I print a quotation mark in C?

Without a backslash, special characters have a natural special meaning. With a backslash they print as they appear.

\   -   escape the next character
"   -   start or end of string
’   -   start or end a character constant
%   -   start a format specification
\\  -   print a backslash
\"  -   print a double quote
\’  -   print a single quote
%%  -   print a percent sign

The statement

printf("  \"  "); 

will print you the quotes. You can also print these special characters \a, \b, \f, \n, \r, \t and \v with a (slash) preceeding it.

SQL select * from column where year = 2010

select * from mytable where year(Columnx) = 2010

Regarding index usage (answering Simon's comment):

if you have an index on Columnx, SQLServer WON'T use it if you use the function "year" (or any other function).

There are two possible solutions for it, one is doing the search by interval like Columnx>='01012010' and Columnx<='31122010' and another one is to create a calculated column with the year(Columnx) expression, index it, and then do the filter on this new column

Git - How to fix "corrupted" interactive rebase?

Had same problem in Eclipse. Could not Rebase=>abort from Eclipse.

Executing git rebase --abort from Git Bash Worked for me.

Escaping a forward slash in a regular expression

If you are using C#, you do not need to escape it.

Textarea Auto height

I used jQuery AutoSize. When I tried using Elastic it frequently gave me bogus heights (really tall textarea's). jQuery AutoSize has worked well and hasn't had this issue.

How to highlight cell if value duplicate in same column for google spreadsheet?

Highlight duplicates (in column C):

=COUNTIF(C:C, C1) > 1

Explanation: The C1 here doesn't refer to the first row in C. Because this formula is evaluated by a conditional format rule, instead, when the formula is checked to see if it applies, the C1 effectively refers to whichever row is currently being evaluated to see if the highlight should be applied. (So it's more like INDIRECT(C &ROW()), if that means anything to you!). Essentially, when evaluating a conditional format formula, anything which refers to row 1 is evaluated against the row that the formula is being run against. (And yes, if you use C2 then you asking the rule to check the status of the row immediately below the one currently being evaluated.)

So this says, count up occurences of whatever is in C1 (the current cell being evaluated) that are in the whole of column C and if there is more than 1 of them (i.e. the value has duplicates) then: apply the highlight (because the formula, overall, evaluates to TRUE).

Highlight the first duplicate only:

=AND(COUNTIF(C:C, C1) > 1, COUNTIF(C$1:C1, C1) = 1)

Explanation: This only highlights if both of the COUNTIFs are TRUE (they appear inside an AND()).

The first term to be evaluated (the COUNTIF(C:C, C1) > 1) is the exact same as in the first example; it's TRUE only if whatever is in C1 has a duplicate. (Remember that C1 effectively refers to the current row being checked to see if it should be highlighted).

The second term (COUNTIF(C$1:C1, C1) = 1) looks similar but it has three crucial differences:

It doesn't search the whole of column C (like the first one does: C:C) but instead it starts the search from the first row: C$1 (the $ forces it to look literally at row 1, not at whichever row is being evaluated).

And then it stops the search at the current row being evaluated C1.

Finally it says = 1.

So, it will only be TRUE if there are no duplicates above the row currently being evaluated (meaning it must be the first of the duplicates).

Combined with that first term (which will only be TRUE if this row has duplicates) this means only the first occurrence will be highlighted.

Highlight the second and onwards duplicates:

=AND(COUNTIF(C:C, C1) > 1, NOT(COUNTIF(C$1:C1, C1) = 1), COUNTIF(C1:C, C1) >= 1)

Explanation: The first expression is the same as always (TRUE if the currently evaluated row is a duplicate at all).

The second term is exactly the same as the last one except it's negated: It has a NOT() around it. So it ignores the first occurence.

Finally the third term picks up duplicates 2, 3 etc. COUNTIF(C1:C, C1) >= 1 starts the search range at the currently evaluated row (the C1 in the C1:C). Then it only evaluates to TRUE (apply highlight) if there is one or more duplicates below this one (and including this one): >= 1 (it must be >= not just > otherwise the last duplicate is ignored).

How to use regex in XPath "contains" function

If you're using Selenium with Firefox you should be able to use EXSLT extensions, and regexp:test()

Does this work for you?

String expr = "//*[regexp:test(@id, 'sometext[0-9]+_text')]";
driver.findElement(By.xpath(expr));

Difference between jar and war in Java

A .war file has a specific structure in terms of where certain files will be. Other than that, yes, it's just a .jar.

How to do a PUT request with curl?

Using the -X flag with whatever HTTP verb you want:

curl -X PUT -d arg=val -d arg2=val2 localhost:8080

This example also uses the -d flag to provide arguments with your PUT request.

Shared-memory objects in multiprocessing

If you use an operating system that uses copy-on-write fork() semantics (like any common unix), then as long as you never alter your data structure it will be available to all child processes without taking up additional memory. You will not have to do anything special (except make absolutely sure you don't alter the object).

The most efficient thing you can do for your problem would be to pack your array into an efficient array structure (using numpy or array), place that in shared memory, wrap it with multiprocessing.Array, and pass that to your functions. This answer shows how to do that.

If you want a writeable shared object, then you will need to wrap it with some kind of synchronization or locking. multiprocessing provides two methods of doing this: one using shared memory (suitable for simple values, arrays, or ctypes) or a Manager proxy, where one process holds the memory and a manager arbitrates access to it from other processes (even over a network).

The Manager approach can be used with arbitrary Python objects, but will be slower than the equivalent using shared memory because the objects need to be serialized/deserialized and sent between processes.

There are a wealth of parallel processing libraries and approaches available in Python. multiprocessing is an excellent and well rounded library, but if you have special needs perhaps one of the other approaches may be better.

What is the easiest way to initialize a std::vector with hardcoded elements?

In C++0x you will be able to do it in the same way that you did with an array, but not in the current standard.

With only language support you can use:

int tmp[] = { 10, 20, 30 };
std::vector<int> v( tmp, tmp+3 ); // use some utility to avoid hardcoding the size here

If you can add other libraries you could try boost::assignment:

vector<int> v = list_of(10)(20)(30);

To avoid hardcoding the size of an array:

// option 1, typesafe, not a compile time constant
template <typename T, std::size_t N>
inline std::size_t size_of_array( T (&)[N] ) {
   return N;
}
// option 2, not typesafe, compile time constant
#define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))

// option 3, typesafe, compile time constant
template <typename T, std::size_t N>
char (&sizeof_array( T(&)[N] ))[N];    // declared, undefined
#define ARRAY_SIZE(x) sizeof(sizeof_array(x))

Remove last character from C++ string

Simple solution if you are using C++11. Probably O(1) time as well:

st.pop_back();

javascript filter array multiple conditions

This is an easily understandable functional solution

_x000D_
_x000D_
let filtersObject = {_x000D_
  address: "England",_x000D_
  name: "Mark"_x000D_
};_x000D_
_x000D_
let users = [{_x000D_
    name: 'John',_x000D_
    email: '[email protected]',_x000D_
    age: 25,_x000D_
    address: 'USA'_x000D_
  },_x000D_
  {_x000D_
    name: 'Tom',_x000D_
    email: '[email protected]',_x000D_
    age: 35,_x000D_
    address: 'England'_x000D_
  },_x000D_
  {_x000D_
    name: 'Mark',_x000D_
    email: '[email protected]',_x000D_
    age: 28,_x000D_
    address: 'England'_x000D_
  }_x000D_
];_x000D_
_x000D_
function filterUsers(users, filtersObject) {_x000D_
  //Loop through all key-value pairs in filtersObject_x000D_
  Object.keys(filtersObject).forEach(function(key) {_x000D_
    //Loop through users array checking each userObject_x000D_
    users = users.filter(function(userObject) {_x000D_
      //If userObject's key:value is same as filtersObject's key:value, they stay in users array_x000D_
      return userObject[key] === filtersObject[key]_x000D_
    })_x000D_
  });_x000D_
  return users;_x000D_
}_x000D_
_x000D_
//ES6_x000D_
function filterUsersES(users, filtersObject) {_x000D_
  for (let key in filtersObject) {_x000D_
    users = users.filter((userObject) => userObject[key] === filtersObject[key]);_x000D_
  }_x000D_
  return users;_x000D_
}_x000D_
_x000D_
console.log(filterUsers(users, filtersObject));_x000D_
console.log(filterUsersES(users, filtersObject));
_x000D_
_x000D_
_x000D_

How to add parameters into a WebRequest?

The code below differs from all other code because at the end it prints the response string in the console that the request returns. I learned in previous posts that the user doesn't get the response Stream and displays it.

//Visual Basic Implementation Request and Response String
  Dim params = "key1=value1&key2=value2"
    Dim byteArray = UTF8.GetBytes(params)
    Dim url = "https://okay.com"
    Dim client = WebRequest.Create(url)
    client.Method = "POST"
    client.ContentType = "application/x-www-form-urlencoded"
    client.ContentLength = byteArray.Length
    Dim stream = client.GetRequestStream()

    //sending the data
    stream.Write(byteArray, 0, byteArray.Length)
    stream.Close()

//getting the full response in a stream        
Dim response = client.GetResponse().GetResponseStream()

//reading the response 
Dim result = New StreamReader(response)

//Writes response string to Console
    Console.WriteLine(result.ReadToEnd())
    Console.ReadKey()

Bootstrap modal: is not a function

The problem is due to having jQuery instances more than one time. Take care if you are using many files with multiples instance of jQuery. Just leave 1 instance of jQuery and your code will work.

<script type="text/javascript" src="https://code.jquery.com/jquery-2.1.4.min.js"></script>

Make a UIButton programmatically in Swift

Swift 2.2 Xcode 7.3

Since Objective-C String Literals are deprecated now for button callback methods

let button:UIButton = UIButton(frame: CGRectMake(100, 400, 100, 50))
button.backgroundColor = UIColor.blackColor()
button.setTitle("Button", forState: UIControlState.Normal)
button.addTarget(self, action:#selector(self.buttonClicked), forControlEvents: .TouchUpInside)
self.view.addSubview(button)

func buttonClicked() {
     print("Button Clicked")
}

Swift 3 Xcode 8

let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
button.backgroundColor = .black
button.setTitle("Button", for: .normal)
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

func buttonClicked() {
    print("Button Clicked")
}

Swift 4 Xcode 9

let button:UIButton = UIButton(frame: CGRect(x: 100, y: 400, width: 100, height: 50))
button.backgroundColor = .black
button.setTitle("Button", for: .normal)
button.addTarget(self, action:#selector(self.buttonClicked), for: .touchUpInside)
self.view.addSubview(button)

@objc func buttonClicked() {
    print("Button Clicked")
}

Change NULL values in Datetime format to empty string

Select isnull(date_column_name,cast('1900-01-01' as DATE)) from table name

How to use Comparator in Java to sort

For the sake of completeness, here's a simple one-liner compare method:

Collections.sort(people, new Comparator<Person>() {
    @Override
    public int compare(Person lhs, Person rhs) {  
        return Integer.signum(lhs.getId() - rhs.getId());  
    }
});

How to include header files in GCC search path?

The -I directive does the job:

gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c 

CKEditor, Image Upload (filebrowserUploadUrl)

New CKeditor doesn't have file manager included (CKFinder is payable). You can integrate free filemanager that is good looking and easy to implement in CKeditor.

http://labs.corefive.com/2009/10/30/an-open-file-manager-for-ckeditor-3-0/

You dowload it, copy it to your project. All instructions are there but you basically just put path to added filemanager index.html page in your code.

CKEDITOR.replace( 'meeting_notes',
{
startupFocus : true,
toolbar :
[
['ajaxsave'],
['Bold', 'Italic', 'Underline', '-', 'NumberedList', 'BulletedList', '-', 'Link', 'Unlink' ],
['Cut','Copy','Paste','PasteText'],
['Undo','Redo','-','RemoveFormat'],
['TextColor','BGColor'],
['Maximize', 'Image']
],
filebrowserUploadUrl : '/filemanager/index.html' // you must write path to filemanager where you have copied it.
});    

Most languages are supported (php, asp, MVC && aspx - ashx,...)).

Java: how to add image to Jlabel?

(If you are using NetBeans IDE) Just create a folder in your project but out side of src folder. Named the folder Images. And then put the image into the Images folder and write code below.

// Import ImageIcon     
ImageIcon iconLogo = new ImageIcon("Images/YourCompanyLogo.png");
// In init() method write this code
jLabelYourCompanyLogo.setIcon(iconLogo);

Now run your program.

How to get the Parent's parent directory in Powershell?

Version for a directory

get-item is your friendly helping hand here.

(get-item $scriptPath ).parent.parent

If you Want the string only

(get-item $scriptPath ).parent.parent.FullName

Version for a file

If $scriptPath points to a file then you have to call Directory property on it first, so the call would look like this

(get-item $scriptPath).Directory.Parent.Parent.FullName

Remarks
This will only work if $scriptPath exists. Otherwise you have to use Split-Path cmdlet.

Running Groovy script from the command line

You need to run the script like this:

groovy helloworld.groovy

Postgresql - change the size of a varchar column to lower length

Ok, I'm probably late to the party, BUT...

THERE'S NO NEED TO RESIZE THE COLUMN IN YOUR CASE!

Postgres, unlike some other databases, is smart enough to only use just enough space to fit the string (even using compression for longer strings), so even if your column is declared as VARCHAR(255) - if you store 40-character strings in the column, the space usage will be 40 bytes + 1 byte of overhead.

The storage requirement for a short string (up to 126 bytes) is 1 byte plus the actual string, which includes the space padding in the case of character. Longer strings have 4 bytes of overhead instead of 1. Long strings are compressed by the system automatically, so the physical requirement on disk might be less. Very long values are also stored in background tables so that they do not interfere with rapid access to shorter column values.

(http://www.postgresql.org/docs/9.0/interactive/datatype-character.html)

The size specification in VARCHAR is only used to check the size of the values which are inserted, it does not affect the disk layout. In fact, VARCHAR and TEXT fields are stored in the same way in Postgres.

JUnit: how to avoid "no runnable methods" in test utils classes

In your test class if wrote import org.junit.jupiter.api.Test; delete it and write import org.junit.Test; In this case it worked me as well.

Could not obtain information about Windows NT group user

Active Directory is refusing access to your SQL Agent. The Agent should be running under an account that is recognized by STAR domain controller.

How to make spring inject value into a static field

As these answers are old, I found this alternative. It is very clean and works with just java annotations:

To fix it, create a “none static setter” to assign the injected value for the static variable. For example :

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class GlobalValue {

public static String DATABASE;

@Value("${mongodb.db}")
public void setDatabase(String db) {
    DATABASE = db;
}
}

https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

Is Ruby pass by reference or by value?

It should be noted that you do not have to even use the "replace" method to change the value original value. If you assign one of the hash values for a hash, you are changing the original value.

def my_foo(a_hash)
  a_hash["test"]="reference"
end;

hash = {"test"=>"value"}
my_foo(hash)
puts "Ruby is pass-by-#{hash["test"]}"

Using PropertyInfo to find out the property type

Use PropertyInfo.PropertyType to get the type of the property.

public bool ValidateData(object data)
{
    foreach (PropertyInfo propertyInfo in data.GetType().GetProperties())
    {
        if (propertyInfo.PropertyType == typeof(string))
        {
            string value = propertyInfo.GetValue(data, null);

            if value is not OK
            {
                return false;
            }
        }
    }            

    return true;
}

Eclipse: How do I add the javax.servlet package to a project?

For me doesnt put jars to lib directory and set to Build path enought.

The right thing was add it to Deployment Assembly.

Original asnwer

ASP.NET MVC Ajax Error handling

For handling errors from ajax calls on the client side, you assign a function to the error option of the ajax call.

To set a default globally, you can use the function described here: http://api.jquery.com/jQuery.ajaxSetup.

How to change Navigation Bar color in iOS 7?

In viewDidLoad, set:

    self.navigationController.navigationBar.barTintColor = [UIColor blueColor];

Change ( blueColor ) to whatever color you'd like.

Jquery Setting Value of Input Field

This should work.

$(".formData").val("valuesgoeshere")

For empty

$(".formData").val("")

If this does not work, you should post a jsFiddle.

Demo:

_x000D_
_x000D_
$(function() {_x000D_
  $(".resetInput").on("click", function() {_x000D_
    $(".formData").val("");_x000D_
  });_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="text" class="formData" value="yoyoyo">_x000D_
_x000D_
_x000D_
<button class="resetInput">Click Here to reset</button>
_x000D_
_x000D_
_x000D_