Programs & Examples On #Opencascade

Open CASCADE Technology is a software development platform. It includes C++ components for 3D surface and solid modeling, visualization, data exchange and rapid application development.

Default argument values in JavaScript functions

In javascript you can call a function (even if it has parameters) without parameters.

So you can add default values like this:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   //your code
}

and then you can call it like func(); to use default parameters.

Here's a test:

function func(a, b){
   if (typeof(a)==='undefined') a = 10;
   if (typeof(b)==='undefined') b = 20;

   alert("A: "+a+"\nB: "+b);
}
//testing
func();
func(80);
func(100,200);

"The semaphore timeout period has expired" error for USB connection

I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.

For me it was that wrong Bits per second value was set.

Cookies on localhost with explicit domain

Cookie needs to specify SameSite attribute, None value used to be the default, but recent browser versions made Lax the default value to have reasonably robust defense against some classes of cross-site request forgery (CSRF) attacks.

Along with SameSite=Lax you should also have Domain=localhost, so your cookie will be associated to localhost and kept. It should look something like this:

document.cookie = `${name}=${value}${expires}; Path=/; Domain=localhost; SameSite=Lax`;

https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie/SameSite

Moment.js transform to date object

To convert any date, for example utc:

moment( moment().utc().format( "YYYY-MM-DD HH:mm:ss" )).toDate()

MySQL: Insert datetime into other datetime field

Try

    UPDATE products SET former_date=20111218131717 WHERE id=1

Alternatively, you might want to look at using the STR_TO_DATE (see STR_TO_DATE(str,format)) function.

Convert hex string (char []) to int?

Assuming you mean it's a string, how about strtol?

MySQL Database won't start in XAMPP Manager-osx

Just Click on Managed Servers Tab in XAMPP MANAGER , Now select MySQL Database, Click on configure on right side.

Change port from 3306 to 3307 and it will work.

Turning multi-line string into single comma-separated

Another Perl solution, similar to Dan Fego's awk:

perl -ane 'print "$F[1],"' file.txt | sed 's/,$/\n/'

-a tells perl to split the input line into the @F array, which is indexed starting at 0.

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

The command build in pipeline is there to trigger other jobs in jenkins.

Example on github

The job must exist in Jenkins and can be parametrized. As for the branch, I guess you can read it from git

How does C#'s random number generator work?

You can use Random.Next(int maxValue):

Return: A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values ordinarily includes zero but not maxValue. However, if maxValue equals zero, maxValue is returned.

var r = new Random();
// print random integer >= 0 and  < 100
Console.WriteLine(r.Next(100));

For this case however you could use Random.Next(int minValue, int maxValue), like this:

// print random integer >= 1 and < 101
Console.WriteLine(r.Next(1, 101);)
// or perhaps (if you have this specific case)
Console.WriteLine(r.Next(100) + 1);

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

In my case it was because the file was minified with wrong scope. Use Array!

app.controller('StoreController', ['$http', function($http) {
    ...
}]);

Coffee syntax:

app.controller 'StoreController', Array '$http', ($http) ->
  ...

Android: how do I check if activity is running?

I think more clear like that:

  public boolean isRunning(Context ctx) {
        ActivityManager activityManager = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> tasks = activityManager.getRunningTasks(Integer.MAX_VALUE);

        for (RunningTaskInfo task : tasks) {
            if (ctx.getPackageName().equalsIgnoreCase(task.baseActivity.getPackageName())) 
                return true;                                  
        }

        return false;
    }

How to take screenshot of a div with JavaScript?

If you wish to have "Save as" dialog, just pass image into php script, which adds appropriate headers

Example "all-in-one" script script.php

<?php if(isset($_GET['image'])):
    $image = $_GET['image'];

    if(preg_match('#^data:image/(.*);base64,(.*)$#s', $image, $match)){
        $base64 = $match[2];
        $imageBody = base64_decode($base64);
        $imageFormat = $match[1];

        header('Content-type: application/octet-stream');
        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: private", false); // required for certain browsers
        header("Content-Disposition: attachment; filename=\"file.".$imageFormat."\";" ); //png is default for toDataURL
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".strlen($imageBody));
        echo $imageBody;
    }
    exit();
endif;?>

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js?ver=1.7.2'></script>
<canvas id="canvas" width="300" height="150"></canvas>
<button id="btn">Save</button>
<script>
    $(document).ready(function(){
        var canvas = document.getElementById('canvas');
        var oCtx = canvas.getContext("2d");
        oCtx.beginPath();
        oCtx.moveTo(0,0);
        oCtx.lineTo(300,150);
        oCtx.stroke();

        $('#btn').on('click', function(){
            // opens dialog but location doesnt change due to SaveAs Dialog
            document.location.href = '/script.php?image=' + canvas.toDataURL();
        });
    });
</script>

How do I create a Bash alias?

For macOS Catalina Users:

Step 1: create or update .zshrc file

vi ~/.zshrc

Step 2: Add your alias line

alias blah="/usr/bin/blah"

Step 3: Source .zshrc

source ~/.zshrc 

Step 4: Check you're alias, by typing alias on the command prompt

alias

Integer.valueOf() vs. Integer.parseInt()

First Question: Difference between parseInt and valueOf in java?

Second Question:

NumberFormat format = NumberFormat.getInstance(Locale.FRANCE);
Number number = format.parse("1,234");
double d = number.doubleValue();

Third Question:

DecimalFormat df = new DecimalFormat();
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setDecimalSeparator('.');
symbols.setGroupingSeparator(',');
df.setDecimalFormatSymbols(symbols);
df.parse(p);

SQL query for finding records where count > 1

I wouldn't recommend the HAVING keyword for newbies, it is essentially for legacy purposes.

I am not clear on what is the key for this table (is it fully normalized, I wonder?), consequently I find it difficult to follow your specification:

I would like to find all records for all users that have more than one payment per day with the same account number... Additionally, there should be a filter than only counts the records whose ZIP code is different.

So I've taken a literal interpretation.

The following is more verbose but could be easier to understand and therefore maintain (I've used a CTE for the table PAYMENT_TALLIES but it could be a VIEW:

WITH PAYMENT_TALLIES (user_id, zip, tally)
     AS
     (
      SELECT user_id, zip, COUNT(*) AS tally
        FROM PAYMENT
       GROUP 
          BY user_id, zip
     )
SELECT DISTINCT *
  FROM PAYMENT AS P
 WHERE EXISTS (
               SELECT * 
                 FROM PAYMENT_TALLIES AS PT
                WHERE P.user_id = PT.user_id
                      AND PT.tally > 1
              );

JavaScript for handling Tab Key press

Only one suggestion instead of 9 you can use KeyCodes.TAB.

Difference between float and decimal data type

MySQL recently changed they way they store the DECIMAL type. In the past they stored the characters (or nybbles) for each digit comprising an ASCII (or nybble) representation of a number - vs - a two's complement integer, or some derivative thereof.

The current storage format for DECIMAL is a series of 1,2,3,or 4-byte integers whose bits are concatenated to create a two's complement number with an implied decimal point, defined by you, and stored in the DB schema when you declare the column and specify it's DECIMAL size and decimal point position.

By way of example, if you take a 32-bit int you can store any number from 0 - 4,294,967,295. That will only reliably cover 999,999,999, so if you threw out 2 bits and used (1<<30 -1) you'd give up nothing. Covering all 9-digit numbers with only 4 bytes is more efficient than covering 4 digits in 32 bits using 4 ASCII characters, or 8 nybble digits. (a nybble is 4-bits, allowing values 0-15, more than is needed for 0-9, but you can't eliminate that waste by going to 3 bits, because that only covers values 0-7)

The example used on the MySQL online docs uses DECIMAL(18,9) as an example. This is 9 digits ahead of and 9 digits behind the implied decimal point, which as explained above requires the following storage.

As 18 8-bit chars: 144 bits

As 18 4-bit nybbles: 72 bits

As 2 32-bit integers: 64 bits

Currently DECIMAL supports a max of 65 digits, as DECIMAL(M,D) where the largest value for M allowed is 65, and the largest value of D allowed is 30.

So as not to require chunks of 9 digits at a time, integers smaller than 32-bits are used to add digits using 1,2 and 3 byte integers. For some reason that defies logic, signed, instead of unsigned ints were used, and in so doing, 1 bit gets thrown out, resulting in the following storage capabilities. For 1,2 and 4 byte ints the lost bit doesn't matter, but for the 3-byte int it's a disaster because an entire digit is lost due to the loss of that single bit.

With an 7-bit int: 0 - 99

With a 15-bit int: 0 - 9,999

With a 23-bit int: 0 - 999,999 (0 - 9,999,999 with a 24-bit int)

1,2,3 and 4-byte integers are concatenated together to form a "bit pool" DECIMAL uses to represent the number precisely as a two's complement integer. The decimal point is NOT stored, it is implied.

This means that no ASCII to int conversions are required of the DB engine to convert the "number" into something the CPU recognizes as a number. No rounding, no conversion errors, it's a real number the CPU can manipulate.

Calculations on this arbitrarily large integer must be done in software, as there is no hardware support for this kind of number, but these libraries are very old and highly optimized, having been written 50 years ago to support IBM 370 Fortran arbitrary precision floating point data. They're still a lot slower than fixed-sized integer algebra done with CPU integer hardware, or floating point calculations done on the FPU.

In terms of storage efficiency, because the exponent of a float is attached to each and every float, specifying implicitly where the decimal point is, it is massively redundant, and therefore inefficient for DB work. In a DB you already know where the decimal point is to go up front, and every row in the table that has a value for a DECIMAL column need only look at the 1 & only specification of where that decimal point is to be placed, stored in the schema as the arguments to a DECIMAL(M,D) as the implication of the M and the D values.

The many remarks found here about which format is to be used for various kinds of applications are correct, so I won't belabor the point. I took the time to write this here because whoever is maintaining the linked MySQL online documentation doesn't understand any of the above and after rounds of increasingly frustrating attempts to explain it to them I gave up. A good indication of how poorly they understood what they were writing is the very muddled and almost indecipherable presentation of the subject matter.

As a final thought, if you have need of high-precision floating point computation, there've been tremendous advances in floating point code in the last 20 years, and hardware support for 96-bit and Quadruple Precision float are right around the corner, but there are good arbitrary precision libraries out there if manipulation of the stored value is important.

combining two data frames of different lengths

Hope this will work for you!

You can use library(qpcR) for combining two matrix with unequal size.

resultant_matrix <- qpcR:::cbind.na(matrix1, matrix2)

NOTE:- The resultant matrix will be of size of matrix2.

cmake and libpthread

Here is the right anwser:

ADD_EXECUTABLE(your_executable ${source_files})

TARGET_LINK_LIBRARIES( your_executable
pthread
)

equivalent to

-lpthread

Invoke-WebRequest, POST with parameters

Put your parameters in a hash table and pass them like this:

$postParams = @{username='me';moredata='qwerty'}
Invoke-WebRequest -Uri http://example.com/foobar -Method POST -Body $postParams

How to enable Auto Logon User Authentication for Google Chrome

If you add your site to "Local Intranet" in

Chrome > Options > Under the Hood > Change Proxy Settings > Security (tab) > Local Intranet/Sites > Advanced.

Add you site URL here and it will work.

Update for New Version of Chrome

Chrome > Settings > Advanced > System > Open Proxy Settings > Security (tab) > Local Intranet > Sites (button) > Advanced.

Query to search all packages for table and/or column

By the way, if you need to add other characters such as "(" or ")" because the column may be used as "UPPER(bqr)", then those options can be added to the lists of before and after characters.

(\s|\(|\.|,|^)bqr(\s|,|\)|$)

How to set standard encoding in Visual Studio

What

It is possible with EditorConfig.

EditorConfig helps developers define and maintain consistent coding styles between different editors and IDEs.

This also includes file encoding.

EditorConfig is built-in Visual Studio 2017 by default, and I there were plugins available for versions as old as VS2012. Read more from EditorConfig Visual Studio Plugin page.

How

You can set up a EditorConfig configuration file high enough in your folder structure to span all your intended repos (up to your drive root should your files be really scattered everywhere) and configure the setting charset:

charset: set to latin1, utf-8, utf-8-bom, utf-16be or utf-16le to control the character set.

You can add filters and exceptions etc on every folder level or by file name/type should you wish for finer control.

Once configured then compatible IDEs should automatically do it's thing to make matching files comform to set rules. Note that Visual Studio does not automatically convert all your files but do its bit when you work with files in IDE (open and save).

What next

While you could have a Visual-studio-wide setup, I strongly suggest to still include an EditorConfig root to your solution version control, so that explicit settings are automatically synced to all team members as well. Your drive root editorconfig file can be the fallback should some project not have their own editorconfig files set up yet.

.htaccess, order allow, deny, deny from all: confused?

This is a quite confusing way of using Apache configuration directives.

Technically, the first bit is equivalent to

Allow From All

This is because Order Deny,Allow makes the Deny directive evaluated before the Allow Directives. In this case, Deny and Allow conflict with each other, but Allow, being the last evaluated will match any user, and access will be granted.

Now, just to make things clear, this kind of configuration is BAD and should be avoided at all cost, because it borders undefined behaviour.

The Limit sections define which HTTP methods have access to the directory containing the .htaccess file.

Here, GET and POST methods are allowed access, and PUT and DELETE methods are denied access. Here's a link explaining what the various HTTP methods are: http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html

However, it's more than often useless to use these limitations as long as you don't have custom CGI scripts or Apache modules that directly handle the non-standard methods (PUT and DELETE), since by default, Apache does not handle them at all.

It must also be noted that a few other methods exist that can also be handled by Limit, namely CONNECT, OPTIONS, PATCH, PROPFIND, PROPPATCH, MKCOL, COPY, MOVE, LOCK, and UNLOCK.

The last bit is also most certainly useless, since any correctly configured Apache installation contains the following piece of configuration (for Apache 2.2 and earlier):

#
# The following lines prevent .htaccess and .htpasswd files from being 
# viewed by Web clients. 
#
<Files ~ "^\.ht">
    Order allow,deny
    Deny from all
    Satisfy all
</Files>

which forbids access to any file beginning by ".ht".

The equivalent Apache 2.4 configuration should look like:

<Files ~ "^\.ht">
    Require all denied
</Files>

How can I run a php without a web server?

For windows system you should be able to run php by following below steps:

  1. Download php version you want to use and put it in c:\php.
  2. append ;c:\php to your system path using cmd or gui.
  3. call $ php -S localhost:8000 command in a folder which you want to serve the pages from.

C - gettimeofday for computing time?

To subtract timevals:

gettimeofday(&t0, 0);
/* ... */
gettimeofday(&t1, 0);
long elapsed = (t1.tv_sec-t0.tv_sec)*1000000 + t1.tv_usec-t0.tv_usec;

This is assuming you'll be working with intervals shorter than ~2000 seconds, at which point the arithmetic may overflow depending on the types used. If you need to work with longer intervals just change the last line to:

long long elapsed = (t1.tv_sec-t0.tv_sec)*1000000LL + t1.tv_usec-t0.tv_usec;

one line if statement in php

Something like this?

($var > 2 ? echo "greater" : echo "smaller")

How to enter a formula into a cell using VBA?

You aren't building your formula right.

Worksheets("EmployeeCosts").Range("B" & var1a).Formula =  "=SUM(H5:H" & var1a & ")"

This does the same as the following lines do:

Dim myFormula As String
myFormula = "=SUM(H5:H"
myFormula = myFormula & var1a
myformula = myformula & ")"

which is what you are trying to do.

Also, you want to have the = at the beginning of the formala.

How to convert BigDecimal to Double in Java?

Use doubleValue method present in BigDecimal class :

double doubleValue()

Converts this BigDecimal to a double.

missing FROM-clause entry for table

Because that gtab82 table isn't in your FROM or JOIN clause. You refer gtab82 table in these cases: gtab82.memno and gtab82.memacid

Timeout a command in bash without unnecessary delay

#! /bin/bash
timeout=10
interval=1
delay=3
(
    ((t = timeout)) || :

    while ((t > 0)); do
        echo "$t"
        sleep $interval
        # Check if the process still exists.
        kill -0 $$ 2> /dev/null || exit 0
        ((t -= interval)) || :
    done

    # Be nice, post SIGTERM first.
    { echo SIGTERM to $$ ; kill -s TERM $$ ; sleep $delay ; kill -0 $$ 2> /dev/null && { echo SIGKILL to $$ ; kill -s KILL $$ ; } ; }
) &

exec "$@"

JQuery addclass to selected div, remove class if another div is selected

It's all about the selector. You can change your code to be something like this:

<div class="formbuilder">
    <div class="active">Heading</div>
    <div>1</div>
    <div>2</div>
    <div>3</div>
    <div>4</div>
</div>

Then use this javascript:

$(document).ready(function () {
    $('.formbuilder div').on('click', function () {
        $('.formbuilder div').removeClass('active');
        $(this).addClass('active');
    });
});

The example in a working jsfiddle

See this api about the selector I used: http://api.jquery.com/descendant-selector/

How do I disable the security certificate check in Python requests

Use requests.packages.urllib3.disable_warnings() and verify=False on requests methods.

import requests
from urllib3.exceptions import InsecureRequestWarning

# Suppress only the single warning from urllib3 needed.
requests.packages.urllib3.disable_warnings(category=InsecureRequestWarning)

# Set `verify=False` on `requests.post`.
requests.post(url='https://example.com', data={'bar':'baz'}, verify=False)

CSS values using HTML5 data attribute

You can create with javascript some css-rules, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/

var addRule = (function (sheet) {
    if(!sheet) return;
    return function (selector, styles) {
        if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
        if (sheet.addRule) return sheet.addRule(selector, styles);
    }
}(document.styleSheets[document.styleSheets.length - 1]));

var i = 101;
while (i--) {
    addRule("[data-width='" + i + "%']", "width:" + i + "%");
}

This creates 100 pseudo-selectors like this:

[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }

Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.

Getting Google+ profile picture url with user_id

2020 Solution Please comment if no longer available.

In order to get profile URL from authenticated user.

GET https://people.googleapis.com/v1/people/[THE_USER_ID_OF_THE_AUTHENTICATED_USER]?personFields=photos&key=[YOUR_API_KEY] HTTP/1.1

Authorization: Bearer [YOUR_ACCESS_TOKEN]
Accept: application/json

Response:

{
  "resourceName": "people/[THE_USER_ID_OF_THE_AUTHENTICATED_USER]",
  "etag": "12345",
  "photos": [
    {
      "metadata": {
        "primary": true,
        "source": {
          "type": "PROFILE",
          "id": "[THE_USER_ID_OF_THE_AUTHENTICATED_USER]"
        }
      },
      "url": "https://lh3.googleusercontent.com/a-/blablabla=s100"
    }
  ]
}

and the link can be used as:

<img src="https://lh3.googleusercontent.com/a-/blablabla=s100">

CSS: how to get scrollbars for div inside container of fixed height

setting the overflow should take care of it, but you need to set the height of Content also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.

See Example: http://jsfiddle.net/ftkbL/1/

Stop all active ajax requests in jQuery

Using ajaxSetup is not correct, as is noted on its doc page. It only sets up defaults, and if some requests override them there will be a mess.

I am way late to the party, but just for future reference if someone is looking for a solution to the same problem, here is my go at it, inspired by and largely identical to the previous answers, but more complete

// Automatically cancel unfinished ajax requests 
// when the user navigates elsewhere.
(function($) {
  var xhrPool = [];
  $(document).ajaxSend(function(e, jqXHR, options){
    xhrPool.push(jqXHR);
  });
  $(document).ajaxComplete(function(e, jqXHR, options) {
    xhrPool = $.grep(xhrPool, function(x){return x!=jqXHR});
  });
  var abort = function() {
    $.each(xhrPool, function(idx, jqXHR) {
      jqXHR.abort();
    });
  };

  var oldbeforeunload = window.onbeforeunload;
  window.onbeforeunload = function() {
    var r = oldbeforeunload ? oldbeforeunload() : undefined;
    if (r == undefined) {
      // only cancel requests if there is no prompt to stay on the page
      // if there is a prompt, it will likely give the requests enough time to finish
      abort();
    }
    return r;
  }
})(jQuery);

"Cannot create an instance of OLE DB provider" error as Windows Authentication user

For error 7302 in particular, I discovered, in my registry, when looking for OraOLEDB.Oracle that the InprocServer32 location was wrong.

If that's the case, or you can't find that string in the registry, then you'll have to install or re-register the component.

I had to delete the key from the GUID level, and then find the ProgID (OraOLEDB.Oracle) key, and delete that too. (The ProgID links to the CLSID as a pair).

Then I re-registered OraOLEDB.Oracle by calling regsvr32.exe on ORAOLEDB*.dll.

Just re-registering alone didn't solve the problem, I had to delete the registry keys to make it point to the correct location. Alternatively, hack the InprocServer32 location.

Now I have error 7308, about single threaded apartments; rolling on!

Make a phone call programmatically

The Java RoboVM equivalent:

public void dial(String number)
{
  NSURL url = new NSURL("tel://" + number);
  UIApplication.getSharedApplication().openURL(url);
}

What is the best way to call a script from another script?

If you want test1.py to remain executable with the same functionality as when it's called inside service.py, then do something like:

test1.py

def main():
    print "I am a test"
    print "see! I do nothing productive."

if __name__ == "__main__":
    main()

service.py

import test1
# lots of stuff here
test1.main() # do whatever is in test1.py

Setting the default page for ASP.NET (Visual Studio) server configuration

Right click on the web page you want to use as the default page and choose "Set as Start Page" whenever you run the web application from Visual Studio, it will open the selected page.

Printing integer variable and string on same line in SQL

Double check if you have set and initial value for int and decimal values to be printed.

This sample is printing an empty line

declare @Number INT
print 'The number is : ' + CONVERT(VARCHAR, @Number)

And this sample is printing -> The number is : 1

declare @Number INT = 1
print 'The number is : ' + CONVERT(VARCHAR, @Number)

How to append data to a json file?

Using a instead of w should let you update the file instead of creating a new one/overwriting everything in the existing file.

See this answer for a difference in the modes.

Select first occurring element after another element

Just hit on this when trying to solve this type of thing my self.

I did a selector that deals with the element after being something other than a p.

.here .is.the #selector h4 + * {...}

Hope this helps anyone who finds it :)

python save image from url

import random
import urllib.request

def download_image(url):
    name = random.randrange(1,100)
    fullname = str(name)+".jpg"
    urllib.request.urlretrieve(url,fullname)     
download_image("http://site.meishij.net/r/58/25/3568808/a3568808_142682562777944.jpg")

How to insert values in table with foreign key using MySQL?

http://dev.mysql.com/doc/refman/5.0/en/insert-select.html

For case1:

INSERT INTO TAB_STUDENT(name_student, id_teacher_fk)
SELECT 'Joe The Student', id_teacher
  FROM TAB_TEACHER
 WHERE name_teacher = 'Professor Jack'
 LIMIT 1

For case2 you just have to do 2 separate insert statements

Vue equivalent of setTimeout?

vuejs 2

first add this to methods

methods:{
    sayHi: function () {
      var v = this;
      setTimeout(function () {
        v.message = "Hi Vue!";
    }, 3000);
   }

after that call this method on mounted

mounted () {
  this.sayHi()
}

Remove part of string in Java

originalString.replaceFirst("[(].*?[)]", "");

https://ideone.com/jsZhSC
replaceFirst() can be replaced by replaceAll()

Resize command prompt through commands

Although the answers given here can be used to temporarily change window size, they don't seem to affect font size (at least not on my PC). I have an alternative way. I don't know if this what you're looking for but if you want to make changes automatically/permanently to Console font/window size, you can always do a script that edits the registry:

HKEY_CURRENT_USER\Console
HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe
HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_WindowsPowerShell_v1.0_powershell.exe

Those keys deal with the consoles that come up when your run a script or press shift and select "open command prompt here". The Command Prompt entry in your start menu does not use the registry to store it's preferences but stores the prefs in the shortcut itself.

I have a monitor that I can run in 720p native or 1440p supersampling. I needed a quick way to change my console's font/window size, so I made these scripts. These scripts do two things: (1) change the font/window sizes in the registry and (2) swap out the shortcuts in the Start menu with ones that have a different window and font size. I basically made two sets of copies of the Command Prompt and Power Shell shortcuts and stored them in Documents. One set of shortcuts was configured with Consolas font size at 16 for my monitor is in 720p (called it "Command Prompt.720pRes.lnk") and another version of the same shortcut was configure with font size at 36 (called it "Command Prompt.HighRes.lnk"). The script will copy from the set I want to use to overwrite the Start menu one.

console-1440p.cmd:

::Assign New Window and Font Size for Windows Command Prompt
set CMDpNewFont=00240000
set CMDpNewWindowSize=000f0078
set commandPromptLinkFlag=highRes



 ::Make temporary .reg file to resize command console

>%temp%\consoleSIZEchanger.reg ECHO Windows Registry Editor Version 5.00
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_WindowsPowerShell_v1.0_powershell.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%


::Merge and delete consoleSIZEchanger.reg
REGEDIT /S %temp%\consoleSIZEchanger.reg 
del %temp%\consoleSIZEchanger.reg 

::Copy Preconfigured Command Prompt/PowerShell shortcuts to Pinned Start Menu, Accessories and any other Custom Location you would define
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell.lnk"                 
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell (x86).lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell (x86).lnk"

console-720p.cmd:

::Assign New Window and Font Size for Windows Command Prompt
set CMDpNewFont=00100000
set CMDpNewWindowSize=0014007d
set commandPromptLinkFlag=720Res



 ::Make temporary .reg file to resize command console
>%temp%\consoleSIZEchanger.reg ECHO Windows Registry Editor Version 5.00
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_cmd.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%
>>%temp%\consoleSIZEchanger.reg ECHO.
>>%temp%\consoleSIZEchanger.reg ECHO [HKEY_CURRENT_USER\Console\%%SystemRoot%%_system32_WindowsPowerShell_v1.0_powershell.exe]
>>%temp%\consoleSIZEchanger.reg ECHO "WindowSize"=dword:%CMDpNewWindowSize%
>>%temp%\consoleSIZEchanger.reg ECHO "FontSize"=dword:%CMDpNewFont%


::Merge and delete consoleSIZEchanger.reg
REGEDIT /S %temp%\consoleSIZEchanger.reg 
del %temp%\consoleSIZEchanger.reg 

::Copy Preconfigured Command Prompt/PowerShell shortcuts to Pinned Start Menu, Accessories and any other Custom Location you would define
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Command Prompt.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Accessories\Command Prompt.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell.lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell.%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell.lnk"                 
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell\Windows PowerShell (x86).lnk"
copy "%homedrive%%homepath%\Documents\Windows PowerShell (x86).%commandPromptLinkFlag%.lnk" "%homedrive%%homepath%\AppData\Roaming\Microsoft\Internet Explorer\Quick Launch\User Pinned\StartMenu\Windows PowerShell (x86).lnk"

Adding a column to a dataframe in R

That is a pretty standard use case for apply():

R> vec <- 1:10
R> DF <- data.frame(start=c(1,3,5,7), end=c(2,6,7,9))
R> DF$newcol <- apply(DF,1,function(row) mean(vec[ row[1] : row[2] ] ))
R> DF
  start end newcol
1     1   2    1.5
2     3   6    4.5
3     5   7    6.0
4     7   9    8.0
R> 

You can also use plyr if you prefer but here is no real need to go beyond functions from base R.

How to upload files on server folder using jsp

You cannot upload like this.

http://grand-shopping.com/<"some folder">

You need a physical path exactly like in your local

C:/Users/puneet verma/Downloads/

What you can do is create some local path where your server is working. Hence you can store and retrieve the file. If you bought some domain from any websites there will be path to upload the files. You create these variable as static constant and use it based on the server you are working (Local/Website).

Resolve build errors due to circular dependency amongst classes

Here is the solution for templates: How to handle circular dependencies with templates

The clue to solving this problem is to declare both classes before providing the definitions (implementations). It’s not possible to split the declaration and definition into separate files, but you can structure them as if they were in separate files.

Generate a dummy-variable

The simplest way to produce these dummy variables is something like the following:

> print(year)
[1] 1956 1957 1957 1958 1958 1959
> dummy <- as.numeric(year == 1957)
> print(dummy)
[1] 0 1 1 0 0 0
> dummy2 <- as.numeric(year >= 1957)
> print(dummy2)
[1] 0 1 1 1 1 1

More generally, you can use ifelse to choose between two values depending on a condition. So if instead of a 0-1 dummy variable, for some reason you wanted to use, say, 4 and 7, you could use ifelse(year == 1957, 4, 7).

.append(), prepend(), .after() and .before()

This image displayed below gives a clear understanding and shows the exact difference between .append(), .prepend(), .after() and .before()

jQuery infographic

You can see from the image that .append() and .prepend() adds the new elements as child elements (brown colored) to the target.

And .after() and .before() adds the new elements as sibling elements (black colored) to the target.

Here is a DEMO for better understanding.


EDIT: the flipped versions of those functions:

jQuery insertion infographic, plus flipped versions of the functions

Using this code:

var $target = $('.target');

$target.append('<div class="child">1. append</div>');
$target.prepend('<div class="child">2. prepend</div>');
$target.before('<div class="sibling">3. before</div>');
$target.after('<div class="sibling">4. after</div>');

$('<div class="child flipped">or appendTo</div>').appendTo($target);
$('<div class="child flipped">or prependTo</div>').prependTo($target);
$('<div class="sibling flipped">or insertBefore</div>').insertBefore($target);
$('<div class="sibling flipped">or insertAfter</div>').insertAfter($target);

on this target:

<div class="target">
    This is the target div to which new elements are associated using jQuery
</div>

So although these functions flip the parameter order, each creates the same element nesting:

var $div = $('<div>').append($('<img>'));
var $img = $('<img>').appendTo($('<div>'))

...but they return a different element. This matters for method chaining.

basic authorization command for curl

Use the -H header again before the Authorization:Basic things. So it will be

curl -i \
    -H 'Accept:application/json' \
    -H 'Authorization:Basic BASE64_string' \
    http://example.com

Here, BASE64_string = Base64 of username:password

Experimental decorators warning in TypeScript compilation

I faced the same issue while creating an Injectable Services in Angular 2. I have all the things at place in tsconfig.json .Still I was getting this error at ColorsImmutable line.

@Injectable()
export class ColorsImmutable {

And fix was to register the Service at module Level or Component Level using the providers array.

providers:[ColorsImmutable ],

What Are The Best Width Ranges for Media Queries

You can take a look here for a longer list of screen sizes and respective media queries.

Or go for Bootstrap media queries:

/* Large desktop */
@media (min-width: 1200px) { ... }

/* Portrait tablet to landscape and desktop */
@media (min-width: 768px) and (max-width: 979px) { ... }

/* Landscape phone to portrait tablet */
@media (max-width: 767px) { ... }

/* Landscape phones and down */
@media (max-width: 480px) { ... }

Additionally you might wanty to take a look at Foundation's media queries with the following default settings:

// Media Queries

$screenSmall: 768px !default;
$screenMedium: 1279px !default;
$screenXlarge: 1441px !default;

How to update array value javascript?

How about;

function keyValue(key, value){
    this.Key = key;
    this.Value = value;
};
keyValue.prototype.updateTo = function(newKey, newValue) {
    this.Key = newKey;
    this.Value = newValue;  
};

array[1].updateTo("xxx", "999");   

Saving and Reading Bitmaps/Images from Internal memory in Android

// mutiple image retrieve

 File folPath = new File(getIntent().getStringExtra("folder_path"));
 File[] imagep = folPath.listFiles();

 for (int i = 0; i < imagep.length ; i++) {
     imageModelList.add(new ImageModel(imagep[i].getAbsolutePath(), Uri.parse(imagep[i].getAbsolutePath())));
 }
 imagesAdapter.notifyDataSetChanged();

Pip install - Python 2.7 - Windows 7

pip is installed by default when we install Python in windows. After setting up the environment variables path for python executables, we can run python interpreter from the command line on windows CMD After that, we can directly use the python command with pip option to install further packages as following:-

C:\ python -m pip install python_module_name

This will install the module using pip.

Mac zip compress without __MACOSX folder?

You can't.

But what you can do is delete those unwanted folders after zipping. Command line zip takes different arguments where one, the -d, is for deleting contents based on a regex. So you can use it like this:

zip -d filename.zip __MACOSX/\*

Are the decimal places in a CSS width respected?

The width will be rounded to an integer number of pixels.

I don't know if every browser will round it the same way though. They all seem to have a different strategy when rounding sub-pixel percentages. If you're interested in the details of sub-pixel rounding in different browsers, there's an excellent article on ElastiCSS.

edit: I tested @Skilldrick's demo in some browsers for the sake of curiosity. When using fractional pixel values (not percentages, they work as suggested in the article I linked) IE9p7 and FF4b7 seem to round to the nearest pixel, while Opera 11b, Chrome 9.0.587.0 and Safari 5.0.3 truncate the decimal places. Not that I hoped that they had something in common after all...

New lines inside paragraph in README.md

According to Github API two empty lines are a new paragraph (same as here in stackoverflow)

You can test it with http://prose.io

What command means "do nothing" in a conditional in Bash?

The no-op command in shell is : (colon).

if [ "$a" -ge 10 ]
then
    :
elif [ "$a" -le 5 ]
then
    echo "1"
else
    echo "2"
fi

From the bash manual:

: (a colon)
Do nothing beyond expanding arguments and performing redirections. The return status is zero.

Add to integers in a list

You can append to the end of a list:

foo = [1, 2, 3, 4, 5]
foo.append(4)
foo.append([8,7])    
print(foo)            # [1, 2, 3, 4, 5, 4, [8, 7]]

You can edit items in the list like this:

foo = [1, 2, 3, 4, 5]
foo[3] = foo[3] + 4     
print(foo)            # [1, 2, 3, 8, 5]

Insert integers into the middle of a list:

x = [2, 5, 10]
x.insert(2, 77)
print(x)              # [2, 5, 77, 10]

Why is AJAX returning HTTP status code 0?

It is important to note, that ajax calls can fail even within a session which is defined by a cookie with a certain domain prefixed with www. When you then call your php script e.g. without the www. prefix in the url, the call will fail and viceversa, too.

Is there a good Valgrind substitute for Windows?

I've been loving Memory Validator, from a company called Software Verification.

Entry point for Java applications: main(), init(), or run()?

Java has a special static method:

public static void main(String[] args) { ... }

which is executed in a class when the class is started with a java command line:

$ java Class

would execute said method in the class "Class" if it existed.

public void run() { ... }

is required by the Runnable interface, or inherited from the Thread class when creating new threads.

SQL Server Output Clause into a scalar variable

Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;

DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2

In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.

One place this is very helpful is if you want to turn a column into a comma-separated list;

DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list

How to revert to origin's master branch's version of file

Assuming you did not commit the file, or add it to the index, then:

git checkout -- filename

Assuming you added it to the index, but did not commit it, then:

git reset HEAD filename
git checkout -- filename

Assuming you did commit it, then:

git checkout origin/master filename

Assuming you want to blow away all commits from your branch (VERY DESTRUCTIVE):

git reset --hard origin/master

How do I run a Java program from the command line on Windows?

Now (with JDK 9 onwards), you can just use java to get that executed. In order to execute "Hello.java" containing the main, one can use: java Hello.java

You do not need to compile using separately using javac anymore.

How to process images of a video, frame by frame, in video streaming using OpenCV and Python

In openCV's documentation there is an example for getting video frame by frame. It is written in c++ but it is very easy to port the example to python - you can search for each fumction documentation to see how to call them in python.

#include "opencv2/opencv.hpp"

using namespace cv;

int main(int, char**)
{
    VideoCapture cap(0); // open the default camera
    if(!cap.isOpened())  // check if we succeeded
        return -1;

    Mat edges;
    namedWindow("edges",1);
    for(;;)
    {
        Mat frame;
        cap >> frame; // get a new frame from camera
        cvtColor(frame, edges, CV_BGR2GRAY);
        GaussianBlur(edges, edges, Size(7,7), 1.5, 1.5);
        Canny(edges, edges, 0, 30, 3);
        imshow("edges", edges);
        if(waitKey(30) >= 0) break;
    }
    // the camera will be deinitialized automatically in VideoCapture destructor
    return 0;
}

How to check for a valid Base64 encoded string

I would suggest creating a regex to do the job. You'll have to check for something like this: [a-zA-Z0-9+/=] You'll also have to check the length of the string. I'm not sure on this one, but i'm pretty sure if something gets trimmed (other than the padding "=") it would blow up.

Or better yet check out this stackoverflow question

How to get PID of process I've just started within java program?

For GNU/Linux & MacOS (or generally UNIX like) systems, I've used below method which works fine:

private int tryGetPid(Process process)
{
    if (process.getClass().getName().equals("java.lang.UNIXProcess"))
    {
        try
        {
            Field f = process.getClass().getDeclaredField("pid");
            f.setAccessible(true);
            return f.getInt(process);
        }
        catch (IllegalAccessException | IllegalArgumentException | NoSuchFieldException | SecurityException e)
        {
        }
    }

    return 0;
}

remove objects from array by object property

With lodash/underscore:

If you want to modify the existing array itself, then we have to use splice. Here is the little better/readable way using findWhere of underscore/lodash:

var items= [{id:'abc',name:'oh'}, // delete me
                  {id:'efg',name:'em'},
                  {id:'hij',name:'ge'}];

items.splice(_.indexOf(items, _.findWhere(items, { id : "abc"})), 1);

With ES5 or higher

(without lodash/underscore)

With ES5 onwards we have findIndex method on array, so its easier without lodash/underscore

items.splice(items.findIndex(function(i){
    return i.id === "abc";
}), 1);

(ES5 is supported in almost all morden browsers)

About findIndex, and its Browser compatibility

VBA - Range.Row.Count

k = sh.Range("A2", sh.Range("A1").End(xlDown)).Rows.Count

or

k = sh.Range("A2", sh.Range("A1").End(xlDown)).Cells.Count

or

k = sh.Range("A2", sh.Range("A1").End(xlDown)).Count

Multiple line code example in Javadoc comment

Enclose your multiline code with <pre></pre> tags.

How to secure MongoDB with username and password

This is what i did for ubuntu 20.04 and mongodb enterprise 4.4.2:

  1. start mongo shell by typing mongo in terminal.

  2. use admin database:

use admin
  1. create a new user and assign your intended role:
use admin
db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)
  1. exit mongo and add the following line to etc/mongod.conf:
security:
    authorization: enabled
  1. restart mongodb server

(optional) 6.If you want your user to have root access you can either specify it when creating your user like:

db.createUser(
  {
    user: "myUserAdmin",
    pwd: passwordPrompt(), // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)

or you can change user role using:

db.grantRolesToUser('admin', [{ role: 'root', db: 'admin' }])

How to test that a registered variable is not empty?

- name: set pkg copy dir name
  set_fact:
    PKG_DIR: >-
      {% if ansible_os_family == "RedHat" %}centos/*.rpm
      {%- elif ansible_distribution == "Ubuntu" %}ubuntu/*.deb
      {%- elif ansible_distribution == "Kylin Linux Advanced Server" %}kylin/*.deb
      {%- else %}{%- endif %}

How to convert column with dtype as object to string in Pandas Dataframe

since strings data types have variable length, it is by default stored as object dtype. If you want to store them as string type, you can do something like this.

df['column'] = df['column'].astype('|S80') #where the max length is set at 80 bytes,

or alternatively

df['column'] = df['column'].astype('|S') # which will by default set the length to the max len it encounters

How to print number with commas as thousands separators?

Here is another variant using a generator function that works for integers:

def ncomma(num):
    def _helper(num):
        # assert isinstance(numstr, basestring)
        numstr = '%d' % num
        for ii, digit in enumerate(reversed(numstr)):
            if ii and ii % 3 == 0 and digit.isdigit():
                yield ','
            yield digit

    return ''.join(reversed([n for n in _helper(num)]))

And here's a test:

>>> for i in (0, 99, 999, 9999, 999999, 1000000, -1, -111, -1111, -111111, -1000000):
...     print i, ncomma(i)
... 
0 0
99 99
999 999
9999 9,999
999999 999,999
1000000 1,000,000
-1 -1
-111 -111
-1111 -1,111
-111111 -111,111
-1000000 -1,000,000

How can I create a UIColor from a hex string?

Swift 2.0:

Add this method to VC or to Extension of UIColor.

func colorWithHexString (hex:String) -> UIColor {
        var cString:String = hex.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()).uppercaseString

        if (cString.hasPrefix("#")) {
            cString = (cString as NSString).substringFromIndex(1)
        }

        if (cString.characters.count != 6) {
            return UIColor.grayColor()
        }

        let rString = (cString as NSString).substringToIndex(2)
        let gString = ((cString as NSString).substringFromIndex(2) as NSString).substringToIndex(2)
        let bString = ((cString as NSString).substringFromIndex(4) as NSString).substringToIndex(2)

        var r:CUnsignedInt = 0, g:CUnsignedInt = 0, b:CUnsignedInt = 0;
        NSScanner(string: rString).scanHexInt(&r)
        NSScanner(string: gString).scanHexInt(&g)
        NSScanner(string: bString).scanHexInt(&b)


        return UIColor(red: CGFloat(r) / 255.0, green: CGFloat(g) / 255.0, blue: CGFloat(b) / 255.0, alpha: CGFloat(1))
    }

Usage :

    loginButton.tintColor = self.colorWithHexString("#be1337")

     OR

    let hexColor = self.colorWithHexString("#be1337")

Responsive background image in div full width

Here is one way of getting the design that you want.

Start with the following HTML:

<div class="container">
    <div class="row-fluid">
        <div class="span12">
            <div class="nav">nav area</div>
            <div class="bg-image">
                <img src="http://unplugged.ee/wp-content/uploads/2013/03/frank2.jpg">
                 <h1>This is centered text.</h1>
            </div>
            <div class="main">main area</div>
        </div>
    </div>
</div>

Note that the background image is now part of the regular flow of the document.

Apply the following CSS:

.bg-image {
    position: relative;
}
.bg-image img {
    display: block;
    width: 100%;
    max-width: 1200px; /* corresponds to max height of 450px */
    margin: 0 auto;
}
.bg-image h1 {
    position: absolute;
    text-align: center;
    bottom: 0;
    left: 0;
    right: 0;
    color: white;
}
.nav, .main {
    background-color: #f6f6f6;
    text-align: center;
}

How This Works

The image is set an regular flow content with a width of 100%, so it will adjust itself responsively to the width of the parent container. However, you want the height to be no more than 450px, which corresponds to the image width of 1200px, so set the maximum width of the image to 1200px. You can keep the image centered by using display: block and margin: 0 auto.

The text is painted over the image by using absolute positioning. In the simplest case, I stretch the h1 element to be the full width of the parent and use text-align: center to center the text. Use the top or bottom offsets to place the text where it is needed.

If your banner images are going to vary in aspect ratio, you will need to adjust the maximum width value for .bg-image img dynamically using jQuery/Javascript, but otherwise, this approach has a lot to offer.

See demo at: http://jsfiddle.net/audetwebdesign/EGgaN/

How can I disable ARC for a single file in a project?

Add flag “-fno-objc-arc”.

Simple follow steps : App>Targets>Build Phases>Compile Sources> add flag after class “-fno-objc-arc”

How to prevent a file from direct URL Access?

First of all, find where the main apache’s config file httpd.conf is located. If you use Debian, it should be here: /etc/apache/httpd.conf. Using some file editor like Vim or Nano open this file and find the line that looks as follows:

Options Includes Indexes FollowSymLinks MultiViews

then remove word Indexes and save the file. The line should look like this one:

Options Includes FollowSymLinks MultiViews

After it is done, restart apache (e.g. /etc/init.d/apache restart in Debian). That’s it!

How to convert UTF-8 byte[] to string?

To my knowledge none of the given answers guarantee correct behavior with null termination. Until someone shows me differently I wrote my own static class for handling this with the following methods:

// Mimics the functionality of strlen() in c/c++
// Needed because niether StringBuilder or Encoding.*.GetString() handle \0 well
static int StringLength(byte[] buffer, int startIndex = 0)
{
    int strlen = 0;
    while
    (
        (startIndex + strlen + 1) < buffer.Length // Make sure incrementing won't break any bounds
        && buffer[startIndex + strlen] != 0       // The typical null terimation check
    )
    {
        ++strlen;
    }
    return strlen;
}

// This is messy, but I haven't found a built-in way in c# that guarentees null termination
public static string ParseBytes(byte[] buffer, out int strlen, int startIndex = 0)
{
    strlen = StringLength(buffer, startIndex);
    byte[] c_str = new byte[strlen];
    Array.Copy(buffer, startIndex, c_str, 0, strlen);
    return Encoding.UTF8.GetString(c_str);
}

The reason for the startIndex was in the example I was working on specifically I needed to parse a byte[] as an array of null terminated strings. It can be safely ignored in the simple case

CSS: 100% font size - 100% of what?

As you showed convincingly, the font-size: 100%; will not render the same in all browsers. However, you will set your font face in your CSS file, so this will be the same (or a fallback) in all browsers.

I believe font-size: 100%; can be very useful when combining it with em-based design. As this article shows, this will create a very flexible website.

When is this useful? When your site needs to adapt to the visitors' wishes. Take for example an elderly man that puts his default font-size at 24 px. Or someone with a small screen with a large resolution that increases his default font-size because he otherwise has to squint. Most sites would break, but em-based sites are able to cope with these situations.

Error: Unexpected value 'undefined' imported by the module

Another reason could be some code like this:

_x000D_
_x000D_
import { NgModule } from '@angular/core';_x000D_
import { SharedModule } from 'app/shared/shared.module';_x000D_
import { CoreModule } from 'app/core/core.module';_x000D_
import { RouterModule } from '@angular/router';_x000D_
import { COMPANY_ROUTES } from 'app/company/company.routing';_x000D_
import { CompanyService } from 'app/company/services/company.service';_x000D_
import { CompanyListComponent } from 'app/company/components/company-list/company-list.component';_x000D_
_x000D_
@NgModule({_x000D_
    imports: [_x000D_
        CoreModule,_x000D_
        SharedModule,_x000D_
  RouterModule.forChild(COMPANY_ROUTES)_x000D_
    ],_x000D_
    declarations: [_x000D_
  CompanyListComponent_x000D_
    ],_x000D_
    providers: [_x000D_
  CompanyService_x000D_
    ],_x000D_
    exports: [_x000D_
    ]_x000D_
})_x000D_
export class CompanyModule { }
_x000D_
_x000D_
_x000D_

Because exports is empty array and it has , before it, it should be removed.

undefined offset PHP error

Undefined offset means there's an empty array key for example:

$a = array('Felix','Jon','Java');

// This will result in an "Undefined offset" because the size of the array
// is three (3), thus, 0,1,2 without 3
echo $a[3];

You can solve the problem using a loop (while):

$i = 0;
while ($row = mysqli_fetch_assoc($result)) {
    // Increase count by 1, thus, $i=1
    $i++;

    $groupname[$i] = base64_decode(base64_decode($row['groupname']));

    // Set the first position of the array to null or empty
    $groupname[0] = "";
}

How can I extract substrings from a string in Perl?

(\S*)\s*\((.*?)\)\s*(\*?)


(\S*)    picks up anything which is NOT whitespace
\s*      0 or more whitespace characters
\(       a literal open parenthesis
(.*?)    anything, non-greedy so stops on first occurrence of...
\)       a literal close parenthesis
\s*      0 or more whitespace characters
(\*?)    0 or 1 occurances of literal *

og:type and valid values : constantly being parsed as og:type=website

I know this is an old one but it comes up top of Google and all the links provided now seem out of date.

This is the latest list of types Facebook accepts: https://developers.facebook.com/docs/reference/opengraph

If you don't use one of these then the type will default to 'website' which is best used for home pages/summarising a web site.

In answer to the OP you would now want to use a place which will allow you to add lat/long location details.

Is there a way to make numbers in an ordered list bold?

I had a similar issue while writing a newsletter. So I had to inline the style this way:

<ol>
    <li style="font-weight:bold"><span style="font-weight:normal">something</span></li>
    <li style="font-weight:bold"><span style="font-weight:normal">something</span></li>
    <li style="font-weight:bold"><span style="font-weight:normal">something</span></li>
</ol>

CSS background-size: cover replacement for Mobile Safari

html body {
  background: url(/assets/images/header-bg.jpg) no-repeat top center fixed;
  width: 100%;
  height: 100%;
  min-width: 100%;
  min-height: 100%;

  -webkit-background-size: auto auto;
  -moz-background-size: auto auto;
  -o-background-size: auto auto;
  background-size: auto auto;
}

jquery: get elements by class name and add css to each of them

What makes jQuery easy to use is that you don't have to apply attributes to each element. The jQuery object contains an array of elements, and the methods of the jQuery object applies the same attributes to all the elements in the array.

There is also a shorter form for $(document).ready(function(){...}) in $(function(){...}).

So, this is all you need:

$(function(){
  $('div.easy_editor').css('border','9px solid red');
});

If you want the code to work for any element with that class, you can just specify the class in the selector without the tag name:

$(function(){
  $('.easy_editor').css('border','9px solid red');
});

How to stretch div height to fill parent div - CSS

Suppose you have

<body>
  <div id="root" />
</body>

With normal CSS, you can do the following. See a working app https://github.com/onmyway133/Lyrics/blob/master/index.html

#root {
  position: absolute;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
}

With flexbox, you can

html, body {
  height: 100%
}
body {
  display: flex;
  align-items: stretch;
}

#root {
  width: 100%
}

How do you pass a function as a parameter in C?

This question already has the answer for defining function pointers, however they can get very messy, especially if you are going to be passing them around your application. To avoid this unpleasantness I would recommend that you typedef the function pointer into something more readable. For example.

typedef void (*functiontype)();

Declares a function that returns void and takes no arguments. To create a function pointer to this type you can now do:

void dosomething() { }

functiontype func = &dosomething;
func();

For a function that returns an int and takes a char you would do

typedef int (*functiontype2)(char);

and to use it

int dosomethingwithchar(char a) { return 1; }

functiontype2 func2 = &dosomethingwithchar
int result = func2('a');

There are libraries that can help with turning function pointers into nice readable types. The boost function library is great and is well worth the effort!

boost::function<int (char a)> functiontype2;

is so much nicer than the above.

Difference between objectForKey and valueForKey?

Here's a great reason to use objectForKey: wherever possible instead of valueForKey: - valueForKey: with an unknown key will throw NSUnknownKeyException saying "this class is not key value coding-compliant for the key ".

Spark - repartition() vs coalesce()

But also you should make sure that, the data which is coming coalesce nodes should have highly configured, if you are dealing with huge data. Because all the data will be loaded to those nodes, may lead memory exception. Though reparation is costly, i prefer to use it. Since it shuffles and distribute the data equally.

Be wise to select between coalesce and repartition.

Tesseract OCR simple example

Ok. I found the solution here tessnet2 fails to load the Ans given by Adam

Apparently i was using wrong version of tessdata. I was following the the source page instruction intuitively and that caused the problem.

it says

Quick Tessnet2 usage

  1. Download binary here, add a reference of the assembly Tessnet2.dll to your .NET project.

  2. Download language data definition file here and put it in tessdata directory. Tessdata directory and your exe must be in the same directory.

After you download the binary, when you follow the link to download the language file, there are many language files. but none of them are right version. you need to select all version and go to next page for correct version (tesseract-2.00.eng)! They should either update download binary link to version 3 or put the the version 2 language file on the first page. Or at least bold mention the fact that this version issue is a big deal!

Anyway I found it. Thanks everyone.

Showing all errors and warnings

Straight from the php.ini file:

;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
; Error handling and logging ;
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;

; This directive informs PHP of which errors, warnings and notices you would like
; it to take action for. The recommended way of setting values for this
; directive is through the use of the error level constants and bitwise
; operators. The error level constants are below here for convenience as well as
; some common settings and their meanings.
; By default, PHP is set to take action on all errors, notices and warnings EXCEPT
; those related to E_NOTICE and E_STRICT, which together cover best practices and
; recommended coding standards in PHP. For performance reasons, this is the
; recommend error reporting setting. Your production server shouldn't be wasting
; resources complaining about best practices and coding standards. That's what
; development servers and development settings are for.
; Note: The php.ini-development file has this setting as E_ALL. This
; means it pretty much reports everything which is exactly what you want during
; development and early testing.
;
; Error Level Constants:
; E_ALL             - All errors and warnings (includes E_STRICT as of PHP 5.4.0)
; E_ERROR           - fatal run-time errors
; E_RECOVERABLE_ERROR  - almost fatal run-time errors
; E_WARNING         - run-time warnings (non-fatal errors)
; E_PARSE           - compile-time parse errors
; E_NOTICE          - run-time notices (these are warnings which often result
;                     from a bug in your code, but it's possible that it was
;                     intentional (e.g., using an uninitialized variable and
;                     relying on the fact it is automatically initialized to an
;                     empty string)
; E_STRICT          - run-time notices, enable to have PHP suggest changes
;                     to your code which will ensure the best interoperability
;                     and forward compatibility of your code
; E_CORE_ERROR      - fatal errors that occur during PHP's initial startup
; E_CORE_WARNING    - warnings (non-fatal errors) that occur during PHP's
;                     initial startup
; E_COMPILE_ERROR   - fatal compile-time errors
; E_COMPILE_WARNING - compile-time warnings (non-fatal errors)
; E_USER_ERROR      - user-generated error message
; E_USER_WARNING    - user-generated warning message
; E_USER_NOTICE     - user-generated notice message
; E_DEPRECATED      - warn about code that will not work in future versions
;                     of PHP
; E_USER_DEPRECATED - user-generated deprecation warnings
;
; Common Values:
;   E_ALL (Show all errors, warnings and notices including coding standards.)
;   E_ALL & ~E_NOTICE  (Show all errors, except for notices)
;   E_ALL & ~E_NOTICE & ~E_STRICT  (Show all errors, except for notices and coding standards warnings.)
;   E_COMPILE_ERROR|E_RECOVERABLE_ERROR|E_ERROR|E_CORE_ERROR  (Show only errors)
; Default Value: E_ALL & ~E_NOTICE & ~E_STRICT & ~E_DEPRECATED
; Development Value: E_ALL
; Production Value: E_ALL & ~E_DEPRECATED & ~E_STRICT
; http://php.net/error-reporting
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT

For pure development I go for:

error_reporting = E_ALL ^ E_NOTICE ^ E_WARNING

Also don't forget to put display_errors to on

display_errors = On

After that, restart your server for Apache on Ubuntu:

sudo /etc/init.d/apache2 restart

How to select a div element in the code-behind page?

@CarlosLanderas is correct depending on where you've placed the DIV control. The DIV by the way is not technically an ASP control, which is why you cannot find it directly like other controls. But the best way around this is to turn it into an ASP control.

Use asp:Panel instead. It is rendered into a <div> tag anyway...

<asp:Panel id="divSubmitted" runat="server" style="text-align:center" visible="false">
   <asp:Label ID="labSubmitted" runat="server" Text="Roll Call Submitted"></asp:Label>
</asp:Panel>

And in code behind, simply find the Panel control as per normal...

Panel DivCtl1 = (Panel)gvRollCall.FooterRow.FindControl("divSubmitted");
if (DivCtl1 != null)
    DivCtl1.Visible = true;

Please note that I've used FooterRow, as my "psuedo div" is inside the footer row of a Gridview control.

Good coding!

How to pass data from 2nd activity to 1st activity when pressed back? - android

TL;DR Use Activity.startActivityForResult

Long answer:

You should start by reading the Android developer documentation. Specifically the topic of your question is covered in the Starting Activities and Getting Results section of the Activity documentation.

As for example code, the Android SDK provides good examples. Also, other answers here give you short snippets of sample code to use.

However, if you are looking for alternatives, read this SO question. This is a good discussion on how to use startActivityForResults with fragments, as well as couple othe approaches for passing data between activities.

How do I get unique elements in this array?

Errr, it's a bit messy in the view. But I think I've gotten it to work with group (http://mongoid.org/docs/querying/)

Controller

@event_attendees = Activity.only(:user_id).where(:action => 'Attend').order_by(:created_at.desc).group

View

<% @event_attendees.each do |event_attendee| %>    
  <%= event_attendee['group'].first.user.first_name %>
<% end %>

unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard

You can register a class for your UITableViewCell like this:

With Swift 3+:

self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")

With Swift 2.2:

self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell")

Make sure same identifier "cell" is also copied at your storyboard's UITableViewCell.

"self" is for getting the class use the class name followed by .self.

TypeScript hashmap/dictionary interface

Just as a normal js object:

let myhash: IHash = {};   

myhash["somestring"] = "value"; //set

let value = myhash["somestring"]; //get

There are two things you're doing with [indexer: string] : string

  • tell TypeScript that the object can have any string-based key
  • that for all key entries the value MUST be a string type.

enter image description here

You can make a general dictionary with explicitly typed fields by using [key: string]: any;

enter image description here

e.g. age must be number, while name must be a string - both are required. Any implicit field can be any type of value.

As an alternative, there is a Map class:

let map = new Map<object, string>(); 

let key = new Object();

map.set(key, "value");
map.get(key); // return "value"

This allows you have any Object instance (not just number/string) as the key.

Although its relatively new so you may have to polyfill it if you target old systems.

add to array if it isn't there already

you can try using "in_array":

function insert_value($value, &$_arr) {
    if (!in_array($value, $_arr)) {
        $_arr[] = $value;
    }
}

AJAX cross domain call

The only (easy) way to get cross-domain data using AJAX is to use a server side language as the proxy as Andy E noted. Here's a small sample how to implement that using jQuery:

The jQuery part:

$.ajax({
    url: 'proxy.php',
    type: 'POST',
    data: {
        address: 'http://www.google.com'
    },
    success: function(response) {
        // response now contains full HTML of google.com
    }
});

And the PHP (proxy.php):

echo file_get_contents($_POST['address']);

Simple as that. Just be aware of what you can or cannot do with the scraped data.

Cannot open backup device. Operating System error 5

The SQL Server service account does not have permissions to write to the folder C:\Users\Kimpoy\Desktop\Backup\

How can I clear previous output in Terminal in Mac OS X?

The pretty way is printf '\33c\e[3J'

Is there such a thing as min-font-size and max-font-size?

You can use Sass to control min and max font sizes. Here is a brilliant solution by Eduardo Boucas.

https://eduardoboucas.com/blog/2015/06/18/viewport-sized-typography-with-minimum-and-maximum-sizes.html

@mixin responsive-font($responsive, $min, $max: false, $fallback: false) {
  $responsive-unitless: $responsive / ($responsive - $responsive + 1);
  $dimension: if(unit($responsive) == 'vh', 'height', 'width');
  $min-breakpoint: $min / $responsive-unitless * 100;

  @media (max-#{$dimension}: #{$min-breakpoint}) {
    font-size: $min;
  }

  @if $max {
    $max-breakpoint: $max / $responsive-unitless * 100;

    @media (min-#{$dimension}: #{$max-breakpoint}) {
      font-size: $max;
    }
  }

  @if $fallback {
    font-size: $fallback;
  }

  font-size: $responsive;
}

.limit-min {
  @include responsive-font(3vw, 20px);
}

.limit-min-max {
  @include responsive-font(3vw, 20px, 50px);
}

How to Parse a JSON Object In Android

In your JSON format, it do not have starting JSON object

Like :

{
    "info" :       <!-- this is starting JSON object -->
        {
        "caller":"getPoiById",
        "results":
        {
            "indexForPhone":0,
            "indexForEmail":"NULL",
            .
            .
         }
    }
}

Above Json starts with info as JSON object. So while executing :

JSONObject json = new JSONObject(result);    // create JSON obj from string
JSONObject json2 = json.getJSONObject("info");    // this will return correct

Now, we can access result field :

JSONObject jsonResult = json2.getJSONObject("results");
test = json2.getString("name"); // returns "Marina Rasche Werft GmbH & Co. KG"

I think this was missing and so the problem was solved while we use JSONTokener like answer of yours.

Your answer is very fine. Just i think i add this information so i answered

Thank you

Better way to get type of a Javascript variable?

You may find the following function useful:

function typeOf(obj) {
  return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}

Or in ES7 (comment if further improvements)

const { toString } = Object.prototype;

function typeOf(obj) {
  const stringified = obj::toString();
  const type = stringified.split(' ')[1].slice(0, -1);
      
  return type.toLowerCase();
}

Results:

typeOf(); //undefined
typeOf(null); //null
typeOf(NaN); //number
typeOf(5); //number
typeOf({}); //object
typeOf([]); //array
typeOf(''); //string
typeOf(function () {}); //function
typeOf(/a/) //regexp
typeOf(new Date()) //date
typeOf(new Error) //error
typeOf(Promise.resolve()) //promise
typeOf(function *() {}) //generatorfunction
typeOf(new WeakMap()) //weakmap
typeOf(new Map()) //map
typeOf(async function() {}) //asyncfunction

Thanks @johnrees for notifying me of: error, promise, generatorfunction

How can I read the contents of an URL with Python?

You can use requests and beautifulsoup libraries to read data on a website. Just install these two libraries and type the following code.

import requests
import bs4
help(requests)
help(bs4)

You will get all the information you need about the library.

Cosine Similarity between 2 Number Lists

You can use cosine_similarity function form sklearn.metrics.pairwise docs

In [23]: from sklearn.metrics.pairwise import cosine_similarity

In [24]: cosine_similarity([[1, 0, -1]], [[-1,-1, 0]])
Out[24]: array([[-0.5]])

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Applying styles to tables with Twitter Bootstrap

bootstrap provides various classes for table

 <table class="table"></table>
 <table class="table table-bordered"></table>
 <table class="table table-hover"></table>
 <table class="table table-condensed"></table>
 <table class="table table-responsive"></table>

How to duplicate sys.stdout to a log file?

The print statement will call the write() method of any object you assign to sys.stdout.

I would spin up a small class to write to two places at once...

import sys

class Logger(object):
    def __init__(self):
        self.terminal = sys.stdout
        self.log = open("log.dat", "a")

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)  

sys.stdout = Logger()

Now the print statement will both echo to the screen and append to your log file:

# prints "1 2" to <stdout> AND log.dat
print "%d %d" % (1,2)

This is obviously quick-and-dirty. Some notes:

  • You probably ought to parametize the log filename.
  • You should probably revert sys.stdout to <stdout> if you won't be logging for the duration of the program.
  • You may want the ability to write to multiple log files at once, or handle different log levels, etc.

These are all straightforward enough that I'm comfortable leaving them as exercises for the reader. The key insight here is that print just calls a "file-like object" that's assigned to sys.stdout.

Hibernate Criteria Query to get specific columns

I like this approach because it is simple and clean:

    String getCompaniesIdAndName = " select "
            + " c.id as id, "
            + " c.name as name "
            + " from Company c ";

    @Query(value = getCompaniesWithoutAccount)
    Set<CompanyIdAndName> findAllIdAndName();

    public static interface CompanyIdAndName extends DTO {
        Integer getId();

        String getName();

    }

Find the files that have been changed in last 24 hours

This command worked for me

find . -mtime -1 -print

Use cases for the 'setdefault' dict method

One drawback of defaultdict over dict (dict.setdefault) is that a defaultdict object creates a new item EVERYTIME non existing key is given (eg with ==, print). Also the defaultdict class is generally way less common then the dict class, its more difficult to serialize it IME.

P.S. IMO functions|methods not meant to mutate an object, should not mutate an object.

json and empty array

The first version is a null object while the second is an Array object with zero elements.

Null may mean here for example that no location is available for that user, no location has been requested or that some restrictions apply. Hard to tell with no reference to the API.

Setting up JUnit with IntelliJ IDEA

I needed to enable the JUnit plugin, after I linked my project with the jar files.

To enable the JUnit plugin, go to File->Settings, type "JUnit" in the search bar, and under "Plugins," check "JUnit.

vikingsteve's advice above will probably get the libraries linked right. Otherwise, open File->Project Structure, go to Libraries, hit the plus, and then browse to

C:\Program Files (x86)\JetBrains\IntelliJ IDEA Community Edition 14.1.1\lib\

and add these jar files:

hamcrest-core-1.3.jar
junit-4.11.jar 
junit.jar 

Construct pandas DataFrame from items in nested dictionary

pd.concat accepts a dictionary. With this in mind, it is possible to improve upon the currently accepted answer in terms of simplicity and performance by use a dictionary comprehension to build a dictionary mapping keys to sub-frames.

pd.concat({k: pd.DataFrame(v).T for k, v in user_dict.items()}, axis=0)

Or,

pd.concat({
        k: pd.DataFrame.from_dict(v, 'index') for k, v in user_dict.items()
    }, 
    axis=0)

              att_1     att_2
12 Category 1     1  whatever
   Category 2    23   another
15 Category 1    10       foo
   Category 2    30       bar

How to write a large buffer into a binary file in C++, fast?

This did the job (in the year 2012):

#include <stdio.h>
const unsigned long long size = 8ULL*1024ULL*1024ULL;
unsigned long long a[size];

int main()
{
    FILE* pFile;
    pFile = fopen("file.binary", "wb");
    for (unsigned long long j = 0; j < 1024; ++j){
        //Some calculations to fill a[]
        fwrite(a, 1, size*sizeof(unsigned long long), pFile);
    }
    fclose(pFile);
    return 0;
}

I just timed 8GB in 36sec, which is about 220MB/s and I think that maxes out my SSD. Also worth to note, the code in the question used one core 100%, whereas this code only uses 2-5%.

Thanks a lot to everyone.

Update: 5 years have passed it's 2017 now. Compilers, hardware, libraries and my requirements have changed. That's why I made some changes to the code and did some new measurements.

First up the code:

#include <fstream>
#include <chrono>
#include <vector>
#include <cstdint>
#include <numeric>
#include <random>
#include <algorithm>
#include <iostream>
#include <cassert>

std::vector<uint64_t> GenerateData(std::size_t bytes)
{
    assert(bytes % sizeof(uint64_t) == 0);
    std::vector<uint64_t> data(bytes / sizeof(uint64_t));
    std::iota(data.begin(), data.end(), 0);
    std::shuffle(data.begin(), data.end(), std::mt19937{ std::random_device{}() });
    return data;
}

long long option_1(std::size_t bytes)
{
    std::vector<uint64_t> data = GenerateData(bytes);

    auto startTime = std::chrono::high_resolution_clock::now();
    auto myfile = std::fstream("file.binary", std::ios::out | std::ios::binary);
    myfile.write((char*)&data[0], bytes);
    myfile.close();
    auto endTime = std::chrono::high_resolution_clock::now();

    return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
}

long long option_2(std::size_t bytes)
{
    std::vector<uint64_t> data = GenerateData(bytes);

    auto startTime = std::chrono::high_resolution_clock::now();
    FILE* file = fopen("file.binary", "wb");
    fwrite(&data[0], 1, bytes, file);
    fclose(file);
    auto endTime = std::chrono::high_resolution_clock::now();

    return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
}

long long option_3(std::size_t bytes)
{
    std::vector<uint64_t> data = GenerateData(bytes);

    std::ios_base::sync_with_stdio(false);
    auto startTime = std::chrono::high_resolution_clock::now();
    auto myfile = std::fstream("file.binary", std::ios::out | std::ios::binary);
    myfile.write((char*)&data[0], bytes);
    myfile.close();
    auto endTime = std::chrono::high_resolution_clock::now();

    return std::chrono::duration_cast<std::chrono::milliseconds>(endTime - startTime).count();
}

int main()
{
    const std::size_t kB = 1024;
    const std::size_t MB = 1024 * kB;
    const std::size_t GB = 1024 * MB;

    for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << "option1, " << size / MB << "MB: " << option_1(size) << "ms" << std::endl;
    for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << "option2, " << size / MB << "MB: " << option_2(size) << "ms" << std::endl;
    for (std::size_t size = 1 * MB; size <= 4 * GB; size *= 2) std::cout << "option3, " << size / MB << "MB: " << option_3(size) << "ms" << std::endl;

    return 0;
}

This code compiles with Visual Studio 2017 and g++ 7.2.0 (a new requirements). I ran the code with two setups:

  • Laptop, Core i7, SSD, Ubuntu 16.04, g++ Version 7.2.0 with -std=c++11 -march=native -O3
  • Desktop, Core i7, SSD, Windows 10, Visual Studio 2017 Version 15.3.1 with /Ox /Ob2 /Oi /Ot /GT /GL /Gy

Which gave the following measurements (after ditching the values for 1MB, because they were obvious outliers): enter image description here enter image description here Both times option1 and option3 max out my SSD. I didn't expect this to see, because option2 used to be the fastest code on my old machine back then.

TL;DR: My measurements indicate to use std::fstream over FILE.

Connect to network drive with user name and password

Very elegant solution inspired from this one. This one uses only .Net library and does not need to use any command line or Win32 API.

Code for ready reference:

NetworkCredential theNetworkCredential = new NetworkCredential(@"domain\username", "password");
CredentialCache theNetCache = new CredentialCache();
theNetCache.Add(new Uri(@"\\computer"), "Basic", theNetworkCredential);
string[] theFolders = Directory.GetDirectories(@"\\computer\share");

Remove part of string after "."

We can pretend they are filenames and remove extensions:

tools::file_path_sans_ext(a)
# [1] "NM_020506"    "NM_020519"    "NM_001030297" "NM_010281"    "NM_011419"    "NM_053155"

how to run a command at terminal from java program?

You don't actually need to run a command from an xterm session, you can run it directly:

String[] arguments = new String[] {"/path/to/executable", "arg0", "arg1", "etc"};
Process proc = new ProcessBuilder(arguments).start();

If the process responds interactively to the input stream, and you want to inject values, then do what you did before:

OutputStream out = proc.getOutputStream();  
out.write("command\n");  
out.flush();

Don't forget the '\n' at the end though as most apps will use it to identify the end of a single command's input.

Get timezone from users browser using moment(timezone).js

var timedifference = new Date().getTimezoneOffset();

This returns the difference from the clients timezone from UTC time. You can then play around with it as you like.

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

What about like this:

temp_inx = (L + [x]).index(x) 
inx = temp_inx if temp_inx < len(L) else -1

Foreign Key naming scheme

A note from Microsoft concerning SQL Server:

A FOREIGN KEY constraint does not have to be linked only to a PRIMARY KEY constraint in another table; it can also be defined to reference the columns of a UNIQUE constraint in another table.

so, I'll use terms describing dependency instead of the conventional primary/foreign relationship terms.

When referencing the PRIMARY KEY of the independent (parent) table by the similarly named column(s) in the dependent (child) table, I omit the column name(s):

FK_ChildTable_ParentTable

When referencing other columns, or the column names vary between the two tables, or just to be explicit:

FK_ChildTable_childColumn_ParentTable_parentColumn

Remove all git files from a directory?

How to remove all .git directories under a folder in Linux.

Run this find command, it will list all .git directories under the current folder:

find . -type d -name ".git" \
&& find . -name ".gitignore" \
&& find . -name ".gitmodules"

Prints:

./.git
./.gitmodules
./foobar/.git
./footbar2/.git
./footbar2/.gitignore

There should only be like 3 or 4 .git directories because git only has one .git folder for every project. You can rm -rf yourpath each of the above by hand.

If you feel like removing them all in one command and living dangerously:

//Retrieve all the files named ".git" and pump them into 'rm -rf'
//WARNING if you don't understand why/how this command works, DO NOT run it!

( find . -type d -name ".git" \
  && find . -name ".gitignore" \
  && find . -name ".gitmodules" ) | xargs rm -rf

//WARNING, if you accidentally pipe a `.` or `/` or other wildcard
//into xargs rm -rf, then the next question you will have is: "why is
//the bash ls command not found?  Requiring an OS reinstall.

'invalid value encountered in double_scalars' warning, possibly numpy

I encount this while I was calculating np.var(np.array([])). np.var will divide size of the array which is zero in this case.

How to get selected value from Dropdown list in JavaScript

Hope it's working for you

 function GetSelectedItem()
 {
     var index = document.getElementById(select1).selectedIndex;

     alert("value =" + document.getElementById(select1).value); // show selected value
     alert("text =" + document.getElementById(select1).options[index].text); // show selected text 
 }

How to select an element by classname using jqLite?

If elem.find() is not working for you, check that you are including JQuery script before angular script....

A warning - comparison between signed and unsigned integer expressions

The important difference between signed and unsigned ints is the interpretation of the last bit. The last bit in signed types represent the sign of the number, meaning: e.g:

0001 is 1 signed and unsigned 1001 is -1 signed and 9 unsigned

(I avoided the whole complement issue for clarity of explanation! This is not exactly how ints are represented in memory!)

You can imagine that it makes a difference to know if you compare with -1 or with +9. In many cases, programmers are just too lazy to declare counting ints as unsigned (bloating the for loop head f.i.) It is usually not an issue because with ints you have to count to 2^31 until your sign bit bites you. That's why it is only a warning. Because we are too lazy to write 'unsigned' instead of 'int'.

Best way to convert strings to symbols in hash

a shorter one-liner fwiw:

my_hash.inject({}){|h,(k,v)| h.merge({ k.to_sym => v}) }

Using XPATH to search text containing &nbsp;

It seems that OpenQA, guys behind Selenium, have already addressed this problem. They defined some variables to explicitely match whitespaces. In my case, I need to use an XPATH similar to //td[text()="${nbsp}"].

I reproduced here the text from OpenQA concerning this issue (found here):

HTML automatically normalizes whitespace within elements, ignoring leading/trailing spaces and converting extra spaces, tabs and newlines into a single space. When Selenium reads text out of the page, it attempts to duplicate this behavior, so you can ignore all the tabs and newlines in your HTML and do assertions based on how the text looks in the browser when rendered. We do this by replacing all non-visible whitespace (including the non-breaking space "&nbsp;") with a single space. All visible newlines (<br>, <p>, and <pre> formatted new lines) should be preserved.

We use the same normalization logic on the text of HTML Selenese test case tables. This has a number of advantages. First, you don't need to look at the HTML source of the page to figure out what your assertions should be; "&nbsp;" symbols are invisible to the end user, and so you shouldn't have to worry about them when writing Selenese tests. (You don't need to put "&nbsp;" markers in your test case to assertText on a field that contains "&nbsp;".) You may also put extra newlines and spaces in your Selenese <td> tags; since we use the same normalization logic on the test case as we do on the text, we can ensure that assertions and the extracted text will match exactly.

This creates a bit of a problem on those rare occasions when you really want/need to insert extra whitespace in your test case. For example, you may need to type text in a field like this: "foo ". But if you simply write <td>foo </td> in your Selenese test case, we'll replace your extra spaces with just one space.

This problem has a simple workaround. We've defined a variable in Selenese, ${space}, whose value is a single space. You can use ${space} to insert a space that won't be automatically trimmed, like this: <td>foo${space}${space}${space}</td>. We've also included a variable ${nbsp}, that you can use to insert a non-breaking space.

Note that XPaths do not normalize whitespace the way we do. If you need to write an XPath like //div[text()="hello world"] but the HTML of the link is really "hello&nbsp;world", you'll need to insert a real "&nbsp;" into your Selenese test case to get it to match, like this: //div[text()="hello${nbsp}world"].

Check if registry key exists using VBScript

Simplest way avoiding RegRead and error handling tricks. Optional friendly consts for the registry:

Const HKEY_CLASSES_ROOT   = &H80000000
Const HKEY_CURRENT_USER   = &H80000001
Const HKEY_LOCAL_MACHINE  = &H80000002
Const HKEY_USERS          = &H80000003
Const HKEY_CURRENT_CONFIG = &H80000005

Then check with:

Set oReg = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\default:StdRegProv")

If oReg.EnumKey(HKEY_LOCAL_MACHINE, "SYSTEM\Example\Key\", "", "") = 0 Then
  MsgBox "Key Exists"
Else
  MsgBox "Key Not Found"
End If

IMPORTANT NOTES FOR THE ABOVE:

  • There are 4 parameters being passed to EnumKey, not the usual 3.
  • Equals zero means the key EXISTS.
  • The slash after key name is optional and not required.

How to bundle vendor scripts separately and require them as needed with Webpack?

I am not sure if I fully understand your problem but since I had similar issue recently I will try to help you out.

Vendor bundle.

You should use CommonsChunkPlugin for that. in the configuration you specify the name of the chunk (e.g. vendor), and file name that will be generated (vendor.js).

new webpack.optimize.CommonsChunkPlugin("vendor", "vendor.js", Infinity),

Now important part, you have to now specify what does it mean vendor library and you do that in an entry section. One one more item to entry list with the same name as the name of the newly declared chunk (i.e. 'vendor' in this case). The value of that entry should be the list of all the modules that you want to move to vendor bundle. in your case it should look something like:

entry: {
    app: 'entry.js',
    vendor: ['jquery', 'jquery.plugin1']
}

JQuery as global

Had the same problem and solved it with ProvidePlugin. here you are not defining global object but kind of shurtcuts to modules. i.e. you can configure it like that:

new webpack.ProvidePlugin({
    $: "jquery"
})

And now you can just use $ anywhere in your code - webpack will automatically convert that to

require('jquery')

I hope it helped. you can also look at my webpack configuration file that is here

I love webpack, but I agree that the documentation is not the nicest one in the world... but hey.. people were saying same thing about Angular documentation in the begining :)


Edit:

To have entrypoint-specific vendor chunks just use CommonsChunkPlugins multiple times:

new webpack.optimize.CommonsChunkPlugin("vendor-page1", "vendor-page1.js", Infinity),
new webpack.optimize.CommonsChunkPlugin("vendor-page2", "vendor-page2.js", Infinity),

and then declare different extenral libraries for different files:

entry: {
    page1: ['entry.js'],
    page2: ['entry2.js'],
    "vendor-page1": [
        'lodash'
    ],
    "vendor-page2": [
        'jquery'
    ]
},

If some libraries are overlapping (and for most of them) between entry points then you can extract them to common file using same plugin just with different configuration. See this example.

What does the error "arguments imply differing number of rows: x, y" mean?

I had the same error message so I went googling a bit I managed to fix it with the following code.

df<-data.frame(words = unlist(words))

words is a character list.

This just in case somebody else needs the output to be a data frame.

How do I open workbook programmatically as read-only?

Does this work?

Workbooks.Open Filename:=filepath, ReadOnly:=True

Or, as pointed out in a comment, to keep a reference to the opened workbook:

Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)

How to escape special characters in building a JSON string?

Use encodeURIComponent() to encode the string.

Eg.:

var product_list = encodeURIComponent(JSON.stringify(product_list));

You don't need to decode it since the web server automatically do the same.

On delete cascade with doctrine2

There are two kinds of cascades in Doctrine:

1) ORM level - uses cascade={"remove"} in the association - this is a calculation that is done in the UnitOfWork and does not affect the database structure. When you remove an object, the UnitOfWork will iterate over all objects in the association and remove them.

2) Database level - uses onDelete="CASCADE" on the association's joinColumn - this will add On Delete Cascade to the foreign key column in the database:

@ORM\JoinColumn(name="father_id", referencedColumnName="id", onDelete="CASCADE")

I also want to point out that the way you have your cascade={"remove"} right now, if you delete a Child object, this cascade will remove the Parent object. Clearly not what you want.

How do check if a PHP session is empty?

I know this is old, but I ran into an issue where I was running a function after checking if there was a session. It would throw an error everytime I tried loading the page after logging out, still worked just logged an error page. Make sure you use exit(); if you are running into the same problem.

     function sessionexists(){
        if(!empty($_SESSION)){
     return true;
         }else{
     return false;
         }
      }


        if (!sessionexists()){
           redirect("https://www.yoursite.com/");
           exit();
           }else{call_user_func('check_the_page');
         } 

Drawing an SVG file on a HTML5 canvas

You can easily draw simple svgs onto a canvas by:

  1. Assigning the source of the svg to an image in base64 format
  2. Drawing the image onto a canvas

Note: The only drawback of the method is that it cannot draw images embedded in the svg. (see demo)

Demonstration:

(Note that the embedded image is only visible in the svg)

_x000D_
_x000D_
var svg = document.querySelector('svg');_x000D_
var img = document.querySelector('img');_x000D_
var canvas = document.querySelector('canvas');_x000D_
_x000D_
// get svg data_x000D_
var xml = new XMLSerializer().serializeToString(svg);_x000D_
_x000D_
// make it base64_x000D_
var svg64 = btoa(xml);_x000D_
var b64Start = 'data:image/svg+xml;base64,';_x000D_
_x000D_
// prepend a "header"_x000D_
var image64 = b64Start + svg64;_x000D_
_x000D_
// set it as the source of the img element_x000D_
img.src = image64;_x000D_
_x000D_
// draw the image onto the canvas_x000D_
canvas.getContext('2d').drawImage(img, 0, 0);
_x000D_
svg, img, canvas {_x000D_
  display: block;_x000D_
}
_x000D_
SVG_x000D_
_x000D_
<svg height="40">_x000D_
  <rect width="40" height="40" style="fill:rgb(255,0,255);" />_x000D_
  <image xlink:href="https://en.gravatar.com/userimage/16084558/1a38852cf33713b48da096c8dc72c338.png?size=20" height="20px" width="20px" x="10" y="10"></image>_x000D_
</svg>_x000D_
<hr/><br/>_x000D_
_x000D_
IMAGE_x000D_
<img/>_x000D_
<hr/><br/>_x000D_
   _x000D_
CANVAS_x000D_
<canvas></canvas>_x000D_
<hr/><br/>
_x000D_
_x000D_
_x000D_

I/O error(socket error): [Errno 111] Connection refused

I'm not exactly sure what's causing this. You can try looking in your socket.py (mine is a different version, so line numbers from the trace don't match, and I'm afraid some other details might not match as well).

Anyway, it seems like a good practice to put your url fetching code in a try: ... except: ... block, and handle this with a short pause and a retry. The URL you're trying to fetch may be down, or too loaded, and that's stuff you'll only be able to handle in with a retry anyway.

Getting CheckBoxList Item values

//Simple example code:

foreach (var item in YourCheckedListBox.CheckedItems)
{List<string>.Add(item);}

How to pass multiple parameters in a querystring

Query String: ?strID=XXXX&strName=yyyy&strDate=zzzzz

before you redirect:

string queryString = Request.QueryString.ToString();

Response.Redirect("page.aspx?"+queryString);

Traits vs. interfaces

Traits are simply for code reuse.

Interface just provides the signature of the functions that is to be defined in the class where it can be used depending on the programmer's discretion. Thus giving us a prototype for a group of classes.

For reference- http://www.php.net/manual/en/language.oop5.traits.php

How to clear an EditText on click?

Be careful when setting text with an onClick listener on the field you are setting the text. I was doing this and setting the text to an empty string. This was causing the pointer to come up to indicate where my cursor was, which will normally go away after a few seconds. When I did not wait for it to go away before leaving my page causing finish() to be called, it would cause a memory leak and crash my app. Took me a while to figure out what was causing the crash on this one..

Anyway, I would recommend using selectAll() in your on click listener rather than setText() if you can. This way, once the text is selected, the user can start typing and all of the previous text will be cleared.

pic of the suspect pointer: http://i.stack.imgur.com/juJnt.png

Apply CSS style attribute dynamically in Angular JS

The easiest way is to call a function for the style, and have the function return the correct style.

<div style="{{functionThatReturnsStyle()}}"></div>

And in your controller:

$scope.functionThatReturnsStyle = function() {
  var style1 = "width: 300px";
  var style2 = "width: 200px";
  if(condition1)
     return style1;
  if(condition2)
     return style2;
}

When to use RDLC over RDL reports?

From my experience there are few things to think about both things:

I. RDL reports are HOSTED reports generally. This means you need to implement SSRS Server. They are a built in extension of Visual Studio from SQL Server for the reporting language. When you install SSRS you should have an add on called 'Business Intelligence Development Studio' which is much easier to work with the reports than without it.

R eport

D efinition

L angauge

Benefits of RDL reports:

  1. You can host the reports in an environment that has services running for you on them.
  2. You can configure security on an item or inheriting level to handle security as a standalone concept
  3. You can configure the service to send out emails(provided you have an SMTP server you have access to) and save files on schedules
  4. You have a database generally called 'ReportServer' you can query for info on the reports once published.
  5. You can access these reports still through 'ReportViewer' in a client application written in ASP.NET, WPF (with a winform control bleh!), or Winforms in .NET using 'ProcessingMode.Remote'.
  6. You can set parameters a user can see and use to gain more flexibility.
  7. You can configure parts of a report to be used for connection strings as 'Data Sources' as well as a sql query, xml, or other datasets as a 'Dataset'. These parts and others can be stored and configured to cache data on a regular basis.
  8. You can write .NET proxy classes of the services http:// /ReportServer/ReportingService2010 or /ReportExecution2005. You can then make up your OWN methods in .NET for emailing, saving, or manipulating SSRS data from the service directly of a Server hosting SSRS reports in code. Programmatically Export SSRS report from sharepoint using ReportService2010.asmx

Downsides:

  1. SSRS is kind of wonkey compared to other things on getting it up fast. Most people get confused by the security policy and designing reports as an 'add on' to VS. SQL 2005 = VS BIDS 2005 , SQL 2008 = VS BIDS 2008, SQL 2012 = VS BIDS 2010(LOL).
  2. Continuing on 1 the policy for security settings IMHO are idiotically overcomplex. There is server security, database security and roles, two security settings on the page hosted for the service. Most people only set up an admin than can't get in and wonder why other users cannot. Most common complaint or question on SSRS is related to getting in generally from my experience.
  3. You can use 'expressions' that will supposeduly 'enhance' your report. Often times you do more than a few and your report goes to a crawl in performance.
  4. You have a set amount of things you can do and export to. SSRS has no hover over reporting I know of without a javascript hack.
  5. Speed and performance can take a hit as the stupid SSRS config recycles the system and a first report can take a while at times just loading the site. You can get around this by altering it but I have found making a keep alive service for it works better.

II. RDLC reports are CLIENT CONTAINED reports that are NOT HOSTED ANYWHERE. The extra c in the name means 'Client'. Generally this is an extension of the RDL language meant for use only in Visual Studio Client Applications. It exists in Visual Studio when you add a 'reporting' item.

Benefits of RDLC reports:

  1. You can hookup a wcf service much much much more easier to the dataset.
  2. You have more control over the dataset and can use POCO classes filled with Entity framework objects or ADO.NET directly as well as tables themselves. You can monkey with the data for optimization it before binding it to the report.
  3. You can customize the look more with add on's directly in code behind.

Downsides:

  1. You need to handle parameters on your own and while you can implement wrapper methods to help the legwork is a little more than expected and unfortunate.
  2. The user cannot SEE the parameters in a 'ReportViewer' control unless it is in remote mode and accessing an RLD report. Thus you need to make textboxes, dropdowns, radio buttons on your own outside the control to pass to it. Some people like this added control, I do not personally.
  3. Anything you want to do with servicing the reports for distribution you need to build yourself. Emailing, subscriptions, saving. Sorry you need to build that in .NET or else implement a proxy that already does that from above you could just be getting using hosted reports.

Honestly I like both for different purposes. If I want something to go out to analysts that they use all the time and tweak for graphs, charts, drill downs and exports to Excel I use RDL and just have SSRS's site do all the legwork of handling the email distributions. If I want an application that has a report section and I know that application is it's own module with rules and governance I use an RDLC and having the parameters be smaller and be driven by the decisions the user made before getting to the report part of what client they are on and site and then they usually just choose a time frame or type and nothing more. So generally a complex report I would use RDL and for something simple I would use RDLC IMHO.

I hope that helps.

What is the "-->" operator in C/C++?

--> is not an operator. It is in fact two separate operators, -- and >.

The conditional's code decrements x, while returning x's original (not decremented) value, and then compares the original value with 0 using the > operator.

To better understand, the statement could be written as follows:

while( (x--) > 0 )

Error: JavaFX runtime components are missing, and are required to run this application with JDK 11

This worked for me:

File >> Project Structure >> Modules >> Dependency >> + (on left-side of window)

clicking the "+" sign will let you designate the directory where you have unpacked JavaFX's "lib" folder.

Scope is Compile (which is the default.) You can then edit this to call it JavaFX by double-clicking on the line.

then in:

Run >> Edit Configurations

Add this line to VM Options:

--module-path /path/to/JavaFX/lib --add-modules=javafx.controls

(oh and don't forget to set the SDK)

Cannot make file java.io.IOException: No such file or directory

Print the full file name out or step through in a debugger. When I get confused by errors like this, it means that my assumptions and expectations don't match reality. Make sure you can see what the path is; it'll help you figure out where you've gone wrong.

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

In javascript,

You can use the list of all options of multiselect dropdown which will be an Array.Then loop through it to make Selected attributes as false in each Objects.

for(var i=0;i<list.length;i++)
{
   if(list[i].Selected==true)
    {
       list[i].Selected=false;
    }
}

Datetime equal or greater than today in MySQL

SELECT * FROM users WHERE created >= now()

JQuery Bootstrap Multiselect plugin - Set a value as selected in the multiselect dropdown

I hope these functions will help you.

$('#your-select').multiSelect('select', String|Array);

$('#your-select').multiSelect('deselect', String|Array);

$('#your-select').multiSelect('select_all');

$('#your-select').multiSelect('deselect_all');

$('#your-select').multiSelect('refresh');

Reference by this site Reference

jQuery Screen Resolution Height Adjustment

Another example for vertically and horizontally centered div or any object(s):

 var obj = $("#divID");
 var halfsc = $(window).height()/2;
 var halfh = $(obj).height() / 2; 

 var halfscrn = screen.width/2;
 var halfobj =$(obj).width() / 2; 

 var goRight =  halfscrn - halfobj ;
 var goBottom = halfsc - halfh;

 $(obj).css({marginLeft: goRight }).css({marginTop: goBottom });

Getting list of lists into pandas DataFrame

Call the pd.DataFrame constructor directly:

df = pd.DataFrame(table, columns=headers)
df

   Heading1  Heading2
0         1         2
1         3         4

How do I add a custom script to my package.json file that runs a javascript file?

Lets say in scripts you want to run 2 commands with a single command:

"scripts":{
  "start":"any command",
  "singleCommandToRunTwoCommand":"some command here && npm start"
}

Now go to your terminal and run there npm run singleCommandToRunTwoCommand.

Spring: how do I inject an HttpServletRequest into a request-scoped bean?

Spring exposes the current HttpServletRequest object (as well as the current HttpSession object) through a wrapper object of type ServletRequestAttributes. This wrapper object is bound to ThreadLocal and is obtained by calling the static method RequestContextHolder.currentRequestAttributes().

ServletRequestAttributes provides the method getRequest() to get the current request, getSession() to get the current session and other methods to get the attributes stored in both the scopes. The following code, though a bit ugly, should get you the current request object anywhere in the application:

HttpServletRequest curRequest = 
((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
.getRequest();

Note that the RequestContextHolder.currentRequestAttributes() method returns an interface and needs to be typecasted to ServletRequestAttributes that implements the interface.


Spring Javadoc: RequestContextHolder | ServletRequestAttributes

Does file_get_contents() have a timeout setting?

It is worth noting that if changing default_socket_timeout on the fly, it might be useful to restore its value after your file_get_contents call:

$default_socket_timeout = ini_get('default_socket_timeout');
....
ini_set('default_socket_timeout', 10);
file_get_contents($url);
...
ini_set('default_socket_timeout', $default_socket_timeout);

C++ callback using class member

A complete working example from the code above.... for C++11:

#include <stdlib.h>
#include <stdio.h>
#include <functional>

#if __cplusplus <= 199711L
  #error This file needs at least a C++11 compliant compiler, try using:
  #error    $ g++ -std=c++11 ..
#endif

using namespace std;

class EventHandler {
    public:
        void addHandler(std::function<void(int)> callback) {
            printf("\nHandler added...");
            // Let's pretend an event just occured
            callback(1);
        }
};


class MyClass
{
    public:
        MyClass(int);
        // Note: No longer marked `static`, and only takes the actual argument
        void Callback(int x);

    private:
        EventHandler *pHandler;
        int private_x;
};

MyClass::MyClass(int value) {
    using namespace std::placeholders; // for `_1`

    pHandler = new EventHandler();
    private_x = value;
    pHandler->addHandler(std::bind(&MyClass::Callback, this, _1));
}

void MyClass::Callback(int x) {
    // No longer needs an explicit `instance` argument,
    // as `this` is set up properly
    printf("\nResult:%d\n\n", (x+private_x));
}

// Main method
int main(int argc, char const *argv[]) {

    printf("\nCompiler:%ld\n", __cplusplus);
    new MyClass(5);
    return 0;
}


// where $1 is your .cpp file name... this is the command used:
// g++ -std=c++11 -Wall -o $1 $1.cpp
// chmod 700 $1
// ./$1

Output should be:

Compiler:201103

Handler added...
Result:6

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

I followed the steps in killthrush's answer and to my surprise it did not work. Logging in as sa I could see my Windows domain user and had made them a sysadmin, but when I tried logging in with Windows auth I couldn't see my login under logins, couldn't create databases, etc. Then it hit me. That login was probably tied to another domain account with the same name (with some sort of internal/hidden ID that wasn't right). I had left this organization a while back and then came back months later. Instead of re-activating my old account (which they might have deleted) they created a new account with the same domain\username and a new internal ID. Using sa I deleted my old login, re-added it with the same name and added sysadmin. I logged back in with Windows Auth and everything looks as it should. I can now see my logins (and others) and can do whatever I need to do as a sysadmin using my Windows auth login.

Bad Request - Invalid Hostname IIS7

I'm not sure if this was your problem but for anyone that's trying to access his web application from his machine and having this problem:

Make sure you're connecting to 127.0.0.1 (a.k.a localhost) and not to your external IP address.

Your URL should be something like http://localhost:8181/ or http://127.0.0.1:8181 and not http://YourExternalIPaddress:8181/.


Additional information:
The reason this works is because your firewall may block your own request. It can be a firewall on your OS and it can be (the usual) your router.

When you connect to your external IP address, you connect to you from the internet, as if you were a stranger (or a hacker).
However when you connect to your localhost, you connect locally as yourself and the block is obviously not needed (& avoided altogether).

Best way in asp.net to force https for an entire site?

Please use HSTS (HTTP Strict Transport Security)

from http://www.hanselman.com/blog/HowToEnableHTTPStrictTransportSecurityHSTSInIIS7.aspx

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <rewrite>
            <rules>
                <rule name="HTTP to HTTPS redirect" stopProcessing="true">
                    <match url="(.*)" />
                    <conditions>
                        <add input="{HTTPS}" pattern="off" ignoreCase="true" />
                    </conditions>
                    <action type="Redirect" url="https://{HTTP_HOST}/{R:1}"
                        redirectType="Permanent" />
                </rule>
            </rules>
            <outboundRules>
                <rule name="Add Strict-Transport-Security when HTTPS" enabled="true">
                    <match serverVariable="RESPONSE_Strict_Transport_Security"
                        pattern=".*" />
                    <conditions>
                        <add input="{HTTPS}" pattern="on" ignoreCase="true" />
                    </conditions>
                    <action type="Rewrite" value="max-age=31536000" />
                </rule>
            </outboundRules>
        </rewrite>
    </system.webServer>
</configuration>

Original Answer (replaced with the above on 4 December 2015)

basically

protected void Application_BeginRequest(Object sender, EventArgs e)
{
   if (HttpContext.Current.Request.IsSecureConnection.Equals(false) && HttpContext.Current.Request.IsLocal.Equals(false))
   {
    Response.Redirect("https://" + Request.ServerVariables["HTTP_HOST"]
+   HttpContext.Current.Request.RawUrl);
   }
}

that would go in the global.asax.cs (or global.asax.vb)

i dont know of a way to specify it in the web.config

Eclipse Optimize Imports to Include Static Imports

Eclipse 3.4 has a Favourites section under Window->Preferences->Java->Editor->Content Assist

If you use org.junit.Assert a lot, you might find some value to adding it there.

How do I list all the columns in a table?

I know it's late but I use this command for Oracle:

select column_name,data_type,data_length from all_tab_columns where TABLE_NAME = 'xxxx' AND OWNER ='xxxxxxxxxx'

What in the world are Spring beans?

A Bean is a POJO(Plain Old Java Object), which is managed by the spring container.

Spring containers create only one instance of the bean by default. ?This bean it is cached in memory so all requests for the bean will return a shared reference to the same bean.

The @Bean annotation returns an object that spring registers as a bean in application context.?The logic inside the method is responsible for creating the instance.

When do we use @Bean annotation?

When automatic configuration is not an option. For example when we want to wire components from a third party library, because the source code is not available so we cannot annotate the classes with @Component.

A Real time scenario could be that someone wants to connect to Amazon S3 bucket. Because the source is not available he would have to create a @bean.

@Bean
public AmazonS3 awsS3Client() {
    BasicAWSCredentials awsCreds = new BasicAWSCredentials(awsKeyId, accessKey);
    return AmazonS3ClientBuilder.standard().withRegion(Regions.fromName(region))
            .withCredentials(new AWSStaticCredentialsProvider(awsCreds)).build();
}

Source for the code above -> https://www.devglan.com/spring-mvc/aws-s3-java

Because I mentioned @Component Annotation above.

@Component Indicates that an annotated class is a "component". Such classes are considered as candidates for auto-detection when using annotation-based configuration and class path scanning.

Component annotation registers the class as a single bean.

Warning comparison between pointer and integer

In this line ...

if (*message == "\0") {

... as you can see in the warning ...

warning: comparison between pointer and integer
      ('int' and 'char *')

... you are actually comparing an int with a char *, or more specifically, an int with an address to a char.

To fix this, use one of the following:

if(*message == '\0') ...
if(message[0] == '\0') ...
if(!*message) ...

On a side note, if you'd like to compare strings you should use strcmp or strncmp, found in string.h.

How to migrate GIT repository from one server to a new one

To add the new repo location,

git remote add new_repo_name new_repo_url

Then push the content to the new location

git push new_repo_name master

Finally remove the old one

git remote rm origin

After that you can do what bdonlan said and edit the.git/config file to change the new_repo_name to origin. If you don't remove the origin (original remote repository), you can simply just push changes to the new repo with

git push new_repo_name master

Padding characters in printf

echo -n "$PROC_NAME $(printf '\055%.0s' {1..40})" | head -c 40 ; echo -n " [UP]"

Explanation:

  • printf '\055%.0s' {1..40} - Create 40 dashes
    (dash is interpreted as option so use escaped ascii code instead)
  • "$PROC_NAME ..." - Concatenate $PROC_NAME and dashes
  • | head -c 40 - Trim string to first 40 chars

Short form for Java if statement

The way to do it is with ternary operator:

name = city.getName() == null ? city.getName() : "N/A"

However, I believe you have a typo in your code above, and you mean to say:

if (city.getName() != null) ...

how to check if object already exists in a list

If you use EF core add

 .UseSerialColumn();

Example

modelBuilder.Entity<JobItem>(entity =>
        {
            entity.ToTable("jobs");

            entity.Property(e => e.Id)
                .HasColumnName("id")
                .UseSerialColumn();
});

How to Completely Uninstall Xcode and Clear All Settings

FOR UNINSTALLING AND THEN BEING ABLE TO REINSTALL XCODE 9 CORRECTLY

I followed the topmost answer for deleting Xcode 7 and found a major error, deleting ~/Library/Developer will delete an important folder called PrivateFrameworks, which will actually crash Xcode everytime you reinstall and force you to have to get your friends to send you the PrivateFrameworks folder again, a complete waste of time seeing if you needed to uninstall and reinstall Xcode urgently for immediate work purposes.

I have tried editing the topmost answer but see no changes so below is the modified steps you should take for Xcode 9:

Delete

/Applications/Xcode.app

~/Library/Preferences/com.apple.dt.* (Generally anything with com.apple.dt. as prefix is removable in the Preferences folder)

~/Library/Caches/com.apple.dt.Xcode

~/Library/Application Support/Xcode

Everything in /Library/Developer directory except for /Library/Developer/PrivateFrameworks

How to use Google fonts in React.js?

Here are two different ways you can adds fonts to your react app.

Adding local fonts

  1. Create a new folder called fonts in your src folder.

  2. Download the google fonts locally and place them inside the fonts folder.

  3. Open your index.css file and include the font by referencing the path.

@font-face {
  font-family: 'Rajdhani';
  src: local('Rajdhani'), url(./fonts/Rajdhani/Rajdhani-Regular.ttf) format('truetype');
}

Here I added a Rajdhani font.

Now, we can use our font in css classes like this.

.title{
    font-family: Rajdhani, serif;
    color: #0004;
}

Adding Google fonts

If you like to use google fonts (api) instead of local fonts, you can add it like this.

@import url('https://fonts.googleapis.com/css2?family=Rajdhani:wght@300;500&display=swap');

Similarly, you can also add it inside the index.html file using link tag.

<link href="https://fonts.googleapis.com/css2?family=Rajdhani:wght@300;500&display=swap" rel="stylesheet">

(originally posted at https://reactgo.com/add-fonts-to-react-app/)

How do I skip an iteration of a `foreach` loop?

foreach ( int number in numbers )
{
    if ( number < 0 )
    {
        continue;
    }

    //otherwise process number
}

Response::json() - Laravel 5.1

use the helper function in laravel 5.1 instead:

return response()->json(['name' => 'Abigail', 'state' => 'CA']);

This will create an instance of \Illuminate\Routing\ResponseFactory. See the phpDocs for possible parameters below:

/**
* Return a new JSON response from the application.
*
* @param string|array $data
* @param int $status
* @param array $headers
* @param int $options
* @return \Symfony\Component\HttpFoundation\Response 
* @static 
*/
public static function json($data = array(), $status = 200, $headers = array(), $options = 0){

    return \Illuminate\Routing\ResponseFactory::json($data, $status, $headers, $options);
}

What data type to use in MySQL to store images?

What you need, according to your comments, is a 'BLOB' (Binary Large OBject) for both image and resume.

Replace invalid values with None in Pandas DataFrame

Actually in later versions of pandas this will give a TypeError:

df.replace('-', None)
TypeError: If "to_replace" and "value" are both None then regex must be a mapping

You can do it by passing either a list or a dictionary:

In [11]: df.replace('-', df.replace(['-'], [None]) # or .replace('-', {0: None})
Out[11]:
      0
0  None
1     3
2     2
3     5
4     1
5    -5
6    -1
7  None
8     9

But I recommend using NaNs rather than None:

In [12]: df.replace('-', np.nan)
Out[12]:
     0
0  NaN
1    3
2    2
3    5
4    1
5   -5
6   -1
7  NaN
8    9

Newline in JLabel

You can do

JLabel l = new JLabel("<html><p>Hello World! blah blah blah</p></html>", SwingConstants.CENTER);

and it will automatically wrap it where appropriate.

Difference between MEAN.js and MEAN.io

They're essentially the same... They both use swig for templating, they both use karma and mocha for tests, passport integration, nodemon, etc.

Why so similar? Mean.js is a fork of Mean.io and both initiatives were started by the same guy... Mean.io is now under the umbrella of the company Linnovate and looks like the guy (Amos Haviv) stopped his collaboration with this company and started Mean.js. You can read more about the reasons here.

Now... main (or little) differences you can see right now are:


SCAFFOLDING AND BOILERPLATE GENERATION

Mean.io uses a custom cli tool named 'mean'
Mean.js uses Yeoman Generators


MODULARITY

Mean.io uses a more self-contained node packages modularity with client and server files inside the modules.
Mean.js uses modules just in the front-end (for angular), and connects them with Express. Although they were working on vertical modules as well...


BUILD SYSTEM

Mean.io has recently moved to gulp
Mean.js uses grunt


DEPLOYMENT

Both have Dockerfiles in their respective repos, and Mean.io has one-click install on Google Compute Engine, while Mean.js can also be deployed with one-click install on Digital Ocean.


DOCUMENTATION

Mean.io has ok docs
Mean.js has AWESOME docs


COMMUNITY

Mean.io has a bigger community since it was the original boilerplate
Mean.js has less momentum but steady growth


On a personal level, I like more the philosophy and openness of MeanJS and more the traction and modules/packages approach of MeanIO. Both are nice, and you'll end probably modifying them, so you can't really go wrong picking one or the other. Just take them as starting point and as a learning exercise.


ALTERNATIVE “MEAN” SOLUTIONS

MEAN is a generic way (coined by Valeri Karpov) to describe a boilerplate/framework that takes "Mongo + Express + Angular + Node" as the base of the stack. You can find frameworks with this stack that use other denomination, some of them really good for RAD (Rapid Application Development) and building SPAs. Eg:

You also have Hackathon Starter. It doesn't have A of MEAN (it is 'MEN'), but it rocks..

Have fun!

Spring Boot - Cannot determine embedded database driver class for database type NONE

Spring boot will look for datasoure properties in application.properties file.

Please define it in application.properties or yml file

application.properties

spring.datasource.url=xxx
spring.datasource.username=xxx
spring.datasource.password=xxx
spring.datasource.driver-class-name=xxx

If you need your own configuration you could set your own profile and use the datasource values while bean creation.

How do I dynamically set the selected option of a drop-down list using jQuery, JavaScript and HTML?

Here is another way you can change the selected option of a <select> element in javascript. You can use

document.getElementById('salesperson').selectedIndex=1;

Setting it to 1 will make the second element of the dropdown selected. The select element index start from 0.

Here is a sample code. Check if you can use this type of approach:

<html>
<head>
<script language="javascript">

function changeSelected() { 
document.getElementById('salesperson').selectedIndex=1;

} 

</script>
</head>
<body>
<form name="f1">

<select id="salesperson" > 
   <option value"">james</option>
   <option value"">john</option>  
</select> 
<input type="button" value="Change Selected" onClick="changeSelected();">

</form>
</body>
</html>

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

your mail.php on config you declare host as smtp.mailgun.org and port is 587 while on env is different. you need to change your mail.php to

'host' => env('MAIL_HOST', 'mailtrap.io'),
'port' => env('MAIL_PORT', 2525),

if you desire to use mailtrap.Then run

php artisan config:cache

How do I create a simple Qt console application in C++?

Here is one simple way you could structure an application if you want an event loop running.

// main.cpp
#include <QtCore>

class Task : public QObject
{
    Q_OBJECT
public:
    Task(QObject *parent = 0) : QObject(parent) {}

public slots:
    void run()
    {
        // Do processing here

        emit finished();
    }

signals:
    void finished();
};

#include "main.moc"

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    // Task parented to the application so that it
    // will be deleted by the application.
    Task *task = new Task(&a);

    // This will cause the application to exit when
    // the task signals finished.    
    QObject::connect(task, SIGNAL(finished()), &a, SLOT(quit()));

    // This will run the task from the application event loop.
    QTimer::singleShot(0, task, SLOT(run()));

    return a.exec();
}

How to move a marker in Google Maps API

You are using the correct API, but is the "marker" variable visible to the entire script. I don't see this marker variable declared globally.

Maximum size for a SQL Server Query? IN clause? Is there a Better Approach

Every SQL batch has to fit in the Batch Size Limit: 65,536 * Network Packet Size.

Other than that, your query is limited by runtime conditions. It will usually run out of stack size because x IN (a,b,c) is nothing but x=a OR x=b OR x=c which creates an expression tree similar to x=a OR (x=b OR (x=c)), so it gets very deep with a large number of OR. SQL 7 would hit a SO at about 10k values in the IN, but nowdays stacks are much deeper (because of x64), so it can go pretty deep.

Update

You already found Erland's article on the topic of passing lists/arrays to SQL Server. With SQL 2008 you also have Table Valued Parameters which allow you to pass an entire DataTable as a single table type parameter and join on it.

XML and XPath is another viable solution:

SELECT ...
FROM Table
JOIN (
   SELECT x.value(N'.',N'uniqueidentifier') as guid
   FROM @values.nodes(N'/guids/guid') t(x)) as guids
 ON Table.guid = guids.guid;

React - changing an uncontrolled input

Simple solution to resolve this problem is to set an empty value by default :

<input name='myInput' value={this.state.myInput || ''} onChange={this.handleChange} />

The program can't start because cygwin1.dll is missing... in Eclipse CDT

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

How to print a groupby object

If you're simply looking for a way to display it, you could use describe():

grp = df.groupby['colName']
grp.describe()

This gives you a neat table.

C# declare empty string array

If you must create an empty array you can do this:

string[] arr = new string[0];

If you don't know about the size then You may also use List<string> as well like

var valStrings = new List<string>();

// do stuff...

string[] arrStrings = valStrings.ToArray();

How to create a printable Twitter-Bootstrap page

In case someone is looking for a solution for Bootstrap v2.X.X here. I am leaving the solution I was using. This is not fully tested on all browsers however it could be a good start.

1) make sure the media attribute of bootstrap-responsive.css is screen.

<link href="/css/bootstrap-responsive.min.css" rel="stylesheet" media="screen" />

2) create a print.css and make sure its media attribute print

<link href="/css/print.css" rel="stylesheet" media="print" />

3) inside print.css, add the "width" of your website in html & body

html, 
body {
    width: 1200px !important;
}

4.) reproduce the necessary media query classes in print.css because they were inside bootstrap-responsive.css and we have disabled it when printing.

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

Here is full version of print.css:

html, 
body {
    width: 1200px !important;
}

.hidden{display:none;visibility:hidden}
.visible-phone{display:none!important}
.visible-tablet{display:none!important}
.hidden-desktop{display:none!important}
.visible-desktop{display:inherit!important}

Create a 3D matrix

Create a 3D matrix

A = zeros(20, 10, 3);   %# Creates a 20x10x3 matrix

Add a 3rd dimension to a matrix

B = zeros(4,4);  
C = zeros(size(B,1), size(B,2), 4);  %# New matrix with B's size, and 3rd dimension of size 4
C(:,:,1) = B;                        %# Copy the content of B into C's first set of values

zeros is just one way of making a new matrix. Another could be A(1:20,1:10,1:3) = 0 for a 3D matrix. To confirm the size of your matrices you can run: size(A) which gives 20 10 3.

There is no explicit bound on the number of dimensions a matrix may have.

How to determine device screen size category (small, normal, large, xlarge) using code?

Copy and paste this code into your Activity and when it is executed it will Toast the device's screen size category.

int screenSize = getResources().getConfiguration().screenLayout &
        Configuration.SCREENLAYOUT_SIZE_MASK;

String toastMsg;
switch(screenSize) {
    case Configuration.SCREENLAYOUT_SIZE_LARGE:
        toastMsg = "Large screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_NORMAL:
        toastMsg = "Normal screen";
        break;
    case Configuration.SCREENLAYOUT_SIZE_SMALL:
        toastMsg = "Small screen";
        break;
    default:
        toastMsg = "Screen size is neither large, normal or small";
}
Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();