Programs & Examples On #Onkeydown

This event is triggered when when the user is pressing a key or holding down a key.

How to capture a backspace on the onkeydown event

event.key === "Backspace" or "Delete"

More recent and much cleaner: use event.key. No more arbitrary number codes!

input.addEventListener('keydown', function(event) {
    const key = event.key; // const {key} = event; ES6+
    if (key === "Backspace" || key === "Delete") {
        return false;
    }
});

Mozilla Docs

Supported Browsers

Shorten string without cutting words in JavaScript

we can do this easily by using truncate function of lodash

_.truncate('hi-diddly-ho there, neighborino');
// => 'hi-diddly-ho there, neighbo...'

_.truncate('hi-diddly-ho there, neighborino', {
  'length': 24,
  'separator': ' '
 });
// => 'hi-diddly-ho there,...'

go on Lodash Documentation for more clearence.

SQL query to check if a name begins and ends with a vowel

you can also do a hard code like this, where you are checking each and every case possible, it's easy to understand for beginners

SELECT DISTINCT CITY 
FROM STATION
WHERE CITY LIKE 'A%A' OR CITY LIKE 'E%E' OR CITY LIKE 'I%I' OR CITY LIKE 'O%O' OR
CITY LIKE 'U%U' OR CITY LIKE 'A%E' OR CITY LIKE 'A%I' OR CITY LIKE 'A%O' OR 
CITY LIKE 'A%U' OR CITY LIKE 'E%A' OR CITY LIKE 'E%I' OR CITY LIKE 'E%O' OR 
CITY LIKE 'E%U' OR CITY LIKE 'I%A' OR CITY LIKE 'I%E' OR CITY LIKE 'I%O' OR 
CITY LIKE 'I%U' OR CITY LIKE 'O%A' OR CITY LIKE 'O%E' OR CITY LIKE 'O%I' OR 
CITY LIKE 'O%U' OR CITY LIKE 'U%A' OR CITY LIKE 'U%E' OR CITY LIKE 'U%I' OR 
CITY LIKE 'U%O'

How to show all of columns name on pandas dataframe?

you can try this

pd.pandas.set_option('display.max_columns', None)

Emulator error: This AVD's configuration is missing a kernel file

In my own case, I had multiple errors most of which were about mis-configured ANDROID_SDK_ROOT, at the end of the day, one thing seemed to fix the whole thing.

Follow the following process:

After Creating the A new Emulator Device on AVD, go to the Actions menu and click on the arrow pointing downwards as shown below.

enter image description here

Click on Show on Disk

Edit Config.ini

Look for image.sysdir.1

it should have a value like this : **image.sysdir.1=system-images\android-28\google_apis_playstore\x86**

Your own value might be different

Now, fix in the path of the Android Sdk to make a complete path.

image.sysdir.1=**C:\androidsdk**system-images\android-28\google_apis_playstore\x86\

If you noticed, the android sdk path shown above is different from the normal default android sdk, I had to move it to C:/androidsdk to avoid NDK issues as my main USER HOME on my PC has whitespaces which NDK might not support.

NOTE: Moving the SDK directory away from its default directory is usually the cause of these errors AVD emulator gives, most especially as regarding broken and misconfigured path. The fix I provided above is a quick fix, you may have to do that each time you create a new device on AVD Emulator.

This fix should also work when working on CMD with cordova .

How can I use threading in Python?

Using the blazing new concurrent.futures module

def sqr(val):
    import time
    time.sleep(0.1)
    return val * val

def process_result(result):
    print(result)

def process_these_asap(tasks):
    import concurrent.futures

    with concurrent.futures.ProcessPoolExecutor() as executor:
        futures = []
        for task in tasks:
            futures.append(executor.submit(sqr, task))

        for future in concurrent.futures.as_completed(futures):
            process_result(future.result())
        # Or instead of all this just do:
        # results = executor.map(sqr, tasks)
        # list(map(process_result, results))

def main():
    tasks = list(range(10))
    print('Processing {} tasks'.format(len(tasks)))
    process_these_asap(tasks)
    print('Done')
    return 0

if __name__ == '__main__':
    import sys
    sys.exit(main())

The executor approach might seem familiar to all those who have gotten their hands dirty with Java before.

Also on a side note: To keep the universe sane, don't forget to close your pools/executors if you don't use with context (which is so awesome that it does it for you)

How do I load a file into the python console?

From the man page:

-i When a script is passed as first argument or the -c option is used, enter interactive mode after executing the script or the command. It does not read the $PYTHONSTARTUP file. This can be useful to inspect global variables or a stack trace when a script raises an exception.

So this should do what you want:

python -i file.py

How to align absolutely positioned element to center?

try this method, working fine for me

position: absolute;
left: 50%;
transform: translateX(-50%); 

How to POST using HTTPclient content type = application/x-www-form-urlencoded

Another variant to POST this content type and which does not use a dictionary would be:

StringContent postData = new StringContent(JSON_CONTENT, Encoding.UTF8, "application/x-www-form-urlencoded");
using (HttpResponseMessage result = httpClient.PostAsync(url, postData).Result)
{
    string resultJson = result.Content.ReadAsStringAsync().Result;
}

How to make a char string from a C macro's value?

#include <stdio.h>

#define QUOTEME(x) #x

#ifndef TEST_FUN
#  define TEST_FUN func_name
#  define TEST_FUN_NAME QUOTEME(TEST_FUN)
#endif

int main(void)
{
    puts(TEST_FUN_NAME);
    return 0;
}

Reference: Wikipedia's C preprocessor page

Yarn install command error No such file or directory: 'install'

Tried above steps, didn't work on Ubuntu 20. For Ubuntu 20, remove the cmdtest and yarn like suggested above. Install yarn with below commands:

curl -sL https://dl.yarnpkg.com/debian/pubkey.gpg | sudo apt-key add -

echo "deb https://dl.yarnpkg.com/debian/ stable main" | sudo tee /etc/apt/sources.list.d/yarn.list

sudo apt update && sudo apt install yarn

How to push local changes to a remote git repository on bitbucket

Meaning the 2nd parameter('master') of the "git push" command -

$ git push origin master

can be made clear by initiating "push" command from 'news-item' branch. It caused local "master" branch to be pushed to the remote 'master' branch. For more information refer

https://git-scm.com/docs/git-push

where <refspec> in

[<repository> [<refspec>…?]

is written to mean "specify what destination ref to update with what source object."

For your reference, here is a screen capture how I verified this statement.

<code>enter image description here</code>

What's the difference between ng-model and ng-bind

We can use ng-bind with <p> to display, we can use shortcut for ng-bind {{model}}, we cannot use ng-bind with html input controls, but we can use shortcut for ng-bind {{model}} with html input controls.

<input type="text" ng-model="name" placeholder="Enter Something"/>
<input type="text" value="{{name}}" placeholder="Enter Something"/>
  Hello {{name}}
<p ng-bind="name"</p>

Min/Max of dates in an array?

ONELINER:

var min= dates.sort((a,b)=>a-b)[0], max= dates.slice(-1)[0];

result in variables min and max, complexity O(nlogn), editable example here. If your array has no-date values (like null) first clean it by dates=dates.filter(d=> d instanceof Date);.

_x000D_
_x000D_
var dates = [];_x000D_
dates.push(new Date("2011-06-25")); // I change "/" to "-" in "2011/06/25"_x000D_
dates.push(new Date("2011-06-26")); // because conosle log write dates _x000D_
dates.push(new Date("2011-06-27")); // using "-"._x000D_
dates.push(new Date("2011-06-28"));_x000D_
_x000D_
var min= dates.sort((a,b)=>a-b)[0], max= dates.slice(-1)[0];_x000D_
_x000D_
console.log({min,max});
_x000D_
_x000D_
_x000D_

git ignore exception

To exclude everything in a directory, but some sub-directories, do the following:

wp-content/*
!wp-content/plugins/
!wp-content/themes/

Source: https://gist.github.com/444295

Invalid length for a Base-64 char array

    string stringToDecrypt = CypherText.Replace(" ", "+");
    int len = stringToDecrypt.Length;
    byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt); 

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

How to submit a form with JavaScript by clicking a link?

HTML & CSS - No Javascript Solution

Make your button appear like a Bootstrap link

HTML:

<form>
    <button class="btn-link">Submit</button>
</form>

CSS:

.btn-link {

    background: none;
    border: none;
    padding: 0px;
    color: #3097D1;
    font: inherit;

}

.btn-link:hover {

    color: #216a94;
    text-decoration: underline;

}

How to sync with a remote Git repository?

You need to add the original repository (the one that you forked) as a remote.

git remote add github (clone url for the orignal repository)

Then you need to bring in the changes to your local repository

git fetch github

Now you will have all the branches of the original repository in your local one. For example, the master branch will be github/master. With these branches you can do what you will. Merge them into your branches etc

How to create query parameters in Javascript?

This thread points to some code for escaping URLs in php. There's escape() and unescape() which will do most of the work, but the you need add a couple extra things.

function urlencode(str) {
str = escape(str);
str = str.replace('+', '%2B');
str = str.replace('%20', '+');
str = str.replace('*', '%2A');
str = str.replace('/', '%2F');
str = str.replace('@', '%40');
return str;
}

function urldecode(str) {
str = str.replace('+', ' ');
str = unescape(str);
return str;
}

How do I parallelize a simple Python loop?

Have a look at this;

http://docs.python.org/library/queue.html

This might not be the right way to do it, but I'd do something like;

Actual code;

from multiprocessing import Process, JoinableQueue as Queue 

class CustomWorker(Process):
    def __init__(self,workQueue, out1,out2,out3):
        Process.__init__(self)
        self.input=workQueue
        self.out1=out1
        self.out2=out2
        self.out3=out3
    def run(self):
            while True:
                try:
                    value = self.input.get()
                    #value modifier
                    temp1,temp2,temp3 = self.calc_stuff(value)
                    self.out1.put(temp1)
                    self.out2.put(temp2)
                    self.out3.put(temp3)
                    self.input.task_done()
                except Queue.Empty:
                    return
                   #Catch things better here
    def calc_stuff(self,param):
        out1 = param * 2
        out2 = param * 4
        out3 = param * 8
        return out1,out2,out3
def Main():
    inputQueue = Queue()
    for i in range(10):
        inputQueue.put(i)
    out1 = Queue()
    out2 = Queue()
    out3 = Queue()
    processes = []
    for x in range(2):
          p = CustomWorker(inputQueue,out1,out2,out3)
          p.daemon = True
          p.start()
          processes.append(p)
    inputQueue.join()
    while(not out1.empty()):
        print out1.get()
        print out2.get()
        print out3.get()
if __name__ == '__main__':
    Main()

Hope that helps.

How do I get the current year using SQL on Oracle?

Yet another option would be:

SELECT * FROM mytable
 WHERE TRUNC(mydate, 'YEAR') = TRUNC(SYSDATE, 'YEAR');

MySql: Tinyint (2) vs tinyint(1) - what is the difference?

mysql> CREATE TABLE tin3(id int PRIMARY KEY,val TINYINT(10) ZEROFILL);
Query OK, 0 rows affected (0.04 sec)

mysql> INSERT INTO tin3 VALUES(1,12),(2,7),(4,101);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> SELECT * FROM tin3;
+----+------------+
| id | val        |
+----+------------+
|  1 | 0000000012 |
|  2 | 0000000007 |
|  4 | 0000000101 |
+----+------------+
3 rows in set (0.00 sec)

mysql>

mysql> SELECT LENGTH(val) FROM tin3 WHERE id=2;
+-------------+
| LENGTH(val) |
+-------------+
|          10 |
+-------------+
1 row in set (0.01 sec)


mysql> SELECT val+1 FROM tin3 WHERE id=2;
+-------+
| val+1 |
+-------+
|     8 |
+-------+
1 row in set (0.00 sec)

Linq to SQL .Sum() without group ... into

I know this is an old question but why can't you do it like:

db.OrderLineItems.Where(o => o.OrderId == currentOrder.OrderId).Sum(o => o.WishListItem.Price);

I am not sure how to do this using query expressions.

Bulk Insertion in Laravel using eloquent ORM

From Laravel 5.7 with Illuminate\Database\Query\Builder you can use insertUsing method.

$query = [];
foreach($oXML->results->item->item as $oEntry){
    $date = date("Y-m-d H:i:s")
    $query[] = "('{$oEntry->firstname}', '{$oEntry->lastname}', '{$date}')";
}

Builder::insertUsing(['first_name', 'last_name', 'date_added'], implode(', ', $query));

PHP date() format when inserting into datetime in MySQL

Using DateTime class in PHP7+:

function getMysqlDatetimeFromDate(int $day, int $month, int $year): string
{
 $dt = new DateTime();
 $dt->setDate($year, $month, $day);
 $dt->setTime(0, 0, 0, 0); // set time to midnight

 return $dt->format('Y-m-d H:i:s');
}

The property 'value' does not exist on value of type 'HTMLElement'

We could assert

const inputElement: HTMLInputElement = document.getElementById('greet')

Or with as-syntax

const inputElement = document.getElementById('greet') as HTMLInputElement

Giving

const inputValue = inputElement.value // now inferred to be string

Compiling/Executing a C# Source File in Command Prompt

You can build your class files within the VS Command prompt (so that all required environment variables are loaded), not the default Windows command window.

To know more about command line building with csc.exe (the compiler), see this article.

Javascript | Set all values of an array

Actually, you can use this perfect approach:

let arr = Array.apply(null, Array(5)).map(() => 0);
// [0, 0, 0, 0, 0]

This code will create array and fill it with zeroes. Or just:

let arr = new Array(5).fill(0)

Export pictures from excel file into jpg using VBA

If i remember correctly, you need to use the "Shapes" property of your sheet.

Each Shape object has a TopLeftCell and BottomRightCell attributes that tell you the position of the image.

Here's a piece of code i used a while ago, roughly adapted to your needs. I don't remember the specifics about all those ChartObjects and whatnot, but here it is:

For Each oShape In ActiveSheet.Shapes
    strImageName = ActiveSheet.Cells(oShape.TopLeftCell.Row, 1).Value
    oShape.Select
    'Picture format initialization
    Selection.ShapeRange.PictureFormat.Contrast = 0.5: Selection.ShapeRange.PictureFormat.Brightness = 0.5: Selection.ShapeRange.PictureFormat.ColorType = msoPictureAutomatic: Selection.ShapeRange.PictureFormat.TransparentBackground = msoFalse: Selection.ShapeRange.Fill.Visible = msoFalse: Selection.ShapeRange.Line.Visible = msoFalse: Selection.ShapeRange.Rotation = 0#: Selection.ShapeRange.PictureFormat.CropLeft = 0#: Selection.ShapeRange.PictureFormat.CropRight = 0#: Selection.ShapeRange.PictureFormat.CropTop = 0#: Selection.ShapeRange.PictureFormat.CropBottom = 0#: Selection.ShapeRange.ScaleHeight 1#, msoTrue, msoScaleFromTopLeft: Selection.ShapeRange.ScaleWidth 1#, msoTrue, msoScaleFromTopLeft
    '/Picture format initialization
    Application.Selection.CopyPicture
    Set oDia = ActiveSheet.ChartObjects.Add(0, 0, oShape.Width, oShape.Height)
    Set oChartArea = oDia.Chart
    oDia.Activate
    With oChartArea
        .ChartArea.Select
        .Paste
        .Export ("H:\Webshop_Zpider\Strukturbildene\" & strImageName & ".jpg")
    End With
    oDia.Delete 'oChartArea.Delete
Next

How do I get cURL to not show the progress bar?

this could help..

curl 'http://example.com' > /dev/null

How do I change the text of a span element using JavaScript?

I used this one document.querySelector('ElementClass').innerText = 'newtext';

Appears to work with span, texts within classes/buttons

Returning JSON from PHP to JavaScript?

Here are a couple of things missing in the previous answers:

  1. Set header in your PHP:

    header('Content-type: application/json');
    echo json_encode($array);
    
  2. json_encode() can return a JavaScript array instead of JavaScript object, see:
    Returning JSON from a PHP Script
    This could be important to know in some cases as arrays and objects are not the same.

How to give spacing between buttons using bootstrap

The original code is mostly there, but you need btn-groups around each button. In Bootstrap 3 you can use a btn-toolbar and a btn-group to get the job done; I haven't done BS4 but it has similar constructs.

<div class="btn-toolbar" role="toolbar">
  <div class="btn-group" role="group">
    <button class="btn btn-default">Button 1</button>
  </div>
  <div class="btn-group" role="group">
    <button class="btn btn-default">Button 2</button>
  </div>
</div>

Python AttributeError: 'module' object has no attribute 'Serial'

I accidentally installed 'serial' (sudo python -m pip install serial) instead of 'pySerial' (sudo python -m pip install pyserial), which lead to the same error.

If the previously mentioned solutions did not work for you, double check if you installed the correct library.

How to open local file on Jupyter?

simple way is to move your files to be read under the same folder of your python file, then you just need to use the name of the file, without calling another path.

Can you use @Autowired with static fields?

Disclaimer This is by no means standard and there could very well be a better spring way of doing this. None of the above answers address the issues of wiring a public static field.

I wanted to accomplish three things.

  1. Use spring to "Autowire" (Im using @Value)
  2. Expose a public static value
  3. Prevent modification

My object looks like this

private static String BRANCH = "testBranch";

@Value("${content.client.branch}")
public void finalSetBranch(String branch) {
    BRANCH = branch;
}

public static String BRANCH() {
    return BRANCH;
}

We have checked off 1 & 2 already now how do we prevent calls to the setter, since we cannot hide it.

@Component
@Aspect
public class FinalAutowiredHelper {

@Before("finalMethods()")
public void beforeFinal(JoinPoint joinPoint) {
    throw new FinalAutowiredHelper().new ModifySudoFinalError("");
}

@Pointcut("execution(* com.free.content.client..*.finalSetBranch(..))")
public void finalMethods() {}


public class ModifySudoFinalError extends Error {
    private String msg;

    public ModifySudoFinalError(String msg) {
        this.msg = msg;
    }

    @Override
    public String getMessage() {
        return "Attempted modification of a final property: " + msg;
    }
}

This aspect will wrap all methods beginning with final and throw an error if they are called.

I dont think this is particularly useful, but if you are ocd and like to keep you peas and carrots separated this is one way to do it safely.

Important Spring does not call your aspects when it calls a function. Made this easier, to bad I worked out the logic before figuring that out.

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

The JSON spec requires UTF-8 support by decoders. As a result, all JSON decoders can handle UTF-8 just as well as they can handle the numeric escape sequences. This is also the case for Javascript interpreters, which means JSONP will handle the UTF-8 encoded JSON as well.

The ability for JSON encoders to use the numeric escape sequences instead just offers you more choice. One reason you may choose the numeric escape sequences would be if a transport mechanism in between your encoder and the intended decoder is not binary-safe.

Another reason you may want to use numeric escape sequences is to prevent certain characters appearing in the stream, such as <, & and ", which may be interpreted as HTML sequences if the JSON code is placed without escaping into HTML or a browser wrongly interprets it as HTML. This can be a defence against HTML injection or cross-site scripting (note: some characters MUST be escaped in JSON, including " and \).

Some frameworks, including PHP's implementation of JSON, always do the numeric escape sequences on the encoder side for any character outside of ASCII. This is intended for maximum compatibility with limited transport mechanisms and the like. However, this should not be interpreted as an indication that JSON decoders have a problem with UTF-8.

So, I guess you just could decide which to use like this:

  • Just use UTF-8, unless your method of storage or transport between encoder and decoder is not binary-safe.

  • Otherwise, use the numeric escape sequences.

What is the regex for "Any positive integer, excluding 0"

^[1-9]*$ is the simplest I can think of

How to read file from relative path in Java project? java.io.File cannot find the path specified

I could have commented but I have less rep for that. Samrat's answer did the job for me. It's better to see the current directory path through the following code.

    File directory = new File("./");
    System.out.println(directory.getAbsolutePath());

I simply used it to rectify an issue I was facing in my project. Be sure to use ./ to back to the parent directory of the current directory.

    ./test/conf/appProperties/keystore 

UIImage: Resize, then Crop

I found that the Swift 3 posted by Evgenii Kanvets does not uniformly scale the image.

Here is my Swift 4 version of the function that does not squish the image:

static func resizedCroppedImage(image: UIImage, newSize:CGSize) -> UIImage? {

    // This function returns a newImage, based on image
    // - image is scaled uniformaly to fit into a rect of size newSize
    // - if the newSize rect is of a different aspect ratio from the source image
    //     the new image is cropped to be in the center of the source image
    //     (the excess source image is removed)

    var ratio: CGFloat = 0
    var delta: CGFloat = 0
    var drawRect = CGRect()

    if newSize.width > newSize.height {

        ratio = newSize.width / image.size.width
        delta = (ratio * image.size.height) - newSize.height
        drawRect = CGRect(x: 0, y: -delta / 2, width: newSize.width, height: newSize.height + delta)

    } else {

        ratio = newSize.height / image.size.height
        delta = (ratio * image.size.width) - newSize.width
        drawRect = CGRect(x: -delta / 2, y: 0, width: newSize.width + delta, height: newSize.height)

    }

    UIGraphicsBeginImageContextWithOptions(newSize, true, 0.0)
    image.draw(in: drawRect)
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return newImage
} 

The R %in% operator

You can use all

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

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

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

What is the difference between signed and unsigned int

int and unsigned int are two distinct integer types. (int can also be referred to as signed int, or just signed; unsigned int can also be referred to as unsigned.)

As the names imply, int is a signed integer type, and unsigned int is an unsigned integer type. That means that int is able to represent negative values, and unsigned int can represent only non-negative values.

The C language imposes some requirements on the ranges of these types. The range of int must be at least -32767 .. +32767, and the range of unsigned int must be at least 0 .. 65535. This implies that both types must be at least 16 bits. They're 32 bits on many systems, or even 64 bits on some. int typically has an extra negative value due to the two's-complement representation used by most modern systems.

Perhaps the most important difference is the behavior of signed vs. unsigned arithmetic. For signed int, overflow has undefined behavior. For unsigned int, there is no overflow; any operation that yields a value outside the range of the type wraps around, so for example UINT_MAX + 1U == 0U.

Any integer type, either signed or unsigned, models a subrange of the infinite set of mathematical integers. As long as you're working with values within the range of a type, everything works. When you approach the lower or upper bound of a type, you encounter a discontinuity, and you can get unexpected results. For signed integer types, the problems occur only for very large negative and positive values, exceeding INT_MIN and INT_MAX. For unsigned integer types, problems occur for very large positive values and at zero. This can be a source of bugs. For example, this is an infinite loop:

for (unsigned int i = 10; i >= 0; i --) [
    printf("%u\n", i);
}

because i is always greater than or equal to zero; that's the nature of unsigned types. (Inside the loop, when i is zero, i-- sets its value to UINT_MAX.)

How to condense if/else into one line in Python?

Python's if can be used as a ternary operator:

>>> 'true' if True else 'false'
'true'
>>> 'true' if False else 'false'
'false'

How do I refresh a DIV content?

This one $("#yourDiv").load(" #yourDiv > *"); is the best if you are planning to just reload a <div>

Make sure to use an id and not a class. Also, remember to paste <script src="https://code.jquery.com/jquery-3.5.1.js"></script> in the <head> section of the html file, if you haven't already. In opposite case it won't work.

What is a segmentation fault?

Segmentation fault is also caused by hardware failures, in this case the RAM memories. This is the less common cause, but if you don't find an error in your code, maybe a memtest could help you.

The solution in this case, change the RAM.

edit:

Here there is a reference: Segmentation fault by hardware

How to multiply a BigDecimal by an integer in Java

First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

Second, it takes another BigDecimal as the argument, not an int.

If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

How to change a css class style through Javascript?

There are two ways in which this can be accomplished using vanilla javascript. The first is className and the second is classList. className works in all browsers but can be unwieldy to work with when modifying an element's class attribute. classList is an easier way to modify an element's class(es).

To outright set an element's class attribute, className is the way to go, otherwise to modify an element's class(es), it's easier to use classList.

Initial Html

<div id="ID"></div>

Setting the class attribute

var div = document.getElementById('ID');
div.className = "foo bar car";

Result:

<div id="ID" class="foo bar car"></div>

Adding a class

div.classList.add("car");// Class already exists, nothing happens
div.classList.add("tar");

Note: There's no need to test if a class exists before adding it. If a class needs to be added, just add it. If it already exists, a duplicate won't be added.
Result:

<div id="ID" class="foo bar car tar"></div>

Removing a class

div.classList.remove("car");
div.classList.remove("tar");
div.classList.remove("car");// No class of this name exists, nothing happens

Note: Just like add, if a class needs to be removed, remove it. If it's there, it'll be removed, otherwise nothing will happen.
Result:

<div id="ID" class="foo bar"></div>

Checking if a class attribute contains a specific class

if (div.classList.contains("foo")) {
  // Do stuff
}

Toggling a class

var classWasAdded = div.classList.toggle("bar"); // "bar" gets removed
// classWasAdded is false since "bar" was removed

classWasAdded = div.classList.toggle("bar"); // "bar" gets added
// classWasAdded is true since "bar" was added

.toggle has a second boolean parameter that, in my opinion, is redundant and isn't worth going over.

For more information on classList, check out MDN. It also covers browser compatibility if that's a concern, which can be addressed by using Modernizr for detection and a polyfill if needed.

Running code in main thread from another thread

for Kotlin, you can use Anko corountines:

update

doAsync {
   ...
}

deprecated

async(UI) {
    // Code run on UI thread
    // Use ref() instead of this@MyActivity
}

How to find the statistical mode?

Here is my data.table solution that returns row-wise modes for a complete table. I use it to infer row class. It takes care of the new-ish set() function in data.table and should be pretty fast. It does not manage NA though but that could be added by looking at the numerous other solutions on this page.

majorityVote <- function(mat_classes) {
  #mat_classes = dt.pour.centroids_num
  dt.modes <- data.table(mode = integer(nrow(mat_classes)))
  for (i in 1:nrow(mat_classes)) {
    cur.row <- mat_classes[i]
    cur.mode <- which.max(table(t(cur.row)))
    set(dt.modes, i=i, j="mode", value = cur.mode)
  }

  return(dt.modes)
}

Possible usage:

newClass <- majorityVote(my.dt)  # just a new vector with all the modes

Duplicate keys in .NET dictionaries?

i use this simple class:

public class ListMap<T,V> : List<KeyValuePair<T, V>>
{
    public void Add(T key, V value) {
        Add(new KeyValuePair<T, V>(key, value));
    }

    public List<V> Get(T key) {
        return FindAll(p => p.Key.Equals(key)).ConvertAll(p=> p.Value);
    }
}

usage:

var fruits = new ListMap<int, string>();
fruits.Add(1, "apple");
fruits.Add(1, "orange");
var c = fruits.Get(1).Count; //c = 2;

Replace last occurrence of a string in a string

You can use strrpos() to find last match.

$string = "picture_0007_value";
$findChar =strrpos($string,"_");

$string[$findChar]=".";

echo $string;

Output : picture_0007.value

Validate Dynamically Added Input fields

jquery validation plugin version work fine v1.15.0 but v1.17.0 not work for me.

$(document).find('#add_patient_form').validate({
          ignore: [],
          rules:{
            'email[]':
            {
              required:true,
            },               
          },
          messages:{
            'email[]':
            {
              'required':'Required'
            },            
          },    
        });

Array length in angularjs returns undefined

Make it like this:

$scope.users.data.length;

Java JTable getting the data of the selected row

Just simple like this:

    tbl.addMouseListener(new MouseListener() {
        @Override
        public void mouseReleased(MouseEvent e) {
        }
        @Override
        public void mousePressed(MouseEvent e) {
            String selectedCellValue = (String) tbl.getValueAt(tbl.getSelectedRow() , tbl.getSelectedColumn());
            System.out.println(selectedCellValue);
        }
        @Override
        public void mouseExited(MouseEvent e) {
        }
        @Override
        public void mouseEntered(MouseEvent e) {
        }
        @Override
        public void mouseClicked(MouseEvent e) {
        }
    });

In Linux, how to tell how much memory processes are using?

Use top or htop and pay attention to the "RES" (resident memory size) column.

How to .gitignore all files/folder in a folder, but not the folder itself?

Put this .gitignore into the folder, then git add .gitignore.

*
*/
!.gitignore

The * line tells git to ignore all files in the folder, but !.gitignore tells git to still include the .gitignore file. This way, your local repository and any other clones of the repository all get both the empty folder and the .gitignore it needs.

Edit: May be obvious but also add */ to the .gitignore to also ignore subfolders.

Mockito test a void method throws an exception

The parentheses are poorly placed.

You need to use:

doThrow(new Exception()).when(mockedObject).methodReturningVoid(...);
                                          ^

and NOT use:

doThrow(new Exception()).when(mockedObject.methodReturningVoid(...));
                                                                   ^

This is explained in the documentation

HTML meta tag for content language

another language meta tag is og:locale and you can define og:locale meta tag for social media

<meta property="og:locale" content="en" />

Firefox and SSL: sec_error_unknown_issuer

June 2014:

This is the configuration I used and it working fine after banging my head on the wall for some days. I use Express 3.4 (I think is the same for Express 4.0)

var privateKey  = fs.readFileSync('helpers/sslcert/key.pem', 'utf8');
var certificate = fs.readFileSync('helpers/sslcert/csr.pem', 'utf8');

files = ["COMODORSADomainValidationSecureServerCA.crt",
         "COMODORSAAddTrustCA.crt",
         "AddTrustExternalCARoot.crt"
        ];

ca = (function() {
  var _i, _len, _results;

  _results = [];
  for (_i = 0, _len = files.length; _i < _len; _i++) {
    file = files[_i];
    _results.push(fs.readFileSync("helpers/sslcert/" + file));
  }
  return _results;
})();

var credentials = {ca:ca, key: privateKey, cert: certificate};

// process.env.PORT : Heroku Config environment
var port = process.env.PORT || 4000;

var app = express();
var server = http.createServer(app).listen(port, function() {
        console.log('Express HTTP server listening on port ' + server.address().port);
});
https.createServer(credentials, app).listen(3000, function() {
        console.log('Express HTTPS server listening on port ' + server.address().port);
});

// redirect all http requests to https
app.use(function(req, res, next) {
  if(!req.secure) {
    return res.redirect(['https://mydomain.com', req.url].join(''));
  }
  next();
});

Then I redirected the 80 and 443 ports:

sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 4000
sudo iptables -t nat -A PREROUTING -p tcp --dport 443 -j REDIRECT --to-ports 3000

As you can see after checking my certifications I have 4 [0,1,2,3]:

openssl s_client -connect mydomain.com:443 -showcerts | grep "^ "

ubuntu@ip-172-31-5-134:~$ openssl s_client -connect mydomain.com:443 -showcerts | grep "^ "
depth=3 C = SE, O = AddTrust AB, OU = AddTrust External TTP Network, CN = AddTrust External CA Root
verify error:num=19:self signed certificate in certificate chain
verify return:0
 0 s:/OU=Domain Control Validated/OU=PositiveSSL/CN=mydomain.com
   i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
 1 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Domain Validation Secure Server CA
   i:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
 2 s:/C=GB/ST=Greater Manchester/L=Salford/O=COMODO CA Limited/CN=COMODO RSA Certification Authority
   i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
 3 s:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
   i:/C=SE/O=AddTrust AB/OU=AddTrust External TTP Network/CN=AddTrust External CA Root
    Protocol  : TLSv1.1
    Cipher    : AES256-SHA
    Session-ID: 8FDEAEE92ED20742.....3E7D80F93226142DD
    Session-ID-ctx:
    Master-Key: C9E4AB966E41A85EEB7....4D73C67088E1503C52A9353C8584E94
    Key-Arg   : None
    PSK identity: None
    PSK identity hint: None
    SRP username: None
    TLS session ticket lifetime hint: 300 (seconds)
    TLS session ticket:
    0000 - 7c c8 36 80 95 4d 4c 47-d8 e3 ca 2e 70 a5 8f ac   |.6..MLG....p...
    0010 - 90 bd 4a 26 ef f7 d6 bc-4a b3 dd 8f f6 13 53 e9   ..J&..........S.
    0020 - f7 49 c6 48 44 26 8d ab-a8 72 29 c8 15 73 f5 79   .I.HD&.......s.y
    0030 - ca 79 6a ed f6 b1 7f 8a-d2 68 0a 52 03 c5 84 32   .yj........R...2
    0040 - be c5 c8 12 d8 f4 36 fa-28 4f 0e 00 eb d1 04 ce   ........(.......
    0050 - a7 2b d2 73 df a1 8b 83-23 a6 f7 ef 6e 9e c4 4c   .+.s...........L
    0060 - 50 22 60 e8 93 cc d8 ee-42 22 56 a7 10 7b db 1e   P"`.....B.V..{..
    0070 - 0a ad 4a 91 a4 68 7a b0-9e 34 01 ec b8 7b b2 2f   ..J......4...{./
    0080 - e8 33 f5 a9 48 11 36 f8-69 a6 7a a6 22 52 b1 da   .3..H...i....R..
    0090 - 51 18 ed c4 d9 3d c4 cc-5b d7 ff 92 4e 91 02 9e   .....=......N...
    Start Time: 140...549
    Timeout   : 300 (sec)
    Verify return code: 19 (self signed certificate in certificate chain)

Good luck! PD: if u want more answers please check: http://www.benjiegillam.com/2012/06/node-dot-js-ssl-certificate-chain/

Environ Function code samples for VBA

As alluded to by Eric, you can use environ with ComputerName argument like so:

MsgBox Environ("USERNAME")

Some additional information that might be helpful for you to know:

  1. The arguments are not case sensitive.
  2. There is a slightly faster performing string version of the Environ function. To invoke it, use a dollar sign. (Ex: Environ$("username")) This will net you a small performance gain.
  3. You can retrieve all System Environment Variables using this function. (Not just username.) A common use is to get the "ComputerName" value to see which computer the user is logging onto from.
  4. I don't recommend it for most situations, but it can be occasionally useful to know that you can also access the variables with an index. If you use this syntax the the name of argument and the value are returned. In this way you can enumerate all available variables. Valid values are 1 - 255.
    Sub EnumSEVars()
        Dim strVar As String
        Dim i As Long
        For i = 1 To 255
            strVar = Environ$(i)
            If LenB(strVar) = 0& Then Exit For
            Debug.Print strVar
        Next
    End Sub

How to count number of records per day?

select DateAdded, count(CustID)
from Responses
WHERE DateAdded >=dateadd(day,datediff(day,0,GetDate())- 7,0)
GROUP BY DateAdded

linux execute command remotely

I guess ssh is the best secured way for this, for example :

ssh -OPTIONS -p SSH_PORT user@remote_server "remote_command1; remote_command2; remote_script.sh"  

where the OPTIONS have to be deployed according to your specific needs (for example, binding to ipv4 only) and your remote command could be starting your tomcat daemon.

Note:
If you do not want to be prompt at every ssh run, please also have a look to ssh-agent, and optionally to keychain if your system allows it. Key is... to understand the ssh keys exchange process. Please take a careful look to ssh_config (i.e. the ssh client config file) and sshd_config (i.e. the ssh server config file). Configuration filenames depend on your system, anyway you'll find them somewhere like /etc/sshd_config. Ideally, pls do not run ssh as root obviously but as a specific user on both sides, servers and client.

Some extra docs over the source project main pages :

ssh and ssh-agent
man ssh

http://www.snailbook.com/index.html
https://help.ubuntu.com/community/SSH/OpenSSH/Configuring

keychain
http://www.gentoo.org/doc/en/keychain-guide.xml
an older tuto in French (by myself :-) but might be useful too :
http://hornetbzz.developpez.com/tutoriels/debian/ssh/keychain/

Java Currency Number format

I did not find any good solution after google search, just post my solution for other to reference. use priceToString to format money.

public static String priceWithDecimal (Double price) {
    DecimalFormat formatter = new DecimalFormat("###,###,###.00");
    return formatter.format(price);
}

public static String priceWithoutDecimal (Double price) {
    DecimalFormat formatter = new DecimalFormat("###,###,###.##");
    return formatter.format(price);
}

public static String priceToString(Double price) {
    String toShow = priceWithoutDecimal(price);
    if (toShow.indexOf(".") > 0) {
        return priceWithDecimal(price);
    } else {
        return priceWithoutDecimal(price);
    }
}

How to handle invalid SSL certificates with Apache HttpClient?

I'm useing httpclient 3.1.X ,and this works for me

        try {
        SSLContext sslContext = SSLContext.getInstance("TLS");
        TrustManager trustManager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        };
        sslContext.init(null, new TrustManager[]{trustManager}, null);
        SslContextSecureProtocolSocketFactory socketFactory = new SslContextSecureProtocolSocketFactory(sslContext,false);
        Protocol.registerProtocol("https", new Protocol("https", (ProtocolSocketFactory) socketFactory, 443));//??????HttpUtils
    } catch (Throwable e) {
        e.printStackTrace();

}

public class SslContextSecureProtocolSocketFactory implements      SecureProtocolSocketFactory {

private SSLContext sslContext;
private boolean verifyHostname;

public SslContextSecureProtocolSocketFactory(SSLContext sslContext, boolean verifyHostname) {
    this.verifyHostname = true;
    this.sslContext = sslContext;
    this.verifyHostname = verifyHostname;
}

public SslContextSecureProtocolSocketFactory(SSLContext sslContext) {
    this(sslContext, true);
}

public SslContextSecureProtocolSocketFactory(boolean verifyHostname) {
    this((SSLContext)null, verifyHostname);
}

public SslContextSecureProtocolSocketFactory() {
    this((SSLContext)null, true);
}

public synchronized void setHostnameVerification(boolean verifyHostname) {
    this.verifyHostname = verifyHostname;
}

public synchronized boolean getHostnameVerification() {
    return this.verifyHostname;
}

public Socket createSocket(String host, int port, InetAddress clientHost, int clientPort) throws IOException, UnknownHostException {
    SSLSocketFactory sf = this.getSslSocketFactory();
    SSLSocket sslSocket = (SSLSocket)sf.createSocket(host, port, clientHost, clientPort);
    this.verifyHostname(sslSocket);
    return sslSocket;
}

public Socket createSocket(String host, int port, InetAddress localAddress, int localPort, HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    if(params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    } else {
        int timeout = params.getConnectionTimeout();
        Socket socket = null;
        SSLSocketFactory socketfactory = this.getSslSocketFactory();
        if(timeout == 0) {
            socket = socketfactory.createSocket(host, port, localAddress, localPort);
        } else {
            socket = socketfactory.createSocket();
            InetSocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
            InetSocketAddress remoteaddr = new InetSocketAddress(host, port);
            socket.bind(localaddr);
            socket.connect(remoteaddr, timeout);
        }

        this.verifyHostname((SSLSocket)socket);
        return socket;
    }
}

public Socket createSocket(String host, int port) throws IOException, UnknownHostException {
    SSLSocketFactory sf = this.getSslSocketFactory();
    SSLSocket sslSocket = (SSLSocket)sf.createSocket(host, port);
    this.verifyHostname(sslSocket);
    return sslSocket;
}

public Socket createSocket(Socket socket, String host, int port, boolean autoClose) throws IOException, UnknownHostException {
    SSLSocketFactory sf = this.getSslSocketFactory();
    SSLSocket sslSocket = (SSLSocket)sf.createSocket(socket, host, port, autoClose);
    this.verifyHostname(sslSocket);
    return sslSocket;
}

private void verifyHostname(SSLSocket socket) throws SSLPeerUnverifiedException, UnknownHostException {
    synchronized(this) {
        if(!this.verifyHostname) {
            return;
        }
    }

    SSLSession session = socket.getSession();
    String hostname = session.getPeerHost();

    try {
        InetAddress.getByName(hostname);
    } catch (UnknownHostException var10) {
        throw new UnknownHostException("Could not resolve SSL sessions server hostname: " + hostname);
    }

    X509Certificate[] certs = (X509Certificate[])((X509Certificate[])session.getPeerCertificates());
    if(certs != null && certs.length != 0) {
        X500Principal subjectDN = certs[0].getSubjectX500Principal();
        List cns = this.getCNs(subjectDN);
        boolean foundHostName = false;
        Iterator i$ = cns.iterator();
        AntPathMatcher matcher  = new AntPathMatcher();
        while(i$.hasNext()) {
            String cn = (String)i$.next();
            if(matcher.match(cn.toLowerCase(),hostname.toLowerCase())) {
                foundHostName = true;
                break;
            }
        }

        if(!foundHostName) {
            throw new SSLPeerUnverifiedException("HTTPS hostname invalid: expected \'" + hostname + "\', received \'" + cns + "\'");
        }
    } else {
        throw new SSLPeerUnverifiedException("No server certificates found!");
    }
}

private List<String> getCNs(X500Principal subjectDN) {
    ArrayList cns = new ArrayList();
    StringTokenizer st = new StringTokenizer(subjectDN.getName(), ",");

    while(st.hasMoreTokens()) {
        String cnField = st.nextToken();
        if(cnField.startsWith("CN=")) {
            cns.add(cnField.substring(3));
        }
    }

    return cns;
}

protected SSLSocketFactory getSslSocketFactory() {
    SSLSocketFactory sslSocketFactory = null;
    synchronized(this) {
        if(this.sslContext != null) {
            sslSocketFactory = this.sslContext.getSocketFactory();
        }
    }

    if(sslSocketFactory == null) {
        sslSocketFactory = (SSLSocketFactory)SSLSocketFactory.getDefault();
    }

    return sslSocketFactory;
}

public synchronized void setSSLContext(SSLContext sslContext) {
    this.sslContext = sslContext;
}

}

Getting results between two dates in PostgreSQL

To have a query working in any locale settings, consider formatting the date yourself:

SELECT * 
  FROM testbed 
 WHERE start_date >= to_date('2012-01-01','YYYY-MM-DD')
   AND end_date <= to_date('2012-04-13','YYYY-MM-DD');

Determining the version of Java SDK on the Mac

Run this command in your terminal:

$ java -version

java version "1.8.0_181"
Java(TM) SE Runtime Environment (build 1.8.0_181-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.181-b13, mixed mode)
Cristians-MacBook-Air:~ fa$ 

What is the best collation to use for MySQL with PHP?

In your database upload file, add the followin line before any line:

SET NAMES utf8;

And your problem should be solved.

Recommended method for escaping HTML in Java

For those who use Google Guava:

import com.google.common.html.HtmlEscapers;
[...]
String source = "The less than sign (<) and ampersand (&) must be escaped before using them in HTML";
String escaped = HtmlEscapers.htmlEscaper().escape(source);

How to get screen width and height

Display display = getActivity().getWindowManager().getDefaultDisplay(); 
int screenWidth = display.getWidth();
int screenHeight = display.getHeight();
Log.d("Tag", "Getting Width >> " + screenWidth);
Log.d("Tag", "Getting Height >> " + screenHeight);

This worked properly in my application

How do I find the index of a character in a string in Ruby?

index(substring [, offset]) ? fixnum or nil
index(regexp [, offset]) ? fixnum or nil

Returns the index of the first occurrence of the given substring or pattern (regexp) in str. Returns nil if not found. If the second parameter is present, it specifies the position in the string to begin the search.

"hello".index('e')             #=> 1
"hello".index('lo')            #=> 3
"hello".index('a')             #=> nil
"hello".index(?e)              #=> 1
"hello".index(/[aeiou]/, -3)   #=> 4

Check out ruby documents for more information.

Escaping ampersand in URL

This may help if someone want it in PHP

$variable ="candy_name=M&M";
$variable = str_replace("&", "%26", $variable);

Singleton in Android

EDIT :

The implementation of a Singleton in Android is not "safe" (see here) and you should use a library dedicated to this kind of pattern like Dagger or other DI library to manage the lifecycle and the injection.


Could you post an example from your code ?

Take a look at this gist : https://gist.github.com/Akayh/5566992

it works but it was done very quickly :

MyActivity : set the singleton for the first time + initialize mString attribute ("Hello") in private constructor and show the value ("Hello")

Set new value to mString : "Singleton"

Launch activityB and show the mString value. "Singleton" appears...

DateTimePicker: pick both date and time

Set the Format to Custom and then specify the format:

dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = "MM/dd/yyyy hh:mm:ss";  

or however you want to lay it out. You could then type in directly the date/time. If you use MMM, you'll need to use the numeric value for the month for entry, unless you write some code yourself for that (e.g., 5 results in May)

Don't know about the picker for date and time together. Sounds like a custom control to me.

How to make MySQL table primary key auto increment with some prefix

I know it is late but I just want to share on what I have done for this. I'm not allowed to add another table or trigger so I need to generate it in a single query upon insert. For your case, can you try this query.

CREATE TABLE YOURTABLE(
IDNUMBER VARCHAR(7) NOT NULL PRIMARY KEY,
ENAME VARCHAR(30) not null
);

Perform a select and use this select query and save to the parameter @IDNUMBER

(SELECT IFNULL
     (CONCAT('LHPL',LPAD(
       (SUBSTRING_INDEX
        (MAX(`IDNUMBER`), 'LHPL',-1) + 1), 5, '0')), 'LHPL001')
    AS 'IDNUMBER' FROM YOURTABLE ORDER BY `IDNUMBER` ASC)

And then Insert query will be :

INSERT INTO YOURTABLE(IDNUMBER, ENAME) VALUES 
(@IDNUMBER, 'EMPLOYEE NAME');

The result will be the same as the other answer but the difference is, you will not need to create another table or trigger. I hope that I can help someone that have a same case as mine.

Create a Bitmap/Drawable from file path

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

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

Chmod recursively

To make everything writable by the owner, read/execute by the group, and world executable:

chmod -R 0755

To make everything wide open:

chmod -R 0777

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

Try this it worked in Ubuntu and RedHat:

java -XX:+PrintFlagsFinal -version | grep -iE 'HeapSize|PermSize|ThreadStackSize'

For Windows:

java -XX:+PrintFlagsFinal -version | findstr /i "HeapSize PermSize ThreadStackSize"

For Mac

java -XX:+PrintFlagsFinal -version | grep -iE 'heapsize|permsize|threadstacksize'

The output of all this commands resembles the output below:

uintx InitialHeapSize                          := 20655360        {product}
uintx MaxHeapSize                              := 331350016       {product}
uintx PermSize                                  = 21757952        {pd product}
uintx MaxPermSize                               = 85983232        {pd product}
intx ThreadStackSize                           = 1024            {pd product}
java version "1.7.0_05"
Java(TM) SE Runtime Environment (build 1.7.0_05-b05)
Java HotSpot(TM) 64-Bit Server VM (build 23.1-b03, mixed mode)

To find the size in MB, divide the value with (1024*1024).

How do I set the classpath in NetBeans?

Maven

The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.

Dependency

Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.

Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.

Repository

Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).

Easy to Use

Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.

enter image description here

Why is it important to override GetHashCode when Equals method is overridden?

We have two problems to cope with.

  1. You cannot provide a sensible GetHashCode() if any field in the object can be changed. Also often a object will NEVER be used in a collection that depends on GetHashCode(). So the cost of implementing GetHashCode() is often not worth it, or it is not possible.

  2. If someone puts your object in a collection that calls GetHashCode() and you have overrided Equals() without also making GetHashCode() behave in a correct way, that person may spend days tracking down the problem.

Therefore by default I do.

public class Foo
{
    public int FooId { get; set; }
    public string FooName { get; set; }

    public override bool Equals(object obj)
    {
        Foo fooItem = obj as Foo;

        if (fooItem == null)
        {
           return false;
        }

        return fooItem.FooId == this.FooId;
    }

    public override int GetHashCode()
    {
        // Some comment to explain if there is a real problem with providing GetHashCode() 
        // or if I just don't see a need for it for the given class
        throw new Exception("Sorry I don't know what GetHashCode should do for this class");
    }
}

What is the difference between procedural programming and functional programming?

To Understand the difference, one needs to to understand that "the godfather" paradigm of both procedural and functional programming is the imperative programming.

Basically procedural programming is merely a way of structuring imperative programs in which the primary method of abstraction is the "procedure." (or "function" in some programming languages). Even Object Oriented Programming is just another way of structuring an imperative program, where the state is encapsulated in objects, becoming an object with a "current state," plus this object has a set of functions, methods, and other stuff that let you the programmer manipulate or update the state.

Now, in regards to functional programming, the gist in its approach is that it identifies what values to take and how these values should be transferred. (so there is no state, and no mutable data as it takes functions as first class values and pass them as parameters to other functions).

PS: understanding every programming paradigm is used for should clarify the differences between all of them.

PSS: In the end of the day, programming paradigms are just different approaches to solving problems.

PSS: this quora answer has a great explanation.

Inserting image into IPython notebook markdown

Getting an image into Jupyter NB is a much simpler operation than most people have alluded to here.

1) Simply create an empty Markdown cell. 2) Then drag-and-drop the image file into the empty Markdown cell.

The Markdown code that will insert the image then appears.

For example, a string shown highlighted in gray below will appear in the Jupyter cell:

![Venus_flytrap_taxonomy.jpg](attachment:Venus_flytrap_taxonomy.jpg)

3) Then execute the Markdown cell by hitting Shift-Enter. The Jupyter server will then insert the image, and the image will then appear.

I am running Jupyter notebook server is: 5.7.4 with Python 3.7.0 on Windows 7.

This is so simple !!

Oracle to_date, from mm/dd/yyyy to dd-mm-yyyy

select to_char(to_date('1/21/2000','mm/dd/yyyy'),'dd-mm-yyyy') from dual

How to see tomcat is running or not

for localhost,the defaut port is 8080,you can test the link http://localhost:8080 in you browser.if you can see tomcat home page,your tomcat is running

Regex to match 2 digits, optional decimal, two digits

(?<![\d.])(\d{1,2}|\d{0,2}\.\d{1,2})?(?![\d.])

Matches:

  • Your examples
  • 33.

Does not match:

  • 333.33
  • 33.333

Can I set max_retries for requests.request?

Be careful, Martijn Pieters's answer isn't suitable for version 1.2.1+. You can't set it globally without patching the library.

You can do this instead:

import requests
from requests.adapters import HTTPAdapter

s = requests.Session()
s.mount('http://www.github.com', HTTPAdapter(max_retries=5))
s.mount('https://www.github.com', HTTPAdapter(max_retries=5))

Is there a RegExp.escape function in JavaScript?

The functions in the other answers are overkill for escaping entire regular expressions (they may be useful for escaping parts of regular expressions that will later be concatenated into bigger regexps).

If you escape an entire regexp and are done with it, quoting the metacharacters that are either standalone (., ?, +, *, ^, $, |, \) or start something ((, [, {) is all you need:

String.prototype.regexEscape = function regexEscape() {
  return this.replace(/[.?+*^$|({[\\]/g, '\\$&');
};

And yes, it's disappointing that JavaScript doesn't have a function like this built-in.

What's a simple way to get a text input popup dialog box on an iPhone

In Xamarin and C#:

var alert = new UIAlertView ("Your title", "Your description", null, "Cancel", new [] {"OK"});
alert.AlertViewStyle = UIAlertViewStyle.PlainTextInput;
alert.Clicked += (s, b) => {
    var title = alert.ButtonTitle(b.ButtonIndex);
    if (title == "OK") {
        var text = alert.GetTextField(0).Text;
        ...
    }
};

alert.Show();

How to automatically allow blocked content in IE?

Alternatively, as long as permissions are not given, the good old <noscript> tags works. You can cover the page in css and tell them what's wrong, ... without using javascript ofcourse.

Convert a PHP object to an associative array

Also you can use The Symfony Serializer Component

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$array = json_decode($serializer->serialize($object, 'json'), true);

How to convert CSV file to multiline JSON?

Use pandas and the json library:

import pandas as pd
import json
filepath = "inputfile.csv"
output_path = "outputfile.json"

df = pd.read_csv(filepath)

# Create a multiline json
json_list = json.loads(df.to_json(orient = "records"))

with open(output_path, 'w') as f:
    for item in json_list:
        f.write("%s\n" % item)

Use a.any() or a.all()

This should also work and is a closer answer to what is asked in the question:

for i in range(len(x)):
    if valeur.item(i) <= 0.6:
        print ("this works")
    else:   
        print ("valeur is too high")

Extracting text from a PDF file using PDFMiner in python?

This works in May 2020 using PDFminer six in Python3.

Installing the package

$ pip install pdfminer.six

Importing the package

from pdfminer.high_level import extract_text

Using a PDF saved on disk

text = extract_text('report.pdf')

Or alternatively:

with open('report.pdf','rb') as f:
    text = extract_text(f)

Using PDF already in memory

If the PDF is already in memory, for example if retrieved from the web with the requests library, it can be converted to a stream using the io library:

import io

response = requests.get(url)
text = extract_text(io.BytesIO(response.content))

Performance and Reliability compared with PyPDF2

PDFminer.six works more reliably than PyPDF2 (which fails with certain types of PDFs), in particular PDF version 1.7

However, text extraction with PDFminer.six is significantly slower than PyPDF2 by a factor of 6.

I timed text extraction with timeit on a 15" MBP (2018), timing only the extraction function (no file opening etc.) with a 10 page PDF and got the following results:

PDFminer.six: 2.88 sec
PyPDF2:       0.45 sec

pdfminer.six also has a huge footprint, requiring pycryptodome which needs GCC and other things installed pushing a minimal install docker image on Alpine Linux from 80 MB to 350 MB. PyPDF2 has no noticeable storage impact.

Convert timestamp to date in Oracle SQL

If you have milliseconds in the date string, you can use the following.

select TO_TIMESTAMP(SUBSTR('2020-09-10T09:37:28.378-07:00',1,23), 'YYYY-MM-DD"T"HH24:MI:SS:FF3')From Dual;

And then convert it to Date with:

select trunc(TO_TIMESTAMP(SUBSTR('2020-09-10T09:37:28.378-07:00',1,23), 'YYYY-MM-DD"T"HH24:MI:SS:FF3')) From Dual;

It worked for me, hope it will help you as well.

Form content type for a json HTTP POST?

I have wondered the same thing. Basically it appears that the html spec has different content types for html and form data. Json only has a single content type.

According to the spec, a POST of json data should have the content-type:
application/json

Relevant portion of the HTML spec

6.7 Content types (MIME types)
...
Examples of content types include "text/html", "image/png", "image/gif", "video/mpeg", "text/css", and "audio/basic".

17.13.4 Form content types
...
application/x-www-form-urlencoded
This is the default content type. Forms submitted with this content type must be encoded as follows

Relevant portion of the JSON spec

  1. IANA Considerations
    The MIME media type for JSON text is application/json.

How to find a value in an array and remove it by using PHP array functions?

The unset array_search has some pretty terrible side effects because it can accidentally strip the first element off your array regardless of the value:

        // bad side effects
        $a = [0,1,2,3,4,5];
        unset($a[array_search(3, $a)]);
        unset($a[array_search(6, $a)]);
        $this->log_json($a);
        // result: [1,2,4,5]
        // what? where is 0?
        // it was removed because false is interpreted as 0

        // goodness
        $b = [0,1,2,3,4,5];
        $b = array_diff($b, [3,6]);
        $this->log_json($b);
        // result: [0,1,2,4,5]

If you know that the value is guaranteed to be in the array, go for it, but I think the array_diff is far safer. (I'm using php7)

How can I escape square brackets in a LIKE clause?

I needed to exclude names that started with an underscore from a query, so I ended up with this:

WHERE b.[name] not like '\_%' escape '\'  -- use \ as the escape character

Magento How to debug blank white screen

I had the same problem, it was solved after re-installing my Theme

How to move certain commits to be based on another branch in git?

This is a classic case of rebase --onto:

 # let's go to current master (X, where quickfix2 should begin)
 git checkout master

 # replay every commit *after* quickfix1 up to quickfix2 HEAD.
 git rebase --onto master quickfix1 quickfix2 

So you should go from

o-o-X (master HEAD)
     \ 
      q1a--q1b (quickfix1 HEAD)
              \
               q2a--q2b (quickfix2 HEAD)

to:

      q2a'--q2b' (new quickfix2 HEAD)
     /
o-o-X (master HEAD)
     \ 
      q1a--q1b (quickfix1 HEAD)

This is best done on a clean working tree.
See git config --global rebase.autostash true, especially after Git 2.10.

Barcode scanner for mobile phone for Website in form

Check this out: http://qrdroid.com/web-masters.php

You can create a link in your web form, something like:

http://qrdroid.com/scan?q=http://www.your-site.com/your-form.php?code={CODE}

When somebody clicks that link, an app to scan the code will be opened. After the user scans the code, http://www.your-site.com/your-form.php?code={CODE} will be automatically called. You can then make your-form.php read the parameter code to prepopulate the field.

Jquery Date picker Default Date

While the defaultDate does not set the widget. What is needed is something like:

$(".datepicker").datepicker({
    showButtonPanel: true,
    numberOfMonths: 2

});

$(".datepicker[value='']").datepicker("setDate", "-0d"); 

How to serialize Joda DateTime with Jackson JSON processor?

For those with Spring Boot you have to add the module to your context and it will be added to your configuration like this.

@Bean
public Module jodaTimeModule() {
    return new JodaModule();
}

And if you want to use the new java8 time module jsr-310.

@Bean
public Module jodaTimeModule() {
    return new JavaTimeModule();
}

How to get the Android Emulator's IP address?

If you do truly want the IP assigned to your emulator:

adb shell
ifconfig eth0

Which will give you something like:

eth0: ip 10.0.2.15 mask 255.255.255.0 flags [up broadcast running multicast]

Multiple parameters in a List. How to create without a class?

To add to what other suggested I like the following construct to avoid the annoyance of adding members to keyvaluepair collections.

public class KeyValuePairList<Tkey,TValue> : List<KeyValuePair<Tkey,TValue>>{
    public void Add(Tkey key, TValue value){
        base.Add(new KeyValuePair<Tkey, TValue>(key, value));
    }
}

What this means is that the constructor can be initialized with better syntax::

var myList = new KeyValuePairList<int,string>{{1,"one"},{2,"two"},{3,"three"}};

I personally like the above code over the more verbose examples Unfortunately C# does not really support tuple types natively so this little hack works wonders.

If you find yourself really needing more than 2, I suggest creating abstractions against the tuple type.(although Tuple is a class not a struct like KeyValuePair this is an interesting distinction).

Curiously enough, the initializer list syntax is available on any IEnumerable and it allows you to use any Add method, even those not actually enumerable by your object. It's pretty handy to allow things like adding an object[] member as a params object[] member.

ASP.NET Custom Validator Client side & Server Side validation not firing

Thanks for that info on the ControlToValidate LukeH!

What I was trying to do in my code was to only ensure that some text field A has some text in the field when text field B has a particular value. Otherwise, A can be blank or whatever else. Getting rid of the ControlToValidate="A" in my mark up fixed the issue for me.

Cheers!

Order columns through Bootstrap4

Since column-ordering doesn't work in Bootstrap 4 beta as described in the code provided in the revisited answer above, you would need to use the following (as indicated in the codeply 4 Flexbox order demo - alpha/beta links that were provided in the answer).

<div class="container">
<div class="row">
    <div class="col-3 col-md-6">
        <div class="card card-block">1</div>
    </div>
    <div class="col-6 col-md-12  flex-md-last">
        <div class="card card-block">3</div>
    </div>
    <div class="col-3 col-md-6 ">
        <div class="card card-block">2</div>
    </div>
</div>

Note however that the "Flexbox order demo - beta" goes to an alpha codebase, and changing the codebase to Beta (and running it) results in the divs incorrectly displaying in a single column -- but that looks like a codeply issue since cutting and pasting the code out of codeply works as described.

Combining CSS Pseudo-elements, ":after" the ":last-child"

You can combine pseudo-elements! Sorry guys, I figured this one out myself shortly after posting the question. Maybe it's less commonly used because of compatibility issues.

li:last-child:before { content: "and "; }

li:last-child:after { content: "."; }

This works swimmingly. CSS is kind of amazing.

Convert datetime to Unix timestamp and convert it back in python

If you want to convert a python datetime to seconds since epoch you should do it explicitly:

>>> import datetime
>>> datetime.datetime(2012, 04, 01, 0, 0).strftime('%s')
'1333234800'
>>> (datetime.datetime(2012, 04, 01, 0, 0) - datetime.datetime(1970, 1, 1)).total_seconds()
1333238400.0

In Python 3.3+ you can use timestamp() instead:

>>> import datetime
>>> datetime.datetime(2012, 4, 1, 0, 0).timestamp()
1333234800.0

How to filter JSON Data in JavaScript or jQuery?

It iterates through the json objects, and searches each value you are concerned about, 'website', and if it equals "yahoo" you can then return that value or do whatever you like there. Right now it just logs that element to the console.

jsonObj.forEach(function (element, index) {
    if(element['website'] === 'yahoo'){
        console.log('found', element)   
    }
})

Get Value of Radio button group

Your quotes only need to surround the value part of the attribute-equals selector, [attr='val'], like this:

$('a#check_var').click(function() {
  alert($("input:radio[name='r']:checked").val()+ ' '+
        $("input:radio[name='s']:checked").val());
});?

You can see the working version here.

How to get the second column from command output?

Use -F [field separator] to split the lines on "s:

awk -F '"' '{print $2}' your_input_file

or for input from pipe

<some_command> | awk -F '"' '{print $2}'

output:

A B
C
D

Chart.js v2 hide dataset labels

new Chart('idName', {
      type: 'typeChar',
      data: data,
      options: {
        legend: {
          display: false
        }
      }
    });

currently unable to handle this request HTTP ERROR 500

I was having "(...) unable to handle this request. http error 500" and found out it was from a require_once that was working locally, on a windows machine, with backslash (\) as separator for directories but when i uploaded to my server it stopped working. I changed it to forward slash (/) and now is ok.

require_once ( 'cards\cards.php' ); // **http error 500**

require_once ( 'cards/cards.php' ); // OK

Should I use string.isEmpty() or "".equals(string)?

The main benefit of "".equals(s) is you don't need the null check (equals will check its argument and return false if it's null), which you seem to not care about. If you're not worried about s being null (or are otherwise checking for it), I would definitely use s.isEmpty(); it shows exactly what you're checking, you care whether or not s is empty, not whether it equals the empty string

MySql Table Insert if not exist otherwise update

Try using this:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index orPRIMARY KEY, MySQL performs an [UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...

The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...

How do I get the opposite (negation) of a Boolean in Python?

If you are trying to implement a toggle, so that anytime you re-run a persistent code its being negated, you can achieve that as following:

try:
    toggle = not toggle
except NameError:
    toggle = True

Running this code will first set the toggle to True and anytime this snippet ist called, toggle will be negated.

MySQL - Meaning of "PRIMARY KEY", "UNIQUE KEY" and "KEY" when used together while creating a table

MySQL unique and primary keys serve to identify rows. There can be only one Primary key in a table but one or more unique keys. Key is just index.

for more details you can check http://www.geeksww.com/tutorials/database_management_systems/mysql/tips_and_tricks/mysql_primary_key_vs_unique_key_constraints.php

to convert mysql to mssql try this and see http://gathadams.com/2008/02/07/convert-mysql-to-ms-sql-server/

How to launch an EXE from Web page (asp.net)

Did you try a UNC share?

\\server\share\foo.exe

Run a shell script with an html button

PHP is likely the easiest.

Just make a file script.php that contains <?php shell_exec("yourscript.sh"); ?> and send anybody who clicks the button to that destination. You can return the user to the original page with header:

<?php
shell_exec("yourscript.sh");
header('Location: http://www.website.com/page?success=true');
?>

Reference: http://php.net/manual/en/function.shell-exec.php

Call multiple functions onClick ReactJS

Maybe you can use arrow function (ES6+) or the simple old function declaration.

Normal function declaration type (Not ES6+):

<link href="#" onClick={function(event){ func1(event); func2();}}>Trigger here</link>

Anonymous function or arrow function type (ES6+)

<link href="#" onClick={(event) => { func1(event); func2();}}>Trigger here</link>

The second one is the shortest road that I know. Hope it helps you!

ImportError: No module named PyQt4

You have to check which Python you are using. I had the same problem because the Python I was using was not the same one that brew was using. In your command line:

  1. which python
    output: /usr/bin/python
  2. which brew
    output: /usr/local/bin/brew     //so they are different
  3. cd /usr/local/lib/python2.7/site-packages
  4. ls   //you can see PyQt4 and sip are here
  5. Now you need to add usr/local/lib/python2.7/site-packages to your python path.
  6. open ~/.bash_profile   //you will open your bash_profile file in your editor
  7. Add 'export PYTHONPATH=/usr/local/lib/python2.7/site-packages:$PYTHONPATH' to your bash file and save it
  8. Close your terminal and restart it to reload the shell
  9. python
  10. import PyQt4    // it is ok now

Fill remaining vertical space - only CSS

All you need is a bit of improved markup. Wrap the second within the first and it will render under.

<div id="wrapper">
    <div id="first">
        Here comes the first content
        <div id="second">I will render below the first content</div>
    </div>
</div>

Demo

Accessing elements of Python dictionary by index

With the following small function, digging into a tree-shaped dictionary becomes quite easy:

def dig(tree, path):
    for key in path.split("."):
        if isinstance(tree, dict) and tree.get(key):
            tree = tree[key]
        else:
            return None
    return tree

Now, dig(mydict, "Apple.Mexican") returns 10, while dig(mydict, "Grape") yields the subtree {'Arabian':'25','Indian':'20'}. If a key is not contained in the dictionary, dig returns None.

Note that you can easily change (or even parameterize) the separator char from '.' to '/', '|' etc.

How do I use modulus for float/double?

I thought the regular modulus operator would work for this in java, but it can't be hard to code. Just divide the numerator by the denominator, and take the integer portion of the result. Multiply that by the denominator, and subtract the result from the numerator.

x = n / d
xint = Integer portion of x
result = n - d * xint

Difference between Console.Read() and Console.ReadLine()?

Console.Read() reads just a single character, while Console.ReadLine() reads all characters until the end of line.

How can I find out the total physical memory (RAM) of my linux box suitable to be parsed by a shell script?

Total memory in Mb:

x=$(awk '/MemTotal/ {print $2}' /proc/meminfo)
echo $((x/1024))

or:

x=$(awk '/MemTotal/ {print $2}' /proc/meminfo) ; echo $((x/1024))

Explanation of "ClassCastException" in Java

A Java ClassCastException is an Exception that can occur when you try to improperly convert a class from one type to another.

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class ClassCastExceptionExample {

  public ClassCastExceptionExample() {

    List list = new ArrayList();
    list.add("one");
    list.add("two");
    Iterator it = list.iterator();
    while (it.hasNext()) {
        // intentionally throw a ClassCastException by trying to cast a String to an
        // Integer (technically this is casting an Object to an Integer, where the Object 
        // is really a reference to a String:
        Integer i = (Integer)it.next();
    }
  }
 public static void main(String[] args) {
  new ClassCastExceptionExample();
 }
}

If you try to run this Java program you’ll see that it will throw the following ClassCastException:

Exception in thread "main" java.lang.ClassCastException: java.lang.String
at ClassCastExceptionExample  (ClassCastExceptionExample.java:15)
at ClassCastExceptionExample.main  (ClassCastExceptionExample.java:19)

The reason an exception is thrown here is that when I’m creating my list object, the object I store in the list is the String “one,” but then later when I try to get this object out I intentionally make a mistake by trying to cast it to an Integer. Because a String cannot be directly cast to an Integer — an Integer is not a type of String — a ClassCastException is thrown.

Echo equivalent in PowerShell for script testing

There are several ways:

Write-Host: Write directly to the console, not included in function/cmdlet output. Allows foreground and background colour to be set.

Write-Debug: Write directly to the console, if $DebugPreference set to Continue or Stop.

Write-Verbose: Write directly to the console, if $VerbosePreference set to Continue or Stop.

The latter is intended for extra optional information, Write-Debug for debugging (so would seem to fit in this case).

Additional: In PSH2 (at least) scripts using cmdlet binding will automatically get the -Verbose and -Debug switch parameters, locally enabling Write-Verbose and Write-Debug (i.e. overriding the preference variables) as compiled cmdlets and providers do.

Regex - how to match everything except a particular pattern

notnot, resurrecting this ancient question because it had a simple solution that wasn't mentioned. (Found your question while doing some research for a regex bounty quest.)

I'm faced with a situation where I have to match an (A and ~B) pattern.

The basic regex for this is frighteningly simple: B|(A)

You just ignore the overall matches and examine the Group 1 captures, which will contain A.

An example (with all the disclaimers about parsing html in regex): A is digits, B is digits within <a tag

The regex: <a.*?<\/a>|(\d+)

Demo (look at Group 1 in the lower right pane)

Reference

How to match pattern except in situations s1, s2, s3

How to match a pattern unless...

How can I create a carriage return in my C# string

Along with Environment.NewLine and the literal \r\n or just \n you may also use a verbatim string in C#. These begin with @ and can have embedded newlines. The only thing to keep in mind is that " needs to be escaped as "". An example:

string s = @"This is a string
that contains embedded new lines,
that will appear when this string is used."

Remove gutter space for a specific div only

To add to Skelly's Bootstrap 3 no-gutter answer above (https://stackoverflow.com/a/21282059/662883)

Add the following to prevent gutters on a row containing only one column (useful when using column-wrapping: http://getbootstrap.com/css/#grid-example-wrapping):

.row.no-gutter [class*='col-']:only-child,
.row.no-gutter [class*='col-']:only-child
{
    padding-right: 0;
    padding-left: 0;
}

How do I prevent a form from being resized by the user?

Add some code to the Form Load event:

me.maximumsize = new size(Width, Height)
me.minimumsize = me.maximumsize
me.maximizebox = false
me.minimizebox = false

Example: For a Form height and width of 50 pixels each:

me.maximumsize = new size(50, 50)
me.minimumsize = me.maximumsize
me.maximizebox = false
me.minimizebox = false

Note that setting maximumsize and minimumsize to the same size as shown here prevents resizing the Form.

How to pass multiple checkboxes using jQuery ajax post

If you're not set on rolling your own solution, check out this jQuery plugin:

malsup.com/jquery/form/

It will do that and more for you. It's highly recommended.

string.Replace in AngularJs

In Javascript method names are camel case, so it's replace, not Replace:

$scope.newString = oldString.replace("stackover","NO");

Note that contrary to how the .NET Replace method works, the Javascript replace method replaces only the first occurrence if you are using a string as first parameter. If you want to replace all occurrences you need to use a regular expression so that you can specify the global (g) flag:

$scope.newString = oldString.replace(/stackover/g,"NO");

See this example.

How to change sa password in SQL Server 2008 express?

I didn't know the existing sa password so this is what I did:

  1. Open Services in Control Panel

  2. Find the "SQL Server (SQLEXPRESS)" entry and select properties

  3. Stop the service

  4. Enter "-m" at the beginning of the "Start parameters" fields. If there are other parameters there already add a semi-colon after -m;

  5. Start the service

  6. Open a Command Prompt

Enter the command:

osql -S YourPcName\SQLEXPRESS -E

(change YourPcName to whatever your PC is called).

  1. At the prompt type the following commands:
alter login sa enable
go
sp_password NULL,'new_password','sa'
go
quit
  1. Stop the "SQL Server (SQLEXPRESS)" service

  2. Remove the "-m" from the Start parameters field

  3. Start the service

ImportError: DLL load failed: %1 is not a valid Win32 application

Or you have to rebuild the cv2 module for win 64bit.

With ' N ' no of nodes, how many different Binary and Binary Search Trees possible?

Eric Lippert recently had a very in-depth series of blog posts about this: "Every Binary Tree There Is" and "Every Tree There Is" (plus some more after that).

In answer to your specific question, he says:

The number of binary trees with n nodes is given by the Catalan numbers, which have many interesting properties. The nth Catalan number is determined by the formula (2n)! / (n+1)!n!, which grows exponentially.

How do I display the current value of an Android Preference in the Preference summary?

After several hours I've been spent to solve such problem I've implemented this code:

[UPDATE: the final version listing]

public class MyPreferencesActivity extends PreferenceActivity {
    ...
    ListPreference m_updateList;
    ...
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.preferences);

        m_updateList = (ListPreference) findPreference(getString(R.string.pref_update_interval_key));
        String currentValue = m_updateList.getValue();
        if (currentValue == null) {
            m_updateList.setValue((String)m_updateList.getEntryValues()[DEFAULT_UPDATE_TIME_INDEX]);
            currentValue = m_updateList.getValue();
        }
        updateListSummary(currentValue);    

        m_updateList.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
            @Override
            public boolean onPreferenceChange(Preference preference, Object newValue) {
                updateListSummary(newValue.toString());
                return true;
            }       
        });     
    }

    private void updateListSummary(String newValue) {
        int index = m_updateList.findIndexOfValue(newValue);
        CharSequence entry = m_updateList.getEntries()[index];
        m_updateList.setSummary(entry);
    }
}

That was the only solution that worked for me fine. Before I've tried to subclass from ListPreferences and to implement android:summary="bla bla bla %s". Neither worked.

How to delete directory content in Java?

Use FileUtils with FileUtils.deleteDirectory();

How to show all rows by default in JQuery DataTable

Use:

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

The option you should use is iDisplayLength:

$('#adminProducts').dataTable({
  'iDisplayLength': 100
});

$('#table').DataTable({
   "lengthMenu": [ [5, 10, 25, 50, -1], [5, 10, 25, 50, "All"] ]
});

It will Load by default all entries.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
    iDisplayLength: -1
});

Or if using 1.10+

$('#example').dataTable({
    paging: false
});

If you want to load by default 25 not all do this.

$('#example').dataTable({
    aLengthMenu: [
        [25, 50, 100, 200, -1],
        [25, 50, 100, 200, "All"]
    ],
});

Any reason to prefer getClass() over instanceof when generating .equals()?

Correct me if I am wrong, but getClass() will be useful when you want to make sure your instance is NOT a subclass of the class you are comparing with. If you use instanceof in that situation you can NOT know that because:

class A { }

class B extends A { }

Object oA = new A();
Object oB = new B();

oA instanceof A => true
oA instanceof B => false
oB instanceof A => true // <================ HERE
oB instanceof B => true

oA.getClass().equals(A.class) => true
oA.getClass().equals(B.class) => false
oB.getClass().equals(A.class) => false // <===============HERE
oB.getClass().equals(B.class) => true

How do I filter ForeignKey choices in a Django ModelForm?

ForeignKey is represented by django.forms.ModelChoiceField, which is a ChoiceField whose choices are a model QuerySet. See the reference for ModelChoiceField.

So, provide a QuerySet to the field's queryset attribute. Depends on how your form is built. If you build an explicit form, you'll have fields named directly.

form.rate.queryset = Rate.objects.filter(company_id=the_company.id)

If you take the default ModelForm object, form.fields["rate"].queryset = ...

This is done explicitly in the view. No hacking around.

JSON Java 8 LocalDateTime format in Spring Boot

@JsonDeserialize(using= LocalDateDeserializer.class) does not work for me with the below dependency.

<dependency>
    <groupId>com.fasterxml.jackson.datatype</groupId>
    <artifactId>jackson-datatype-jsr310</artifactId>
    <version> 2.9.6</version>
</dependency>

I have used the below code converter to deserialize the date into a java.sql.Date.

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;


@SuppressWarnings("UnusedDeclaration")
@Converter(autoApply = true)
public class LocalDateConverter implements AttributeConverter<java.time.LocalDate, java.sql.Date> {


    @Override
    public java.sql.Date convertToDatabaseColumn(java.time.LocalDate attribute) {

        return attribute == null ? null : java.sql.Date.valueOf(attribute);
    }

    @Override
    public java.time.LocalDate convertToEntityAttribute(java.sql.Date dbData) {

        return dbData == null ? null : dbData.toLocalDate();
    }
}

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

I just had this problem

  1. Having multiple user using the same repo caused the problem
  2. Logout evey other user using the repo

Hope this helps

Java Long primitive type maximum limit

Ranges from -9,223,372,036,854,775,808 to +9,223,372,036,854,775,807.

It will start from -9,223,372,036,854,775,808

Long.MIN_VALUE.

How to convert string to double with proper cultureinfo

I took some help from MSDN, but this is my answer:

double number;
string localStringNumber;
string doubleNumericValueasString = "65.89875";
System.Globalization.NumberStyles style = System.Globalization.NumberStyles.AllowDecimalPoint;

if (double.TryParse(doubleNumericValueasString, style, System.Globalization.CultureInfo.InvariantCulture, out number))
    Console.WriteLine("Converted '{0}' to {1}.", doubleNumericValueasString, number);
else
    Console.WriteLine("Unable to convert '{0}'.", doubleNumericValueasString);
localStringNumber =number.ToString(System.Globalization.CultureInfo.CreateSpecificCulture("de-DE"));

Delete rows with blank values in one particular column

 df[!(is.na(df$start_pc) | df$start_pc==""), ]

Overwriting txt file in java

The easiest way to overwrite a text file is to use a public static field.

this will overwrite the file every time because your only using false the first time through.`

public static boolean appendFile;

Use it to allow only one time through the write sequence for the append field of the write code to be false.

// use your field before processing the write code

appendFile = False;

File fnew=new File("../playlist/"+existingPlaylist.getText()+".txt");
String source = textArea.getText();
System.out.println(source);
FileWriter f2;

try {
     //change this line to read this

    // f2 = new FileWriter(fnew,false);

    // to read this
    f2 = new FileWriter(fnew,appendFile); // important part
    f2.write(source);

    // change field back to true so the rest of the new data will
    // append to the new file.

    appendFile = true;

    f2.close();
 } catch (IOException e) {
       // TODO Auto-generated catch block
       e.printStackTrace();
 }           

Rails how to run rake task

You can run Rake tasks from your shell by running:

rake task_name

To run from from Ruby (e.g., in the Rails console or another Rake task):

Rake::Task['task_name'].invoke

To run multiple tasks in the same namespace with a single task, create the following new task in your namespace:

task :runall => [:iqmedier, :euroads, :mikkelsen, :orville] do
  # This will run after all those tasks have run
end

What is key=lambda

 >>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())

Actually, above codes can be:

>>> sorted(['Some','words','sort','differently'],key=str.lower)

According to https://docs.python.org/2/library/functions.html?highlight=sorted#sorted, key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

Bad Request, Your browser sent a request that this server could not understand

I just deleted my stored cookies, site data, and cache from my browser... It worked. I'm using firefox...

Save internal file in my own internal folder in Android

Save:

public boolean saveFile(Context context, String mytext){
    Log.i("TESTE", "SAVE");
    try {
        FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        out.write(mytext);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

Load:

public String load(Context context){
    Log.i("TESTE", "FILE");
    try {
        FileInputStream fis = context.openFileInput("file_name"+".txt");
        BufferedReader r = new BufferedReader(new InputStreamReader(fis));
        String line= r.readLine();
        r.close();
        return line;
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TESTE", "FILE - false");
        return null;
    }
}

Twitter bootstrap scrollable table

This is may not a solution for large row count. I simply use duplication table trick to get the thing done for small row count table while it can keep flex column width, you can try this fiddle.

(The fixed width column is the method I use for large row count table which require only the header row duplication)

Sample Code:

<div style="height:30px;overflow:hidden;margin-right:15px;">
   <table class="table">
       <thead>
           <tr>
                <th>Col 1</th>
                <th>Col 2</th>
                <th>Col 3</th>
            </tr>
        </thead>
        <tbody>
            <tr>
                <td>Cel 1,1</td>
                <td>Cel 1,2</td>
                <td>Cel 1,3</td>
            </tr>
            <tr>
                <td>Cel 2,1</td>
                <td>Cel 2,2</td>
                <td>Cel 2,3</td>
            </tr>
            <tr>
                <td>Cel 3,1</td>
                <td>Cel 3,2</td>
                <td>Cel 3,3</td>
            </tr>


        </tbody>
    </table>
</div>
<div style="height:100px;overflow-y:scroll;;">
    <table class="table">
        <thead>

        </thead>
        <tbody>
            <tr>
                <td>Cel 1,1</td>
                <td>Cel 1,2</td>
                <td>Cel 1,3</td>
            </tr>
            <tr>
                <td>Cel 2,1</td>
                <td>Cel 2,2</td>
                <td>Cel 2,3</td>
            </tr>
            <tr>
                <td>Cel 3,1</td>
                <td>Cel 3,2</td>
                <td>Cel 3,3</td>
            </tr>
             <tr style="color:white">
                <th>Col 1</th>
                <th>Col 2</th>
                <th>Col 3</th>
            </tr>
        </tbody>
    </table>
</div>

Spring MVC - How to get all request params in a map in Spring controller?

@SuppressWarnings("unchecked")
Map<String,String[]> requestMapper=request.getParameterMap();
JsonObject jsonObject=new JsonObject();
for(String key:requestMapper.keySet()){
    jsonObject.addProperty(key, requestMapper.get(key)[0]);
}

All params will be stored in jsonObject.

java.io.IOException: Broken pipe

increase the response.getBufferSize() get the buffer size and compare with the bytes you want to transfer !

Fixed header, footer with scrollable content

Here's what worked for me. I had to add a margin-bottom so the footer wouldn't eat up my content:

header {
  height: 20px;
  background-color: #1d0d0a;
  position: fixed;
  top: 0;
  width: 100%;
  overflow: hide;
}

content {
  margin-left: auto;
  margin-right: auto;
  margin-bottom: 100px;
  margin-top: 20px;
  overflow: auto;
  width: 80%;
}

footer {
  position: fixed;
  bottom: 0px;
  overflow: hide;
  width: 100%;
}

Check input value length

You can add a form onsubmit handler, something like:

<form onsubmit="return validate();">

</form>


<script>function validate() {
 // check if input is bigger than 3
 var value = document.getElementById('titleeee').value;
 if (value.length < 3) {
   return false; // keep form from submitting
 }

 // else form is good let it submit, of course you will 
 // probably want to alert the user WHAT went wrong.

 return true;
}</script>

Random row selection in Pandas dataframe

sample

As of v0.20.0, you can use pd.DataFrame.sample, which can be used to return a random sample of a fixed number rows, or a percentage of rows:

df = df.sample(n=k)     # k rows
df = df.sample(frac=k)  # int(len(df.index) * k) rows

For reproducibility, you can specify an integer random_state, equivalent to using np.ramdom.seed. So, instead of setting, for example, np.random.seed = 0, you can:

df = df.sample(n=k, random_state=0)

jQuery .live() vs .on() method for adding a click event after loading dynamic html

I used 'live' in my project but one of my friend suggested that i should use 'on' instead of live. And when i tried to use that i experienced a problem like you had.

On my pages i create buttons table rows and many dom stuff dynamically. but when i use on the magic disappeared.

The other solutions like use it like a child just calls your functions every time on every click. But i find a way to make it happen again and here is the solution.

Write your code as:

function caller(){
    $('.ObjectYouWntToCall').on("click", function() {...magic...});
}

Call caller(); after you create your object in the page like this.

$('<dom class="ObjectYouWntToCall">bla... bla...<dom>').appendTo("#whereeveryouwant");
caller();

By this way your function is called when it is supposed to not every click on the page.

How to use EOF to run through a text file in C?

I would suggest you to use fseek-ftell functions.

FILE *stream = fopen("example.txt", "r");

if(!stream) {
    puts("I/O error.\n");
    return;
}

fseek(stream, 0, SEEK_END);
long size = ftell(stream);
fseek(stream, 0, SEEK_SET);

while(1) {

    if(ftell(stream) == size) {
        break;
    }

    /* INSERT ROUTINE */

}

fclose(stream);

Leave only two decimal places after the dot

Use string interpolation decimalVar:0.00

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

Imagine you are developing a web-application and you decide to decouple the functionality from the presentation of the application, because it affords greater freedom.

You create an API and let others implement their own front-ends over it as well. What you just did here is implement an SOA methodology, i.e. using web-services.

Web services make functional building-blocks accessible over standard Internet protocols independent of platforms and programming languages.

So, you design an interchange mechanism between the back-end (web-service) that does the processing and generation of something useful, and the front-end (which consumes the data), which could be anything. (A web, mobile, or desktop application, or another web-service). The only limitation here is that the front-end and back-end must "speak" the same "language".


That's where SOAP and REST come in. They are standard ways you'd pick communicate with the web-service.

SOAP:

SOAP internally uses XML to send data back and forth. SOAP messages have rigid structure and the response XML then needs to be parsed. WSDL is a specification of what requests can be made, with which parameters, and what they will return. It is a complete specification of your API.

REST:

REST is a design concept.

The World Wide Web represents the largest implementation of a system conforming to the REST architectural style.

It isn't as rigid as SOAP. RESTful web-services use standard URIs and methods to make calls to the webservice. When you request a URI, it returns the representation of an object, that you can then perform operations upon (e.g. GET, PUT, POST, DELETE). You are not limited to picking XML to represent data, you could pick anything really (JSON included)

Flickr's REST API goes further and lets you return images as well.


JSON and XML, are functionally equivalent, and common choices. There are also RPC-based frameworks like GRPC based on Protobufs, and Apache Thrift that can be used for communication between the API producers and consumers. The most common format used by web APIs is JSON because of it is easy to use and parse in every language.

Fill background color left to right CSS

The thing you will need to do here is use a linear gradient as background and animate the background position. In code:

Use a linear gradient (50% red, 50% blue) and tell the browser that background is 2 times larger than the element's width (width:200%, height:100%), then tell it to position the background left.

background: linear-gradient(to right, red 50%, blue 50%);
background-size: 200% 100%;
background-position:left bottom;

On hover, change the background position to right bottom and with transition:all 2s ease;, the position will change gradually (it's nicer with linear tough) background-position:right bottom;

http://jsfiddle.net/75Umu/3/

As for the -vendor-prefix'es, see the comments to your question

extra If you wish to have a "transition" in the colour, you can make it 300% width and make the transition start at 34% (a bit more than 1/3) and end at 65% (a bit less than 2/3).

background: linear-gradient(to right, red 34%, blue 65%);
background-size: 300% 100%;

Demo:

_x000D_
_x000D_
div {
    font: 22px Arial;
    display: inline-block;
    padding: 1em 2em;
    text-align: center;
    color: white;
    background: red; /* default color */

    /* "to left" / "to right" - affects initial color */
    background: linear-gradient(to left, salmon 50%, lightblue 50%) right;
    background-size: 200%;
    transition: .5s ease-out;
}
div:hover {
    background-position: left;
}
_x000D_
<div>Hover me</div>
_x000D_
_x000D_
_x000D_

How can I solve the error 'TS2532: Object is possibly 'undefined'?

Edit / Update:

If you are using Typescript 3.7 or newer you can now also do:

    const data = change?.after?.data();

    if(!data) {
      console.error('No data here!');
       return null
    }

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }

Original Response

Typescript is saying that change or data is possibly undefined (depending on what onUpdate returns).

So you should wrap it in a null/undefined check:

if(change && change.after && change.after.data){
    const data = change.after.data();

    const maxLen = 100;
    const msgLen = data.messages.length;
    const charLen = JSON.stringify(data).length;

    const batch = db.batch();

    if (charLen >= 10000 || msgLen >= maxLen) {

      // Always delete at least 1 message
      const deleteCount = msgLen - maxLen <= 0 ? 1 : msgLen - maxLen
      data.messages.splice(0, deleteCount);

      const ref = db.collection("chats").doc(change.after.id);

      batch.set(ref, data, { merge: true });

      return batch.commit();
    } else {
      return null;
    }
}

If you are 100% sure that your object is always defined then you can put this:

const data = change.after!.data();

How can I declare enums using java

public enum MyEnum {
   ONE(1),
   TWO(2);
   private int value;
   private MyEnum(int value) {
      this.value = value;
   }
   public int getValue() {
      return value;
   }
}

In short - you can define any number of parameters for the enum as long as you provide constructor arguments (and set the values to the respective fields)

As Scott noted - the official enum documentation gives you the answer. Always start from the official documentation of language features and constructs.

Update: For strings the only difference is that your constructor argument is String, and you declare enums with TEST("test")

Why is the parent div height zero when it has floated children

Content that is floating does not influence the height of its container. The element contains no content that isn't floating (so nothing stops the height of the container being 0, as if it were empty).

Setting overflow: hidden on the container will avoid that by establishing a new block formatting context. See methods for containing floats for other techniques and containing floats for an explanation about why CSS was designed this way.

Rename a column in MySQL

Rename column name in mysql

alter table categories change  type  category_type varchar(255);

Rails 4 - passing variable to partial

You need the full render partial syntax if you are passing locals

<%= render @users, :locals => {:size => 30} %>

Becomes

<%= render :partial => 'users', :collection => @users, :locals => {:size => 30} %>

Or to use the new hash syntax

<%= render partial: 'users', collection: @users, locals: {size: 30} %>

Which I think is much more readable

insert/delete/update trigger in SQL server

I use that for all status (update, insert and delete)

CREATE TRIGGER trg_Insert_Test
ON [dbo].[MyTable]
AFTER UPDATE, INSERT, DELETE 
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Activity  NVARCHAR (50)

-- update
IF EXISTS (SELECT * FROM inserted) AND EXISTS (SELECT * FROM deleted)
BEGIN
    SET @Activity = 'UPDATE'
END

-- insert
IF EXISTS (SELECT * FROM inserted) AND NOT EXISTS(SELECT * FROM deleted)
BEGIN
    SET @Activity = 'INSERT'
END

-- delete
IF EXISTS (SELECT * FROM deleted) AND NOT EXISTS(SELECT * FROM inserted)
BEGIN
    SET @Activity = 'DELETE'
END



-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl

-- get last 1 row
SELECT * INTO #tmpTbl FROM (SELECT TOP 1 * FROM (SELECT * FROM inserted
                                                 UNION 
                                                 SELECT * FROM deleted
                                                 ) AS A ORDER BY A.Date DESC
                            ) AS T


-- try catch
BEGIN TRY 

    INSERT INTO MyTable  (
           [Code]
          ,[Name]
           .....
          ,[Activity])
    SELECT [Code]
          ,[Name]
          ,@Activity 
    FROM #tmpTbl

END TRY BEGIN CATCH END CATCH


-- delete temp table
IF OBJECT_ID('tempdb..#tmpTbl') IS NOT NULL DROP TABLE #tmpTbl

SET NOCOUNT OFF;
END

JFrame in full screen Java

You can use properties tool.
Set 2 properties for your JFrame:

extendedState 6
resizeable    true

How to list all AWS S3 objects in a bucket using Java

I know this is an old post, but this still might be usefull to anyone: The Java/Android SDK on version 2.1 provides a method called setMaxKeys. Like this:

s3objects.setMaxKeys(arg0)

You probably found a solution by now, but please check one answer as correct so that it might help others in the future.

Maximum length for MySQL type text

TEXT is a string data type that can store up to 65,535 characters. But still if you want to store more data then change its data type to LONGTEXT

ALTER TABLE name_tabel CHANGE text_field LONGTEXT CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL;

npm install errors with Error: ENOENT, chmod

I tried all the stuff I found on the net (npm cache clear and rm -rf ~/.npm), but nothing seems to work. What solved the issue was updating node (and npm) to the latest version. Try that.

changing iframe source with jquery

Using attr() pointing to an external domain may trigger an error like this in Chrome: "Refused to display document because display forbidden by X-Frame-Options". The workaround to this can be to move the whole iframe HTML code into the script (eg. using .html() in jQuery).

Example:

var divMapLoaded = false;
$("#container").scroll(function() {
    if ((!divMapLoaded) && ($("#map").position().left <= $("#map").width())) {
    $("#map-iframe").html("<iframe id=\"map-iframe\" " +
        "width=\"100%\" height=\"100%\" frameborder=\"0\" scrolling=\"no\" " +
        "marginheight=\"0\" marginwidth=\"0\" " +
        "src=\"http://www.google.it/maps?t=m&amp;cid=0x3e589d98063177ab&amp;ie=UTF8&amp;iwloc=A&amp;brcurrent=5,0,1&amp;ll=41.123115,16.853177&amp;spn=0.005617,0.009943&amp;output=embed\"" +
        "></iframe>");
    divMapLoaded = true;
}

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

Make sure you import csv file using Pandas

import pandas as pd

condition = pd.isnull(data[i][j])

JavaScript click event listener on class

Yow can use querySelectorAll to select all the classes and loop through them to assign the eventListener. The if condition checks if it contains the class name.

const arrClass = document.querySelectorAll(".className");
for (let i of arrClass) {
  i.addEventListener("click", (e) => {
    if (e.target.classList.contains("className")) {
        console.log("Perfrom Action")
    }
  })
}

List rows after specific date

Simply put:

SELECT * 
FROM TABLE_NAME
WHERE
dob > '1/21/2012'

Where 1/21/2012 is the date and you want all data, including that date.

SELECT * 
FROM TABLE_NAME
WHERE
dob BETWEEN '1/21/2012' AND '2/22/2012'

Use a between if you're selecting time between two dates

How to 'update' or 'overwrite' a python list

If you are trying to take a value from the same array and trying to update it, you can use the following code.

{  'condition': { 
                     'ts': [   '5a81625ba0ff65023c729022',
                               '5a8161ada0ff65023c728f51',
                               '5a815fb4a0ff65023c728dcd']}

If the collection is userData['condition']['ts'] and we need to

    for i,supplier in enumerate(userData['condition']['ts']): 
        supplier = ObjectId(supplier)
        userData['condition']['ts'][i] = supplier

The output will be

{'condition': {   'ts': [   ObjectId('5a81625ba0ff65023c729022'),
                            ObjectId('5a8161ada0ff65023c728f51'),
                            ObjectId('5a815fb4a0ff65023c728dcd')]}

Insert at first position of a list in Python

From the documentation:

list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a),x) is equivalent to a.append(x)

http://docs.python.org/2/tutorial/datastructures.html#more-on-lists

Missing Microsoft RDLC Report Designer in Visual Studio

This trouble passed me. If you can't repair this trouble, perhaps can you review all Framework versions that you have in your system. For example, if you have ReportViewer for Framework 4.5 and your project is assembly in Framework 2 or another Framework minor at 4.5. The differents versions Framework sometime have problems.

How do you pull first 100 characters of a string in PHP

try this function

function summary($str, $limit=100, $strip = false) {
    $str = ($strip == true)?strip_tags($str):$str;
    if (strlen ($str) > $limit) {
        $str = substr ($str, 0, $limit - 3);
        return (substr ($str, 0, strrpos ($str, ' ')).'...');
    }
    return trim($str);
}

Extract substring in Bash

Building on jor's answer (which doesn't work for me):

substring=$(expr "$filename" : '.*_\([^_]*\)_.*')

Programmatically get the version number of a DLL

Answer by @Ben proved to be useful for me. But I needed to check the product version as it was the main increment happening in my software and followed semantic versioning.

myFileVersionInfo.ProductVersion

This method met my expectations

Update: Instead of explicitly mentioning dll path in program (as needed in production version), we can get product version using Assembly.

Assembly assembly = Assembly.GetExecutingAssembly();
FileVersionInfo fileVersionInfo =FileVersionInfo.GetVersionInfo(assembly.Location); 
string ProdVersion= fileVersionInfo.ProductVersion;

Using Node.JS, how do I read a JSON file into (server) memory?

In Node 8 you can use the built-in util.promisify() to asynchronously read a file like this

const {promisify} = require('util')
const fs = require('fs')
const readFileAsync = promisify(fs.readFile)

readFileAsync(`${__dirname}/my.json`, {encoding: 'utf8'})
  .then(contents => {
    const obj = JSON.parse(contents)
    console.log(obj)
  })
  .catch(error => {
    throw error
  })

How to find tags with only certain attributes - BeautifulSoup

find using an attribute in any tag

<th class="team" data-sort="team">Team</th>    
soup.find_all(attrs={"class": "team"}) 

<th data-sort="team">Team</th>  
soup.find_all(attrs={"data-sort": "team"}) 
 

Get class labels from Keras functional model

It is possible to save a "list" of labels in keras model directly. This way the user who uses the model for predictions and does not have any other sources of information can perform the lookup himself. Here is a dummy example of how one can perform an "injection" of labels

# assume we get labels as list
labels = ["cat","dog","horse","tomato"]
# here we start building our model with input image 299x299 and one output layer
xx = Input(shape=(299,299,3))
flat = Flatten()(xx)
output = Dense(shape=(4))(flat)
# here we perform injection of labels
tf_labels = tf.constant([labels],dtype="string")
tf_labels = tf.tile(labels,[tf.shape(xx)[0],1])
output_labels = Lambda(lambda x: tf_labels,name="label_injection")(xx)
#and finaly creating a model
model=tf.keras.Model(xx,[output,output_labels])

When used for prediction, this model returns tensor of scores and tensot of string labels. Model like this can be saved to h5. In this case the file contains the labels. This model can also be exported to saved_model and used for serving in the cloud.

How can I easily switch between PHP versions on Mac OSX?

If you have both versions of PHP installed, you can switch between versions using the link and unlink brew commands.

For example, to switch between PHP 7.4 and PHP 7.3

brew unlink [email protected]
brew link [email protected]

PS: both versions of PHP have be installed for these commands to work.

Changing minDate and maxDate on the fly using jQuery DatePicker

You have a couple of options...

1) You need to call the destroy() method not remove() so...

$('#date').datepicker('destroy');

Then call your method to recreate the datepicker object.

2) You can update the property of the existing object via

$('#date').datepicker('option', 'minDate', new Date(startDate));
$('#date').datepicker('option', 'maxDate', new Date(endDate));

or...

$('#date').datepicker('option', { minDate: new Date(startDate),
                                  maxDate: new Date(endDate) });

What does (function($) {})(jQuery); mean?

Actually, this example helped me to understand what does (function($) {})(jQuery); mean.

Consider this:

// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4

And now consider this:

  • jQuery is a variable holding jQuery object.
  • $ is a variable name like any other (a, $b, a$b etc.) and it doesn't have any special meaning like in PHP.

Knowing that we can take another look at our example:

var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4

// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4

Typescript: How to define type for a function callback (as any function type, not universal any) used in a method parameter

Following from Ryan's answer, I think that the interface you are looking for is defined as follows:

interface Param {
    title: string;
    callback: () => void;
}

How to call Base Class's __init__ method from the child class?

You can call the super class's constructor like this

class A(object):
    def __init__(self, number):
        print "parent", number

class B(A):
    def __init__(self):
        super(B, self).__init__(5)

b = B()

NOTE:

This will work only when the parent class inherits object

How can I wait for set of asynchronous callback functions?

You can use jQuery's Deferred object along with the when method.

deferredArray = [];
forloop {
    deferred = new $.Deferred();
    ajaxCall(function() {
      deferred.resolve();
    }
    deferredArray.push(deferred);
}

$.when(deferredArray, function() {
  //this code is called after all the ajax calls are done
});

Calculating Waiting Time and Turnaround Time in (non-preemptive) FCFS queue

wt = tt - cpu tm.
Tt = cpu tm + wt.

Where wt is a waiting time and tt is turnaround time. Cpu time is also called burst time.

Difference between 'cls' and 'self' in Python classes?

It's used in case of a class method. Check this reference for further details.

EDIT: As clarified by Adrien, it's a convention. You can actually use anything but cls and self are used (PEP8).

How to set entire application in portrait mode only?

Adding <preference name="orientation" value="portrait" /> under <widget> in my config.xml worked for me.

(The other solutions either didn't work on my device, were overwritten during building or gave deprecation errors during the build process.)

How to implement the factory method pattern in C++ correctly

I don't try to answer all of my questions, as I believe it is too broad. Just a couple of notes:

there are cases when object construction is a task complex enough to justify its extraction to another class.

That class is in fact a Builder, rather than a Factory.

In the general case, I don't want to force the users of the factory to be restrained to dynamic allocation.

Then you could have your factory encapsulate it in a smart pointer. I believe this way you can have your cake and eat it too.

This also eliminates the issues related to return-by-value.

Conclusion: Making a factory by returning an object is indeed a solution for some cases (such as the 2-D vector previously mentioned), but still not a general replacement for constructors.

Indeed. All design patterns have their (language specific) constraints and drawbacks. It is recommended to use them only when they help you solve your problem, not for their own sake.

If you are after the "perfect" factory implementation, well, good luck.

Padding is invalid and cannot be removed?

A serval times of fighting, I finally solved the problem.
(Note: I use standard AES as symmetric algorithm. This answer may not suitable for everyone.)

  1. Change the algorithm class. Replace the RijndaelManaged class to AESManaged one.
  2. Do not explicit set the KeySize of algorithm class, left them default.
    (This is the very important step. I think there is a bug in KeySize property.)

Here is a list you want to check which argument you might have missed:

  • Key
    (byte array, length must be exactly one of 16, 24, 32 byte for different key size.)
  • IV
    (byte array, 16 bytes)
  • CipherMode
    (One of CBC, CFB, CTS, ECB, OFB)
  • PaddingMode
    (One of ANSIX923, ISO10126, None, PKCS7, Zeros)

Radio/checkbox alignment in HTML/CSS

@sfjedi

I've created a class and assigned the css values to it.

.radioA{
   vertical-align: middle;
}

It is working and you can check it in the below link. http://jsfiddle.net/gNVsC/ Hope it was useful.