Programs & Examples On #Conditional breakpoint

In software development, a conditional breakpoint is an intentional stopping or pausing place in a program, put in place for debugging purposes, when a conditions such as the reading, writing, or modification of a specific location in an area of memory, occurs.

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

Since GDB 7.5 you can use these native Convenience Functions:

$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)

Seems quite less problematic than having to execute a "foreign" strcmp() on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.

Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running show configuration inside GDB and searching for --with-python. This little oneliner does the trick, too:

$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python'
             --with-python=/usr (relocatable)

For your demo case, the usage would be

break <where> if $_streq(x, "hello")

or, if your breakpoint already exists and you just want to add the condition to it

condition <breakpoint number> $_streq(x, "hello")

$_streq only matches the whole string, so if you want something more cunning you should use $_regex, which supports the Python regular expression syntax.

Break when a value changes using the Visual Studio debugger

I remember the way you described it using Visual Basic 6.0. In Visual Studio, the only way I have found so far is by specifying a breakpoint condition.

How to use conditional breakpoint in Eclipse?

A way that might be more convenient: where you want a breakpoint, write a no-op if statement and set a breakpoint in its contents.

if(tablist[i].equalsIgnoreCase("LEADDELEGATES")) {
-->    int noop = 0; //don't do anything
}

(the breakpoint is represented by the arrow)

This way, the breakpoint only triggers if your condition is true. This could potentially be easier without that many pop-ups.

CSS background image to fit width, height should auto-scale in proportion

Based on tips from https://developer.mozilla.org/en-US/docs/CSS/background-size I end up with the following recipe that worked for me

body {
        overflow-y: hidden ! important;
        overflow-x: hidden ! important;
        background-color: #f8f8f8;
        background-image: url('index.png');
        /*background-size: cover;*/
        background-size: contain;
        background-repeat: no-repeat;
        background-position: right;
}

Recommended SQL database design for tags or tagging

If you are using a database that supports map-reduce, like couchdb, storing tags in a plain text field or list field is indeed the best way. Example:

tagcloud: {
  map: function(doc){ 
    for(tag in doc.tags){ 
      emit(doc.tags[tag],1) 
    }
  }
  reduce: function(keys,values){
    return values.length
  }
}

Running this with group=true will group the results by tag name, and even return a count of the number of times that tag was encountered. It's very similar to counting the occurrences of a word in text.

Install Qt on Ubuntu

Also take a look at awesome project aqtinstall https://github.com/miurahr/aqtinstall/ (it can install any Qt version on Linux, Mac and Windows machines without any interaction!) and GitHub Action that uses this tool: https://github.com/jurplel/install-qt-action

svn cleanup: sqlite: database disk image is malformed

After a power blackout, I ran into the database disk image is malformed error and the suggested reindex nodes command did not fix all issues due to violated constraints. Also the procedure described in http://mail-archives.apache.org/mod_mbox/subversion-users/201111.mbox/%[email protected]%3E did not resolve the problem.

Solution in my case:

  • Checkout the svn repository again into a temporary folder
  • Copy, i.e. replace, the file ".svn/wc.db" from the new checkout to the corrupt one

This may be useful, if your original svn checkout contains many modified or unversioned files and you don't want to switch to a fresh svn checkout.

Get first and last date of current month with JavaScript or jQuery

Very simple, no library required:

var date = new Date();
var firstDay = new Date(date.getFullYear(), date.getMonth(), 1);
var lastDay = new Date(date.getFullYear(), date.getMonth() + 1, 0);

or you might prefer:

var date = new Date(), y = date.getFullYear(), m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);

EDIT

Some browsers will treat two digit years as being in the 20th century, so that:

new Date(14, 0, 1);

gives 1 January, 1914. To avoid that, create a Date then set its values using setFullYear:

var date = new Date();
date.setFullYear(14, 0, 1); // 1 January, 14

SQL Insert Multiple Rows

Wrap each row of values to be inserted in brackets/parenthesis (value1, value2, value3) and separate the brackets/parenthesis by comma for as many as you wish to insert into the table.

INSERT INTO example
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

WARNING: Can't verify CSRF token authenticity rails

Ugrading from an older app to rails 3.1, including the csrf meta tag is still not solving it. On the rubyonrails.org blog, they give some upgrade tips, and specifically this line of jquery which should go in the head section of your layout:

$(document).ajaxSend(function(e, xhr, options) {
 var token = $("meta[name='csrf-token']").attr("content");
  xhr.setRequestHeader("X-CSRF-Token", token);
});

taken from this blog post: http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails.

In my case, the session was being reset upon each ajax request. Adding the above code solved that issue.

Pentaho Data Integration SQL connection

First of all you need to download Mysql connector which is compatible with your pentaho version.after that paste it to data-integration/lib folder and restart your pentaho. check this https://help.pentaho.com/Documentation/8.1/Setup/JDBC_Drivers_Reference#MY_SQL

Are 64 bit programs bigger and faster than 32 bit versions?

I typically see a 30% speed improvement for compute-intensive code on x86-64 compared to x86. This is most likely due to the fact that we have 16 x 64 bit general purpose registers and 16 x SSE registers instead of 8 x 32 bit general purpose registers and 8 x SSE registers. This is with the Intel ICC compiler (11.1) on an x86-64 Linux - results with other compilers (e.g. gcc), or with other operating systems (e.g. Windows), may be different of course.

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

Return value in a Bash function

Another way to achive this is name references (requires Bash 4.3+).

function example {
  local -n VAR=$1
  VAR=foo
}

example RESULT
echo $RESULT

How to debug external class library projects in visual studio?

I run two instances of visual studio--one for the external dll and one for the main application.
In the project properties of the external dll, set the following:

Build Events:

  • copy /y "$(TargetDir)$(TargetName).dll" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).dll"

  • copy /y "$(TargetDir)$(TargetName).pdb" "C:\<path-to-main> \bin\$(ConfigurationName)\$(TargetName).pdb"

Debug:

  • Start external program: C:\<path-to-main>\bin\debug\<AppName>.exe

  • Working Directory C:\<path-to-main>\bin\debug

This way, whenever I build the external dll, it gets updated in the main application's directory. If I hit debug from the external dll's project--the main application runs, but the debugger only hits breakpoints in the external dll. If I hit debug from the main project, the main application runs with the most recently built external dll, but now the debugger only hits breakpoints in the main project.

I realize one debugger will do the job for both, but I find it easier to keep the two straight this way.

How to rollback everything to previous commit

I searched for multiple options to get my git reset to specific commit, but most of them aren't so satisfactory.

I generally use this to reset the git to the specific commit in source tree.

  1. select commit to reset on sourcetree.

  2. In dropdowns select the active branch , first Parent Only

  3. And right click on "Reset branch to this commit" and select hard reset option (soft, mixed and hard)

  4. and then go to terminal git push -f

You should be all set!

(How) can I count the items in an enum?

There's not really a good way to do this, usually you see an extra item in the enum, i.e.

enum foobar {foo, bar, baz, quz, FOOBAR_NR_ITEMS};

So then you can do:

int fuz[FOOBAR_NR_ITEMS];

Still not very nice though.

But of course you do realize that just the number of items in an enum is not safe, given e.g.

enum foobar {foo, bar = 5, baz, quz = 20};

the number of items would be 4, but the integer values of the enum values would be way out of the array index range. Using enum values for array indexing is not safe, you should consider other options.

edit: as requested, made the special entry stick out more.

Replace text inside td using jQuery having td containing other elements

A bit late to the party, but JQuery change inner text but preserve html has at least one approach not mentioned here:

var $td = $("#demoTable td");
$td.html($td.html().replace('Tap on APN and Enter', 'new text'));

Without fixing the text, you could use (snother)[https://stackoverflow.com/a/37828788/1587329]:

var $a = $('#demoTable td');
var inner = '';
$a.children.html().each(function() {
    inner = inner + this.outerHTML;
});
$a.html('New text' + inner);

Git: Merge a Remote branch locally

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

You need to fetch the remote branch:

git fetch origin aRemoteBranch

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

git checkout master
git merge origin/aRemoteBranch

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

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

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

From aLocalBranch, run git combine remoteBranch
Alias:

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

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

git checkout -b myBranch origin/aBranch
git merge anotherLocalBranch

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

How to prevent page scrolling when scrolling a DIV element?

In the solution above there is a little mistake regarding Firefox. In Firefox "DOMMouseScroll" event has no e.detail property,to get this property you should write the following 'e.originalEvent.detail'.

Here is a working solution for Firefox:

$.fn.isolatedScroll = function() {
    this.on('mousewheel DOMMouseScroll', function (e) {
        var delta = e.wheelDelta || (e.originalEvent && e.originalEvent.wheelDelta) || -e.originalEvent.detail,
            bottomOverflow = (this.scrollTop + $(this).outerHeight() - this.scrollHeight) >= 0,
            topOverflow = this.scrollTop <= 0;

        if ((delta < 0 && bottomOverflow) || (delta > 0 && topOverflow)) {
            e.preventDefault();
        }
    });
    return this;
};

jquery $(window).height() is returning the document height

I had the same problem, and using this solved it.

var w = window.innerWidth;
var h = window.innerHeight;

Sum of Numbers C++

You can try:

int sum = startingNumber; 
for (int i=0; i < positiveInteger; i++) {     
    sum += i;
}
cout << sum;

But much easier is to note that the sum 1+2+...+n = n*(n+1) / 2, so you do not need a loop at all, just use the formula n*(n+1)/2.

How to programmatically round corners and set random background colors

Copying @cimlman's comment into a top-level answer for more visibility:

PaintDrawable(Color.CYAN).apply {
  setCornerRadius(24f)
}

FYI: ShapeDrawable (and its subtype, PaintDrawable) uses default intrinsic width and height of 0. If the drawable does not show up in your usecase, you might have to set the dimensions manually:

PaintDrawable(Color.CYAN).apply {
  intrinsicWidth = -1
  intrinsicHeight = -1
  setCornerRadius(24f)
}

-1 is a magic constant which indicates that a Drawable has no intrinsic width and height of its own (Source).

Python class returning value

the worked proposition for me is __call__ on class who create list of little numbers:

import itertools
    
class SmallNumbers:
    def __init__(self, how_much):
        self.how_much = int(how_much)
        self.work_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        self.generated_list = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
        start = 10
        end = 100
        for cmb in range(2, len(str(self.how_much)) + 1):
            self.ListOfCombinations(is_upper_then=start, is_under_then=end, combinations=cmb)
            start *= 10
            end *= 10

    def __call__(self, number, *args, **kwargs):
        return self.generated_list[number]

    def ListOfCombinations(self, is_upper_then, is_under_then, combinations):
        multi_work_list = eval(str('self.work_list,') * combinations)
        nbr = 0
        for subset in itertools.product(*multi_work_list):
            if is_upper_then <= nbr < is_under_then:
                self.generated_list.append(''.join(subset))
                if self.how_much == nbr:
                    break
            nbr += 1

and to run it:

if __name__ == '__main__':
        sm = SmallNumbers(56)
        print(sm.generated_list)
        print(sm.generated_list[34], sm.generated_list[27], sm.generated_list[10])
        print('The Best', sm(15), sm(55), sm(49), sm(0))

result

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '50', '51', '52', '53', '54', '55', '56']
34 27 10
The Best 15 55 49 0

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

As pointed out here you must use the script in the UMD subdirectory, in my case

        bundles.Add(new ScriptBundle("~/bundles/projectbundle").Include(
            "~/Scripts/umd/popper.js",
            "~/Scripts/bootstrap.js",
            "~/Scripts/respond.js",
            "~/Scripts/summernote-bs4.js"));

Specifically this: "~/Scripts/umd/popper.js",

Java; String replace (using regular expressions)?

String input = "hello I'm a java dev" +
"no job experience needed" +
"senior software engineer" +
"java job available for senior software engineer";

String fixedInput = input.replaceAll("(java|job|senior)", "<b>$1</b>");

How do I use this JavaScript variable in HTML?

You can create an element with an id and then assign that length value to that element.

_x000D_
_x000D_
var name = prompt("What's your name?");_x000D_
var lengthOfName = name.length_x000D_
document.getElementById('message').innerHTML = lengthOfName;
_x000D_
<p id='message'></p>
_x000D_
_x000D_
_x000D_

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag

The rules for turning on the carry flag in binary/integer math are two:

  1. The carry flag is set if the addition of two numbers causes a carry out of the most significant (leftmost) bits added. 1111 + 0001 = 0000 (carry flag is turned on)

  2. The carry (borrow) flag is also set if the subtraction of two numbers requires a borrow into the most significant (leftmost) bits subtracted. 0000 - 0001 = 1111 (carry flag is turned on) Otherwise, the carry flag is turned off (zero).

    • 0111 + 0001 = 1000 (carry flag is turned off [zero])
    • 1000 - 0001 = 0111 (carry flag is turned off [zero])

In unsigned arithmetic, watch the carry flag to detect errors.

In signed arithmetic, the carry flag tells you nothing interesting.

Overflow Flag

The rules for turning on the overflow flag in binary/integer math are two:

  1. If the sum of two numbers with the sign bits off yields a result number with the sign bit on, the "overflow" flag is turned on. 0100 + 0100 = 1000 (overflow flag is turned on)

  2. If the sum of two numbers with the sign bits on yields a result number with the sign bit off, the "overflow" flag is turned on. 1000 + 1000 = 0000 (overflow flag is turned on)

Otherwise the "overflow" flag is turned off

  • 0100 + 0001 = 0101 (overflow flag is turned off)
  • 0110 + 1001 = 1111 (overflow flag turned off)
  • 1000 + 0001 = 1001 (overflow flag turned off)
  • 1100 + 1100 = 1000 (overflow flag is turned off)

Note that you only need to look at the sign bits (leftmost) of the three numbers to decide if the overflow flag is turned on or off.

If you are doing two's complement (signed) arithmetic, overflow flag on means the answer is wrong - you added two positive numbers and got a negative, or you added two negative numbers and got a positive.

If you are doing unsigned arithmetic, the overflow flag means nothing and should be ignored.

For more clarification please refer: http://teaching.idallen.com/dat2343/10f/notes/040_overflow.txt

Do fragments really need an empty constructor?

Here is my simple solution:

1 - Define your fragment

public class MyFragment extends Fragment {

    private String parameter;

    public MyFragment() {
    }

    public void setParameter(String parameter) {
        this.parameter = parameter;
    } 
}

2 - Create your new fragment and populate the parameter

    myfragment = new MyFragment();
    myfragment.setParameter("here the value of my parameter");

3 - Enjoy it!

Obviously you can change the type and the number of parameters. Quick and easy.

How can I install a .ipa file to my iPhone simulator

UPDATE: For Xcode 8.0+ you need to follow below Steps:

  1. Download application from iTunes
  2. Select downloaded app, right click show in finder
  3. Copy .ipa file to Desktop, rename it to .zip file
  4. Extract that .zip file and you will get directory with application name
  5. Check that directory you will find app file in Payload folder, copy this app file

  6. Go to ~/Library/Developer/CoreSimulator/Devices

FYI: Library folder is hidden by default in mac, you can see hidden file using below command.

defaults write com.apple.finder AppleShowAllFiles YES;
killall Finder /System/Library/CoreServices/Finder.app

Now here you'll see many directories with long hexadecimal names, these all are simulators.

To find your desired simulator, sort these directories using "Arranged By > Date Modified".

Select that simulator file and go to below location.

  1. <HEXADECIMAL-SIMULATOR-STRING>/data/Containers/Bundle/Application/
  2. Create new folder name with <download-app-name> and paste app file in that folder
  3. Open Terminal and run below command to install this application

    xcrun simctl install booted <APP_FILE_PATH>
    

Example <APP_FILE_PATH> will be looks like below:

~/Library/Developer/CoreSimulator/Devices/<HEXADECIMAL-SIMULATOR-STRING>/data/Containers/Bundle/Application/<APP_NAME>

What is the "Temporary ASP.NET Files" folder for?

The CLR uses it when it is compiling at runtime. Here is a link to MSDN that explains further.

ionic build Android | error: No installed build tools found. Please install the Android build tools

2018

The "android" command is deprecated.

try

sdkmanager "build-tools;27.0.3"

This work for me, as #Fadhil said

How to locate the Path of the current project directory in Java (IDE)?

YOU CANT.

Java-Projects does not have ONE path! Java-Projects has multiple pathes even so one Class can have multiple locations in different classpath's in one "Project".

So if you have a calculator.jar located in your JRE/lib and one calculator.jar with the same classes on a CD: if you execute the calculator.jar the classes from the CD, the java-vm will take the classes from the JRE/lib!

This problem often comes to programmers who like to load resources deployed inside of the Project. In this case,

System.getResource("/likebutton.png") 

is taken for example.

Regex that matches integers in between whitespace or start/end of string only

^(-+)?[1-9][0-9]*$ starts with a - or + for 0 or 1 times, then you want a non zero number (because there is not such a thing -0 or +0) and then it continues with any number from 0 to 9

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

How do I create a constant in Python?

You can wrap a constant in a numpy array, flag it write only, and always call it by index zero.

import numpy as np

# declare a constant
CONSTANT = 'hello'

# put constant in numpy and make read only
CONSTANT = np.array([CONSTANT])
CONSTANT.flags.writeable = False
# alternatively: CONSTANT.setflags(write=0)

# call our constant using 0 index    
print 'CONSTANT %s' % CONSTANT[0]

# attempt to modify our constant with try/except
new_value = 'goodbye'
try:
    CONSTANT[0] = new_value
except:
    print "cannot change CONSTANT to '%s' it's value '%s' is immutable" % (
        new_value, CONSTANT[0])

# attempt to modify our constant producing ValueError
CONSTANT[0] = new_value



>>>
CONSTANT hello
cannot change CONSTANT to 'goodbye' it's value 'hello' is immutable
Traceback (most recent call last):
  File "shuffle_test.py", line 15, in <module>
    CONSTANT[0] = new_value
ValueError: assignment destination is read-only

of course this only protects the contents of the numpy, not the variable "CONSTANT" itself; you can still do:

CONSTANT = 'foo'

and CONSTANT would change, however that would quickly throw an TypeError the first time CONSTANT[0] is later called in the script.

although... I suppose if you at some point changed it to

CONSTANT = [1,2,3]

now you wouldn't get the TypeError anymore. hmmmm....

https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.setflags.html

Controlling mouse with Python

Quick and dirty function that'll left click wherever clicks times on Windows 7 using the ctypes library. No downloads required.

import ctypes

SetCursorPos = ctypes.windll.user32.SetCursorPos
mouse_event = ctypes.windll.user32.mouse_event

def left_click(x, y, clicks=1):
  SetCursorPos(x, y)
  for i in xrange(clicks):
   mouse_event(2, 0, 0, 0, 0)
   mouse_event(4, 0, 0, 0, 0)

left_click(200, 200) #left clicks at 200, 200 on your screen. Was able to send 10k clicks instantly.

String.format() to format double in java

String.format("%4.3f" , x) ;

It means that we need total 4 digits in ans , of which 3 should be after decimal . And f is the format specifier of double . x means the variable for which we want to find it . Worked for me . . .

How to print an exception in Python 3?

Here is the way I like that prints out all of the error stack.

import logging

try:
    1 / 0
except Exception as _e:
    # any one of the follows:
    # print(logging.traceback.format_exc())
    logging.error(logging.traceback.format_exc())

The output looks as the follows:

ERROR:root:Traceback (most recent call last):
  File "/PATH-TO-YOUR/filename.py", line 4, in <module>
    1 / 0
ZeroDivisionError: division by zero

LOGGING_FORMAT :

LOGGING_FORMAT = '%(asctime)s\n  File "%(pathname)s", line %(lineno)d\n  %(levelname)s [%(message)s]'

How to get primary key of table?

Shortest possible code seems to be something like

// $dblink contain database login details 
// $tblName the current table name 
$r = mysqli_fetch_assoc(mysqli_query($dblink, "SHOW KEYS FROM $tblName WHERE Key_name = 'PRIMARY'")); 
$iColName = $r['Column_name']; 

How to prevent XSS with HTML/PHP?

In order of preference:

  1. If you are using a templating engine (e.g. Twig, Smarty, Blade), check that it offers context-sensitive escaping. I know from experience that Twig does. {{ var|e('html_attr') }}
  2. If you want to allow HTML, use HTML Purifier. Even if you think you only accept Markdown or ReStructuredText, you still want to purify the HTML these markup languages output.
  3. Otherwise, use htmlentities($var, ENT_QUOTES | ENT_HTML5, $charset) and make sure the rest of your document uses the same character set as $charset. In most cases, 'UTF-8' is the desired character set.

Also, make sure you escape on output, not on input.

How to vertically align elements in a div?

Now that flexbox support is increasing, this CSS applied to the containing element would vertically center the contained item:

.container {        
    display: flex;
    align-items: center;
}

Use the prefixed version if you also need to target Explorer 10, and old (< 4.4) Android browsers:

.container {
    display: -ms-flexbox;
    display: -webkit-flex;
    display: flex;

    -ms-flex-align: center;
    -webkit-align-items: center;
    -webkit-box-align: center;

    align-items: center;
}

How do I show running processes in Oracle DB?

I suspect you would just want to grab a few columns from V$SESSION and the SQL statement from V$SQL. Assuming you want to exclude the background processes that Oracle itself is running

SELECT sess.process, sess.status, sess.username, sess.schemaname, sql.sql_text
  FROM v$session sess,
       v$sql     sql
 WHERE sql.sql_id(+) = sess.sql_id
   AND sess.type     = 'USER'

The outer join is to handle those sessions that aren't currently active, assuming you want those. You could also get the sql_fulltext column from V$SQL which will have the full SQL statement rather than the first 1000 characters, but that is a CLOB and so likely a bit more complicated to deal with.

Realistically, you probably want to look at everything that is available in V$SESSION because it's likely that you can get a lot more information than SP_WHO provides.

An error occurred while executing the command definition. See the inner exception for details

I had a similar situation with the 'An error occurred while executing the command definition' error. I had some views which were grabbing from another db which used current user security. The second db did not allow the login for the user of the first db causing this issue to occur. I added the db login to the server it was trying to get to from the original server and this fixed the issue. Check your views and see if there are any linked dbs which have different security than the db you are logging onto originally.

Paste text on Android Emulator

For Mac users, a MUCH easier way is to do this right in the android emulator:

  • click and hold for a second or two
  • release click
  • the option 'paste' will appear as follow

enter image description here

How do I remove the last comma from a string using PHP?

Use the rtrim function:

rtrim($my_string, ',');

The Second parameter indicates the character to be deleted.

Remove empty elements from an array in Javascript

foo = [0, 1, 2, "", , false, 3, "four", null]

foo.filter(function(e) {
    return e === 0 ? '0' : e
})

returns

[0, 1, 2, 3, "four"]

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

The query below will result in dd-mmm-yy format.

select 
cast(DAY(getdate()) as varchar)+'-'+left(DATEname(m,getdate()),3)+'-'+  
Right(Year(getdate()),2)

How to Convert JSON object to Custom C# object?

The following 2 examples make use of either

  1. JavaScriptSerializer under System.Web.Script.Serialization Or
  2. Json.Decode under System.Web.Helpers

Example 1: using System.Web.Script.Serialization

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Script.Serialization;

namespace Tests
{
    [TestClass]
    public class JsonTests
    {
        [TestMethod]
        public void Test()
        {
            var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            dynamic jsonObject = serializer.Deserialize<dynamic>(json);

            dynamic x = jsonObject["user"]; // result is Dictionary<string,object> user with fields name, teamname, email and players with their values
            x = jsonObject["user"]["name"]; // result is asdf
            x = jsonObject["user"]["players"]; // result is object[] players with its values
        }
    }
}

Usage: JSON object to Custom C# object

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Script.Serialization;
using System.Linq;

namespace Tests
{
    [TestClass]
    public class JsonTests
    {
        [TestMethod]
        public void TestJavaScriptSerializer()
        {
            var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
            User user = new User(json);
            Console.WriteLine("Name : " + user.name);
            Console.WriteLine("Teamname : " + user.teamname);
            Console.WriteLine("Email : " + user.email);
            Console.WriteLine("Players:");
            foreach (var player in user.players)
                Console.WriteLine(player);
        }
    }

    public class User {
        public User(string json) {
            JavaScriptSerializer serializer = new JavaScriptSerializer();
            var jsonObject = serializer.Deserialize<dynamic>(json);
            name = (string)jsonObject["user"]["name"];
            teamname = (string)jsonObject["user"]["teamname"];
            email = (string)jsonObject["user"]["email"];
            players = jsonObject["user"]["players"];
        }

        public string name { get; set; }
        public string teamname { get; set; }
        public string email { get; set; }
        public Array players { get; set; }
    }
}

Example 2: using System.Web.Helpers

using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Helpers;

namespace Tests
{
    [TestClass]
    public class JsonTests
    {
        [TestMethod]
        public void TestJsonDecode()
        {
            var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
            dynamic jsonObject = Json.Decode(json);

            dynamic x = jsonObject.user; // result is dynamic json object user with fields name, teamname, email and players with their values
            x = jsonObject.user.name; // result is asdf
            x = jsonObject.user.players; // result is dynamic json array players with its values
        }
    }
}

Usage: JSON object to Custom C# object

using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Web.Helpers;
using System.Linq;

namespace Tests
{
    [TestClass]
    public class JsonTests
    {
        [TestMethod]
        public void TestJsonDecode()
        {
            var json = "{\"user\":{\"name\":\"asdf\",\"teamname\":\"b\",\"email\":\"c\",\"players\":[\"1\",\"2\"]}}";
            User user = new User(json);
            Console.WriteLine("Name : " + user.name);
            Console.WriteLine("Teamname : " + user.teamname);
            Console.WriteLine("Email : " + user.email);
            Console.WriteLine("Players:");
            foreach (var player in user.players)
                Console.WriteLine(player);
        }
    }

    public class User {
        public User(string json) {
            var jsonObject = Json.Decode(json);
            name = (string)jsonObject.user.name;
            teamname = (string)jsonObject.user.teamname;
            email = (string)jsonObject.user.email;
            players = (DynamicJsonArray) jsonObject.user.players;
        }

        public string name { get; set; }
        public string teamname { get; set; }
        public string email { get; set; }
        public Array players { get; set; }
    }
}

This code requires adding System.Web.Helpers namespace found in,

%ProgramFiles%\Microsoft ASP.NET\ASP.NET Web Pages{VERSION}\Assemblies\System.Web.Helpers.dll

Or

%ProgramFiles(x86)%\Microsoft ASP.NET\ASP.NET Web Pages{VERSION}\Assemblies\System.Web.Helpers.dll

Hope this helps!

GROUP BY + CASE statement

Your query would work already - except that you are running into naming conflicts or just confusing the output column (the CASE expression) with source column result, which has different content.

...
GROUP BY model.name, attempt.type, attempt.result
...

You need to GROUP BY your CASE expression instead of your source column:

...
GROUP BY model.name, attempt.type
       , CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END
...

Or provide a column alias that's different from any column name in the FROM list - or else that column takes precedence:

SELECT ...
     , CASE WHEN attempt.result = 0 THEN 0 ELSE 1 END AS result1
...
GROUP BY model.name, attempt.type, result1
...

The SQL standard is rather peculiar in this respect. Quoting the manual here:

An output column's name can be used to refer to the column's value in ORDER BY and GROUP BY clauses, but not in the WHERE or HAVING clauses; there you must write out the expression instead.

And:

If an ORDER BY expression is a simple name that matches both an output column name and an input column name, ORDER BY will interpret it as the output column name. This is the opposite of the choice that GROUP BY will make in the same situation. This inconsistency is made to be compatible with the SQL standard.

Bold emphasis mine.

These conflicts can be avoided by using positional references (ordinal numbers) in GROUP BY and ORDER BY, referencing items in the SELECT list from left to right. See solution below.
The drawback is, that this may be harder to read and vulnerable to edits in the SELECT list (one might forget to adapt positional references accordingly).

But you do not have to add the column day to the GROUP BY clause, as long as it holds a constant value (CURRENT_DATE-1).

Rewritten and simplified with proper JOIN syntax and positional references it could look like this:

SELECT m.name
     , a.type
     , CASE WHEN a.result = 0 THEN 0 ELSE 1 END AS result
     , CURRENT_DATE - 1 AS day
     , count(*) AS ct
FROM   attempt    a
JOIN   prod_hw_id p USING (hard_id)
JOIN   model      m USING (model_id)
WHERE  ts >= '2013-11-06 00:00:00'  
AND    ts <  '2013-11-07 00:00:00'
GROUP  BY 1,2,3
ORDER  BY 1,2,3;

Also note that I am avoiding the column name time. That's a reserved word and should never be used as identifier. Besides, your "time" obviously is a timestamp or date, so that is rather misleading.

Easiest way to use SVG in Android?

Android Studio supports SVG from 1.4 onwards

Here is a video on how to import.

form_for with nested resources

Be sure to have both objects created in controller: @post and @comment for the post, eg:

@post = Post.find params[:post_id]
@comment = Comment.new(:post=>@post)

Then in view:

<%= form_for([@post, @comment]) do |f| %>

Be sure to explicitly define the array in the form_for, not just comma separated like you have above.

Return JSON for ResponseEntity<String>

@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String so() {
    return "This is a String";
}

Apache HttpClient Interim Error: NoHttpResponseException

Same problem for me on apache http client 4.5.5 adding default header

Connection: close

resolve the problem

WCF error - There was no endpoint listening at

I was getting the same error with a service access. It was working in browser, but wasnt working when I try to access it in my asp.net/c# application. I changed application pool from appPoolIdentity to NetworkService, and it start working. Seems like a permission issue to me.

How to access the services from RESTful API in my angularjs page?

For instance your json looks like this : {"id":1,"content":"Hello, World!"}

You can access this thru angularjs like so:

angular.module('app', [])
    .controller('myApp', function($scope, $http) {
        $http.get('http://yourapp/api').
            then(function(response) {
                $scope.datafromapi = response.data;
            });
    });

Then on your html you would do it like this:

<!doctype html>
<html ng-app="myApp">
    <head>
        <title>Hello AngularJS</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="myApp">
            <p>The ID is {{datafromapi.id}}</p>
            <p>The content is {{datafromapi.content}}</p>
        </div>
    </body>
</html>

This calls the CDN for angularjs in case you don't want to download them.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="hello.js"></script>

Hope this helps.

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

jQuery override default validation error message display (Css) Popup/Tooltip like

A few things:

First, I don't think you really need a validation error for a radio fieldset because you could just have one of the fields checked by default. Most people would rather correct something then provide something. For instance:

   Age: (*) 12 - 18 | () 19 - 30 | 31 - 50 

is more likely to be changed to the right answer as the person DOESN'T want it to go to the default. If they see it blank, they are more likely to think "none of your business" and skip it.

Second, I was able to get the effect I think you are wanting without any positioning properties. You just add padding-right to the form (or the div of the form, whatever) to provide enough room for your error and make sure your error will fit in that area. Then, you have a pre-set up css class called "error" and you set it as having a negative margin-top roughly the height of your input field and a margin-left about the distance from the left to where your padding-right should start. I tried this out, it's not great, but it works with three properties and requires no floats or absolutes:

   <style type="text/css">
    .error {
        width: 13em; /* Ensures that the div won't exceed right padding of form */
        margin-top: -1.5em;  /*Moves the div up to the same level as input */
        margin-left: 11em;   /*Moves div to the right */
        font-size: .9em;     /*Makes sure that the error div is smaller than input */
    }

   <form>
   <label for="name">Name:</label><input id="name" type="textbox" />
   <div class="error"><<< This field is required!</div>
   <label for="numb">Phone:</label><input id="numb" type="textbox" />
   <div class="error"><<< This field is required!</div>
   </form>

What is a callback?

In computer programming, a callback is executable code that is passed as an argument to other code.

Wikipedia: Callback (computer science)

C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).

Swap DIV position with CSS only

Assuming Nothing Follows Them

If these two div elements are basically your main layout elements, and nothing follows them in the html, then there is a pure HMTL/CSS solution that takes the normal order shown in this fiddle and is able to flip it vertically as shown in this fiddle using one additional wrapper div like so:

HTML

<div class="wrapper flipit">
   <div id="first_div">first div</div>
   <div id="second_div">second div</div>
</div>

CSS

.flipit {
    position: relative;
}
.flipit #first_div {
    position: absolute;
    top: 100%;
    width: 100%;
}

This would not work if elements follow these div's, as this fiddle illustrates the issue if the following elements are not wrapped (they get overlapped by #first_div), and this fiddle illustrates the issue if the following elements are also wrapped (the #first_div changes position with both the #second_div and the following elements). So that is why, depending on your use case, this method may or may not work.

For an overall layout scheme, where all other elements exist inside the two div's, it can work. For other scenarios, it will not.

C# Remove object from list of objects

Originally I used a foreach but then realised you can't use this while modifying a collection

You can create a copy of the collection and iterate over that using ToList() to create to copy:

 foreach(Chunk chunk in ChunkList.ToList())
 {
     if (chunk.UniqueID == ChunkID)
     {
         ChunkList.Remove(chunk);
     }
 }

What does "TypeError 'xxx' object is not callable" means?

The exception is raised when you try to call not callable object. Callable objects are (functions, methods, objects with __call__)

>>> f = 1
>>> callable(f)
False
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable

How to convert date to string and to date again?

tl;dr

How to convert date to string and to date again?

LocalDate.now().toString()

2017-01-23

…and…

LocalDate.parse( "2017-01-23" )

java.time

The Question uses troublesome old date-time classes bundled with the earliest versions of Java. Those classes are now legacy, supplanted by the java.time classes built into Java 8, Java 9, and later.

Determining today’s date requires a time zone. For any given moment the date varies around the globe by zone.

If not supplied by you, your JVM’s current default time zone is applied. That default can change at any moment during runtime, and so is unreliable. I suggest you always specify your desired/expected time zone.

ZoneId z = ZoneId.of( "America/Montreal" ) ;
LocalDate ld = LocalDate.now( z ) ;

ISO 8601

Your desired format of YYYY-MM-DD happens to comply with the ISO 8601 standard.

That standard happens to be used by default by the java.time classes when parsing/generating strings. So you can simply call LocalDate::parse and LocalDate::toString without specifying a formatting pattern.

String s = ld.toString() ;

To parse:

LocalDate ld = LocalDate.parse( s ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Javascript - Replace html using innerHTML

You should chain the replace() together instead of assigning the result and replacing again.

var strMessage1 = document.getElementById("element1") ;
strMessage1.innerHTML = strMessage1.innerHTML
                        .replace(/aaaaaa./g,'<a href=\"http://www.google.com/')
                        .replace(/.bbbbbb/g,'/world\">Helloworld</a>');

See DEMO.

Center image using text-align center?

I came across this post, and it worked for me:

_x000D_
_x000D_
img {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  margin: auto;_x000D_
}
_x000D_
<div style="border: 1px solid black; position:relative; min-height: 200px">_x000D_
  <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a">_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

(Vertical and horizontal alignment)

How do I get a value of datetime.today() in Python that is "timezone aware"?

Here is one way to generate it with the stdlib:

import time
from datetime import datetime

FORMAT='%Y-%m-%dT%H:%M:%S%z'
date=datetime.strptime(time.strftime(FORMAT, time.localtime()),FORMAT)

date will store the local date and the offset from UTC, not the date at UTC timezone, so you can use this solution if you need to identify which timezone the date is generated at. In this example and in my local timezone:

date
datetime.datetime(2017, 8, 1, 12, 15, 44, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))

date.tzname()
'UTC+02:00'

The key is adding the %z directive to the representation FORMAT, to indicate the UTC offset of the generated time struct. Other representation formats can be consulted in the datetime module docs

If you need the date at the UTC timezone, you can replace time.localtime() with time.gmtime()

date=datetime.strptime(time.strftime(FORMAT, time.gmtime()),FORMAT)

date    
datetime.datetime(2017, 8, 1, 10, 23, 51, tzinfo=datetime.timezone.utc)

date.tzname()
'UTC'

Edit

This works only on python3. The z directive is not available on python 2 _strptime.py code

How do I compare 2 rows from the same table (SQL Server)?

Some people find the following alternative syntax easier to see what is going on:

select t1.value,t2.value
from MyTable t1
    inner join MyTable t2 on
        t1.id = t2.id
where t1.id = @id

How to draw a graph in LaTeX?

TikZ can do this.

A quick demo:

\documentclass{article}

\usepackage{tikz}

\begin{document}

\begin{tikzpicture}
  [scale=.8,auto=left,every node/.style={circle,fill=blue!20}]
  \node (n6) at (1,10) {6};
  \node (n4) at (4,8)  {4};
  \node (n5) at (8,9)  {5};
  \node (n1) at (11,8) {1};
  \node (n2) at (9,6)  {2};
  \node (n3) at (5,5)  {3};

  \foreach \from/\to in {n6/n4,n4/n5,n5/n1,n1/n2,n2/n5,n2/n3,n3/n4}
    \draw (\from) -- (\to);

\end{tikzpicture}

\end{document}

produces:

enter image description here

More examples @ http://www.texample.net/tikz/examples/tag/graphs/

More information about TikZ: http://sourceforge.net/projects/pgf/ where I guess an installation guide will also be present.

How to list all the files in android phone by using adb shell?

This command will show also if the file is hidden adb shell ls -laR | grep filename

Casting a number to a string in TypeScript

Use the "+" symbol to cast a string to a number.

window.location.hash = +page_number;

ImageView rounded corners

found the easy way.. round imageview with user define radius:

http://shortcutsandroid.blogspot.in/2015/02/round-image-view-in-android.html

just add imageView.setRadius();

//it will set radius for the round imageView.

Inheritance with base class constructor with parameters

I could be wrong, but I believe since you are inheriting from foo, you have to call a base constructor. Since you explicitly defined the foo constructor to require (int, int) now you need to pass that up the chain.

public bar(int a, int b) : base(a, b)
{
     c = a * b;
}

This will initialize foo's variables first and then you can use them in bar. Also, to avoid confusion I would recommend not naming parameters the exact same as the instance variables. Try p_a or something instead, so you won't accidentally be handling the wrong variable.

Open links in new window using AngularJS

this is the code of your button

<a href="AddNewUserAdmin" 
   class="btn btn-info " 
   ng-click="showaddnewuserpage()">
  <span class="glyphicon glyphicon-plus-sign"></span> Add User</a>

in the controller just add this function.

 var app = angular.module('userAPP', []);

app.controller('useraddcontroller', function ($scope, $http, $window) {

$scope.showaddnewuserpage = function () {

    $window.location.href = ('/AddNewUserAdmin');
}

});

How to set top-left alignment for UILabel for iOS application?

I have this problem to but my label was in UITableViewCell, and in fund that the easiest way to solve the problem was to create an empty UIView and set the label inside it with constraints to the top and to the left side only, on off curse set the number of lines to 0

explicit casting from super class to subclass

In order to avoid this kind of ClassCastException, if you have:

class A
class B extends A

You can define a constructor in B that takes an object of A. This way we can do the "cast" e.g.:

public B(A a) {
    super(a.arg1, a.arg2); //arg1 and arg2 must be, at least, protected in class A
    // If B class has more attributes, then you would initilize them here
}

Getting assembly name

Assembly.GetExecutingAssembly().Location

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Add a link to an image in a css style sheet

You don't add links to style sheets. They are for describing the style of the page. You would change your mark-up or add JavaScript to navigate when the image is clicked.

Based only on your style you would have:

<a href="home.com" id="logo"></a>

Why does the Visual Studio editor show dots in blank spaces?

~ FOR VISUAL STUDIO 6 ~

use: ctrl+shift+8 to toggle on/off.

(or manualy go to: Edit> Advance > "View Whitespaces")

goodluck!

Works also for Visual Studio 2008, when Tools/Options/Environment/Keyboard/Mapping Scheme: Visual C++ 6 is selected.

Java - Using Accessor and Mutator methods

You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables

public class IDCard {
    public String name, fileName;
    public int id;

    public IDCard(final String name, final String fileName, final int id) {
        this.name = name;
        this.fileName = fileName
        this.id = id;
    }

    public String getName() {
        return name;
    }
}

You can the create an IDCard and use the accessor like this:

final IDCard card = new IDCard();
card.getName();

Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.

If you use the static keyword then those variables are common across every instance of IDCard.

A couple of things to bear in mind:

  1. don't add useless comments - they add code clutter and nothing else.
  2. conform to naming conventions, use lower case of variable names - name not Name.

Running interactive commands in Paramiko

I had the same problem trying to make an interactive ssh session using ssh, a fork of Paramiko.

I dug around and found this article:

Updated link (last version before the link generated a 404): http://web.archive.org/web/20170912043432/http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/

To continue your example you could do

ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command("psql -U factory -d factory -f /tmp/data.sql")
ssh_stdin.write('password\n')
ssh_stdin.flush()
output = ssh_stdout.read()

The article goes more in depth, describing a fully interactive shell around exec_command. I found this a lot easier to use than the examples in the source.

Original link: http://jessenoller.com/2009/02/05/ssh-programming-with-paramiko-completely-different/

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

How did you declare the version?

<version>4.8.2</version>

Be aware of the meaning from this declaration explained here (see NOTES):

When declaring a "normal" version such as 3.8.2 for Junit, internally this is represented as "allow anything, but prefer 3.8.2." This means that when a conflict is detected, Maven is allowed to use the conflict algorithms to choose the best version. If you specify [3.8.2], it means that only 3.8.2 will be used and nothing else.

To force using the version 4.8.2 try

<version>[4.8.2]</version>

As you do not have any other dependencies in your project there shouldn't be any conflicts that cause your problem. The first declaration should work for you if you are able to get this version from a repository. Do you inherit dependencies from a parent pom?

How do I detect "shift+enter" and generate a new line in Textarea?

Using ReactJS ES6 here's the simplest way

shift + enter New Line at any position

enter Blocked

_x000D_
_x000D_
class App extends React.Component {_x000D_
_x000D_
 constructor(){_x000D_
    super();_x000D_
    this.state = {_x000D_
      message: 'Enter is blocked'_x000D_
    }_x000D_
  }_x000D_
  onKeyPress = (e) => {_x000D_
     if (e.keyCode === 13 && e.shiftKey) {_x000D_
        e.preventDefault();_x000D_
        let start = e.target.selectionStart,_x000D_
            end = e.target.selectionEnd;_x000D_
        this.setState(prevState => ({ message:_x000D_
            prevState.message.substring(0, start)_x000D_
            + '\n' +_x000D_
            prevState.message.substring(end)_x000D_
        }),()=>{_x000D_
            this.input.selectionStart = this.input.selectionEnd = start + 1;_x000D_
        })_x000D_
    }else if (e.keyCode === 13) { // block enter_x000D_
      e.preventDefault();_x000D_
    }_x000D_
    _x000D_
  };_x000D_
_x000D_
  render(){_x000D_
    return(_x000D_
      <div>_x000D_
      New line with shift enter at any position<br />_x000D_
       <textarea _x000D_
       value={this.state.message}_x000D_
       ref={(input)=> this.input = input}_x000D_
       onChange={(e)=>this.setState({ message: e.target.value })}_x000D_
       onKeyDown={this.onKeyPress}/>_x000D_
      </div>_x000D_
    )_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<App />, document.getElementById('root'));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='root'></div>
_x000D_
_x000D_
_x000D_

Sending credentials with cross-domain posts?

In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:

$.ajax(
        'https://foo.bar.com,
        {
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: successFunc
        }
    );

The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:

An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT

Linking dll in Visual Studio

On Windows you do not link with a .dll file directly – you must use the accompanying .lib file instead. To do that go to Project -> Properties -> Configuration Properties -> Linker -> Additional Dependencies and add path to your .lib as a next line.

You also must make sure that the .dll file is either in the directory contained by the %PATH% environment variable or that its copy is in Output Directory (by default, this is Debug\Release under your project's folder).

If you don't have access to the .lib file, one alternative is to load the .dll manually during runtime using WINAPI functions such as LoadLibrary and GetProcAddress.

How to get the request parameters in Symfony 2?

You can Use The following code to get your form field values

use Symfony\Component\HttpFoundation\Request;

public function updateAction(Request $request)
{
    // retrieve GET and POST variables respectively
    $request->query->get('foo');
    $request->request->get('bar', 'default value if bar does not exist');
}

Or You can also get all the form values as array by using

$request->request->all()

`col-xs-*` not working in Bootstrap 4

col-xs-* have been dropped in Bootstrap 4 in favor of col-*.

Replace col-xs-12 with col-12 and it will work as expected.

Also note col-xs-offset-{n} were replaced by offset-{n} in v4.

How to create a new column in a select query

SELECT field1, 
       field2,
       'example' AS newfield
FROM TABLE1

This will add a column called "newfield" to the output, and its value will always be "example".

When I run `npm install`, it returns with `ERR! code EINTEGRITY` (npm 5.3.0)

This was not yet mentioned but make sure that your SYSTEM TIME is correct. If it is too out of sync it will cause a EINTEGRITY error. When you are doing npm publish / install.

How to auto-remove trailing whitespace in Eclipse?

In a pinch, for those editors that don't support removal of trailing whitespace at all (e.g. the XML editor), you can remove it from all lines by doing a find and replace, enabling regular expressions, then finding "[\t ]+$" and replacing it with "" (blank). There's probably a better regex to do that but it works for me without needing to install AnyEdit.

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

I had the same errors.

I added System.Data.Entity.Repository from Nuget Packages and the errors disappears.

Hope it wil help!

Why aren't python nested functions called closures?

Python has a weak support for closure. To see what I mean take the following example of a counter using closure with JavaScript:

function initCounter(){
    var x = 0;
    function counter  () {
        x += 1;
        console.log(x);
    };
    return counter;
}

count = initCounter();

count(); //Prints 1
count(); //Prints 2
count(); //Prints 3

Closure is quite elegant since it gives functions written like this the ability to have "internal memory". As of Python 2.7 this is not possible. If you try

def initCounter():
    x = 0;
    def counter ():
        x += 1 ##Error, x not defined
        print x
    return counter

count = initCounter();

count(); ##Error
count();
count();

You'll get an error saying that x is not defined. But how can that be if it has been shown by others that you can print it? This is because of how Python it manages the functions variable scope. While the inner function can read the outer function's variables, it cannot write them.

This is a shame really. But with just read-only closure you can at least implement the function decorator pattern for which Python offers syntactic sugar.

Update

As its been pointed out, there are ways to deal with python's scope limitations and I'll expose some.

1. Use the global keyword (in general not recommended).

2. In Python 3.x, use the nonlocal keyword (suggested by @unutbu and @leewz)

3. Define a simple modifiable class Object

class Object(object):
    pass

and create an Object scope within initCounter to store the variables

def initCounter ():
    scope = Object()
    scope.x = 0
    def counter():
        scope.x += 1
        print scope.x

    return counter

Since scope is really just a reference, actions taken with its fields do not really modify scope itself, so no error arises.

4. An alternative way, as @unutbu pointed out, would be to define each variable as an array (x = [0]) and modify it's first element (x[0] += 1). Again no error arises because x itself is not modified.

5. As suggested by @raxacoricofallapatorius, you could make x a property of counter

def initCounter ():

    def counter():
        counter.x += 1
        print counter.x

    counter.x = 0
    return counter

Entity Framework - "An error occurred while updating the entries. See the inner exception for details"

I was facing the same problem and non of the above solutions helped me. In my Web Api 2 project, I had actually updated my database and had placed a unique constraint on an SQL table column. That was actually causing the problem. Simply Checking the the duplicate column values before inserting helped me fix the problem!

comparing elements of the same array in java

First things first, you need to loop to < a.length rather than a.length - 1. As this is strictly less than you need to include the upper bound.

So, to check all pairs of elements you can do:

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

But this will compare, for example a[2] to a[3] and then a[3] to a[2]. Given that you are checking != this seems wasteful.

A better approach would be to compare each element i to the rest of the array:

for (int i = 0; i < a.length; i++) {
    for (int k = i + 1; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

So if you have the indices [1...5] the comparison would go

  1. 1 -> 2
  2. 1 -> 3
  3. 1 -> 4
  4. 1 -> 5
  5. 2 -> 3
  6. 2 -> 4
  7. 2 -> 5
  8. 3 -> 4
  9. 3 -> 5
  10. 4 -> 5

So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.

Convert char array to string use C

You can use strcpy but remember to end the array with '\0'

char array[20]; char string[100];

array[0]='1'; array[1]='7'; array[2]='8'; array[3]='.'; array[4]='9'; array[5]='\0';
strcpy(string, array);
printf("%s\n", string);

.crx file install in chrome

File format
This tool parses .CRX version 2 format documented by Google. In general, .CRX file format consist of few parts:

Magic header
Version of file format
Public Key information and a package signature Zipped contents of the extension source code Magic header is a signature of the file telling that this file is Chrome Extension. Using this header the operating system can determine the actual type of the file (MIME type is application/x-chrome-extension), and how should it be treaten (is it executable? is it a text file?). Then the window system can show beautiful icon to the user.

In .CRX files the magic header has a constant value Cr24 or 0x43723234.

The version is provided by vendor. The version bytes are 0x02000000.

The next part of the file contains the length of the public key information and the length of a digital signature.

All .CRX packages distributed via Chrome WebStore should have public key information and digital signature in order to make possible for browser to check that the package has been transmitted without modifications and that no additions or replacements were made.

After all of the header stuff, typically ending up on 307'th byte, comes the code of extension, stored as zip-archive. So the remainder of the .crx file is the well-known .zip archive.

.crx file opened in the hex editor called HexFiend (on Mac) The header part of a .crx file selected on the picture above. Obviously, you can extract the remaining .zip archive "by hand" using any simple hex editor. In this example, we use handy HexFiend editor on Mac.

The CRX Extractor loads a file provided, checks a magic header, version and trims the file, so only .zip archive remains. Then it returns obtained .zip archive to user.

ref:
https://crxextractor.com/about.html

https://github.com/vladignatyev/crx-extractor

javaw.exe cannot find path

Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:

-vm
path/javaw.exe

for example:

-vm 
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe

Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays

To iterate over an object which has a json format like below

{
  "mango": { "color": "orange", "taste": "sweet" }
  "lemon": { "color": "yellow", "taste": "sour" }
}
  1. Assign it to a variable

    let rawData = { "mang":{...}, "lemon": {...} }

  2. Create a empty array(s) for holding the values(or keys)

    let dataValues = []; //For values

    let dataKeys = []; //For keys

  3. Loop over the keys and add the values(and keys) to variables

    for(let key in rawData) { //Pay attention to the 'in' dataValues.push(rawData[key]); dataKeys.push(key); }

  4. Now you have an array of keys and values which you can use in *ngFor or a for loop

    for(let d of dataValues) { console.log("Data Values",d); }

    <tr *ngFor='let data of dataValues'> ..... </tr>

Response to preflight request doesn't pass access control check

My "API Server" is an PHP Application so to solve this problem I found the below solution to work:

Place the lines in index.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token');

Python requests - print entire http request (raw)?

test_print.py content:

import logging
import pytest
import requests
from requests_toolbelt.utils import dump


def print_raw_http(response):
    data = dump.dump_all(response, request_prefix=b'', response_prefix=b'')
    return '\n' * 2 + data.decode('utf-8')

@pytest.fixture
def logger():
    log = logging.getLogger()
    log.addHandler(logging.StreamHandler())
    log.setLevel(logging.DEBUG)
    return log

def test_print_response(logger):
    session = requests.Session()
    response = session.get('http://127.0.0.1:5000/')
    assert response.status_code == 300, logger.warning(print_raw_http(response))

hello.py content:

from flask import Flask
app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

Run:

 $ python -m flask hello.py
 $ python -m pytest test_print.py

Stdout:

------------------------------ Captured log call ------------------------------
DEBUG    urllib3.connectionpool:connectionpool.py:225 Starting new HTTP connection (1): 127.0.0.1:5000
DEBUG    urllib3.connectionpool:connectionpool.py:437 http://127.0.0.1:5000 "GET / HTTP/1.1" 200 13
WARNING  root:test_print_raw_response.py:25 

GET / HTTP/1.1
Host: 127.0.0.1:5000
User-Agent: python-requests/2.23.0
Accept-Encoding: gzip, deflate
Accept: */*
Connection: keep-alive


HTTP/1.0 200 OK
Content-Type: text/html; charset=utf-8
Content-Length: 13
Server: Werkzeug/1.0.1 Python/3.6.8
Date: Thu, 24 Sep 2020 21:00:54 GMT

Hello, World!

How do you add a Dictionary of items into another Dictionary

You can also use reduce to merge them. Try this in the playground

let d1 = ["a":"foo","b":"bar"]
let d2 = ["c":"car","d":"door"]

let d3 = d1.reduce(d2) { (var d, p) in
   d[p.0] = p.1
   return d
}

Check a radio button with javascript

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

Native JS solution:

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

JQuery solution:

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

Allow anonymous authentication for a single folder in web.config?

Use <location> configuration tag, and <allow users="?"/> to allow anonymous only or <allow users="*"/> for all:

<configuration>
   <location path="Path/To/Public/Folder">
      <system.web>
         <authorization>
            <allow users="?"/>
         </authorization>
      </system.web>
   </location>
</configuration>

SQL Server: Multiple table joins with a WHERE clause

SELECT Computer.Computer_Name, Application1.Name, Max(Soft.[Version]) as Version1
FROM Application1
inner JOIN Software
    ON Application1.ID = Software.Application_Id
cross join Computer
Left JOIN Software_Computer
    ON Software_Computer.Computer_Id = Computer.ID and Software_Computer.Software_Id = Software.Id
Left JOIN Software as Soft
    ON Soft.Id = Software_Computer.Software_Id
WHERE Computer.ID = 1 
GROUP BY Computer.Computer_Name, Application1.Name 

Swift extract regex matches

Even if the matchesInString() method takes a String as the first argument, it works internally with NSString, and the range parameter must be given using the NSString length and not as the Swift string length. Otherwise it will fail for "extended grapheme clusters" such as "flags".

As of Swift 4 (Xcode 9), the Swift standard library provides functions to convert between Range<String.Index> and NSRange.

func matches(for regex: String, in text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex)
        let results = regex.matches(in: text,
                                    range: NSRange(text.startIndex..., in: text))
        return results.map {
            String(text[Range($0.range, in: text)!])
        }
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

Example:

let string = "€4€9"
let matched = matches(for: "[0-9]", in: string)
print(matched)
// ["4", "9"]

Note: The forced unwrap Range($0.range, in: text)! is safe because the NSRange refers to a substring of the given string text. However, if you want to avoid it then use

        return results.flatMap {
            Range($0.range, in: text).map { String(text[$0]) }
        }

instead.


(Older answer for Swift 3 and earlier:)

So you should convert the given Swift string to an NSString and then extract the ranges. The result will be converted to a Swift string array automatically.

(The code for Swift 1.2 can be found in the edit history.)

Swift 2 (Xcode 7.3.1) :

func matchesForRegexInText(regex: String, text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text,
                                            options: [], range: NSMakeRange(0, nsString.length))
        return results.map { nsString.substringWithRange($0.range)}
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

Example:

let string = "€4€9"
let matches = matchesForRegexInText("[0-9]", text: string)
print(matches)
// ["4", "9"]

Swift 3 (Xcode 8)

func matches(for regex: String, in text: String) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex)
        let nsString = text as NSString
        let results = regex.matches(in: text, range: NSRange(location: 0, length: nsString.length))
        return results.map { nsString.substring(with: $0.range)}
    } catch let error {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

Example:

let string = "€4€9"
let matched = matches(for: "[0-9]", in: string)
print(matched)
// ["4", "9"]

How can I check a C# variable is an empty string "" or null?

if (string.IsNullOrEmpty(myString)) {
   //
}

How to find and turn on USB debugging mode on Nexus 4

Navigate to Settings > About Phone > scroll to the bottom > tap Build number seven (7) times. You'll get a short pop-up in the lower area of your display saying that you're now a developer. 2. Go back and now access the Developer options menu, check 'USB debugging' and click OK on the prompt. This Guide Might Help You : How to Enable USB Debugging in Android Phones

Timer function to provide time in nano seconds using C++

If this is for Linux, I've been using the function "gettimeofday", which returns a struct that gives the seconds and microseconds since the Epoch. You can then use timersub to subtract the two to get the difference in time, and convert it to whatever precision of time you want. However, you specify nanoseconds, and it looks like the function clock_gettime() is what you're looking for. It puts the time in terms of seconds and nanoseconds into the structure you pass into it.

do <something> N times (declarative syntax)

Just use a loop:

var times = 10;
for(var i=0; i < times; i++){
    doSomething();
}

How to concatenate columns in a Postgres SELECT?

Try this

select textcat(textcat(FirstName,' '),LastName) AS Name from person;

'JSON' is undefined error in JavaScript in Internet Explorer

Please add json2.js in your project . i was faced the same issue i have fixed.

please use the link: https://raw.github.com/douglascrockford/JSON-js/master/json2.js and create new file json.js, copy the page and past into newly created file , and move that file into your web application.

I hope it will work.

Error - Android resource linking failed (AAPT2 27.0.3 Daemon #0)

Found one of the reasons which causes this problem

When we try to use any

string,style,color,etc,

in manifest file that is not present in values (string.xml,style.xml,color.xml,etc,) then this type of error occurs

Pycharm/Python OpenCV and CV2 install error

You are getting those errors because opencv and cv2 are not the python package names.

These are both included as part of the opencv-python package available to install from pip.

If you are using python 2 you can install with pip:

 pip install opencv-python

Or use the equivilent for python 3:

pip3 install opencv-python

After running the appropriate pip command your package should be available to use from python.

Redirect pages in JSP?

Hello there: If you need more control on where the link should redirect to, you could use this solution.

Ie. If the user is clicking in the CHECKOUT link, but you want to send him/her to checkout page if its registered(logged in) or registration page if he/she isn't.

You could use JSTL core LIKE:

<!--include the library-->
<%@ taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core" %>

<%--create a var to store link--%>
<core:set var="linkToRedirect">
  <%--test the condition you need--%>
  <core:choose>
    <core:when test="${USER IS REGISTER}">
      checkout.jsp
    </core:when>
    <core:otherwise>
      registration.jsp
    </core:otherwise>
  </core:choose>
</core:set>

EXPLAINING: is the same as...

 //pseudo code
 if(condition == true)
   set linkToRedirect = checkout.jsp
 else
   set linkToRedirect = registration.jsp

THEN: in simple HTML...

<a href="your.domain.com/${linkToRedirect}">CHECKOUT</a>

Search for string within text column in MySQL

You could probably use the LIKE clause to do some simple string matching:

SELECT * FROM items WHERE items.xml LIKE '%123456%'

If you need more advanced functionality, take a look at MySQL's fulltext-search functions here: http://dev.mysql.com/doc/refman/5.1/en/fulltext-search.html

MVC 4 - Return error message from Controller - Show in View

The Return View(model) returns you error because you don't fill the model with the values in your post method and the model data for the dropdown is empty. Please provide the Get method to explain further how to manage displaying the error. In order to the error to be shown you should use this:

[HttpPost]
public ActionResult form_edit(FormModels model)
{          
   if(ModelState.IsValid())
   {
      --- operations 
      return Redirect("OtherAction", "SomeController");
   }

   // here you can use a little trick
   //fill the model property that holds the information for the dropdown with the data 

   // you haven't provided the get method but it should look something like this
   model.Countries = ... some data goes here;
   model.dd_value = ... some other data;
   model.dd_text = ... other data;

   ModelState.AddModelError("", "adfdghdghgdhgdhdgda");
   return View(model);
}

and then in the view just use :

@model mvc_cs.Models.FormModels
@using ctrlr = mvc_cs.Controllers.FormController


@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{

    <table>
    <tr>
    <td>       
    @Html.ValidationSummary(true)             
    </td>
    </tr>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.content_name)
        @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")

    </th>
</tr>
</table>

<table>
<tr>
    <td>
        <input  type="submit" value="Submit" />
    </td>
</tr>
</table>
}

This should work okay.

If you just use RedirectToAction it will redirect you to the get method --> you will have no error but the view will be just reloaded and no error would be shown.

other way around is that you can pass the error not by ModelState.AddError, but with ViewData["error"] like this:

[HttpPost]
public ActionResult form_edit(FormModels model)
{          
   TempData["error"] = "someErrorMessage";
   return RedirectToAction("form_Post", "Form");
}

[HttpGet]
public ActionResult form_edit()
{
    do stuff here ----
    ViewData["error"] = TempData["error"];
    return View();
}

@model mvc_cs.Models.FormModels
@using ctrlr = mvc_cs.Controllers.FormController


@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{

    <table>
    <tr>
    <td>       
    <div>@ViewData["error"]</div>             
    </td>
    </tr>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.content_name)
        @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")

    </th>
</tr>
</table>

<table>
<tr>
    <td>
        <input  type="submit" value="Submit" />
    </td>
</tr>
</table>
}

Cannot use a leading ../ to exit above the top directory

You can use ~/img/myImage.png instead of ../img/myImage.png to avoid this error in ASP.NET pages.

Redeploy alternatives to JRebel

Hotswap Agent is an extension to DCEVM which supports many Java frameworks (reload Spring bean definition, Hibernate entity mapping, logger level setup, ...).

There is also lot of documentation how to setup DCEVM and compiled binaries for Java 1.7.

forward declaration of a struct in C?

A struct (without a typedef) often needs to (or should) be with the keyword struct when used.

struct A;                      // forward declaration
void function( struct A *a );  // using the 'incomplete' type only as pointer

If you typedef your struct you can leave out the struct keyword.

typedef struct A A;          // forward declaration *and* typedef
void function( A *a );

Note that it is legal to reuse the struct name

Try changing the forward declaration to this in your code:

typedef struct context context;

It might be more readable to do add a suffix to indicate struct name and type name:

typedef struct context_s context_t;

Take the content of a list and append it to another list

Take a look at itertools.chain for a fast way to treat many small lists as a single big list (or at least as a single big iterable) without copying the smaller lists:

>>> import itertools
>>> p = ['a', 'b', 'c']
>>> q = ['d', 'e', 'f']
>>> r = ['g', 'h', 'i']
>>> for x in itertools.chain(p, q, r):
        print x.upper()

How do I initialize an empty array in C#?

As I know you can't make array without size, but you can use

List<string> l = new List<string>() 

and then l.ToArray().

How do I define a method in Razor?

You can simply declare them as local functions in a razor block (i.e. @{}).

@{
    int Add(int x, int y)
    {
        return x + y;
    }
}

<div class="container">
    <p>
        @Add(2, 5)
    </p>
</div>

Is there a max array length limit in C++?

I'm surprised the max_size() member function of std::vector has not been mentioned here.

"Returns the maximum number of elements the container is able to hold due to system or library implementation limitations, i.e. std::distance(begin(), end()) for the largest container."

We know that std::vector is implemented as a dynamic array underneath the hood, so max_size() should give a very close approximation of the maximum length of a dynamic array on your machine.

The following program builds a table of approximate maximum array length for various data types.

#include <iostream>
#include <vector>
#include <string>
#include <limits>

template <typename T>
std::string mx(T e) {
    std::vector<T> v;
    return std::to_string(v.max_size());
}

std::size_t maxColWidth(std::vector<std::string> v) {
    std::size_t maxWidth = 0;

    for (const auto &s: v)
        if (s.length() > maxWidth)
            maxWidth = s.length();

    // Add 2 for space on each side
    return maxWidth + 2;
}

constexpr long double maxStdSize_t = std::numeric_limits<std::size_t>::max();

// cs stands for compared to std::size_t
template <typename T>
std::string cs(T e) {
    std::vector<T> v;
    long double maxSize = v.max_size();
    long double quotient = maxStdSize_t / maxSize;
    return std::to_string(quotient);
}

int main() {
    bool v0 = 0;
    char v1 = 0;

    int8_t v2 = 0;
    int16_t v3 = 0;
    int32_t v4 = 0;
    int64_t v5 = 0;

    uint8_t v6 = 0;
    uint16_t v7 = 0;
    uint32_t v8 = 0;
    uint64_t v9 = 0;

    std::size_t v10 = 0;
    double v11 = 0;
    long double v12 = 0;

    std::vector<std::string> types = {"data types", "bool", "char", "int8_t", "int16_t",
                                      "int32_t", "int64_t", "uint8_t", "uint16_t",
                                      "uint32_t", "uint64_t", "size_t", "double",
                                      "long double"};

    std::vector<std::string> sizes = {"approx max array length", mx(v0), mx(v1), mx(v2),
                                      mx(v3), mx(v4), mx(v5), mx(v6), mx(v7), mx(v8),
                                      mx(v9), mx(v10), mx(v11), mx(v12)};

    std::vector<std::string> quotients = {"max std::size_t / max array size", cs(v0),
                                          cs(v1), cs(v2), cs(v3), cs(v4), cs(v5), cs(v6),
                                          cs(v7), cs(v8), cs(v9), cs(v10), cs(v11), cs(v12)};

    std::size_t max1 = maxColWidth(types);
    std::size_t max2 = maxColWidth(sizes);
    std::size_t max3 = maxColWidth(quotients);

    for (std::size_t i = 0; i < types.size(); ++i) {
        while (types[i].length() < (max1 - 1)) {
            types[i] = " " + types[i];
        }

        types[i] += " ";

        for  (int j = 0; sizes[i].length() < max2; ++j)
            sizes[i] = (j % 2 == 0) ? " " + sizes[i] : sizes[i] + " ";

        for  (int j = 0; quotients[i].length() < max3; ++j)
            quotients[i] = (j % 2 == 0) ? " " + quotients[i] : quotients[i] + " ";

        std::cout << "|" << types[i] << "|" << sizes[i] << "|" << quotients[i] << "|\n";
    }

    std::cout << std::endl;

    std::cout << "N.B. max std::size_t is: " <<
        std::numeric_limits<std::size_t>::max() << std::endl;

    return 0;
}

On my macOS (clang version 5.0.1), I get the following:

|  data types | approx max array length | max std::size_t / max array size |
|        bool |   9223372036854775807   |             2.000000             |
|        char |   9223372036854775807   |             2.000000             |
|      int8_t |   9223372036854775807   |             2.000000             |
|     int16_t |   9223372036854775807   |             2.000000             |
|     int32_t |   4611686018427387903   |             4.000000             |
|     int64_t |   2305843009213693951   |             8.000000             |
|     uint8_t |   9223372036854775807   |             2.000000             |
|    uint16_t |   9223372036854775807   |             2.000000             |
|    uint32_t |   4611686018427387903   |             4.000000             |
|    uint64_t |   2305843009213693951   |             8.000000             |
|      size_t |   2305843009213693951   |             8.000000             |
|      double |   2305843009213693951   |             8.000000             |
| long double |   1152921504606846975   |             16.000000            |

N.B. max std::size_t is: 18446744073709551615

On ideone gcc 8.3 I get:

|  data types | approx max array length | max std::size_t / max array size |
|        bool |   9223372036854775744   |             2.000000             |
|        char |   18446744073709551615  |             1.000000             |
|      int8_t |   18446744073709551615  |             1.000000             |
|     int16_t |   9223372036854775807   |             2.000000             |
|     int32_t |   4611686018427387903   |             4.000000             |
|     int64_t |   2305843009213693951   |             8.000000             |
|     uint8_t |   18446744073709551615  |             1.000000             |
|    uint16_t |   9223372036854775807   |             2.000000             |
|    uint32_t |   4611686018427387903   |             4.000000             |
|    uint64_t |   2305843009213693951   |             8.000000             |
|      size_t |   2305843009213693951   |             8.000000             |
|      double |   2305843009213693951   |             8.000000             |
| long double |   1152921504606846975   |             16.000000            |

N.B. max std::size_t is: 18446744073709551615

It should be noted that this is a theoretical limit and that on most computers, you will run out of memory far before you reach this limit. For example, we see that for type char on gcc, the maximum number of elements is equal to the max of std::size_t. Trying this, we get the error:

prog.cpp: In function ‘int main()’:
prog.cpp:5:61: error: size of array is too large
  char* a1 = new char[std::numeric_limits<std::size_t>::max()];

Lastly, as @MartinYork points out, for static arrays the maximum size is limited by the size of your stack.

insert vertical divider line between two nested divs, not full height

Use a div for your divider. It will always be centered vertically regardless to whether left and right divs are equal in height. You can reuse it anywhere on your site.

.divider{
    position:absolute;
    left:50%;
    top:10%;
    bottom:10%;
    border-left:1px solid white;
}

Check working example at http://jsfiddle.net/gtKBs/

Fast way to discover the row count of a table in PostgreSQL

You can get the count by the below query (without * or any column names).

select from table_name;

Hashmap does not work with int, char

Hashmaps can only use classes, not primitives. This page from programmerinterview.com might be of use in guiding you to finding the answer. To be honest, I haven't figured out the answer to this problem in detail myself.

How do you do natural logs (e.g. "ln()") with numpy in Python?

I usually do like this:

from numpy import log as ln

Perhaps this can make you more comfortable.

Ruby on Rails. How do I use the Active Record .build method in a :belongs to relationship?

@article = user.articles.build(:title => "MainTitle")
@article.save

Chrome:The website uses HSTS. Network errors...this page will probably work later

When you visited https://localhost previously at some point it not only visited this over a secure channel (https rather than http), it also told your browser, using a special HTTP header: Strict-Transport-Security (often abbreviated to HSTS), that it should ONLY use https for all future visits.

This is a security feature web servers can use to prevent people being downgraded to http (either intentionally or by some evil party).

However if you then then turn off your https server, and just want to browse http you can't (by design - that's the point of this security feature).

HSTS also does prevents you from accepting and skipping past certificate errors.

To reset this, so HSTS is no longer set for localhost, type the following in your Chrome address bar:

chrome://net-internals/#hsts

Where you will be able to delete this setting for "localhost".

You might also want to find out what was setting this to avoid this problem in future!

Note that for other sites (e.g. www.google.com) these are "preloaded" into the Chrome code and so cannot be removed. When you query them at chrome://net-internals/#hsts you will see them listed as static HSTS entries.

And finally note that Google has started preloading HSTS for the entire .dev domain: https://ma.ttias.be/chrome-force-dev-domains-https-via-preloaded-hsts/

No function matches the given name and argument types

In my particular case the function was actually missing. The error message is the same. I am using the Postgresql plugin PostGIS and I had to reinstall that for whatever reason.

Pretty-print an entire Pandas Series / DataFrame

You can also use the option_context, with one or more options:

with pd.option_context('display.max_rows', None, 'display.max_columns', None):  # more options can be specified also
    print(df)

This will automatically return the options to their previous values.

If you are working on jupyter-notebook, using display(df) instead of print(df) will use jupyter rich display logic (like so).

Using SSIS BIDS with Visual Studio 2012 / 2013

First Off, I object to this other question regarding Visual Studio 2015 as a duplicate question. How do I open SSRS (.rptproj) and SSIS (.dtproj) files in Visual Studio 2015? [duplicate]

Basically this question has the title ...Visual Studio 2012 / 2013 What about ALL the improvements and changes to VS 2015 ??? SSDT has been updated and changed. The entire way of doing various additions and updates is different.

So having vented / rant - I did open a VS 2015 update 2 instance and proceeded to open an existing solution that include a .rptproj project. Now this computer does not yet have sql server installed on it yet.

Solution for ME : Tools --> Extension and Updates --> Updates --> sql server tooling updates

Click on Update button and wait a long time and SSDT then installs and close visual studio 2015 and re-open and it works for me.

In case it is NOT found in VS 2015 for some reason : scroll to the bottom, pick your language iso https://msdn.microsoft.com/en-us/mt186501.aspx?f=255&MSPPError=-2147217396

How to center content in a bootstrap column?

//add this to your css
    .myClass{
          margin 0 auto;
          }

// add the class to the span tag( could add it to the div and not using a span  
// at all
    <div class="row">
   <div class="col-xs-1 center-block">
       <span class="myClass">aaaaaaaaaaaaaaaaaaaaaaaaaaa</span>
   </div>
 </div>

Java generics: multiple generic parameters?

In your function definition you're constraining sets a and b to the same type. You can also write

public <X,Y> void myFunction(Set<X> s1, Set<Y> s2){...}

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

I just did some dumb try and error with the 2 values of rowHeight and estimatedRowHeight and just thought it might provide some debugging insight:

If you set them both OR only set the estimatedRowHeight you will get the desired behavior:

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 1.00001 // MUST be greater than 1

It's suggested that you do your best to get the correct estimate, but the end result isn't different. It will just affect your performance.

enter image description here


If you only set the rowHeight ie only do:

tableView.rowHeight = UITableViewAutomaticDimension

your end result would not be as desired:

enter image description here


If you set the estimatedRowHeight to 1 or smaller then you will crash regardless of the rowHeight.

tableView.rowHeight = UITableViewAutomaticDimension
tableView.estimatedRowHeight = 1 

I crashed with the following error message:

Terminating app due to uncaught exception
'NSInternalInconsistencyException', reason: 'table view row height
must not be negative - provided height for index path (<NSIndexPath:
0xc000000000000016> {length = 2, path = 0 - 0}) is -1.000000'
    ...some other lines...

libc++abi.dylib: terminating with uncaught exception of type
NSException

Iterating through a golang map

You could just write it out in multiline like this,

$ cat dict.go
package main

import "fmt"

func main() {
        items := map[string]interface{}{
                "foo": map[string]int{
                        "strength": 10,
                        "age": 2000,
                },
                "bar": map[string]int{
                        "strength": 20,
                        "age": 1000,
                },
        }
        for key, value := range items {
                fmt.Println("[", key, "] has items:")
                for k,v := range value.(map[string]int) {
                        fmt.Println("\t-->", k, ":", v)
                }

        }
}

And the output:

$ go run dict.go
[ foo ] has items:
        --> strength : 10
        --> age : 2000
[ bar ] has items:
        --> strength : 20
        --> age : 1000

Concatenate a NumPy array to another NumPy array

Actually one can always create an ordinary list of numpy arrays and convert it later.

In [1]: import numpy as np

In [2]: a = np.array([[1,2],[3,4]])

In [3]: b = np.array([[1,2],[3,4]])

In [4]: l = [a]

In [5]: l.append(b)

In [6]: l = np.array(l)

In [7]: l.shape
Out[7]: (2, 2, 2)

In [8]: l
Out[8]: 
array([[[1, 2],
        [3, 4]],

       [[1, 2],
        [3, 4]]])

yii2 redirect in controller action does not work?

Don't use exit(0); That's bad practice at the best of times. Use Yii::$app->end();

So your code would look like

$this->redirect(['index'], 302);
Yii::$app->end();

That said though the actual problem was stopping POST requests, this is the wrong solution to that problem (although it does work). To stop POST requests you need to use access control.

public function behaviors()
{
    return [
        'access' => [
            'class' => \yii\filters\AccessControl::className(),
            'only' => ['create', 'update'],
            'rules' => [
                // deny all POST requests
                [
                    'allow' => false,
                    'verbs' => ['POST']
                ],
                // allow authenticated users
                [
                    'allow' => true,
                    'roles' => ['@'],
                ],
                // everything else is denied
            ],
        ],
    ];
}

How does Java resolve a relative path in new File()?

On windows and Netbeans you can set the relative path as:

    new FileReader("src\\PACKAGE_NAME\\FILENAME");

On Linux and Netbeans you can set the relative path as:

    new FileReader("src/PACKAGE_NAME/FILENAME");

If you have your code inside Source Packages I do not know if it is the same for eclipse or other IDE

How to run single test method with phpunit?

If you're in netbeans you can right click in the test method and click "Run Focused Test Method".

Run Focused Test Method menu

403 - Forbidden: Access is denied. You do not have permission to view this directory or page using the credentials that you supplied

I had the same problem. It turned out that I didn't specify a default page and I didn't have any page that is named after the default page convention (default.html, defult.aspx etc). As a result, ASP.NET doesn't allow the user to browse the directory (not a problem in Visual Studio built-in web server that allows you to view the directory) and shows the error message. To fix it, I added one default page in Web.Config and it worked.

<system.webServer>
    <defaultDocument>
        <files>
            <add value="myDefault.aspx"/>
        </files>
    </defaultDocument>
</system.webServer>

Detect Safari browser

Read many answers and posts and determined the most accurate solution. Tested in Safari, Chrome, Firefox (desktop and iOS versions). First we need to detect Apple vendor and then exclude Chrome and Firefox (for iOS).

let isSafari = navigator.vendor.match(/apple/i) &&
             !navigator.userAgent.match(/crios/i) &&
             !navigator.userAgent.match(/fxios/i);

if (isSafari) {
  //
} else {
  //
}

How can I get the current time in C#?

try this:

 string.Format("{0:HH:mm:ss tt}", DateTime.Now);

for further details you can check it out : How do you get the current time of day?

Show popup after page load

  <script type="text/javascript">
  jQuery(document).ready(function(){
         setTimeout(PopUp(),5000); // invoke Popup function after 5 seconds 
  });
   </script>

How do I set a background-color for the width of text, not the width of the entire element, using CSS?

h1 is a block level element. You will need to use something like span instead as it is an inline level element (ie: it does not span the whole row).

In your case, I would suggest the following:

style.css

.highlight 
{
   background-color: green;
}

html

<span class="highlight">only the text will be highlighted</span>

Where do I find the bashrc file on Mac?

On your Terminal:

  • Type cd ~/ to go to your home folder.

  • Type touch .bash_profile to create your new file.

  • Edit .bash_profile with your code editor (or you can just type open -e .bash_profile to open it in TextEdit).
  • Type . .bash_profile to reload .bash_profile and update any functions you add.

Change text color with Javascript?

Try below code:

$(document).ready(function(){
$('#about').css({'background-color':'black'});    
});

http://jsfiddle.net/jPCFC/

How do I create a crontab through a script

Here is how to modify cron a entry without directly editing the cron file (which is frowned upon).

crontab -l -u <user> | sed 's/find/replace/g' | crontab -u <user> -

If you want to remove a cron entry, use this:

crontab -l -u <user> | sed '/find/d' | crontab -u <user> -

I realize this is not what gaurav was asking for, but why not have all the solutions in one place?

JDBC ResultSet: I need a getDateTime, but there is only getDate and getTimeStamp

this worked:

    Date date = null;
    String dateStr = rs.getString("doc_date");
    if (dateStr != null) {
        date = dateFormat.parse(dateStr);
    }

using SimpleDateFormat.

Using an IF Statement in a MySQL SELECT query

How to use an IF statement in the MySQL "select list":

select if (1>2, 2, 3);                         //returns 3
select if(1<2,'yes','no');                     //returns yes
SELECT IF(STRCMP('test','test1'),'no','yes');  //returns no

How to use an IF statement in the MySQL where clause search condition list:

create table penguins (id int primary key auto_increment, name varchar(100))
insert into penguins (name) values ('rico')
insert into penguins (name) values ('kowalski')
insert into penguins (name) values ('skipper')

select * from penguins where 3 = id
-->3    skipper

select * from penguins where (if (true, 2, 3)) = id
-->2    kowalski

How to use an IF statement in the MySQL "having clause search conditions":

select * from penguins 
where 1=1
having (if (true, 2, 3)) = id
-->1    rico

Use an IF statement with a column used in the select list to make a decision:

select (if (id = 2, -1, 1)) item
from penguins
where 1=1
--> 1
--> -1
--> 1

If statements embedded in SQL queries is a bad "code smell". Bad code has high "WTF's per minute" during code review. This is one of those things. If I see this in production with your name on it, I'm going to automatically not like you.

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

Note that if you are installing this through Anaconda, you will need to open Anaconda as an administrator and then launch the command prompt from there.

Otherwise, you can also run "Anaconda prompt" directly as an administrator to uninstall and install packages.

How to set time to a date object in java

I should like to contribute the modern answer. This involves using java.time, the modern Java date and time API, and not the old Date nor Calendar except where there’s no way to avoid it.

Your issue is very likely really a timezone issue. When it is Tue Aug 09 00:00:00 IST 2011, in time zones west of IST midnight has not yet been reached. It is still Aug 8. If for example your API for putting the date into Excel expects UTC, the date will be the day before the one you intended. I believe the real and good solution is to produce a date-time of 00:00 UTC (or whatever time zone or offset is expected and used at the other end).

    LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
    ZonedDateTime utcDateDime = yourDate.atStartOfDay(ZoneOffset.UTC);
    System.out.println(utcDateDime);

This prints

2018-02-27T00:00Z

Z means UTC (think of it as offset zero from UTC or Zulu time zone). Better still, of course, if you could pass the LocalDate from the first code line to Excel. It doesn’t include time-of-day, so there is no confusion possible. On the other hand, if you need an old-fashioned Date object for that, convert just before handing the Date on:

    Date oldfashionedDate = Date.from(utcDateDime.toInstant());
    System.out.println(oldfashionedDate);

On my computer this prints

Tue Feb 27 01:00:00 CET 2018

Don’t be fooled, it is correct. My time zone (Central European Time) is at offset +01:00 from UTC in February (standard time), so 01:00:00 here is equal to 00:00:00 UTC. It’s just Date.toString() grabbing the JVMs time zone and using it for producing the string.

How can I set it to something like 5:30 pm?

To answer your direct question directly, if you have a ZonedDateTime, OffsetDateTime or LocalDateTime, in all of these cases the following will accomplish what you asked for:

    yourDateTime = yourDateTime.with(LocalTime.of(17, 30));

If yourDateTime was a LocalDateTime of 2018-02-27T00:00, it will now be 2018-02-27T17:30. Similarly for the other types, only they include offset and time zone too as appropriate.

If you only had a date, as in the first snippet above, you can also add time-of-day information to it:

    LocalDate yourDate = LocalDate.of(2018, Month.FEBRUARY, 27);
    LocalDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30));

For most purposes you should prefer to add the time-of-day in a specific time zone, though, for example

    ZonedDateTime dateTime = yourDate.atTime(LocalTime.of(17, 30))
            .atZone(ZoneId.of("Asia/Kolkata"));

This yields 2018-02-27T17:30+05:30[Asia/Kolkata].

Date and Calendar vs java.time

The Date class that you use as well as Calendar and SimpleDateFormat used in the other answers are long outdated, and SimpleDateFormat in particular has proven troublesome. In all cases the modern Java date and time API is so much nicer to work with. Which is why I wanted to provide this answer to an old question that is still being visited.

Link: Oracle Tutorial Date Time, explaining how to use java.time.

jQuery Combobox/select autocomplete?

Have a look at the following example of the jQueryUI Autocomplete, as it is keeping a select around and I think that is what you are looking for. Hope this helps.

http://jqueryui.com/demos/autocomplete/#combobox

Download files from server php

If the folder is accessible from the browser (not outside the document root of your web server), then you just need to output links to the locations of those files. If they are outside the document root, you will need to have links, buttons, whatever, that point to a PHP script that handles getting the files from their location and streaming to the response.

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

I fixed this issue by installing: sudo apt-get install libstdc++6

In my case, I ran into this issue after installing MongoDB 3.0.1

mongo: /usr/lib/x86_64-linux-gnu/libstdc++.so.6: version `GLIBCXX_3.4.18' not found (required by mongo)

dd: How to calculate optimal blocksize?

This is totally system dependent. You should experiment to find the optimum solution. Try starting with bs=8388608. (As Hitachi HDDs seems to have 8MB cache.)

Javascript return number of days,hours,minutes,seconds between two dates

I call it the "snowman ? method" and I think it's a little more flexible when you need additional timespans like weeks, moths, years, centuries... and don't want too much repetitive code:

var d = Math.abs(date_future - date_now) / 1000;                           // delta
var r = {};                                                                // result
var s = {                                                                  // structure
    year: 31536000,
    month: 2592000,
    week: 604800, // uncomment row to ignore
    day: 86400,   // feel free to add your own row
    hour: 3600,
    minute: 60,
    second: 1
};

Object.keys(s).forEach(function(key){
    r[key] = Math.floor(d / s[key]);
    d -= r[key] * s[key];
});

// for example: {year:0,month:0,week:1,day:2,hour:34,minute:56,second:7}
console.log(r);

Have a FIDDLE / ES6 Version (2018) / TypeScript Version (2019)

Inspired by Alnitak's answer.

How to backup a local Git repository?

[Just leaving this here for my own reference.]

My bundle script called git-backup looks like this

#!/usr/bin/env ruby
if __FILE__ == $0
        bundle_name = ARGV[0] if (ARGV[0])
        bundle_name = `pwd`.split('/').last.chomp if bundle_name.nil? 
        bundle_name += ".git.bundle"
        puts "Backing up to bundle #{bundle_name}"
        `git bundle create /data/Dropbox/backup/git-repos/#{bundle_name} --all`
end

Sometimes I use git backup and sometimes I use git backup different-name which gives me most of the possibilities I need.

Calling pylab.savefig without display in ipython

We don't need to plt.ioff() or plt.show() (if we use %matplotlib inline). You can test above code without plt.ioff(). plt.close() has the essential role. Try this one:

%matplotlib inline
import pylab as plt

# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()

# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)

# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')

If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2) to the end of it, you will see nothing.

In conclusion, if you close figure by plt.close(fig), it won't be displayed.

Convert array of strings to List<string>

From .Net 3.5 you can use LINQ extension method that (sometimes) makes code flow a bit better.

Usage looks like this:

using System.Linq; 

// ...

public void My()
{
    var myArray = new[] { "abc", "123", "zyx" };
    List<string> myList = myArray.ToList();
}

PS. There's also ToArray() method that works in other way.

No module named pkg_resources

I experienced that error in my Google App Engine environment. And pip install -t lib setuptools fixed the issue.

React: why child component doesn't update when prop changes

Because children do not rerender if the props of the parent change, but if its STATE changes :)

What you are showing is this: https://facebook.github.io/react/tips/communicate-between-components.html

It will pass data from parent to child through props but there is no rerender logic there.

You need to set some state to the parent then rerender the child on parent change state. This could help. https://facebook.github.io/react/tips/expose-component-functions.html

0xC0000005: Access violation reading location 0x00000000

The problem here, as explained in other comments, is that the pointer is being dereference without being properly initialized. Operating systems like Linux keep the lowest addresses (eg first 32MB: 0x00_0000 -0x200_0000) out of the virtual address space of a process. This is done because dereferencing zeroed non-initialized pointers is a common mistake, like in this case. So when this type of mistake happens, instead of actually reading a random variable that happens to be at address 0x0 (but not the memory address the pointer would be intended for if initialized properly), the pointer would be reading from a memory address outside of the process's virtual address space. This causes a page fault, which results in a segmentation fault, and a signal is sent to the process to kill it. That's why you are getting the access violation error.

A SQL Query to select a string between two known strings

You're getting the starting position of 'punishment immediately', but passing that in as the length parameter for your substring.

You would need to substract the starting position of 'the dog' from the charindex of 'punishment immediately', and then add the length of the 'punishment immediately' string to your third parameter. This would then give you the correct text.

Here's some rough, hacky code to illustrate the process:

DECLARE @text VARCHAR(MAX)
SET @text = 'All I knew was that the dog had been very bad and required harsh punishment immediately regardless of what anyone else thought.'

DECLARE @start INT
SELECT @start = CHARINDEX('the dog',@text)

DECLARE @endLen INT
SELECT @endLen = LEN('immediately')

DECLARE @end INT
SELECT @end = CHARINDEX('immediately',@text)
SET @end = @end - @start + @endLen

SELECT @end

SELECT SUBSTRING(@text,@start,@end)

Result: the dog had been very bad and required harsh punishment immediately

ORA-01652 Unable to extend temp segment by in tablespace

Create a new datafile by running the following command:

alter tablespace TABLE_SPACE_NAME add datafile 'D:\oracle\Oradata\TEMP04.dbf'            
   size 2000M autoextend on;

How can I show a message box with two buttons?

Remember - if you set the buttons to vbOkOnly - it will always return 1.

So you can't decide if a user clicked on the close or the OK button. You just have to add a vbOk option.

How to make an introduction page with Doxygen

As of v1.8.8 there is also the option USE_MDFILE_AS_MAINPAGE. So make sure to add your index file, e.g. README.md, to INPUT and set it as this option's value:

INPUT += README.md
USE_MDFILE_AS_MAINPAGE = README.md

How to create range in Swift?

(1..<10)

returns...

Range = 1..<10

Hibernate: "Field 'id' doesn't have a default value"

When your field is not nullable it requires a default value to be specified on table creation. Recreate a table with AUTO_INCREMENT properly initialized so DB will not require default value since it will generate it by itself and never put NULL there.

CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)

);

https://www.w3schools.com/sql/sql_autoincrement.asp

Difference between the 'controller', 'link' and 'compile' functions when defining a directive

  1. running code before Compilation : use controller
  2. running code after Compilation : use Link

Angular convention : write business logic in controller and DOM manipulation in link.

Apart from this you can call one controller function from link function of another directive.For example you have 3 custom directives

<animal>
<panther>
<leopard></leopard>
</panther> 
</animal>

and you want to access animal from inside of "leopard" directive.

http://egghead.io/lessons/angularjs-directive-communication will be helpful to know about inter-directive communication

javascript close current window

TRY this out it works fine ...

<!DOCTYPE html>
<html>
<body>

<input type="button"  onclick="openWin()" value="open"/>
<input type="button"  onclick="closeWin()" value="close"/>

<script>
var myWindow;

function openWin()
{
myWindow = window.open("","myWindow","width=200,height=100");
myWindow.document.write("<p>This is 'myWindow'</p>");
}

function closeWin()
{
myWindow.close();
}
</script>

</body>
</html>

this works as you want it to work

Get random item from array

echo $items[array_rand($items)];

array_rand()

Stored procedure with default parameters

I wrote with parameters that are predefined

They are not "predefined" logically, somewhere inside your code. But as arguments of SP they have no default values and are required. To avoid passing those params explicitly you have to define default values in SP definition:

Alter Procedure [Test]
    @StartDate AS varchar(6) = NULL, 
    @EndDate AS varchar(6) = NULL
AS
...

NULLs or empty strings or something more sensible - up to you. It does not matter since you are overwriting values of those arguments in the first lines of SP.

Now you can call it without passing any arguments e.g. exec dbo.TEST

Pad a number with leading zeros in JavaScript

You did say you had a number-

String.prototype.padZero= function(len, c){
    var s= '', c= c || '0', len= (len || 2)-this.length;
    while(s.length<len) s+= c;
    return s+this;
}
Number.prototype.padZero= function(len, c){
    return String(this).padZero(len,c);
}

How to access global variables

I suggest use the common way of import.

First I will explain the way it called "relative import" maybe this way cause of some error

Second I will explain the common way of import.

FIRST:

In go version >= 1.12 there is some new tips about import file and somethings changed.

1- You should put your file in another folder for example I create a file in "model" folder and the file's name is "example.go"

2- You have to use uppercase when you want to import a file!

3- Use Uppercase for variables, structures and functions that you want to import in another files

Notice: There is no way to import the main.go in another file.

file directory is:

root
|_____main.go
|_____model
          |_____example.go

this is a example.go:

package model

import (
    "time"
)

var StartTime = time.Now()

and this is main.go you should use uppercase when you want to import a file. "Mod" started with uppercase

package main

import (
    Mod "./model"
    "fmt"
)

func main() {
    fmt.Println(Mod.StartTime)
}

NOTE!!!

NOTE: I don't recommend this this type of import!

SECOND:

(normal import)

the better way import file is:

your structure should be like this:

root
|_____github.com
         |_________Your-account-name-in-github
         |                |__________Your-project-name
         |                                |________main.go
         |                                |________handlers
         |                                |________models
         |               
         |_________gorilla
                         |__________sessions

and this is a example:

package main

import (
    "github.com/gorilla/sessions"
)

func main(){
     //you can use sessions here
}

so you can import "github.com/gorilla/sessions" in every where that you want...just import it.

Regex, every non-alphanumeric character except white space or colon

Try this:

[^a-zA-Z0-9 :]

JavaScript example:

"!@#$%* ABC def:123".replace(/[^a-zA-Z0-9 :]/g, ".")

See a online example:

http://jsfiddle.net/vhMy8/

using nth-child in tables tr td

table tr td:nth-child(2) {
    background: #ccc;
}

Working example: http://jsfiddle.net/gqr3J/

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

Fit Image in ImageButton in Android

I want them to cover 75% of the button area.

Use android:padding="20dp" (adjust the padding as needed) to control how much the image takes up on the button.

but where as some images cover less area, some are too big to fit into the imageButton. How to programatically resize and show them?

Use a android:scaleType="fitCenter" to have Android scale the images, and android:adjustViewBounds="true" to have them adjust their bounds due to scaling.

All of these attributes can be set in code on each ImageButton at runtime. However, it is much easier to set and preview in xml in my opinion.

Also, do not use sp for anything other than text size, it is scaled depending on the text size preference the user sets, so your sp dimensions will be larger than your intended if the user has a "large" text setting. Use dp instead, as it is not scaled by the user's text size preference.

Here's a snippet of what each button should look like:

    <ImageButton
        android:id="@+id/button_topleft"
        android:layout_width="0dp"
        android:layout_height="match_parent"
        android:layout_marginBottom="5dp"
        android:layout_marginLeft="2dp"
        android:layout_marginRight="5dp"
        android:layout_marginTop="0dp"
        android:layout_weight="1"
        android:adjustViewBounds="true"
        android:padding="20dp"
        android:scaleType="fitCenter" />

Sample Button

How does "FOR" work in cmd batch file?

I know this is SUPER old... but just for fun I decided to give this a try:

@Echo OFF
setlocal
set testpath=%path: =#%
FOR /F "tokens=* delims=;" %%P in ("%testpath%") do call :loop %%P
:loop
if '%1'=='' goto endloop
set testpath=%1
set testpath=%testpath:#= %
echo %testpath%
SHIFT
goto :loop
:endloop
pause
endlocal
exit

This doesn't require a count and will go until it finishes. I had the same problem with spaces but it made it through the entire variable. The key to this is the loop labels and the SHIFT function.

Using JAXB to unmarshal/marshal a List<String>

From a personal blog post, it is not necessary to create a specific JaxbList < T > object.

Assuming an object with a list of strings:

@XmlRootElement
public class ObjectWithList {

    private List<String> list;

    @XmlElementWrapper(name="MyList")
    @XmlElement
    public List<String> getList() {
        return list;
    }

    public void setList(List<String> list) {
        this.list = list;
    }

}

A JAXB round trip:

public static void simpleExample() throws JAXBException {

    List<String> l = new ArrayList<String>();
    l.add("Somewhere");
    l.add("This and that");
    l.add("Something");

    // Object with list
    ObjectWithList owl = new ObjectWithList();
    owl.setList(l);

    JAXBContext jc = JAXBContext.newInstance(ObjectWithList.class);
    ObjectWithList retr = marshallUnmarshall(owl, jc);

    for (String s : retr.getList()) {
        System.out.println(s);
    } System.out.println(" ");

}

Produces the following:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<objectWithList>
    <MyList>
        <list>Somewhere</list>
        <list>This and that</list>
        <list>Something</list>
    </MyList>
</objectWithList>

Foreign key referencing a 2 columns primary key in SQL Server

The key is "the order of the column should be the same"

Example:

create Table A (
    A_ID char(3) primary key,
    A_name char(10) primary key,
    A_desc desc char(50)
)

create Table B (
    B_ID char(3) primary key,
    B_A_ID char(3),
    B_A_Name char(10),
    constraint [Fk_B_01] foreign key (B_A_ID,B_A_Name) references A(A_ID,A_Name)
)

the column order on table A should be --> A_ID then A_Name; defining the foreign key should follow the same order as well.

Print a div content using Jquery

None of the solutions above work perfectly.They either loses CSS or have to include/edit external CSS file. I found a perfect solution that will not lose your CSS nor you have to edit/add external CSS.

HTML:

<div id='printarea'>
    <p>This is a sample text for printing purpose.</p>
    <input type='button' id='btn' value='Print' onclick='printFunc();'>
</div>
<p>Do not print.</p

JQuery:

function printFunc() {
    var divToPrint = document.getElementById('printarea');
    var htmlToPrint = '' +
        '<style type="text/css">' +
        'table th, table td {' +
        'border:1px solid #000;' +
        'padding;0.5em;' +
        '}' +
        '</style>';
    htmlToPrint += divToPrint.outerHTML;
    newWin = window.open("");
    newWin.document.write("<h3 align='center'>Print Page</h3>");
    newWin.document.write(htmlToPrint);
    newWin.print();
    newWin.close();
    }

Get content of a cell given the row and column numbers

It took me a while, but here's how I made it dynamic. It doesn't depend on a sorted table.

First I started with a column of state names (Column A) and a column of aircraft in each state (Column B). (Row 1 is a header row).

Finding the cell that contains the number of aircraft was:

=MATCH(MAX($B$2:$B$54),$B$2:$B$54,0)+MIN(ROW($B$2:$B$54))-1

I put that into a cell and then gave that cell a name, "StateRow" Then using the tips from above, I wound up with this:

=INDIRECT(ADDRESS(StateRow,1))

This returns the name of the state from the dynamic value in row "StateRow", column 1

Now, as the values in the count column change over time as more data is entered, I always know which state has the most aircraft.

set option "selected" attribute from dynamic created option

Good question. You will need to modify the HTML itself rather than rely on DOM properties.

var opt = $("option[val=ID]"),
    html = $("<div>").append(opt.clone()).html();
html = html.replace(/\>/, ' selected="selected">');
opt.replaceWith(html);

The code grabs the option element for Indonesia, clones it and puts it into a new div (not in the document) to retrieve the full HTML string: <option value="ID">Indonesia</option>.

It then does a string replace to add the attribute selected="selected" as a string, before replacing the original option with this new one.

I tested it on IE7. See it with the reset button working properly here: http://jsfiddle.net/XmW49/

Heroku + node.js error (Web process failed to bind to $PORT within 60 seconds of launch)

In my case, I was using Babel with the babel-plugin-transform-inline-environment-variables plugin. Apparently, Heroku does not set the PORT env variable when doing a deployment, so process.env.PORT will be replaced by undefined, and your code will fallback to the development port which Heroku does not know anything about.

XAMPP installation on Win 8.1 with UAC Warning

As ivan.sim writes in his answer

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC(User Account Control) as it restricts certain administrative function needed to run a web server.
  3. Install in C://xampp.

Problem with the correct answer is in the explanation of point 2., and magicandre1981 writes more about it

Moving the slider down doesn't completely disable UAC since Windows 8. This is changed compared to Windows 7, because the new Store apps require an active UAC. With UAC off, they no longer run.


How can we then disable UAC and install XAMPP?

Easy. Go to Registry Editor and navigate to

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

Registry Editor

Right click EnableLUA and modify the Value data to 0.

EnableLUA

Then restart your computer and you're ready to install XAMPP.

Installing XAMPP

XAMPP installed

XAMPP Control Panel

How can I insert into a BLOB column from an insert statement in sqldeveloper?

  1. insert into mytable(id, myblob) values (1,EMPTY_BLOB);
  2. SELECT * FROM mytable mt where mt.id=1 for update
  3. Click on the Lock icon to unlock for editing
  4. Click on the ... next to the BLOB to edit
  5. Select the appropriate tab and click open on the top left.
  6. Click OK and commit the changes.

When to use window.opener / window.parent / window.top

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a <frame> or <iframe>
  • window.top refers to the top-most window from a window nested in one or more layers of <iframe> sub-windows

Those will be null (or maybe undefined) when they're not relevant to the referring window's situation. ("Referring window" means the window in whose context the JavaScript code is run.)

Add leading zeroes/0's to existing Excel values to certain length

If you use custom formatting and need to concatenate those values elsewhere, you can copy them and Paste Special --> Values elsewhere in the sheet (or on a different sheet), then concatenate those values.

Practical uses of different data structures

Any ranking of various data structures will be at least partially tied to problem context. It would help to learn how to analyze time and space performance of algorithms. Typically, "big O notation" is used, e.g. binary search is in O(log n) time, which means that the time to search for an element is the log (in base 2, implicitly) of the number of elements. Intuitively, since every step discards half of the remaining data as irrelevant, doubling the number of elements will increases the time by 1 step. (Binary search scales rather well.) Space performance concerns how the amount of memory grows for larger data sets. Also, note that big-O notation ignores constant factors - for smaller data sets, an O(n^2) algorithm may still be faster than an O(n * log n) algorithm that has a higher constant factor. Complex algorithms often have more work to do on startup.

Besides time and space, other characteristics include whether a data structure is sorted (trees and skiplists are sorted, hash tables are not), persistence (binary trees can reuse pointers from older versions, while hash tables are modified in place), etc.

While you'll need to learn the behavior of several data structures to be able to compare them, one way to develop a sense for why they differ in performance is to closely study a few. I'd suggest comparing singly-linked lists, binary search trees, and skip lists, all of which are relatively simple, but have very different characteristics. Think about how much work it takes to find a value, add a new value, find all values in order, etc.

There are various texts on analyzing algorithms / data structure performance that people recommend, but what really made them make sense to me was learning OCaml. Dealing with complex data structures is ML's strong suit, and their behavior is much clearer when you can avoid pointers and memory management as in C. (Learning OCaml just to understand data structures is almost certainly the long way around, though. :) )

How can I directly view blobs in MySQL Workbench

casting works, but it is a pain, so I would recommend using spioter's method unless you are using a lot of truly blob data.

SELECT CAST(OLD_PASSWORD("test") AS CHAR)

You can also cast as other types, and even restrict the size, but most of the time I just use CHAR: http://dev.mysql.com/doc/refman/5.5/en/cast-functions.html#function_cast

Eclipse Java Missing required source folder: 'src'

Create the src folder in the project.

How is Pythons glob.glob ordered?

It is probably not sorted at all and uses the order at which entries appear in the filesystem, i.e. the one you get when using ls -U. (At least on my machine this produces the same order as listing glob matches).

Objective-C : BOOL vs bool

The Objective-C type you should use is BOOL. There is nothing like a native boolean datatype, therefore to be sure that the code compiles on all compilers use BOOL. (It's defined in the Apple-Frameworks.

Why does CreateProcess give error 193 (%1 is not a valid Win32 app)

Let me add an example here:

I'm trying to build Alluxio on windows platform and got the same issue, it's because the pom.xml contains below step:

      <plugin>
        <artifactId>exec-maven-plugin</artifactId>
        <groupId>org.codehaus.mojo</groupId>
        <inherited>false</inherited>
        <executions>
          <execution>
            <id>Check that there are no Windows line endings</id>
            <phase>compile</phase>
            <goals>
              <goal>exec</goal>
            </goals>
            <configuration>
              <executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
            </configuration>
          </execution>
        </executions>
      </plugin>

The .sh file is not executable on windows so the error throws.

Comment it out if you do want build Alluxio on windows.

How to center a checkbox in a table cell?

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<table class="table table-bordered">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th></th>_x000D_
      <th class="text-center">Left</th>_x000D_
      <th class="text-center">Center</th>_x000D_
      <th class="text-center">Right</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <th>_x000D_
        <span>Bootstrap (class="text-left")</span>_x000D_
      </th>_x000D_
      <td class="text-left">_x000D_
        <input type="checkbox" />_x000D_
      </td>_x000D_
      <td class="text-center">_x000D_
        <input type="checkbox" checked />_x000D_
      </td>_x000D_
      <td class="text-right">_x000D_
        <input type="checkbox" />_x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>_x000D_
        <span>HTML attribute (align="left")</span>_x000D_
      </th>_x000D_
      <td align="left">_x000D_
        <input type="checkbox" />_x000D_
      </td>_x000D_
      <td align="center">_x000D_
        <input type="checkbox" checked />_x000D_
      </td>_x000D_
      <td align="right">_x000D_
        <input type="checkbox" />_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_