Programs & Examples On #Strace

strace is a Linux/UNIX tool for logging and analysing the system calls made by a user-side process.

How should strace be used?

strace is a good tool for learning how your program makes various system calls (requests to the kernel) and also reports the ones that have failed along with the error value associated with that failure. Not all failures are bugs. For example, a code that is trying to search for a file may get a ENOENT (No such file or directory) error but that may be an acceptable scenario in the logic of the code.

One good use case of using strace is to debug race conditions during temporary file creation. For example a program that may be creating files by appending the process ID (PID) to some predecided string may face problems in multi-threaded scenarios. [A PID+TID (process id + thread id) or a better system call such as mkstemp will fix this].

It is also good for debugging crashes. You may find this (my) article on strace and debugging crashes useful.

Systrace for Windows

strace supported By Git,as Michael Fox Mention Maybe not useful for complex/windows software.

Copy-item Files in Folders and subfolders in the same directory structure of source server using PowerShell

I had trouble with the most popular answer (overthinking). It put AFolder in the \Server\MyFolder\AFolder and I wanted the contents of AFolder and below in MyFolder. This didn't work.

Copy-Item -Verbose -Path C:\MyFolder\AFolder -Destination \\Server\MyFolder -recurse -Force

Plus I needed to Filter and only copy *.config files.

This didn't work, with "\*" because it did not recurse

Copy-Item -Verbose -Path C:\MyFolder\AFolder\* -Filter *.config -Destination \\Server\MyFolder -recurse -Force

I ended up lopping off the beginning of the path string, to get the childPath relative to where I was recursing from. This works for the use-case in question and went down many subdirectories, which some other solutions do not.

Get-Childitem -Path "$($sourcePath)/**/*.config" -Recurse | 
ForEach-Object {
  $childPath = "$_".substring($sourcePath.length+1)
  $dest = "$($destPath)\$($childPath)" #this puts a \ between dest and child path
  Copy-Item -Verbose -Path $_ -Destination $dest -Force   
}

Restore a deleted file in the Visual Studio Code Recycle Bin

If you just deleted the file, know that VSCode 1.52 (Dec. 2020) will support:

Undo file operations in Explorer

Explorer now supports Undo and Redo for all file operations: delete, rename, copy, move, new file and new folder.

Make sure the focus is in the Explorer and trigger the Undo or Redo commands and your last file operation will be undone or redone respectively.
Keep in mind that we have separate undo stacks for the editor and the explorer and we choose which one to undo based on focus.

Explorer Undo -- https://media.githubusercontent.com/media/microsoft/vscode-docs/vnext/release-notes/images/1_52/explorer-undo.gif

JQuery Validate Dropdown list

Easiest way to get it done is by adding required into your select

Select the best option
<br/>

<select name="dd1" id="dd1" required>
<option value="none">None</option>
<option value="o1">option 1</option>
<option value="o2">option 2</option>
<option value="o3">option 3</option>
</select> 

<br/><br/>?

time delayed redirect?

You can include this directly in your buttun. It works very well. I hope it'll be useful for you. onclick="setTimeout('location.href = ../../dashboard.xhtml;', 7000);"

Find mouse position relative to element

Taken from this tutorial, with corrections made thanks to the top comment:

function getMousePos( canvas, evt ) {
    var rect = canvas.getBoundingClientRect();
    return {
        x: Math.floor( ( evt.clientX - rect.left ) / ( rect.right - rect.left ) * canvas.width ),
        y: Math.floor( ( evt.clientY - rect.top ) / ( rect.bottom - rect.top ) * canvas.height )
    };
}

Use on a canvas as follows:

var canvas = document.getElementById( 'myCanvas' );
canvas.addEventListener( 'mousemove', function( evt ) {
    var mousePos = getMousePos( canvas, evt );
} );

HTML checkbox onclick called in Javascript

Label without an onclick will behave as you would expect. It changes the input. What you relly want is to execute selectAll() when you click on a label, right? Then only add select all to the label onclick. Or wrap the input into the the label and assign onclick only for the label

<label for="check_all_1" onclick="selectAll(document.wizard_form, this);">
  <input type="checkbox" id="check_all_1" name="check_all_1" title="Select All">
  Select All
</label>

How to get UTC value for SYSDATE on Oracle

Usually, I work with DATE columns, not the larger but more precise TIMESTAMP used by some answers.

The following will return the current UTC date as just that -- a DATE.

CAST(sys_extract_utc(SYSTIMESTAMP) AS DATE)

I often store dates like this, usually with the field name ending in _UTC to make it clear for the developer. This allows me to avoid the complexity of time zones until last-minute conversion by the user's client. Oracle can store time zone detail with some data types, but those types require more table space than DATE, and knowledge of the original time zone is not always required.

How can I get the height of an element using css only

Unfortunately, it is not possible to "get" the height of an element via CSS because CSS is not a language that returns any sort of data other than rules for the browser to adjust its styling.

Your resolution can be achieved with jQuery, or alternatively, you can fake it with CSS3's transform:translateY(); rule.


The CSS Route

If we assume that your target div in this instance is 200px high - this would mean that you want the div to have a margin of 190px?

This can be achieved by using the following CSS:

.dynamic-height {
    -webkit-transform: translateY(100%); //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    transform: translateY(100%);         //if your div is 200px, this will move it down by 200px, if it is 100px it will down by 100px etc
    margin-top: -10px;
}

In this instance, it is important to remember that translateY(100%) will move the element in question downwards by a total of it's own length.

The problem with this route is that it will not push element below it out of the way, where a margin would.


The jQuery Route

If faking it isn't going to work for you, then your next best bet would be to implement a jQuery script to add the correct CSS for you.

jQuery(document).ready(function($){ //wait for the document to load
    $('.dynamic-height').each(function(){ //loop through each element with the .dynamic-height class
        $(this).css({
            'margin-top' : $(this).outerHeight() - 10 + 'px' //adjust the css rule for margin-top to equal the element height - 10px and add the measurement unit "px" for valid CSS
        });
    });
});

Debian 8 (Live-CD) what is the standard login and password?

I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:

login : Debian Live User
password : live

I hope this helps

NTFS performance and large volumes of files and directories

When you create a folder with N entries, you create a list of N items at file-system level. This list is a system-wide shared data structure. If you then start modifying this list continuously by adding/removing entries, I expect at least some lock contention over shared data. This contention - theoretically - can negatively affect performance.

For read-only scenarios I can't imagine any reason for performance degradation of directories with large number of entries.

MySQL query finding values in a comma separated string

All the answers are not really correct, try this:

select * from shirts where 1 IN (colors);

How to create an empty matrix in R?

If you don't know the number of columns ahead of time, add each column to a list and cbind at the end.

List <- list()
for(i in 1:n)
{
    normF <- #something
    List[[i]] <- normF
}
Matrix = do.call(cbind, List)

Swipe to Delete and the "More" button (like in Mail app on iOS 7)

Actual Swift 3 Answer

This is the ONLY function you need. You do not need CanEdit or CommitEditingStyle functions for custom actions.

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let action1 = UITableViewRowAction(style: .default, title: "Action1", handler: {
        (action, indexPath) in
        print("Action1")
    })
    action1.backgroundColor = UIColor.lightGray
    let action2 = UITableViewRowAction(style: .default, title: "Action2", handler: {
        (action, indexPath) in
        print("Action2")
    })
    return [action1, action2]
}

NameError: name 'reduce' is not defined in Python

You can add

from functools import reduce

before you use the reduce.

Connect Device to Mac localhost Server?

I solve a similar problem.

  • connected Mac and iPhone to the same Wi-Fi
  • change the iPhone Wi-Fi setting, set http proxy to manual and change the Server to you Mac ip address and setting the Port. My Port is 80.

image one

image two

  • you can input http://<Mac ip>:<your customer server port> in iPhone's safari

Converting milliseconds to a date (jQuery/JavaScript)

Try using this code:

var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
        year: 'numeric', month: 'numeric', day: 'numeric',
    };

var result = date.toLocaleDateString('en', options); // 10/29/2013

See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Determine the number of rows in a range

You can also use:

Range( RangeName ).end(xlDown).row

to find the last row with data in it starting at your named range.

TypeScript typed array usage

You have an error in your syntax here:

this._possessions = new Thing[100]();

This doesn't create an "array of things". To create an array of things, you can simply use the array literal expression:

this._possessions = [];

Of the array constructor if you want to set the length:

this._possessions = new Array(100);

I have created a brief working example you can try in the playground.

module Entities {  

    class Thing {

    }        

    export class Person {
        private _name: string;
        private _possessions: Thing[];
        private _mostPrecious: Thing;

        constructor (name: string) {
            this._name = name;
            this._possessions = [];
            this._possessions.push(new Thing())
            this._possessions[100] = new Thing();
        }
    }
}

Can a foreign key be NULL and/or duplicate?

Short answer: Yes, it can be NULL or duplicate.

I want to explain why a foreign key might need to be null or might need to be unique or not unique. First remember a Foreign key simply requires that the value in that field must exist first in a different table (the parent table). That is all an FK is by definition. Null by definition is not a value. Null means that we do not yet know what the value is.

Let me give you a real life example. Suppose you have a database that stores sales proposals. Suppose further that each proposal only has one sales person assigned and one client. So your proposal table would have two foreign keys, one with the client ID and one with the sales rep ID. However, at the time the record is created, a sales rep is not always assigned (because no one is free to work on it yet), so the client ID is filled in but the sales rep ID might be null. In other words, usually you need the ability to have a null FK when you may not know its value at the time the data is entered, but you do know other values in the table that need to be entered. To allow nulls in an FK generally all you have to do is allow nulls on the field that has the FK. The null value is separate from the idea of it being an FK.

Whether it is unique or not unique relates to whether the table has a one-one or a one-many relationship to the parent table. Now if you have a one-one relationship, it is possible that you could have the data all in one table, but if the table is getting too wide or if the data is on a different topic (the employee - insurance example @tbone gave for instance), then you want separate tables with a FK. You would then want to make this FK either also the PK (which guarantees uniqueness) or put a unique constraint on it.

Most FKs are for a one to many relationship and that is what you get from a FK without adding a further constraint on the field. So you have an order table and the order details table for instance. If the customer orders ten items at one time, he has one order and ten order detail records that contain the same orderID as the FK.

How do I make an editable DIV look like a text field?

These look the same as their real counterparts in Safari, Chrome, and Firefox. They degrade gracefully and look OK in Opera and IE9, too.

Demo: http://jsfiddle.net/ThinkingStiff/AbKTQ/

CSS:

textarea {
    height: 28px;
    width: 400px;
}

#textarea {
    -moz-appearance: textfield-multiline;
    -webkit-appearance: textarea;
    border: 1px solid gray;
    font: medium -moz-fixed;
    font: -webkit-small-control;
    height: 28px;
    overflow: auto;
    padding: 2px;
    resize: both;
    width: 400px;
}

input {
    margin-top: 5px;
    width: 400px;
}

#input {
    -moz-appearance: textfield;
    -webkit-appearance: textfield;
    background-color: white;
    background-color: -moz-field;
    border: 1px solid darkgray;
    box-shadow: 1px 1px 1px 0 lightgray inset;  
    font: -moz-field;
    font: -webkit-small-control;
    margin-top: 5px;
    padding: 2px 3px;
    width: 398px;    
}

HTML:

<textarea>I am a textarea</textarea>
<div id="textarea" contenteditable>I look like textarea</div>

<input value="I am an input" />
<div id="input" contenteditable>I look like an input</div>

Output:

enter image description here

Is string in array?

You're simply after the Array.Exists function (or the Contains extension method if you're using .NET 3.5, which is slightly more convenient).

Hadoop MapReduce: Strange Result when Storing Previous Value in Memory in a Reduce Class (Java)

It is very inefficient to store all values in memory, so the objects are reused and loaded one at a time. See this other SO question for a good explanation. Summary:

[...] when looping through the Iterable value list, each Object instance is re-used, so it only keeps one instance around at a given time.

Is it possible to ignore one single specific line with Pylint?

Checkout the files in https://github.com/PyCQA/pylint/tree/master/pylint/checkers. I haven't found a better way to obtain the error name from a message than either Ctrl + F-ing those files or using the GitHub search feature:

If the message is "No name ... in module ...", use the search:

No name %r in module %r repo:PyCQA/pylint/tree/master path:/pylint/checkers

Or, to get fewer results:

"No name %r in module %r" repo:PyCQA/pylint/tree/master path:/pylint/checkers

GitHub will show you:

"E0611": (
    "No name %r in module %r",
    "no-name-in-module",
    "Used when a name cannot be found in a module.",

You can then do:

from collections import Sequence # pylint: disable=no-name-in-module

How to get the first 2 letters of a string in Python?

It is as simple as string[:2]. A function can be easily written to do it, if you need.

Even this, is as simple as

def first2(s):
    return s[:2]

How do I set/unset a cookie with jQuery?

I know there are many great answers. Often, I only need to read cookies and I do not want to create overhead by loading additional libraries or defining functions.

Here is how to read cookies in one line of javascript. I found the answer in Guilherme Rodrigues' blog article:

('; '+document.cookie).split('; '+key+'=').pop().split(';').shift()

This reads the cookie named key, nice, clean and simple.

copy db file with adb pull results in 'permission denied' error

You can use run-as shell command to access private application data.

If you only want to copy database you can use this snippet, provided in https://stackoverflow.com/a/31504263/998157

adb -d shell "run-as com.example.test cat /data/data/com.example.test/databases/data.db" > data.db

Capture characters from standard input without waiting for enter to be pressed

If you are on windows, you can use PeekConsoleInput to detect if there's any input,

HANDLE handle = GetStdHandle(STD_INPUT_HANDLE);
DWORD events;
INPUT_RECORD buffer;
PeekConsoleInput( handle, &buffer, 1, &events );

then use ReadConsoleInput to "consume" the input character ..

PeekConsoleInput(handle, &buffer, 1, &events);
if(events > 0)
{
    ReadConsoleInput(handle, &buffer, 1, &events);  
    return buffer.Event.KeyEvent.wVirtualKeyCode;
}
else return 0

to be honest this is from some old code I have, so you have to fiddle a bit with it.

The cool thing though is that it reads input without prompting for anything, so the characters are not displayed at all.

jQuery - Click event on <tr> elements with in a table and getting <td> element values

<script>
jQuery(document).ready(function() {
    jQuery("tr").click(function(){
       alert("Click! "+ jQuery(this).find('td').html());
    });
});
</script>

Check image width and height before upload with Javascript

In my view the perfect answer you must required is

var reader = new FileReader();

//Read the contents of Image File.
reader.readAsDataURL(fileUpload.files[0]);
reader.onload = function (e) {

  //Initiate the JavaScript Image object.
  var image = new Image();

  //Set the Base64 string return from FileReader as source.
  image.src = e.target.result;

  //Validate the File Height and Width.
  image.onload = function () {
    var height = this.height;
    var width = this.width;
    if (height > 100 || width > 100) {
      alert("Height and Width must not exceed 100px.");
      return false;
    }
    alert("Uploaded image has valid Height and Width.");
    return true;
  };
};

Reference - What does this regex mean?

The Stack Overflow Regular Expressions FAQ

See also a lot of general hints and useful links at the tag details page.


Online tutorials

Quantifiers

Character Classes

Escape Sequences

Anchors

(Also see "Flavor-Specific Information ? Java ? The functions in Matcher")

Groups

Lookarounds

Modifiers

Other:

Common Tasks

Advanced Regex-Fu

Flavor-Specific Information

(Except for those marked with *, this section contains non-Stack Overflow links.)

General information

(Links marked with * are non-Stack Overflow links.)

Examples of regex that can cause regex engine to fail

Tools: Testers and Explainers

(This section contains non-Stack Overflow links.)

How to run multiple Python versions on Windows

When you install Python, it will not overwrite other installs of other major versions. So installing Python 2.5.x will not overwrite Python 2.6.x, although installing 2.6.6 will overwrite 2.6.5.

So you can just install it. Then you call the Python version you want. For example:

C:\Python2.5\Python.exe

for Python 2.5 on windows and

C:\Python2.6\Python.exe

for Python 2.6 on windows, or

/usr/local/bin/python-2.5

or

/usr/local/bin/python-2.6

on Windows Unix (including Linux and OS X).

When you install on Unix (including Linux and OS X) you will get a generic python command installed, which will be the last one you installed. This is mostly not a problem as most scripts will explicitly call /usr/local/bin/python2.5 or something just to protect against that. But if you don't want to do that, and you probably don't you can install it like this:

./configure
make
sudo make altinstall

Note the "altinstall" that means it will install it, but it will not replace the python command.

On Windows you don't get a global python command as far as I know so that's not an issue.

SQL DELETE with INNER JOIN

Add .* to s in your first line.

Try:

DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");

How to get user agent in PHP

You can use the jQuery ajax method link if you want to pass data from client to server. In this case you can use $_SERVER['HTTP_USER_AGENT'] variable to found browser user agent.

How do I display Ruby on Rails form validation error messages one at a time?

I resolved it like this:

<% @user.errors.each do |attr, msg| %>
  <li>
    <%= @user.errors.full_messages_for(attr).first if @user.errors[attr].first == msg %>
  </li>
<% end %>

This way you are using the locales for the error messages.

How to center icon and text in a android button with width set to "fill parent"

As suggested by Rodja, prior to 4.0 there isn't a direct way to center the text with the drawable. And indeed setting a padding_left value does move the drawable away from the border. Therefore my suggestion is that on runtime you calculate exactly how many pixels from the left border your drawable needs to be and then pass it using setPadding Your calculation may be something like

int paddingLeft = (button.getWidth() - drawableWidth - textWidth) / 2;

The width of your drawable's is fixed and you can look it up and you can also calculate or guess the text width.

Finally, you would need to multiple the padding value by the screen density, which you can do using DisplayMetrics

Accept server's self-signed ssl certificate in Java client

Trust all SSL certificates:- You can bypass SSL if you want to test on the testing server. But do not use this code for production.

public static class NukeSSLCerts {
protected static final String TAG = "NukeSSLCerts";

public static void nuke() {
    try {
        TrustManager[] trustAllCerts = new TrustManager[] { 
            new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    X509Certificate[] myTrustedAnchors = new X509Certificate[0];  
                    return myTrustedAnchors;
                }

                @Override
                public void checkClientTrusted(X509Certificate[] certs, String authType) {}

                @Override
                public void checkServerTrusted(X509Certificate[] certs, String authType) {}
            }
        };

        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
        HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier() {
            @Override
            public boolean verify(String arg0, SSLSession arg1) {
                return true;
            }
        });
    } catch (Exception e) { 
    }
}

}

Please call this function in onCreate() function in Activity or in your Application Class.

NukeSSLCerts.nuke();

This can be used for Volley in Android.

How to expand and compute log(a + b)?

In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)

(In fact, this identity is often used when implementing log in math libraries).

GitHub: invalid username or password

Disabling 2 factor authentication at github worked for me.

I see that there is a deleted answer that says this, with the deletion reason as "does not answer the question". If it works, then I think it answers the question...

How to join multiple lines of file names into one with custom delimiter?

This command is for the PERL fans :

ls -1 | perl -l40pe0

Here 40 is the octal ascii code for space.

-p will process line by line and print

-l will take care of replacing the trailing \n with the ascii character we provide.

-e is to inform PERL we are doing command line execution.

0 means that there is actually no command to execute.

perl -e0 is same as perl -e ' '

Can not connect to local PostgreSQL

I was getting this same error (it turns out it was an error with postmaster.pid. Here's how I got postgres up and running again (credit to Ricardo Burillo for the fix):

$ rm /usr/local/var/postgres/postmaster.pid 
$ pg_resetxlog -f /usr/local/var/postgres

Sql connection-string for localhost server

When using SQL Express, you need to specify \SQLExpress instance in your connection string:

string str = "Data Source=HARIHARAN-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=True" ;

Angular2 router (@angular/router), how to set default route?

V2.0.0 and later

See also see https://angular.io/guide/router#the-default-route-to-heroes

RouterConfig = [
  { path: '', redirectTo: '/heroes', pathMatch: 'full' },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '', redirectTo: '/detail', pathMatch: 'full' },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

There is also the catch-all route

{ path: '**', redirectTo: '/heroes', pathMatch: 'full' },

which redirects "invalid" urls.

V3-alpha (vladivostok)

Use path / and redirectTo

RouterConfig = [
  { path: '/', redirectTo: 'heroes', terminal: true },
  { path: 'heroes', component: HeroComponent,
    children: [
      { path: '/', redirectTo: 'detail', terminal: true },
      { path: 'detail', component: HeroDetailComponent }
    ] 
  }
];

RC.1 @angular/router

The RC router doesn't yet support useAsDefault. As a workaround you can navigate explicitely.

In the root component

export class AppComponent {
  constructor(router:Router) {
    router.navigate(['/Merge']);
  }
}

for other components

export class OtherComponent {
  constructor(private router:Router) {}

  routerOnActivate(curr: RouteSegment, prev?: RouteSegment, currTree?: RouteTree, prevTree?: RouteTree) : void {
    this.router.navigate(['SomeRoute'], curr);
  }
}

VLook-Up Match first 3 characters of one column with another column

=VLOOKUP(Left(A1,1),B$2:B$22,2,FALSE)

Left is because you are starting the word/alphanumeric text from the left. the number "1" which i have placed is after lookup value in this case "A1" is because my search includes the formula for 1st character. If second character is asked it would be (A1,2) quite simple really :)

How to scroll to bottom in react?

This is how you would solve this in TypeScript (using the ref to a targeted element where you scroll to):

class Chat extends Component <TextChatPropsType, TextChatStateType> {
  private scrollTarget = React.createRef<HTMLDivElement>();
  componentDidMount() {
    this.scrollToBottom();//scroll to bottom on mount
  }

  componentDidUpdate() {
    this.scrollToBottom();//scroll to bottom when new message was added
  }

  scrollToBottom = () => {
    const node: HTMLDivElement | null = this.scrollTarget.current; //get the element via ref

    if (node) { //current ref can be null, so we have to check
        node.scrollIntoView({behavior: 'smooth'}); //scroll to the targeted element
    }
  };

  render <div>
    {message.map((m: Message) => <ChatMessage key={`chat--${m.id}`} message={m}/>}
     <div ref={this.scrollTarget} data-explanation="This is where we scroll to"></div>
   </div>
}

For more information about using ref with React and Typescript you can find a great article here.

How to see data from .RData file?

I think the problem is that you load isfar data.frame but you overwrite it by value returned by load.

Try either:

load("C:/Users/isfar.RData") 
head(isfar)

Or more general way

load("C:/Users/isfar.RData", ex <- new.env())
ls.str(ex) 

Zip lists in Python

Basically the zip function works on lists, tuples and dictionaries in Python. If you are using IPython then just type zip? And check what zip() is about.

If you are not using IPython then just install it: "pip install ipython"

For lists

a = ['a', 'b', 'c']
b = ['p', 'q', 'r']
zip(a, b)

The output is [('a', 'p'), ('b', 'q'), ('c', 'r')

For dictionary:

c = {'gaurav':'waghs', 'nilesh':'kashid', 'ramesh':'sawant', 'anu':'raje'}
d = {'amit':'wagh', 'swapnil':'dalavi', 'anish':'mane', 'raghu':'rokda'}
zip(c, d)

The output is:

[('gaurav', 'amit'),
 ('nilesh', 'swapnil'),
 ('ramesh', 'anish'),
 ('anu', 'raghu')]

How to generate class diagram from project in Visual Studio 2013?

Because one moderator deleted my detailed image-supported answer on this question, just because I copied and pasted from another question, I am forced to put a less detailed answer and I will link the original answer if you want a more visual way to see the solution.


For Visual Studio 2019 and Visual Studio 2017 Users
For People who are missing this old feature in VS2019 (or maybe VS2017) from the old versions of Visual Studio


This feature still available, but it is NOT available by default, you have to install it separately.

  1. Open VS 2019 go to Tools -> Get Tools and Features
  2. Select the Individual components tab and search for Class Designer
  3. Select this Component and Install it, After finish installing this component (you may need to restart visual studio)
  4. Right-click on the project and select Add -> Add New Item
  5. Search for 'class' word and NOW you can see Class Diagram component

see this answer also to see an image associated

https://stackoverflow.com/a/66289543/4390133

(whish that the moderator realized this is the same question and instead of deleting my answer, he could mark one of the questions as duplicated to the other)


Update to create a class-diagram for the whole project
I received a downvote because I did not mention how to generate a diagram for the whole project, here is how to do it (after applying the previous steps)

  1. Add class diagram to the project
  2. if the option Preview Selected Items is enabled in the solution explorer, disabled it temporarily, you can re-enable it later

enter image description here

  1. open the class diagram that you created in step 2 (by double-clicking on it)
  2. drag-and-drop the project from the solution explorer to the class diagram

you could be shocked by the results to the point that you can change your mind and remove your downvote (please do NOT upvote, it is enough to remove your downvote)

How to make an Android Spinner with initial text "Select One"?

I think the easiest way is creating a dummy item on index 0 saying "select one" and then on saving maybe check that selection is not 0.

Spring - @Transactional - What happens in background?

This is a big topic. The Spring reference doc devotes multiple chapters to it. I recommend reading the ones on Aspect-Oriented Programming and Transactions, as Spring's declarative transaction support uses AOP at its foundation.

But at a very high level, Spring creates proxies for classes that declare @Transactional on the class itself or on members. The proxy is mostly invisible at runtime. It provides a way for Spring to inject behaviors before, after, or around method calls into the object being proxied. Transaction management is just one example of the behaviors that can be hooked in. Security checks are another. And you can provide your own, too, for things like logging. So when you annotate a method with @Transactional, Spring dynamically creates a proxy that implements the same interface(s) as the class you're annotating. And when clients make calls into your object, the calls are intercepted and the behaviors injected via the proxy mechanism.

Transactions in EJB work similarly, by the way.

As you observed, through, the proxy mechanism only works when calls come in from some external object. When you make an internal call within the object, you're really making a call through the "this" reference, which bypasses the proxy. There are ways of working around that problem, however. I explain one approach in this forum post in which I use a BeanFactoryPostProcessor to inject an instance of the proxy into "self-referencing" classes at runtime. I save this reference to a member variable called "me". Then if I need to make internal calls that require a change in the transaction status of the thread, I direct the call through the proxy (e.g. "me.someMethod()".) The forum post explains in more detail. Note that the BeanFactoryPostProcessor code would be a little different now, as it was written back in the Spring 1.x timeframe. But hopefully it gives you an idea. I have an updated version that I could probably make available.

SVN remains in conflict?

One more solution below,

If the entire folder is removed and SVNis throwing the error "admin file .svn is missing", the following will be used to resolve the conflict to working state.

svn resolve --accept working "file / directory name "

How do you embed binary data in XML?

If you have control over the XML format, you should turn the problem inside out. Rather than attaching the binary XML you should think about how to enclose a document that has multiple parts, one of which contains XML.

The traditional solution to this is an archive (e.g. tar). But if you want to keep your enclosing document in a text-based format or if you don't have access to an file archiving library, there is also a standardized scheme that is used heavily in email and HTTP which is multipart/* MIME with Content-Transfer-Encoding: binary.

For example if your servers communicate through HTTP and you want to send a multipart document, the primary being an XML document which refers to a binary data, the HTTP communication might look something like this:

POST / HTTP/1.1
Content-Type: multipart/related; boundary="qd43hdi34udh34id344"
... other headers elided ...

--qd43hdi34udh34id344
Content-Type: application/xml

<myxml>
    <data href="cid:data.bin"/>
</myxml>
--qd43hdi34udh34id344
Content-Id: <data.bin>
Content-type: application/octet-stream
Content-Transfer-Encoding: binary

... binary data ...
--qd43hdi34udh34id344--

As in above example, the XML refer to the binary data in the enclosing multipart by using a cid URI scheme which is an identifier to the Content-Id header. The overhead of this scheme would be just the MIME header. A similar scheme can also be used for HTTP response. Of course in HTTP protocol, you also have the option of sending a multipart document into separate request/response.

If you want to avoid wrapping your data in a multipart is to use data URI:

<myxml>
    <data href="data:application/something;charset=utf-8;base64,dGVzdGRhdGE="/>
</myxml>

But this has the base64 overhead.

python paramiko ssh

There is extensive paramiko API documentation you can find at: http://docs.paramiko.org/en/stable/index.html

I use the following method to execute commands on a password protected client:

import paramiko

nbytes = 4096
hostname = 'hostname'
port = 22
username = 'username' 
password = 'password'
command = 'ls'

client = paramiko.Transport((hostname, port))
client.connect(username=username, password=password)

stdout_data = []
stderr_data = []
session = client.open_channel(kind='session')
session.exec_command(command)
while True:
    if session.recv_ready():
        stdout_data.append(session.recv(nbytes))
    if session.recv_stderr_ready():
        stderr_data.append(session.recv_stderr(nbytes))
    if session.exit_status_ready():
        break

print 'exit status: ', session.recv_exit_status()
print ''.join(stdout_data)
print ''.join(stderr_data)

session.close()
client.close()

How to use an output parameter in Java?

Java does not support output parameters. You can use a return value, or pass in an object as a parameter and modify the object.

How can I generate an MD5 hash?

If you actually want the answer back as a string as opposed to a byte array, you could always do something like this:

String plaintext = "your text here";
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(plaintext.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < 32 ){
  hashtext = "0"+hashtext;
}

How can I clone an SQL Server database on the same server in SQL Server 2008 Express?

If the database is not very large, you might look at the 'Script Database' commands in SQL Server Management Studio Express, which are in a context menu off the database item itself in the explorer.

You can choose what all to script; you want the objects and the data, of course. You will then save the entire script to a single file. Then you can use that file to re-create the database; just make sure the USE command at the top is set to the proper database.

Oracle PL/SQL string compare issue

I compare strings using = and not <>. I've found out that in this context = seems to work in more reasonable fashion than <>. I have specified that two empty (or NULL) strings are equal. The real implementation returns PL/SQL boolean, but here I changed that to pls_integer (0 is false and 1 is true) to be able easily demonstrate the function.

create or replace function is_equal(a in varchar2, b in varchar2)
return pls_integer as
begin
  if a is null and b is null then
    return 1;
  end if;

  if a = b then
    return 1;
  end if;

  return 0;
end;
/
show errors

begin
  /* Prints 0 */
  dbms_output.put_line(is_equal('AAA', 'BBB'));
  dbms_output.put_line(is_equal('AAA', null));
  dbms_output.put_line(is_equal(null, 'BBB'));
  dbms_output.put_line(is_equal('AAA', ''));
  dbms_output.put_line(is_equal('', 'BBB'));

  /* Prints 1 */
  dbms_output.put_line(is_equal(null, null));
  dbms_output.put_line(is_equal(null, ''));
  dbms_output.put_line(is_equal('', ''));
  dbms_output.put_line(is_equal('AAA', 'AAA'));
end;
/

How to Copy Text to Clip Board in Android?

use this function for copy to clipboard

public void copyToClipboard(String copyText) {
    int sdk = android.os.Build.VERSION.SDK_INT;
    if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
        android.text.ClipboardManager clipboard = (android.text.ClipboardManager)
                getSystemService(Context.CLIPBOARD_SERVICE);
        clipboard.setText(copyText);
    } else {
        android.content.ClipboardManager clipboard = (android.content.ClipboardManager)
                getSystemService(Context.CLIPBOARD_SERVICE);
        android.content.ClipData clip = android.content.ClipData
                .newPlainText("Your OTP", copyText);
        clipboard.setPrimaryClip(clip);
    }
    Toast toast = Toast.makeText(getApplicationContext(),
            "Your OTP is copied", Toast.LENGTH_SHORT);
    toast.setGravity(Gravity.BOTTOM | Gravity.RIGHT, 50, 50);
    toast.show();
    //displayAlert("Your OTP is copied");
}

How to show all of columns name on pandas dataframe?

Not a conventional answer, but I guess you could transpose the dataframe to look at the rows instead of the columns. I use this because I find looking at rows more 'intuitional' than looking at columns:

data_all2.T

This should let you view all the rows. This action is not permanent, it just lets you view the transposed version of the dataframe.

If the rows are still truncated, just use print(data_all2.T) to view everything.

PHP Accessing Parent Class Variable

With parent::$bb; you try to retrieve the static constant defined with the value of $bb.

Instead, do:

echo $this->bb;

Note: you don't need to call parent::_construct if B is the only class that calls it. Simply don't declare __construct in B class.

javascript filter array of objects

You could utilize jQuery.filter() function to return elements from a subset of the matching elements.

_x000D_
_x000D_
var names = [_x000D_
    { name : "Joe", age:20, email: "[email protected]"},_x000D_
    { name : "Mike", age:50, email: "[email protected]"},_x000D_
    { name : "Joe", age:45, email: "[email protected]"}_x000D_
   ];_x000D_
   _x000D_
   _x000D_
var filteredNames = $(names).filter(function( idx ) {_x000D_
    return names[idx].name === "Joe" && names[idx].age < 30;_x000D_
}); _x000D_
_x000D_
$(filteredNames).each(function(){_x000D_
     $('#output').append(this.name);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="output"/>
_x000D_
_x000D_
_x000D_

Defining a variable with or without export

To illustrate what the other answers are saying:

$ foo="Hello, World"
$ echo $foo
Hello, World
$ bar="Goodbye"
$ export foo
$ bash
bash-3.2$ echo $foo
Hello, World
bash-3.2$ echo $bar

bash-3.2$ 

How to get main window handle from process id?

I checked how .NET determines the main window.

My finding showed that it also uses EnumWindows().

This code should do it similarly to the .NET way:

struct handle_data {
    unsigned long process_id;
    HWND window_handle;
};

HWND find_main_window(unsigned long process_id)
{
    handle_data data;
    data.process_id = process_id;
    data.window_handle = 0;
    EnumWindows(enum_windows_callback, (LPARAM)&data);
    return data.window_handle;
}

BOOL CALLBACK enum_windows_callback(HWND handle, LPARAM lParam)
{
    handle_data& data = *(handle_data*)lParam;
    unsigned long process_id = 0;
    GetWindowThreadProcessId(handle, &process_id);
    if (data.process_id != process_id || !is_main_window(handle))
        return TRUE;
    data.window_handle = handle;
    return FALSE;   
}

BOOL is_main_window(HWND handle)
{   
    return GetWindow(handle, GW_OWNER) == (HWND)0 && IsWindowVisible(handle);
}

Using COALESCE to handle NULL values in PostgreSQL

If you're using 0 and an empty string '' and null to designate undefined you've got a data problem. Just update the columns and fix your schema.

UPDATE pt.incentive_channel
SET   pt.incentive_marketing = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_advertising = NULL
WHERE pt.incentive_marketing = '';

UPDATE pt.incentive_channel
SET   pt.incentive_channel = NULL
WHERE pt.incentive_marketing = '';

This will make joining and selecting substantially easier moving forward.

Preserve Line Breaks From TextArea When Writing To MySQL

Two solutions for this:

  1. PHP function nl2br():

    e.g.,

    echo nl2br("This\r\nis\n\ra\nstring\r");
    
    // will output
    This<br />
    is<br />
    a<br />
    string<br />
    
  2. Wrap the input in <pre></pre> tags.

    See: W3C Wiki - HTML/Elements/pre

Entity Framework. Delete all rows in table

var all = from c in dataDb.Table select c;
dataDb.Table.RemoveRange(all);
dataDb.SaveChanges();

Quick way to clear all selections on a multiselect enabled <select> with jQuery?

In order to clear all selection, I am using like this and its working fine for me. here is the script:

 $("#ddlMultiselect").multiselect("clearSelection");

 $("#ddlMultiselect").multiselect( 'refresh' );

Android: Remove all the previous activities from the back stack

You can try finishAffinity(), it closes all current activities and works on and above Android 4.1

Total width of element (including padding and border) in jQuery

Just for simplicity I encapsulated Andreas Grech's great answer above in some functions. For those who want a bit of cut-and-paste happiness.

function getTotalWidthOfObject(object) {

    if(object == null || object.length == 0) {
        return 0;
    }

    var value       = object.width();
    value           += parseInt(object.css("padding-left"), 10) + parseInt(object.css("padding-right"), 10); //Total Padding Width
    value           += parseInt(object.css("margin-left"), 10) + parseInt(object.css("margin-right"), 10); //Total Margin Width
    value           += parseInt(object.css("borderLeftWidth"), 10) + parseInt(object.css("borderRightWidth"), 10); //Total Border Width
    return value;
}

function  getTotalHeightOfObject(object) {

    if(object == null || object.length == 0) {
        return 0;
    }

    var value       = object.height();
    value           += parseInt(object.css("padding-top"), 10) + parseInt(object.css("padding-bottom"), 10); //Total Padding Width
    value           += parseInt(object.css("margin-top"), 10) + parseInt(object.css("margin-bottom"), 10); //Total Margin Width
    value           += parseInt(object.css("borderTopWidth"), 10) + parseInt(object.css("borderBottomWidth"), 10); //Total Border Width
    return value;
}

Testing HTML email rendering

You could also use PutsMail to test your emails before sending them.

PutsMail is a tool to test HTML emails that will be sent as campaigns, newsletters and others (please, don't use it to spam, help us to make a better world).

Main features:

  • Check HTML & CSS compatibility with email clients
  • Easily send HTML emails for approval or to check how it looks like in email clients

Mocking HttpClient in unit tests

I agree with some of the other answers that the best approach is to mock HttpMessageHandler rather than wrap HttpClient. This answer is unique in that it still injects HttpClient, allowing it to be a singleton or managed with dependency injection.

HttpClient is intended to be instantiated once and re-used throughout the life of an application.

(Source).

Mocking HttpMessageHandler can be a little tricky because SendAsync is protected. Here's a complete example, using xunit and Moq.

using System;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Moq;
using Moq.Protected;
using Xunit;
// Use nuget to install xunit and Moq

namespace MockHttpClient {
    class Program {
        static void Main(string[] args) {
            var analyzer = new SiteAnalyzer(Client);
            var size = analyzer.GetContentSize("http://microsoft.com").Result;
            Console.WriteLine($"Size: {size}");
        }

        private static readonly HttpClient Client = new HttpClient(); // Singleton
    }

    public class SiteAnalyzer {
        public SiteAnalyzer(HttpClient httpClient) {
            _httpClient = httpClient;
        }

        public async Task<int> GetContentSize(string uri)
        {
            var response = await _httpClient.GetAsync( uri );
            var content = await response.Content.ReadAsStringAsync();
            return content.Length;
        }

        private readonly HttpClient _httpClient;
    }

    public class SiteAnalyzerTests {
        [Fact]
        public async void GetContentSizeReturnsCorrectLength() {
            // Arrange
            const string testContent = "test content";
            var mockMessageHandler = new Mock<HttpMessageHandler>();
            mockMessageHandler.Protected()
                .Setup<Task<HttpResponseMessage>>("SendAsync", ItExpr.IsAny<HttpRequestMessage>(), ItExpr.IsAny<CancellationToken>())
                .ReturnsAsync(new HttpResponseMessage {
                    StatusCode = HttpStatusCode.OK,
                    Content = new StringContent(testContent)
                });
            var underTest = new SiteAnalyzer(new HttpClient(mockMessageHandler.Object));

            // Act
            var result = await underTest.GetContentSize("http://anyurl");

            // Assert
            Assert.Equal(testContent.Length, result);
        }
    }
}

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

Iterating over a numpy array

If you only need the indices, you could try numpy.ndindex:

>>> a = numpy.arange(9).reshape(3, 3)
>>> [(x, y) for x, y in numpy.ndindex(a.shape)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]

Export and import table dump (.sql) using pgAdmin

If you have Git bash installed, you can do something like this:

/c/Program\ Files\ \(x86\)/PostgreSQL/9.3/bin/psql -U <pg_role_name> -d <pg_database_name> < <path_to_your>.sql

TypeError: '<=' not supported between instances of 'str' and 'int'

input() by default takes the input in form of strings.

if (0<= vote <=24):

vote takes a string input (suppose 4,5,etc) and becomes uncomparable.

The correct way is: vote = int(input("Enter your message")will convert the input to integer (4 to 4 or 5 to 5 depending on the input)

Detecting superfluous #includes in C/C++?

The problem with detecting superfluous includes is that it can't be just a type dependency checker. A superfluous include is a file which provides nothing of value to the compilation and does not alter another item which other files depend. There are many ways a header file can alter a compile, say by defining a constant, redefining and/or deleting a used macro, adding a namespace which alters the lookup of a name some way down the line. In order to detect items like the namespace you need much more than a preprocessor, you in fact almost need a full compiler.

Lint is more of a style checker and certainly won't have this full capability.

I think you'll find the only way to detect a superfluous include is to remove, compile and run suites.

Getting the last element of a list

Ok, but what about common in almost every language way items[len(items) - 1]? This is IMO the easiest way to get last element, because it does not require anything pythonic knowledge.

jQuery find and replace string

You could do something like this:

$("span, p").each(function() {
    var text = $(this).text();
    text = text.replace("lollypops", "marshmellows");
    $(this).text(text);
});

It will be better to mark all tags with text that needs to be examined with a suitable class name.

Also, this may have performance issues. jQuery or javascript in general aren't really suitable for this kind of operations. You are better off doing it server side.

How to create a video from images with FFmpeg?

-pattern_type glob

This great option makes it easier to select the images in many cases.

Slideshow video with one image per second

ffmpeg -framerate 1 -pattern_type glob -i '*.png' \
  -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4

Add some music to it, cutoff when the presumably longer audio when the images end:

ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
  -c:a copy -shortest -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4

Here are two demos on YouTube:

Be a hippie and use the Theora patent-unencumbered video format:

ffmpeg -framerate 1 -pattern_type glob -i '*.png' -i audio.ogg \
  -c:a copy -shortest -c:v libtheora -r 30 -pix_fmt yuv420p out.ogg

Your images should of course be sorted alphabetically, typically as:

0001-first-thing.jpg
0002-second-thing.jpg
0003-and-third.jpg

and so on.

I would also first ensure that all images to be used have the same aspect ratio, possibly by cropping them with imagemagick or nomacs beforehand, so that ffmpeg will not have to make hard decisions. In particular, the width has to be divisible by 2, otherwise conversion fails with: "width not divisible by 2".

Normal speed video with one image per frame at 30 FPS

ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
  -c:v libx264 -pix_fmt yuv420p out.mp4

Here's what it looks like:

GIF generated with: https://askubuntu.com/questions/648603/how-to-create-an-animated-gif-from-mp4-video-via-command-line/837574#837574

Add some audio to it:

ffmpeg -framerate 30 -pattern_type glob -i '*.png' \
  -i audio.ogg -c:a copy -shortest -c:v libx264 -pix_fmt yuv420p out.mp4

Result: https://www.youtube.com/watch?v=HG7c7lldhM4

These are the test media I've used:a

wget -O opengl-rotating-triangle.zip https://github.com/cirosantilli/media/blob/master/opengl-rotating-triangle.zip?raw=true
unzip opengl-rotating-triangle.zip
cd opengl-rotating-triangle
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg

Images generated with: How to use GLUT/OpenGL to render to a file?

It is cool to observe how much the video compresses the image sequence way better than ZIP as it is able to compress across frames with specialized algorithms:

  • opengl-rotating-triangle.mp4: 340K
  • opengl-rotating-triangle.zip: 7.3M

Convert one music file to a video with a fixed image for YouTube upload

Answered at: https://superuser.com/questions/700419/how-to-convert-mp3-to-youtube-allowed-video-format/1472572#1472572

Full realistic slideshow case study setup step by step

There's a bit more to creating slideshows than running a single ffmpeg command, so here goes a more interesting detailed example inspired by this timeline.

Get the input media:

mkdir -p orig
cd orig
wget -O 1.png https://upload.wikimedia.org/wikipedia/commons/2/22/Australopithecus_afarensis.png
wget -O 2.jpg https://upload.wikimedia.org/wikipedia/commons/6/61/Homo_habilis-2.JPG
wget -O 3.jpg https://upload.wikimedia.org/wikipedia/commons/c/cb/Homo_erectus_new.JPG
wget -O 4.png https://upload.wikimedia.org/wikipedia/commons/1/1f/Homo_heidelbergensis_-_forensic_facial_reconstruction-crop.png
wget -O 5.jpg https://upload.wikimedia.org/wikipedia/commons/thumb/5/5a/Sabaa_Nissan_Militiaman.jpg/450px-Sabaa_Nissan_Militiaman.jpg
wget -O audio.ogg https://upload.wikimedia.org/wikipedia/commons/7/74/Alnitaque_%26_Moon_Shot_-_EURO_%28Extended_Mix%29.ogg
cd ..

# Convert all to PNG for consistency.
# https://unix.stackexchange.com/questions/29869/converting-multiple-image-files-from-jpeg-to-pdf-format
# Hardlink the ones that are already PNG.
mkdir -p png
mogrify -format png -path png orig/*.jpg
ln -P orig/*.png png

Now we have a quick look at all image sizes to decide on the final aspect ratio:

identify png/*

which outputs:

png/1.png PNG 557x495 557x495+0+0 8-bit sRGB 653KB 0.000u 0:00.000
png/2.png PNG 664x800 664x800+0+0 8-bit sRGB 853KB 0.000u 0:00.000
png/3.png PNG 544x680 544x680+0+0 8-bit sRGB 442KB 0.000u 0:00.000
png/4.png PNG 207x238 207x238+0+0 8-bit sRGB 76.8KB 0.000u 0:00.000
png/5.png PNG 450x600 450x600+0+0 8-bit sRGB 627KB 0.000u 0:00.000

so the classic 480p (640x480 == 4/3) aspect ratio seems appropriate.

Do one conversion with minimal resizing to make widths even (TODO automate for any width, here I just manually looked at identify output and reduced width and height by one):

mkdir -p raw
convert png/1.png -resize 556x494 raw/1.png
ln -P png/2.png png/3.png png/4.png png/5.png raw
ffmpeg -framerate 1 -pattern_type glob -i 'raw/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p raw.mp4

This produces terrible output, because as seen from:

ffprobe raw.mp4

ffmpeg just takes the size of the first image, 556x494, and then converts all others to that exact size, breaking their aspect ratio.

Now let's convert the images to the target 480p aspect ratio automatically by cropping as per ImageMagick: how to minimally crop an image to a certain aspect ratio?

mkdir -p auto
mogrify -path auto -geometry 640x480^ -gravity center -crop 640x480+0+0 png/*.png
ffmpeg -framerate 1 -pattern_type glob -i 'auto/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p auto.mp4

So now, the aspect ratio is good, but inevitably some cropping had to be done, which kind of cut up interesting parts of the images.

The other option is to pad with black background to have the same aspect ratio as shown at: Resize to fit in a box and set background to black on "empty" part

mkdir -p black
ffmpeg -framerate 1 -pattern_type glob -i 'black/*.png' -i orig/audio.ogg -c:v libx264 -c:a copy -shortest -r 30 -pix_fmt yuv420p black.mp4

Generally speaking though, you will ideally be able to select images with the same or similar aspect ratios to avoid those problems in the first place.

About the CLI options

Note however that despite the name, -glob this is not as general as shell Glob patters, e.g.: -i '*' fails: https://trac.ffmpeg.org/ticket/3620 (apparently because filetype is deduced from extension).

-r 30 makes the -framerate 1 video 30 FPS to overcome bugs in players like VLC for low framerates: VLC freezes for low 1 FPS video created from images with ffmpeg Therefore it repeats each frame 30 times to keep the desired 1 image per second effect.

Next steps

You will also want to:

TODO: learn to cut and concatenate multiple audio files into the video without intermediate files, I'm pretty sure it's possible:

Tested on

ffmpeg 3.4.4, vlc 3.0.3, Ubuntu 18.04.

Bibliography

Disable text input history

<input type="text" autocomplete="off"/>

Should work. Alternatively, use:

<form autocomplete="off" … >

for the entire form (see this related question).

Count immediate child div elements using jQuery

$("div", "#superpics").size();

Date minus 1 year?

an easiest way which i used and worked well

date('Y-m-d', strtotime('-1 year'));

this worked perfect.. hope this will help someone else too.. :)

C# Ignore certificate errors?

Allowing all certificates is very powerful but it could also be dangerous. If you would like to only allow valid certificates plus some certain certificates it could be done like this.

.Net core:

using (var httpClientHandler = new HttpClientHandler())
{
    httpClientHandler.ServerCertificateCustomValidationCallback = (message, cert, chain, sslPolicyErrors) => {
        if (sslPolicyErrors == SslPolicyErrors.None)
        {
            return true;   //Is valid
        }

        if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
        {
            return true;
        }
        return false;
    };
    using (var httpClient = new HttpClient(httpClientHandler))
    {
        var httpResponse = httpClient.GetAsync("https://example.com").Result;
    }
}

.Net framework:

System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate (
    object sender,
    X509Certificate cert,
    X509Chain chain,
    SslPolicyErrors sslPolicyErrors)
{
    if (sslPolicyErrors == SslPolicyErrors.None)
    {
        return true;   //Is valid
    }

    if (cert.GetCertHashString() == "99E92D8447AEF30483B1D7527812C9B7B3A915A7")
    {
        return true;
    }

    return false;
};

Update:

How to get cert.GetCertHashString() value in Chrome:

Click on Secure or Not Secure in the address bar.

enter image description here

enter image description here

Then click on Certificate -> Details -> Thumbprint and copy the value. Remember to do cert.GetCertHashString().ToLower().

enter image description here

WAMP shows error 'MSVCR100.dll' is missing when install

I had the same problem but none of the answer above worked. Here's what did the job for me:

  1. download msvcr110.dll, msvcr120.dll, msvcp120.dll and vcruntime140.dll from dll-files.com
  2. Copy them into System32
  3. Uninstall wamp
  4. Reinstall wamp

How to open Emacs inside Bash

Just type emacs -nw. This won't open an X window.

Text overflow ellipsis on two lines

Use this if above is not working

 display: -webkit-box;
 max-width: 100%;
 margin: 0 auto;
 -webkit-line-clamp: 2;
 /* autoprefixer: off */
 -webkit-box-orient: vertical;
 /* autoprefixer: on */
 overflow: hidden;
 text-overflow: ellipsis;

Read and Write CSV files including unicode with Python 2.7

Because str in python2 is bytes actually. So if want to write unicode to csv, you must encode unicode to str using utf-8 encoding.

def py2_unicode_to_str(u):
    # unicode is only exist in python2
    assert isinstance(u, unicode)
    return u.encode('utf-8')

Use class csv.DictWriter(csvfile, fieldnames, restval='', extrasaction='raise', dialect='excel', *args, **kwds):

  • py2
    • The csvfile: open(fp, 'w')
    • pass key and value in bytes which are encoded with utf-8
      • writer.writerow({py2_unicode_to_str(k): py2_unicode_to_str(v) for k,v in row.items()})
  • py3
    • The csvfile: open(fp, 'w')
    • pass normal dict contains str as row to writer.writerow(row)

Finally code

import sys

is_py2 = sys.version_info[0] == 2

def py2_unicode_to_str(u):
    # unicode is only exist in python2
    assert isinstance(u, unicode)
    return u.encode('utf-8')

with open('file.csv', 'w') as f:
    if is_py2:
        data = {u'Python??': u'Python??', u'Python??2': u'Python??2'}

        # just one more line to handle this
        data = {py2_unicode_to_str(k): py2_unicode_to_str(v) for k, v in data.items()}

        fields = list(data[0])
        writer = csv.DictWriter(f, fieldnames=fields)

        for row in data:
            writer.writerow(row)
    else:
        data = {'Python??': 'Python??', 'Python??2': 'Python??2'}

        fields = list(data[0])
        writer = csv.DictWriter(f, fieldnames=fields)

        for row in data:
            writer.writerow(row)

Conclusion

In python3, just use the unicode str.

In python2, use unicode handle text, use str when I/O occurs.

What is the role of the bias in neural networks?

If you're working with images, you might actually prefer to not use a bias at all. In theory, that way your network will be more independent of data magnitude, as in whether the picture is dark, or bright and vivid. And the net is going to learn to do it's job through studying relativity inside your data. Lots of modern neural networks utilize this.

For other data having biases might be critical. It depends on what type of data you're dealing with. If your information is magnitude-invariant --- if inputting [1,0,0.1] should lead to the same result as if inputting [100,0,10], you might be better off without a bias.

Refreshing all the pivot tables in my excel workbook with a macro

Yes.

ThisWorkbook.RefreshAll

Or, if your Excel version is old enough,

Dim Sheet as WorkSheet, Pivot as PivotTable
For Each Sheet in ThisWorkbook.WorkSheets
    For Each Pivot in Sheet.PivotTables
        Pivot.RefreshTable
        Pivot.Update
    Next
Next

Java collections convert a string to a list of characters

IntStream can be used to access each character and add them to the list.

String str = "abc";
List<Character> charList = new ArrayList<>();
IntStream.range(0,str.length()).forEach(i -> charList.add(str.charAt(i)));

SQL Server: Query fast, but slow from procedure

I was facing the same issue & this post was very helpful to me but none of the posted answers solved my specific issue. I wanted to post the solution that worked for me in hopes that it can help someone else.

https://stackoverflow.com/a/24016676/814299

At the end of your query, add OPTION (OPTIMIZE FOR (@now UNKNOWN))

download csv file from web api in angular js

The a.download is not supported by IE. At least at the HTML5 "supported" pages. :(

Check if element is visible in DOM

Just for the reference it should be noted that getBoundingClientRect() can work in certain cases.

For example, a simple check that the element is hidden using display: none could look somewhat like this:

var box = element.getBoundingClientRect();
var visible = box.width && box.height;

This is also handy because it also covers zero-width, zero-height and position: fixed cases. However, it shall not report elements hidden with opacity: 0 or visibility: hidden (but neither would offsetParent).

POST data to a URL in PHP

cURL-less you can use in php5

$url = 'URL';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
        'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

redirect while passing arguments

I found that none of the answers here applied to my specific use case, so I thought I would share my solution.

I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:

/app/4903294/my-great-car?email=coolguy%40gmail.com to

/public/4903294/my-great-car?email=coolguy%40gmail.com

Here's the solution that worked for me.

return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))

Hope this helps someone!

Python: Get HTTP headers from urllib2.urlopen call?

One-liner:

$ python -c "import urllib2; print urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1)).open(urllib2.Request('http://google.com'))"

How to indent a few lines in Markdown markup?

Use a no-break space directly   (not the same as !).

(You could insert HTML or some esoteric markdown code, but I can think of better reasons to break compatibility with standard markdown.)

How to set the "Content-Type ... charset" in the request header using a HTML link

This is not possible from HTML on. The closest what you can get is the accept-charset attribute of the <form>. Only MSIE browser adheres that, but even then it is doing it wrong (e.g. CP1252 is actually been used when it says that it has sent ISO-8859-1). Other browsers are fully ignoring it and they are using the charset as specified in the Content-Type header of the response. Setting the character encoding right is basically fully the responsiblity of the server side. The client side should just send it back in the same charset as the server has sent the response in.

To the point, you should really configure the character encoding stuff entirely from the server side on. To overcome the inability to edit URIEncoding attribute, someone here on SO wrote a (complex) filter: Detect the URI encoding automatically in Tomcat. You may find it useful as well (note: I haven't tested it).


Update: Noted should be that the meta tag as given in your question is ignored when the content is been transferred over HTTP. Instead, the HTTP response Content-Type header will be used to determine the content type and character encoding. You can determine the HTTP header with for example Firebug, in the Net panel.

alt text

How to set headers in http get request?

Pay attention that in http.Request header "Host" can not be set via Set method

req.Header.Set("Host", "domain.tld")

but can be set directly:

req.Host = "domain.tld":

req, err := http.NewRequest("GET", "http://10.0.0.1/", nil)
if err != nil {
    ...
}

req.Host = "domain.tld"
client := &http.Client{}
resp, err := client.Do(req)

Checking for a null object in C++

C++ references naturally can't be null, you don't need the check. The function can only be called by passing a reference to an existing object.

Why is char[] preferred over String for passwords?

There is nothing that char array gives you vs String unless you clean it up manually after use, and I haven't seen anyone actually doing that. So to me the preference of char[] vs String is a bit exaggerated.

Take a look at the widely used Spring Security library here and ask yourself - are Spring Security guys incompetent or char[] passwords just don't make much sense. When some nasty hacker grabs memory dumps of your RAM be sure s/he'll get all the passwords even if you use sophisticated ways to hide them.

However, Java changes all the time, and some scary features like String Deduplication feature of Java 8 might intern String objects without your knowledge. But that's a different conversation.

Explanation of polkitd Unregistered Authentication Agent

Policykit is a system daemon and policykit authentication agent is used to verify identity of the user before executing actions. The messages logged in /var/log/secure show that an authentication agent is registered when user logs in and it gets unregistered when user logs out. These messages are harmless and can be safely ignored.

How to get the path of a running JAR file?

return new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation()
    .toURI()).getPath();

Replace "MyClass" with the name of your class.

Obviously, this will do odd things if your class was loaded from a non-file location.

How do you add a JToken to an JObject?

I think you're getting confused about what can hold what in JSON.Net.

  • A JToken is a generic representation of a JSON value of any kind. It could be a string, object, array, property, etc.
  • A JProperty is a single JToken value paired with a name. It can only be added to a JObject, and its value cannot be another JProperty.
  • A JObject is a collection of JProperties. It cannot hold any other kind of JToken directly.

In your code, you are attempting to add a JObject (the one containing the "banana" data) to a JProperty ("orange") which already has a value (a JObject containing {"colour":"orange","size":"large"}). As you saw, this will result in an error.

What you really want to do is add a JProperty called "banana" to the JObject which contains the other fruit JProperties. Here is the revised code:

JObject foodJsonObj = JObject.Parse(jsonText);
JObject fruits = foodJsonObj["food"]["fruit"] as JObject;
fruits.Add("banana", JObject.Parse(@"{""colour"":""yellow"",""size"":""medium""}"));

where is gacutil.exe?

On Windows 2012 R2, you can't install Visual Studio or SDK. You can use powershell to register assemblies into GAC. It didn't need any special installation for me.

Set-location "C:\Temp"
[System.Reflection.Assembly]::Load("System.EnterpriseServices, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")
$publish = New-Object System.EnterpriseServices.Internal.Publish
$publish.GacInstall("C:\Temp\myGacLibrary.dll")

If you need to get the name and PublicKeyToken see this question.

How to use *ngIf else?

Syntax for ngIf/Else

<div *ngIf=”condition; else elseBlock”>Truthy condition</div>
<ng-template #elseBlock>Falsy condition</ng-template>

enter image description here

Using NgIf / Else/ Then explicit syntax

To add then template we just have to bind it to a template explicitly.

<div *ngIf=”condition; then thenBlock else elseBlock”> ... </div> 
<ng-template #thenBlock>Then template</ng-template>
<ng-template #elseBlock>Else template</ng-template>

enter image description here

Observables with NgIf and Async Pipe

For more details

enter image description here

Regex for quoted string with escaping quotes

As provided by ePharaoh, the answer is

/"([^"\\]*(\\.[^"\\]*)*)"/

To have the above apply to either single quoted or double quoted strings, use

/"([^"\\]*(\\.[^"\\]*)*)"|\'([^\'\\]*(\\.[^\'\\]*)*)\'/

How to run a method every X seconds

Here I used a thread in onCreate() an Activity repeatly, timer does not allow everything in some cases Thread is the solution

     Thread t = new Thread() {
        @Override
        public void run() {
            while (!isInterrupted()) {
                try {
                    Thread.sleep(10000);  //1000ms = 1 sec
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {

                            SharedPreferences mPrefs = getSharedPreferences("sam", MODE_PRIVATE);
                            Gson gson = new Gson();
                            String json = mPrefs.getString("chat_list", "");
                            GelenMesajlar model = gson.fromJson(json, GelenMesajlar.class);
                            String sam = "";

                            ChatAdapter adapter = new ChatAdapter(Chat.this, model.getData());
                            listview.setAdapter(adapter);
                           // listview.setStackFromBottom(true);
                          //  Util.showMessage(Chat.this,"Merhabalar");
                        }
                    });

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

    t.start();

In case it needed it can be stoped by

@Override
protected void onDestroy() {
    super.onDestroy();
    Thread.interrupted();
    //t.interrupted();
}

Set HTML dropdown selected option using JSTL

Real simple. You just need to have the string 'selected' added to the right option. In the following code, ${myBean.foo == val ? 'selected' : ' '} will add the string 'selected' if the option's value is the same as the bean value;

<select name="foo" id="foo" value="${myBean.foo}">
    <option value="">ALL</option>
    <c:forEach items="${fooList}" var="val"> 
        <option value="${val}" ${myBean.foo == val ? 'selected' : ' '}><c:out value="${val}" ></c:out></option>   
    </c:forEach>                     
</select>

How can I declare and define multiple variables in one line using C++?

As others have mentioned, from C++17 onwards you can make use of structured bindings for multiple variable assignments.

Combining this with std::array and template argument deduction we can write a function that assigns a value to an arbitrary number of variables without repeating the type or value.

#include <iostream>
#include <array>

template <int N, typename T> auto assign(T value)
{
    std::array<T, N> out;
    out.fill(value);
    return out;
}

int main()
{
    auto [a, b, c] = assign<3>(1);

    for (const auto& v : {a, b, c})
    {
        std::cout << v << std::endl;
    }

    return 0;
}

Demo

Printing object properties in Powershell

# Json to object
$obj = $obj | ConvertFrom-Json
Write-host $obj.PropertyName

What is an alternative to execfile in Python 3?

You could write your own function:

def xfile(afile, globalz=None, localz=None):
    with open(afile, "r") as fh:
        exec(fh.read(), globalz, localz)

If you really needed to...

The R %in% operator

You can use all

> all(1:6 %in% 0:36)
[1] TRUE
> all(1:60 %in% 0:36)
[1] FALSE

On a similar note, if you want to check whether any of the elements is TRUE you can use any

> any(1:6 %in% 0:36)
[1] TRUE
> any(1:60 %in% 0:36)
[1] TRUE
> any(50:60 %in% 0:36)
[1] FALSE

Delete item from array and shrink array

without using the System.arraycopy method you can delete an element from an array with the following

    int i = 0;
    int x = 0;
    while(i < oldArray.length){
        if(oldArray[i] == 3)i++;

        intArray[x] = oldArray[i];
        i++;
        x++;
    }

where 3 is the value you want to remove.

Find if value in column A contains value from column B?

You could try this

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)

-or-

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row "   & MATCH(<single column I value>,<entire column E range>,0))

you could replace <single column I value> and <entire column E range> with named ranged. That'd probably be the easiest.

Just drag that formula all the way down the length of your I column in whatever column you want.

Passing in class names to react components

pill ${this.props.styleName} will get "pill undefined" when you don't set the props

I prefer

className={ "pill " + ( this.props.styleName || "") }

or

className={ "pill " + ( this.props.styleName ? this.props.styleName : "") }

PHP string "contains"

PHP 8 or newer:

Use the str_contains function.

if (str_contains($str, "."))
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

PHP 7 or older:

if (strpos($str, '.') !== FALSE)
{
    echo 'Found it';
}

else
{
    echo 'Not found.';
}

Note that you need to use the !== operator. If you use != or <> and the '.' is found at position 0, the comparison will evaluate to true because 0 is loosely equal to false.

Plugin execution not covered by lifecycle configuration (JBossas 7 EAR archetype)

I was able to resolve the same problem with maven-antrun-plugin and jaxb2-maven-plugin in Eclipse Kepler 4.3 by appying this solution: http://wiki.eclipse.org/M2E_plugin_execution_not_covered#Eclipse_4.2_add_default_mapping
So the content of my %elipse_workspace_name%/.metadata/.plugins/org.eclipse.m2e.core/lifecycle-mapping-metadata.xml is as follows:

<?xml version="1.0" encoding="UTF-8"?>
<lifecycleMappingMetadata>
  <pluginExecutions>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-antrun-plugin</artifactId>
        <versionRange>1.3</versionRange>
        <goals>
          <goal>run</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
    <pluginExecution>
      <pluginExecutionFilter>
        <groupId>org.codehaus.mojo</groupId>
        <artifactId>jaxb2-maven-plugin</artifactId>
        <versionRange>1.2</versionRange>
        <goals>
          <goal>xjc</goal>
        </goals>
      </pluginExecutionFilter>
      <action>
        <ignore />
      </action>
    </pluginExecution>
  </pluginExecutions>
</lifecycleMappingMetadata>

*Had to restart Eclipse to see the errors gone.

Vertical line using XML drawable

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
  android:shape="rectangle" >
    <stroke android:width="1dp" android:color="@color/white" />
    <size android:width="2dp" />
</shape>

Work's for me . Put it as background of view with fill_parent or fixed sized in dp height

How to call two methods on button's onclick method in HTML or JavaScript?

As stated by Harry Joy, you can do it on the onclick attr like so:

<input type="button" onclick="func1();func2();" value="Call2Functions" />

Or, in your JS like so:

document.getElementById( 'Call2Functions' ).onclick = function()
{
    func1();
    func2();
};

Or, if you are assigning an onclick programmatically, and aren't sure if a previous onclick existed (and don't want to overwrite it):

var Call2FunctionsEle = document.getElementById( 'Call2Functions' ),
    func1 = Call2FunctionsEle.onclick;

Call2FunctionsEle.onclick = function()
{
    if( typeof func1 === 'function' )
    {
        func1();
    }
    func2();
};

If you need the functions run in scope of the element which was clicked, a simple use of apply could be made:

document.getElementById( 'Call2Functions' ).onclick = function()
{
    func1.apply( this, arguments );
    func2.apply( this, arguments );
};

How to extract text from a PDF file?

You can use PDFtoText https://github.com/jalan/pdftotext

PDF to text keeps text format indentation, doesn't matter if you have tables.

How can I change the default width of a Twitter Bootstrap modal box?

Achieved expected result using,

.modal-dialog {
    width: 41% !important;
}

Asynchronous Process inside a javascript for loop

async await is here (ES7), so you can do this kind of things very easily now.

  var i;
  var j = 10;
  for (i = 0; i < j; i++) {
    await asycronouseProcess();
    alert(i);
  }

Remember, this works only if asycronouseProcess is returning a Promise

If asycronouseProcess is not in your control then you can make it return a Promise by yourself like this

function asyncProcess() {
  return new Promise((resolve, reject) => {
    asycronouseProcess(()=>{
      resolve();
    })
  })
}

Then replace this line await asycronouseProcess(); by await asyncProcess();

Understanding Promises before even looking into async await is must (Also read about support for async await)

Saving a high resolution image in R

A simpler way is

ggplot(data=df, aes(x=xvar, y=yvar)) + 
geom_point()

ggsave(path = path, width = width, height = height, device='tiff', dpi=700)

Xcode 6 Bug: Unknown class in Interface Builder file

I solved this problem by typing in the Module name (unfortunately the drop list will show nothing...) in the Custom Class of the identity inspector for all the View controller and views.

You may also need to indicate the target provider. To achieve this objective you can open the storyboard in sourcecode mode and add the "customModuleProvider" attribute in both ViewController and View angle brackets.

How to log cron jobs?

If you'd still like to check your cron jobs you should provide a valid email account when setting the Cron jobs in cPanel.

When you specify a valid email you will receive the output of the cron job that is executed. Thus you will be able to check it and make sure everything has been executed correctly. Note that you will not receive an email if there is no output from the cron job command.

Please bear in mind that you will receive an email for each of the executed cron jobs. This may flood your inbox in case your crons run too often

Best way to show a loading/progress indicator?

Use ProgressDialog

ProgressDialog.show(Context context, CharSequence title, CharSequence message);

enter image description here

However this is considered as an anti pattern today (2013): http://www.youtube.com/watch?v=pEGWcMTxs3I

How do I check if an index exists on a table field in MySQL?

Try use this:

SELECT TRUE
FROM INFORMATION_SCHEMA.KEY_COLUMN_USAGE 
WHERE TABLE_SCHEMA = "{DB_NAME}" 
AND TABLE_NAME = "{DB_TABLE}"
AND COLUMN_NAME = "{DB_INDEXED_FIELD}";

psql: FATAL: database "<user>" does not exist

This is a basic misunderstanding. Simply typing:

pgres

will result in this response:

pgres <db_name> 

It will succeed without error if the user has the permissions to access the db.

One can go into the details of the exported environment variables but that's unnecessary .. this is too basic to fail for any other reason.

Binary Data in JSON String. Something better than Base64

Just to add the resource and complexity standpoint to the discussion. Since doing PUT/POST and PATCH for storing new resources and altering them, one should remember that the content transfer is an exact representation of the content that is stored and that is received by issuing a GET operation.

A multi-part message is often used as a savior but for simplicity reason and for more complex tasks, I prefer the idea of giving the content as a whole. It is self-explaining and it is simple.

And yes JSON is something crippling but in the end JSON itself is verbose. And the overhead of mapping to BASE64 is a way to small.

Using Multi-Part messages correctly one has to either dismantle the object to send, use a property path as the parameter name for automatic combination or will need to create another protocol/format to just express the payload.

Also liking the BSON approach, this is not that widely and easily supported as one would like it to be.

Basically, we just miss something here but embedding binary data as base64 is well established and way to go unless you really have identified the need to do the real binary transfer (which is hardly often the case).

Simulate limited bandwidth from within Chrome?

I'd recommend Charles Proxy - you can choose to slowdown individual sites, also has a whole bunch of HTTP inspection tools.

Edit:

As of June 2014, Chrome now has the ability to do this natively in DevTools - you'll need Chrome 38 though.

The option is accessible from the Network tab via a drop down at the end of the toolbar.

Angular2 Routing with Hashtag to page anchor

I had the same issue. The solution : using View port Scroller https://angular.io/api/common/ViewportScroller#scrolltoanchor

-- app-routing.module.ts code :

import { PageComponent } from './page/page.component';

const routes: Routes = [
   path: 'page', component: PageComponent },
   path: 'page/:id', component: PageComponent }
];

-- Component HTML

  <a (click) = "scrollTo('typeExec')">
    <mat-icon>lens</mat-icon>
  </a>

-- Component's code :

    import { Component } from '@angular/core';
    import { ViewportScroller } from '@angular/common';


    export class ParametrageComponent {

      constructor(private viewScroller: ViewportScroller) {}

      scrollTo(tag : string)
      {
        this.viewScroller.scrollToAnchor(tag);
      }

    }

How to split csv whose columns may contain ,

You could split on all commas that do have an even number of quotes following them.

You would also like to view at the specf for CSV format about handling comma's.

Useful Link : C# Regex Split - commas outside quotes

iOS: Modal ViewController with transparent background

In iOS 8.0 and above it can be done by setting the property modalPresentationStyle to UIModalPresentationOverCurrentContext

//Set property **definesPresentationContext** YES to avoid presenting over presenting-viewController's navigation bar

self.definesPresentationContext = YES; //self is presenting view controller
presentedController.view.backgroundColor = [YOUR_COLOR with alpha OR clearColor]
presentedController.modalPresentationStyle = UIModalPresentationOverCurrentContext;

[self presentViewController:presentedController animated:YES completion:nil];

See Image Attached

Google Chromecast sender error if Chromecast extension is not installed or using incognito

By default Chrome extensions do not run in Incognito mode. You have to explicitly enable the extension to run in Incognito.

Passing a string with spaces as a function argument in bash

you should put quotes and also, your function declaration is wrong.

myFunction()
{
    echo "$1"
    echo "$2"
    echo "$3"
}

And like the others, it works for me as well. Tell us what version of shell you are using.

Multiple rows to one comma-separated value in Sql Server

Test Data

DECLARE @Table1 TABLE(ID INT, Value INT)
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400)

Query

SELECT  ID
       ,STUFF((SELECT ', ' + CAST(Value AS VARCHAR(10)) [text()]
         FROM @Table1 
         WHERE ID = t.ID
         FOR XML PATH(''), TYPE)
        .value('.','NVARCHAR(MAX)'),1,2,' ') List_Output
FROM @Table1 t
GROUP BY ID

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

SQL Server 2017 and Later Versions

If you are working on SQL Server 2017 or later versions, you can use built-in SQL Server Function STRING_AGG to create the comma delimited list:

DECLARE @Table1 TABLE(ID INT, Value INT);
INSERT INTO @Table1 VALUES (1,100),(1,200),(1,300),(1,400);


SELECT ID , STRING_AGG([Value], ', ') AS List_Output
FROM @Table1
GROUP BY ID;

Result Set

+--------------------------+
¦ ID ¦     List_Output     ¦
¦----+---------------------¦
¦  1 ¦  100, 200, 300, 400 ¦
+--------------------------+

DataGridView checkbox column - value and functionality

If you have a gridview containing more than one checkbox .... you should try this ....

Object[] o=new Object[6];

for (int i = 0; i < dgverlist.RowCount; i++)
{
    for (int j = 2; j < dgverlist.ColumnCount; j++)
    {
        DataGridViewCheckBoxCell ch1 = new DataGridViewCheckBoxCell();
        ch1 = (DataGridViewCheckBoxCell)dgverlist.Rows[i].Cells[j];

        if (ch1.Value != null)
        {
           o[i] = ch1.OwningColumn.HeaderText.ToString();

            MessageBox.Show(o[i].ToString());
        }
    }
}

The SELECT permission was denied on the object 'sysobjects', database 'mssqlsystemresource', schema 'sys'

In my case, simply giving the user permissions on the database fixed it.

So Right click on the database -> Click Properties -> [left hand menu] Click Permissions -> and scroll down to Backup database -> Tick "Grant"

Convert php array to Javascript

You do not have to call parseJSON since the output of json_encode is a javascript literal. Just assign it to a js variable.

<script type="text/javascript">
    //Assign php generated json to JavaScript variable
    var tempArray = <?php echo json_encode($php_array); ?>;

   //You will be able to access the properties as 
    alert(tempArray[0].Key);
</script>

How to check if a character in a string is a digit or letter

By using regular expressions:

boolean isChar = character.matches("[a-zA-z]{1}");
boolean isDigit = character.matches("\\d{1}"); 

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

How to get the current user in ASP.NET MVC

IPrincipal currentUser = HttpContext.Current.User;
bool writeEnable = currentUser.IsInRole("Administrator") ||
        ...
                   currentUser.IsInRole("Operator");

How to change the blue highlight color of a UITableViewCell?

Zonble has already provided an excellent answer. I thought it may be useful to include a short code snippet for adding a UIView to the tableview cell that will present as the selected background view.

cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

    UIView *selectionColor = [[UIView alloc] init];
    selectionColor.backgroundColor = [UIColor colorWithRed:(245/255.0) green:(245/255.0) blue:(245/255.0) alpha:1];
    cell.selectedBackgroundView = selectionColor;
  • cell is my UITableViewCell
  • I created a UIView and set its background color using RGB colours (light gray)
  • I then set the cell selectedBackgroundView to be the UIView that I created with my chosen background colour

This worked well for me. Thanks for the tip Zonble.

unexpected T_VARIABLE, expecting T_FUNCTION

You can not put

$connection = sqlite_open("[path]/data/users.sqlite", 0666);

outside the class construction. You have to put that line inside a function or the constructor but you can not place it where you have now.

How to check if a double is null?

I believe Double.NaN might be able to cover this. That is the only 'null' value double contains.

What is the difference between Cygwin and MinGW?

Cygwin emulates entire POSIX environment, while MinGW is minimal tool set for compilation only (compiles native Win application.) So if you want to make your project cross-platform the choice between the two is obvious, MinGW.

Although you might consider using VS on Windows, GCC on Linux/Unices. Most open source projects do that (e.g. Firefox or Python).

Import regular CSS file in SCSS file?

After having the same issue, I got confused with all the answers here and the comments over the repository of sass in github.

I just want to point out that as December 2014, this issue has been resolved. It is now possible to import css files directly into your sass file. The following PR in github solves the issue.

The syntax is the same as now - @import "your/path/to/the/file", without an extension after the file name. This will import your file directly. If you append *.css at the end, it will translate into the css rule @import url(...).

In case you are using some of the "fancy" new module bundlers such as webpack, you will probably need to use use ~ in the beginning of the path. So, if you want to import the following path node_modules/bootstrap/src/core.scss you would write something like
@import "~bootstrap/src/core".

NOTE:
It appears this isn't working for everybody. If your interpreter is based on libsass it should be working fine (checkout this). I've tested using @import on node-sass and it's working fine. Unfortunately this works and doesn't work on some ruby instances.

Angular 4: InvalidPipeArgument: '[object Object]' for pipe 'AsyncPipe'

You get this message when you've used async in your template, but are referring to an object that isn't an Observable.

So for examples sake, lets' say I had these properties in my class:

job:Job
job$:Observable<Job>

Then in my template, I refer to it this way:

{{job | async }}

instead of:

{{job$ | async }}

You wouldn't need the job:Job property if you use the async pipe, but it serves to illustrate a cause of the error.

Load image from resources

You can always use System.Resources.ResourceManager which returns the cached ResourceManager used by this class. Since chan1 and chan2 represent two different images, you may use System.Resources.ResourceManager.GetObject(string name) which returns an object matching your input with the project resources

Example

object O = Resources.ResourceManager.GetObject("chan1"); //Return an object from the image chan1.png in the project
channelPic.Image = (Image)O; //Set the Image property of channelPic to the returned object as Image

Notice: Resources.ResourceManager.GetObject(string name) may return null if the string specified was not found in the project resources.

Thanks,
I hope you find this helpful :)

CUSTOM_ELEMENTS_SCHEMA added to NgModule.schemas still showing Error

Did you use the webpack... if yes please install

angular2-template-loader

and put it

test: /\.ts$/,
   loaders: ['awesome-typescript-loader', 'angular2-template-loader']

Set select option 'selected', by value

Try this. Simple yet effective javaScript + jQuery the lethal combo.

SelectComponent :

<select id="YourSelectComponentID">
            <option value="0">Apple</option>
            <option value="2">Banana</option>
            <option value="3">Cat</option>
            <option value="4">Dolphin</option>
</select>

Selection :

document.getElementById("YourSelectComponentID").value = 4;

Now your option 4 will be selected. You can do this, to select the values on start by default.

$(function(){
   document.getElementById("YourSelectComponentID").value = 4;
});

or create a simple function put the line in it and call the function on anyEvent to select the option

A mixture of jQuery + javaScript does the magic....

javascript window.location in new tab

I don't think there's a way to do this, unless you're writing a browser extension. You could try using window.open and hoping that the user has their browser set to open new windows in new tabs.

How to wait for a JavaScript Promise to resolve before resuming function?

I'm wondering if there is any way to get a value from a Promise or wait (block/sleep) until it has resolved, similar to .NET's IAsyncResult.WaitHandle.WaitOne(). I know JavaScript is single-threaded, but I'm hoping that doesn't mean that a function can't yield.

The current generation of Javascript in browsers does not have a wait() or sleep() that allows other things to run. So, you simply can't do what you're asking. Instead, it has async operations that will do their thing and then call you when they're done (as you've been using promises for).

Part of this is because of Javascript's single threadedness. If the single thread is spinning, then no other Javascript can execute until that spinning thread is done. ES6 introduces yield and generators which will allow some cooperative tricks like that, but we're quite a ways from being able to use those in a wide swatch of installed browsers (they can be used in some server-side development where you control the JS engine that is being used).


Careful management of promise-based code can control the order of execution for many async operations.

I'm not sure I understand exactly what order you're trying to achieve in your code, but you could do something like this using your existing kickOff() function, and then attaching a .then() handler to it after calling it:

function kickOff() {
  return new Promise(function(resolve, reject) {
    $("#output").append("start");

    setTimeout(function() {
      resolve();
    }, 1000);
  }).then(function() {
    $("#output").append(" middle");
    return " end";
  });
}

kickOff().then(function(result) {
    // use the result here
    $("#output").append(result);
});

This will return output in a guaranteed order - like this:

start
middle
end

Update in 2018 (three years after this answer was written):

If you either transpile your code or run your code in an environment that supports ES7 features such as async and await, you can now use await to make your code "appear" to wait for the result of a promise. It is still developing with promises. It does still not block all of Javascript, but it does allow you to write sequential operations in a friendlier syntax.

Instead of the ES6 way of doing things:

someFunc().then(someFunc2).then(result => {
    // process result here
}).catch(err => {
    // process error here
});

You can do this:

// returns a promise
async function wrapperFunc() {
    try {
        let r1 = await someFunc();
        let r2 = await someFunc2(r1);
        // now process r2
        return someValue;     // this will be the resolved value of the returned promise
    } catch(e) {
        console.log(e);
        throw e;      // let caller know the promise was rejected with this reason
    }
}

wrapperFunc().then(result => {
    // got final result
}).catch(err => {
    // got error
});

AngularJS sorting by property

Don't forget that parseInt() only works for Integer values. To sort string values you need to swap this:

array.sort(function(a, b){
  a = parseInt(a[attribute]);
  b = parseInt(b[attribute]);
  return a - b;
});

with this:

array.sort(function(a, b){
  var alc = a[attribute].toLowerCase(),
      blc = b[attribute].toLowerCase();
  return alc > blc ? 1 : alc < blc ? -1 : 0;
});

Getting value of selected item in list box as string

If you are using ListBox in your application and you want to return the selected value of ListBox and display it in a Label or any thing else then use this code, it will help you

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
         label1.Text  = listBox1.SelectedItem.ToString();
    }

How to access Spring MVC model object in javascript file?

Another solution could be using in JSP: <input type="hidden" id="jsonBom" value='${jsonBom}'/>

and getting the value in Javascript with jQuery:

var jsonBom = $('#jsonBom').val();

MVC 3 file upload and model binding

For multiple files; note the newer "multiple" attribute for input:

Form:

@using (Html.BeginForm("FileImport","Import",FormMethod.Post, new {enctype = "multipart/form-data"}))
{
    <label for="files">Filename:</label>
    <input type="file" name="files" multiple="true" id="files" />
    <input type="submit"  />
}

Controller:

[HttpPost]
public ActionResult FileImport(IEnumerable<HttpPostedFileBase> files)
{
    return View();
}

Is there a program to decompile Delphi?

Here's a list : http://delphi.about.com/od/devutilities/a/decompiling_3.htm (and this page mentions some more : http://www.program-transformation.org/Transform/DelphiDecompilers )

I've used DeDe on occasion, but it's not really all that powerfull, and it's not up-to-date with current Delphi versions (latest version it supports is Delphi 7 I believe)

String.equals() with multiple conditions (and one action on result)

Pattern p = Pattern.compile("tom"); //the regular-expression pattern
Matcher m = p.matcher("(bob)(tom)(harry)"); //The data to find matches with

while (m.find()) {
    //do something???
}   

Use regex to find a match maybe?

Or create an array

 String[] a = new String[]{
        "tom",
        "bob",
        "harry"
 };

 if(a.contains(stringtomatch)){
     //do something
 }

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

This is a briefer variation of the accepted answer: the function below extracts the bits from-to inclusive by creating a bitmask. After applying an AND logic over the original number the result is shifted so the function returns just the extracted bits. Skipped index/integrity checks for clarity.

uint16_t extractInt(uint16_t orig16BitWord, unsigned from, unsigned to) 
{
  unsigned mask = ( (1<<(to-from+1))-1) << from;
  return (orig16BitWord & mask) >> from;
}

How to use executeReader() method to retrieve the value of just one cell

using (var conn = new SqlConnection(SomeConnectionString))
using (var cmd = conn.CreateCommand())
{
    conn.Open();
    cmd.CommandText = "SELECT * FROM learer WHERE id = @id";
    cmd.Parameters.AddWithValue("@id", index);
    using (var reader = cmd.ExecuteReader())
    {
        if (reader.Read())
        {
            learerLabel.Text = reader.GetString(reader.GetOrdinal("somecolumn"))
        }
    }
}

7-Zip command to create and extract a password-protected ZIP file on Windows?

To fully script-automate:

Create:

7z -mhc=on -mhe=on -pPasswordHere a %ZipDest% %WhatYouWantToZip%

Unzip:

7z x %ZipFile% -pPasswordHere

(Depending, you might need to: Set Path=C:\Program Files\7-Zip;%Path% )

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

Since it sounds like your JAVA_HOME variable is not set correctly, follow the instructions for setting that.

Setting JAVA_HOME environment variable on MAC OSX 10.9

I would imagine once you set this, it will stop complaining.

Python: Figure out local timezone

now_dt = datetime.datetime.now()
utc_now = datetime.datetime.utcnow()
now_ts, utc_ts = map(time.mktime, map(datetime.datetime.timetuple, (now_dt, utc_now)))
offset = int((now_ts - utc_ts) / 3600)

hope this will help you.

Format numbers to strings in Python

You can use the str.format() to make Python recognize any objects to strings.

Check if a string is a valid Windows directory (folder) path

Here is a solution that leverages the use of Path.GetFullPath as recommended in the answer by @SLaks.

In the code that I am including here, note that IsValidPath(string path) is designed such that the caller does not have to worry about exception handling.

You may also find that the method that it calls, TryGetFullPath(...), also has merit on its own when you wish to safely attempt to get an absolute path.

/// <summary>
/// Gets a value that indicates whether <paramref name="path"/>
/// is a valid path.
/// </summary>
/// <returns>Returns <c>true</c> if <paramref name="path"/> is a
/// valid path; <c>false</c> otherwise. Also returns <c>false</c> if
/// the caller does not have the required permissions to access
/// <paramref name="path"/>.
/// </returns>
/// <seealso cref="Path.GetFullPath"/>
/// <seealso cref="TryGetFullPath"/>
public static bool IsValidPath(string path)
{
    string result;
    return TryGetFullPath(path, out result);
}

/// <summary>
/// Returns the absolute path for the specified path string. A return
/// value indicates whether the conversion succeeded.
/// </summary>
/// <param name="path">The file or directory for which to obtain absolute
/// path information.
/// </param>
/// <param name="result">When this method returns, contains the absolute
/// path representation of <paramref name="path"/>, if the conversion
/// succeeded, or <see cref="String.Empty"/> if the conversion failed.
/// The conversion fails if <paramref name="path"/> is null or
/// <see cref="String.Empty"/>, or is not of the correct format. This
/// parameter is passed uninitialized; any value originally supplied
/// in <paramref name="result"/> will be overwritten.
/// </param>
/// <returns><c>true</c> if <paramref name="path"/> was converted
/// to an absolute path successfully; otherwise, false.
/// </returns>
/// <seealso cref="Path.GetFullPath"/>
/// <seealso cref="IsValidPath"/>
public static bool TryGetFullPath(string path, out string result)
{
    result = String.Empty;
    if (String.IsNullOrWhiteSpace(path)) { return false; }
    bool status = false;

    try
    {
        result = Path.GetFullPath(path);
        status = true;
    }
    catch (ArgumentException) { }
    catch (SecurityException) { }
    catch (NotSupportedException) { }
    catch (PathTooLongException) { }

    return status;
}

Can I make dynamic styles in React Native?

I know this is extremely late, but for anyone still wondering here's an easy solution.

You could just make an array for the styles :

this.state ={
   color: "#fff"
}

style={[
  styles.jewelstyle, {
  backgroundColor: this.state.BGcolor
}

The second will override any original background color as stated in the stylesheet. Then have a function that changes the color:

generateNewColor(){
  var randomColor = '#'+Math.floor(Math.random()*16777215).toString(16);
  this.setState({BGcolor: randomColor})
}

This will generate a random hex color. Then just call that function whenever and bam, new background color.

Editing in the Chrome debugger

I came across this today, when I was playing around with someone else's website.

I realized I could attach a break-point in the debugger to some line of code before what I wanted to dynamically edit. And since break-points stay even after a reload of the page, I was able to edit the changes I wanted while paused at break-point and then continued to let the page load.

So as a quick work around, and if it works with your situation:

  1. Add a break-point at an earlier point in the script
  2. Reload page
  3. Edit your changes into the code
  4. CTRL + s (save changes)
  5. Unpause the debugger

python list by value not by reference

In terms of performance my favorite answer would be:

b.extend(a)

Check how the related alternatives compare with each other in terms of performance:

In [1]: import timeit

In [2]: timeit.timeit('b.extend(a)', setup='b=[];a=range(0,10)', number=100000000)
Out[2]: 9.623248100280762

In [3]: timeit.timeit('b = a[:]', setup='b=[];a=range(0,10)', number=100000000)
Out[3]: 10.84756088256836

In [4]: timeit.timeit('b = list(a)', setup='b=[];a=range(0,10)', number=100000000)
Out[4]: 21.46313500404358

In [5]: timeit.timeit('b = [elem for elem in a]', setup='b=[];a=range(0,10)', number=100000000)
Out[5]: 66.99795293807983

In [6]: timeit.timeit('for elem in a: b.append(elem)', setup='b=[];a=range(0,10)', number=100000000)
Out[6]: 67.9775960445404

In [7]: timeit.timeit('b = deepcopy(a)', setup='from copy import deepcopy; b=[];a=range(0,10)', number=100000000)
Out[7]: 1216.1108016967773

Git fast forward VS no fast forward merge

The --no-ff option is useful when you want to have a clear notion of your feature branch. So even if in the meantime no commits were made, FF is possible - you still want sometimes to have each commit in the mainline correspond to one feature. So you treat a feature branch with a bunch of commits as a single unit, and merge them as a single unit. It is clear from your history when you do feature branch merging with --no-ff.

If you do not care about such thing - you could probably get away with FF whenever it is possible. Thus you will have more svn-like feeling of workflow.

For example, the author of this article thinks that --no-ff option should be default and his reasoning is close to that I outlined above:

Consider the situation where a series of minor commits on the "feature" branch collectively make up one new feature: If you just do "git merge feature_branch" without --no-ff, "it is impossible to see from the Git history which of the commit objects together have implemented a feature—you would have to manually read all the log messages. Reverting a whole feature (i.e. a group of commits), is a true headache [if --no-ff is not used], whereas it is easily done if the --no-ff flag was used [because it's just one commit]."

Graphic showing how --no-ff groups together all commits from feature branch into one commit on master branch

SQL query to find third highest salary in company

You may use this for all employee with 3rd highest salary:

SELECT * FROM `employee` WHERE salary = (
   SELECT DISTINCT(`salary`) FROM `employee` ORDER BY `salary` DESC LIMIT 1 OFFSET 2
);

Cannot open output file, permission denied

In my case - I found a process called

cb_console_runner

I stopped this process and things were ok again.

How to manually set REFERER header in Javascript?

Above solution does not work for me , I have tried following and it is working in all browsers.

simply made a fake ajax call, it will make a entry into referer header.

var request;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
        try {
            request = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {}
    }
}
request.open("GET", url, true);
request.send();

Failed to resolve: com.android.support:appcompat-v7:27.+ (Dependency Error)

Find root build.gradle file and add google maven repo inside allprojects tag

repositories {
        mavenLocal()
        mavenCentral()
        maven {                                  // <-- Add this
            url 'https://maven.google.com/' 
            name 'Google'
        }
    } 

It's better to use specific version instead of variable version

compile 'com.android.support:appcompat-v7:27.0.0'

If you're using Android Plugin for Gradle 3.0.0 or latter version

repositories {
      mavenLocal()
      mavenCentral()
      google()        //---> Add this
} 

and inject dependency in this way :

implementation 'com.android.support:appcompat-v7:27.0.0'

How do I use Maven through a proxy?

I run cntlm localy, configured with NTLMv2 password hashes to authenticate with the corporate proxy, and use

export MAVEN_OPTS="-DproxyHost=127.0.0.1 -DproxyPort=3128"

to use that proxy from maven. Of course the proxy you use should support cntlm/NTLMv2.

How to generate .NET 4.0 classes from xsd?

If you want to generate the class with auto properties, convert the XSD to XML using this then convert the XML to JSON using this and copy to clipboard the result. Then in VS, inside the file where your class will be created, go to Edit>Paste Special>Paste JSON as classes.

Displaying splash screen for longer than default seconds

Use following line in didFinishLaunchingWithOptions: delegate method:

[NSThread sleepForTimeInterval:5.0];

It will stop splash screen for 5.0 seconds.

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

From this post:

To get the entire PC CPU and Memory usage:

using System.Diagnostics;

Then declare globally:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Processor", "% Processor Time", "_Total"); 

Then to get the CPU time, simply call the NextValue() method:

this.theCPUCounter.NextValue();

This will get you the CPU usage

As for memory usage, same thing applies I believe:

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Memory", "Available MBytes");

Then to get the memory usage, simply call the NextValue() method:

this.theMemCounter.NextValue();

For a specific process CPU and Memory usage:

private PerformanceCounter theCPUCounter = 
   new PerformanceCounter("Process", "% Processor Time",              
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

private PerformanceCounter theMemCounter = 
   new PerformanceCounter("Process", "Working Set",
   Process.GetCurrentProcess().ProcessName);

where Process.GetCurrentProcess().ProcessName is the process name you wish to get the information about.

Note that Working Set may not be sufficient in its own right to determine the process' memory footprint -- see What is private bytes, virtual bytes, working set?

To retrieve all Categories, see Walkthrough: Retrieving Categories and Counters

The difference between Processor\% Processor Time and Process\% Processor Time is Processor is from the PC itself and Process is per individual process. So the processor time of the processor would be usage on the PC. Processor time of a process would be the specified processes usage. For full description of category names: Performance Monitor Counters

An alternative to using the Performance Counter

Use System.Diagnostics.Process.TotalProcessorTime and System.Diagnostics.ProcessThread.TotalProcessorTime properties to calculate your processor usage as this article describes.

How to reset Django admin password?

One of the best ways to retrieve the username and password is to view and update them. The User Model provides a perfect way to do so.

In this case, I'm using Django 1.9

  1. Navigate to your root directory i,e. where you "manage.py" file is located using your console or other application such as Git.

  2. Retrieve the Python shell using the command "python manage.py shell".

  3. Import the User Model by typing the following command "from django.contrib.auth.models import User"

  4. Get all the users by typing the following command "users = User.objects.all()"

  5. Print a list of the users For Python 2 users use the command "print users" For Python 3 users use the command "print(users)" The first user is usually the admin.

  6. Select the user you wish to change their password e.g.

    "user = users[0]"

  7. Set the password

    user.set_password('name_of_the_new_password_for_user_selected')

  8. Save the new password

    "user.save()"

Start the server and log in using the username and the updated password.

PHP foreach with Nested Array?

If you know the number of levels in nested arrays you can simply do nested loops. Like so:

//  Scan through outer loop
foreach ($tmpArray as $innerArray) {
    //  Check type
    if (is_array($innerArray)){
        //  Scan through inner loop
        foreach ($innerArray as $value) {
            echo $value;
        }
    }else{
        // one, two, three
        echo $innerArray;
    }
}

if you do not know the depth of array you need to use recursion. See example below:

//  Multi-dementional Source Array
$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(
            7,
            8,
            array("four", 9, 10)
    ))
);

//  Output array
displayArrayRecursively($tmpArray);

/**
 * Recursive function to display members of array with indentation
 *
 * @param array $arr Array to process
 * @param string $indent indentation string
 */
function displayArrayRecursively($arr, $indent='') {
    if ($arr) {
        foreach ($arr as $value) {
            if (is_array($value)) {
                //
                displayArrayRecursively($value, $indent . '--');
            } else {
                //  Output
                echo "$indent $value \n";
            }
        }
    }
}

The code below with display only nested array with values for your specific case (3rd level only)

$tmpArray = array(
    array("one", array(1, 2, 3)),
    array("two", array(4, 5, 6)),
    array("three", array(7, 8, 9))
);

//  Scan through outer loop
foreach ($tmpArray as $inner) {

    //  Check type
    if (is_array($inner)) {
        //  Scan through inner loop
        foreach ($inner[1] as $value) {
           echo "$value \n";
        }
    }
}

Error in installation a R package

In my case, I had to close R session and reinstall all packages. In that session I worked with large tables, I suspect this might have had the effect.

How do I print a double value without scientific notation using Java?

My solution: String str = String.format ("%.0f", yourDouble);

How do I get HTTP Request body content in Laravel?

For those who are still getting blank response with $request->getContent(), you can use:

$request->all()

e.g:

public function foo(Request $request){
   $bodyContent = $request->all();
}

Iterate a certain number of times without storing the iteration number anywhere

The idiom (shared by quite a few other languages) for an unused variable is a single underscore _. Code analysers typically won't complain about _ being unused, and programmers will instantly know it's a shortcut for i_dont_care_wtf_you_put_here. There is no way to iterate without having an item variable - as the Zen of Python puts it, "special cases aren't special enough to break the rules".

How to frame two for loops in list comprehension python

In comprehension, the nested lists iteration should follow the same order than the equivalent imbricated for loops.

To understand, we will take a simple example from NLP. You want to create a list of all words from a list of sentences where each sentence is a list of words.

>>> list_of_sentences = [['The','cat','chases', 'the', 'mouse','.'],['The','dog','barks','.']]
>>> all_words = [word for sentence in list_of_sentences for word in sentence]
>>> all_words
['The', 'cat', 'chases', 'the', 'mouse', '.', 'The', 'dog', 'barks', '.']

To remove the repeated words, you can use a set {} instead of a list []

>>> all_unique_words = list({word for sentence in list_of_sentences for word in sentence}]
>>> all_unique_words
['.', 'dog', 'the', 'chase', 'barks', 'mouse', 'The', 'cat']

or apply list(set(all_words))

>>> all_unique_words = list(set(all_words))
['.', 'dog', 'the', 'chases', 'barks', 'mouse', 'The', 'cat']

How get the base URL via context path in JSF?

JSTL 1.2 variation leveraged from BalusC answer

<c:set var="baseURL" value="${pageContext.request.requestURL.substring(0, pageContext.request.requestURL.length() - pageContext.request.requestURI.length())}${pageContext.request.contextPath}/" />

<head>
  <base href="${baseURL}" />

How do I fix the "You don't have write permissions into the /usr/bin directory" error when installing Rails?

You can use sudo gem install -n /usr/local/bin cocoapods

This works for me.

Delete all documents from index/type without deleting type

The above answers no longer work with ES 6.2.2 because of Strict Content-Type Checking for Elasticsearch REST Requests. The curl command which I ended up using is this:

curl -H'Content-Type: application/json' -XPOST 'localhost:9200/yourindex/_doc/_delete_by_query?conflicts=proceed' -d' { "query": { "match_all": {} }}'

jQuery validation plugin: accept only alphabetical characters?

Be careful,

jQuery.validator.addMethod("lettersonly", function(value, element) 
{
return this.optional(element) || /^[a-z," "]+$/i.test(value);
}, "Letters and spaces only please"); 

[a-z, " "] by adding the comma and quotation marks, you are allowing spaces, commas and quotation marks into the input box.

For spaces + text, just do this:

jQuery.validator.addMethod("lettersonly", function(value, element) 
{
return this.optional(element) || /^[a-z ]+$/i.test(value);
}, "Letters and spaces only please");

[a-z ] this allows spaces aswell as text only.

............................................................................

also the message "Letters and spaces only please" is not required, if you already have a message in messages:

messages:{
        firstname:{
        required: "Enter your first name",
        minlength: jQuery.format("Enter at least (2) characters"),
        maxlength:jQuery.format("First name too long more than (80) characters"),
        lettersonly:jQuery.format("letters only mate")
        },

Adam

Find duplicate records in a table using SQL Server

Select * from dbo.sales group by shoppername having(count(Item) > 1)

Best XML parser for Java

If speed and memory is no problem, dom4j is a really good option. If you need speed, using a StAX parser like Woodstox is the right way, but you have to write more code to get things done and you have to get used to process XML in streams.

SVN: Folder already under version control but not comitting?

A variation on @gauss256's answer, deleting .svn, worked for me:

rm -rf troublesome_folder/.svn
svn add troublesome_folder
svn commit

Before Gauss's solution I tried @jwir3's approach and got no joy:

svn cleanup
svn cleanup *
svn cleanup troublesome_folder
svn add --force troublesome_folder
svn commit

Create a copy of a table within the same database DB2

You have to surround the select part with parenthesis.

CREATE TABLE SCHEMA.NEW_TB AS (
    SELECT *
    FROM SCHEMA.OLD_TB
) WITH NO DATA

Should work. Pay attention to all the things @Gilbert said would not be copied.

I'm assuming DB2 on Linux/Unix/Windows here, since you say DB2 v9.5.

How to convert an iterator to a stream?

Create Spliterator from Iterator using Spliterators class contains more than one function for creating spliterator, for example here am using spliteratorUnknownSize which is getting iterator as parameter, then create Stream using StreamSupport

Spliterator<Model> spliterator = Spliterators.spliteratorUnknownSize(
        iterator, Spliterator.NONNULL);
Stream<Model> stream = StreamSupport.stream(spliterator, false);

<Django object > is not JSON serializable

I found that this can be done rather simple using the ".values" method, which also gives named fields:

result_list = list(my_queryset.values('first_named_field', 'second_named_field'))
return HttpResponse(json.dumps(result_list))

"list" must be used to get data as iterable, since the "value queryset" type is only a dict if picked up as an iterable.

Documentation: https://docs.djangoproject.com/en/1.7/ref/models/querysets/#values

Export to csv/excel from kibana

To export data to csv/excel from Kibana follow the following steps:-

  1. Click on Visualize Tab & select a visualization (if created). If not created create a visualziation.

  2. Click on caret symbol (^) which is present at the bottom of the visualization.

  3. Then you will get an option of Export:Raw Formatted as the bottom of the page.

Please find below attached image showing Export option after clicking on caret symbol.

Please find below attached image showing Export option after clicking on caret symbol.

How do I know the script file name in a Bash script?

To answer Chris Conway, on Linux (at least) you would do this:

echo $(basename $(readlink -nf $0))

readlink prints out the value of a symbolic link. If it isn't a symbolic link, it prints the file name. -n tells it to not print a newline. -f tells it to follow the link completely (if a symbolic link was a link to another link, it would resolve that one as well).

Oracle JDBC intermittent Connection Issue

I faced the same problem when a liquibase was executed from jenkins. Sporadically this error was thrown to the output and the liquibase change logs were not executed at all.

Solution provided: In the jenkin's maven project, the jdk was updated from jdk8-131 to any newer version (eg java8-162).

How to convert QString to std::string?

The simplest way would be QString::toStdString().