Programs & Examples On #Weather api

Perform debounce in React.js

If all you need from the event object is to get the DOM input element, the solution is much simpler – just use ref. Note that this requires Underscore:

class Item extends React.Component {
    constructor(props) {
        super(props);
        this.saveTitle = _.throttle(this.saveTitle.bind(this), 1000);
    }
    saveTitle(){
        let val = this.inputTitle.value;
        // make the ajax call
    }
    render() {
        return <input 
                    ref={ el => this.inputTitle = el } 
                    type="text" 
                    defaultValue={this.props.title} 
                    onChange={this.saveTitle} />
    }
}

How to listen to the window scroll event in a VueJS component?

I think the best approach is just add ".passive"

v-on:scroll.passive='handleScroll'

Django: ImproperlyConfigured: The SECRET_KEY setting must not be empty

To throw another potential solution into the mix, I had a settings folder as well as a settings.py in my project dir. (I was switching back from environment-based settings files to one file. I have since reconsidered.)

Python was getting confused about whether I wanted to import project/settings.py or project/settings/__init__.py. I removed the settings dir and everything now works fine.

Using C# regular expressions to remove HTML tags

Add .+? in <[^>]*> and try this regex (base on this):

<[^>].+?>

c# .net regex demo enter image description here

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

Try use this:

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

Convert SVG to image (JPEG, PNG, etc.) in the browser

There are several ways to convert SVG to PNG using the Canvg library.

In my case, I needed to get the PNG blob from inline SVG.

The library documentation provides an example (see OffscreenCanvas example).

But this method does not work at the moment in Firefox. Yes, you can enable the gfx.offscreencanvas.enabled option in the settings. But will every user on the site do this? :)

However, there is another way that will work in Firefox too.

const el = document.getElementById("some-svg"); //this is our inline SVG

var canvas = document.createElement('canvas'); //create a canvas for the SVG render
canvas.width = el.clientWidth; //set canvas sizes
canvas.height = el.clientHeight;

const svg = new XMLSerializer().serializeToString(el); //convert SVG to string

//render SVG inside canvas
const ctx = canvas.getContext('2d');
const v = await Canvg.fromString(ctx, svg);
await v.render();

let canvasBlob = await new Promise(resolve => canvas.toBlob(resolve));

For the last line thanks to this answer

C# send a simple SSH command

For .Net core i had many problems using SSH.net and also its deprecated. I tried a few other libraries, even for other programming languages. But i found a very good alternative. https://stackoverflow.com/a/64443701/8529170

angularjs - using {{}} binding inside ng-src but ng-src doesn't load

Changing the ng-src value is actually very simple. Like this:

<html ng-app>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.min.js"></script>
</head>
<body>
<img ng-src="{{img_url}}">
<button ng-click="img_url = 'https://farm4.staticflickr.com/3261/2801924702_ffbdeda927_d.jpg'">Click</button>
</body>
</html>

Here is a jsFiddle of a working example: http://jsfiddle.net/Hx7B9/2/

How do I sort a table in Excel if it has cell references in it?

Best way is to keep your reference data on one side of the sheet and all the formulas on the other side of the sheet. then leave a blank column between them (hide it if you want) an then you'll be sorting only the reference data keeping the Formula references pointing always at the same place. Downside is Excel will recalc everytime you sort.

how can I connect to a remote mongo server from Mac OS terminal

You are probably connecting fine but don't have sufficient privileges to run show dbs.

You don't need to run the db.auth if you pass the auth in the command line:

mongo somewhere.mongolayer.com:10011/my_database -u username -p password

Once you connect are you able to see collections?

> show collections

If so all is well and you just don't have admin privileges to the database and can't run the show dbs

Each GROUP BY expression must contain at least one column that is not an outer reference

To start with you can't do this:

having rid!=MAX(rid)

The HAVING clause can only contain things which are attributes of the aggregate groups.

In addition, 1, 2, 3 is not valid in GROUP BY in SQL Server - I think that's only valid in ORDER BY.

Can you explain why this isn't what you are looking for:

select 
LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound,
MAX(qvalues.rid)
 from batchinfo join qvalues on batchinfo.rowid=qvalues.rowid
where LEN(datapath)>4
group by LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound

Render Content Dynamically from an array map function in React Native

Try moving the lapsList function out of your class and into your render function:

render() {
  const lapsList = this.state.laps.map((data) => {
    return (
      <View><Text>{data.time}</Text></View>
    )
  })

  return (
    <View style={styles.container}>
      <View style={styles.footer}>
        <View><Text>coucou test</Text></View>
        {lapsList}
      </View>
    </View>
  )
}

Extension gd is missing from your system - laravel composer Update

For php 7.1

sudo apt-get install php7.1-gd

Cheers!

How to use goto statement correctly

Java also does not use line numbers, which is a necessity for a GOTO function. Unlike C/C++, Java does not have goto statement, but java supports label. The only place where a label is useful in Java is right before nested loop statements. We can specify label name with break to break out a specific outer loop.

How to create a hex dump of file containing only the hex characters without spaces in bash?

Format strings can make hexdump behave exactly as you want it to (no whitespace at all, byte by byte):

hexdump -ve '1/1 "%.2x"'

1/1 means "each format is applied once and takes one byte", and "%.2x" is the actual format string, like in printf. In this case: 2-character hexadecimal number, leading zeros if shorter.

Changing every value in a hash in Ruby

The best way to modify a Hash's values in place is

hash.update(hash){ |_,v| "%#{v}%" }

Less code and clear intent. Also faster because no new objects are allocated beyond the values that must be changed.

select certain columns of a data table

You can create a method that looks like this:

  public static DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2)
    {
        DataTable TempTable = RecordDT_;

        System.Data.DataView view = new System.Data.DataView(TempTable);
        System.Data.DataTable selected = view.ToTable("Selected", false, col1, col2);
        return selected;
    }

You can return as many columns as possible.. just add the columns as call parameters as shown below:

public DataTable SelectedColumns(DataTable RecordDT_, string col1, string col2,string col3,...)

and also add the parameters to this line:

System.Data.DataTable selected = view.ToTable("Selected", false,col1, col2,col3,...);

Then simply implement the function as:

 DataTable myselectedColumnTable=SelectedColumns(OriginalTable,"Col1","Col2",...);

Thanks...

Uncaught TypeError : cannot read property 'replace' of undefined In Grid

It could be because of the property pageable -> pageSizes: true.

Remove this and check again.

Decoding base64 in batch

Actually Windows does have a utility that encodes and decodes base64 - CERTUTIL

I'm not sure what version of Windows introduced this command.

To encode a file:

certutil -encode inputFileName encodedOutputFileName

To decode a file:

certutil -decode encodedInputFileName decodedOutputFileName

There are a number of available verbs and options available to CERTUTIL.

To get a list of nearly all available verbs:

certutil -?

To get help on a particular verb (-encode for example):

certutil -encode -?

To get complete help for nearly all verbs:

certutil -v -?

Mysteriously, the -encodehex verb is not listed with certutil -? or certutil -v -?. But it is described using certutil -encodehex -?. It is another handy function :-)

Update

Regarding David Morales' comment, there is a poorly documented type option to the -encodehex verb that allows creation of base64 strings without header or footer lines.

certutil [Options] -encodehex inFile outFile [type]

A type of 1 will yield base64 without the header or footer lines.

See https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p56536 for a brief listing of the available type formats. And for a more in depth look at the available formats, see https://www.dostips.com/forum/viewtopic.php?f=3&t=8521#p57918.

Not investigated, but the -decodehex verb also has an optional trailing type argument.

Android studio doesn't list my phone under "Choose Device"

I solved the problem like that: go to Run and Select Clean and Rerun.

Implicit type conversion rules in C++ operators

My solution to the problem got WA(wrong answer), then i changed one of int to long long int and it gave AC(accept). Previously, I was trying to do long long int += int * int, and after I rectify it to long long int += long long int * int. Googling I came up with,

1. Arithmetic Conversions

Conditions for Type Conversion:

Conditions Met ---> Conversion

  • Either operand is of type long double. ---> Other operand is converted to type long double.

  • Preceding condition not met and either operand is of type double. ---> Other operand is converted to type double.

  • Preceding conditions not met and either operand is of type float. ---> Other operand is converted to type float.

  • Preceding conditions not met (none of the operands are of floating types). ---> Integral promotions are performed on the operands as follows:

    • If either operand is of type unsigned long, the other operand is converted to type unsigned long.
    • If preceding condition not met, and if either operand is of type long and the other of type unsigned int, both operands are converted to type unsigned long.
    • If the preceding two conditions are not met, and if either operand is of type long, t he other operand is converted to type long.
    • If the preceding three conditions are not met, and if either operand is of type unsigned int, the other operand is converted to type unsigned int.
    • If none of the preceding conditions are met, both operands are converted to type int.

2 . Integer conversion rules

  • Integer Promotions:

Integer types smaller than int are promoted when an operation is performed on them. If all values of the original type can be represented as an int, the value of the smaller type is converted to an int; otherwise, it is converted to an unsigned int. Integer promotions are applied as part of the usual arithmetic conversions to certain argument expressions; operands of the unary +, -, and ~ operators; and operands of the shift operators.

  • Integer Conversion Rank:

    • No two signed integer types shall have the same rank, even if they have the same representation.
    • The rank of a signed integer type shall be greater than the rank of any signed integer type with less precision.
    • The rank of long long int shall be greater than the rank of long int, which shall be greater than the rank of int, which shall be greater than the rank of short int, which shall be greater than the rank of signed char.
    • The rank of any unsigned integer type shall equal the rank of the corresponding signed integer type, if any.
    • The rank of any standard integer type shall be greater than the rank of any extended integer type with the same width.
    • The rank of char shall equal the rank of signed char and unsigned char.
    • The rank of any extended signed integer type relative to another extended signed integer type with the same precision is implementation-defined but still subject to the other rules for determining the integer conversion rank.
    • For all integer types T1, T2, and T3, if T1 has greater rank than T2 and T2 has greater rank than T3, then T1 has greater rank than T3.
  • Usual Arithmetic Conversions:

    • If both operands have the same type, no further conversion is needed.
    • If both operands are of the same integer type (signed or unsigned), the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
    • If the operand that has unsigned integer type has rank greater than or equal to the rank of the type of the other operand, the operand with signed integer type is converted to the type of the operand with unsigned integer type.
    • If the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, the operand with unsigned integer type is converted to the type of the operand with signed integer type.
    • Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type. Specific operations can add to or modify the semantics of the usual arithmetic operations.

Creating default object from empty value in PHP?

If you put "@" character begin of the line then PHP doesn't show any warning/notice for this line. For example:

$unknownVar[$someStringVariable]->totalcall = 10; // shows a warning message that contains: Creating default object from empty value

For preventing this warning for this line you must put "@" character begin of the line like this:

@$unknownVar[$someStringVariable]->totalcall += 10; // no problem. created a stdClass object that name is $unknownVar[$someStringVariable] and created a properti that name is totalcall, and it's default value is 0.
$unknownVar[$someStringVariable]->totalcall += 10; // you don't need to @ character anymore.
echo $unknownVar[$someStringVariable]->totalcall; // 20

I'm using this trick when developing. I don't like disable all warning messages becouse if you don't handle warnings correctly then they will become a big error in future.

Getting an error "fopen': This function or variable may be unsafe." when compling

This is a warning for usual. You can either disable it by

#pragma warning(disable:4996)

or simply use fopen_s like Microsoft has intended.

But be sure to use the pragma before other headers.

How to open the terminal in Atom?

  1. Open your Atom IDE
  2. press ctrl+shift+P and search for "platformio-ide-terminal" package
  3. press install
  4. once installed press ctrl+~ (tilde above tab key in a standard keyboard)
  5. terminal opens enjoy!!!

Swift error : signal SIGABRT how to solve it

A common reason for this type of error is that you might have changed the name of your IBOutlet or IBAction you can simply check this by going to source code.

Click on the main.storyboard and then select open as and then select source code enter image description here

source code will open

and then check whether there is the name of the iboutlet or ibaction that you have changed , if there is then select the part and delete it and then again create iboutlet or ibaction. This should resolve your problem

Is there a way to link someone to a YouTube Video in HD 1080p quality?

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

How can I get the latest JRE / JDK as a zip file rather than EXE or MSI installer?

The Process described by Igor and CharlesB Works to me, since IDE's like NetBeans and Eclipse permit specify the location of the JDK, even software like Apache Tomcat (the ZIP Distribution) use BASH - FILES to set it up (then specify the JDK location using relatives URI).
I Have a USB-HardDisk With NetBeans, Eclipse, Apache Tomcat working with a JDK in "portable mode".
I Had a way to extract a copy of the JDK from the installers files: Install it, Copy it in other place and then uninstall it. A dirty way to extract it, but was successfull.
The place to put EXTRA - LIBS was: %PLACE_WHERE_JDK_ARE%\jre\lib\ext

I am receiving warning in Facebook Application using PHP SDK

You need to ensure that any code that modifies the HTTP headers is executed before the headers are sent. This includes statements like session_start(). The headers will be sent automatically when any HTML is output.

Your problem here is that you're sending the HTML ouput at the top of your page before you've executed any PHP at all.

Move the session_start() to the top of your document :

<?php    session_start(); ?> <html> <head> <title>PHP SDK</title> </head> <body> <?php require_once 'src/facebook.php';    // more PHP code here. 

How to add jQuery code into HTML Page

Before the closing body tag add this (reference to jQuery library). Other hosted libraries can be found here

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

And this

<script>
  //paste your code here
</script>

It should look something like this

<body>
 ........
 ........
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
 <script> Your code </script>
</body>

How to customize the back button on ActionBar

I have checked the question. Here is the steps that I follow. The source code is hosted on GitHub: https://github.com/jiahaoliuliu/sherlockActionBarLab

Override the actual style for the pre-v11 devices.

Copy and paste the follow code in the file styles.xml of the default values folder.

<resources>
    <style name="MyCustomTheme" parent="Theme.Sherlock.Light">
    <item name="homeAsUpIndicator">@drawable/ic_home_up</item>
    </style>
</resources>

Note that the parent could be changed to any Sherlock theme.

Override the actual style for the v11+ devices.

On the same folder where the folder values is, create a new folder called values-v11. Android will automatically look for the content of this folder for devices with API or above.

Create a new file called styles.xml and paste the follow code into the file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyCustomTheme" parent="Theme.Sherlock.Light">
    <item name="android:homeAsUpIndicator">@drawable/ic_home_up</item>
    </style>
</resources>

Note tha the name of the style must be the same as the file in the default values folder and instead of the item homeAsUpIndicator, it is called android:homeAsUpIndicator.

The item issue is because for devices with API 11 or above, Sherlock Action Bar use the default Action Bar which comes with Android, which the key name is android:homeAsUpIndicator. But for the devices with API 10 or lower, Sherlock Action Bar uses its own ActionBar, which the home as up indicator is called simple "homeAsUpIndicator".

Use the new theme in the manifest

Replace the theme for the application/activity in the AndroidManifest file:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/MyCustomTheme" >

.NET obfuscation tools/strategy

I've recently tried piping the output of one free obfuscator into the another free obfuscator - namely Dotfuscator CE and the new Babel obfuscator on CodePlex. More details on my blog.

As for serialization, I've moved that code into a different DLL and included that in the project. I reasoned that there weren't any secrets in there that aren't in the XML anyway, so it didn't need obfuscation. If there is any serious code in those classes, using partial classes in the main assembly should cover it.

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

What is the Swift equivalent of isEqualToString in Objective-C?

In Swift, the == operator is equivalent to Objective C's isEqual: method (it calls the isEqual method instead of just comparing pointers, and there's a new === method for testing that the pointers are the same), so you can just write this as:

if username == "" || password == ""
{
    println("Sign in failed. Empty character")
}

Move column by name to front of table in pandas

Maybe I'm missing something, but a lot of these answers seem overly complicated. You should be able to just set the columns within a single list:

Column to the front:

df = df[ ['Mid'] + [ col for col in df.columns if col != 'Mid' ] ]

Or if instead, you want to move it to the back:

df = df[ [ col for col in df.columns if col != 'Mid' ] + ['Mid'] ]

Or if you wanted to move more than one column:

cols_to_move = ['Mid', 'Zsore']
df           = df[ cols_to_move + [ col for col in df.columns if col not in cols_to_move ] ]

Query a parameter (postgresql.conf setting) like "max_connections"

You can use SHOW:

SHOW max_connections;

This returns the currently effective setting. Be aware that it can differ from the setting in postgresql.conf as there are a multiple ways to set run-time parameters in PostgreSQL. To reset the "original" setting from postgresql.conf in your current session:

RESET max_connections;

However, not applicable to this particular setting. The manual:

This parameter can only be set at server start.

To see all settings:

SHOW ALL;

There is also pg_settings:

The view pg_settings provides access to run-time parameters of the server. It is essentially an alternative interface to the SHOW and SET commands. It also provides access to some facts about each parameter that are not directly available from SHOW, such as minimum and maximum values.

For your original request:

SELECT *
FROM   pg_settings
WHERE  name = 'max_connections';

Finally, there is current_setting(), which can be nested in DML statements:

SELECT current_setting('max_connections');

Related:

PHP is not recognized as an internal or external command in command prompt

You need to Go to My Computer->properties -> Advanced system setting

Now click on Environment Variables..

enter image description here

Add ;C:\xampp\php in path variable value

enter image description here

Now restart command prompt DONE!

Note: Make sure you run CMD via run as administrator

Image vs Bitmap class

This is a clarification because I have seen things done in code which are honestly confusing - I think the following example might assist others.

As others have said before - Bitmap inherits from the Abstract Image class

Abstract effectively means you cannot create a New() instance of it.

    Image imgBad1 = new Image();        // Bad - won't compile
    Image imgBad2 = new Image(200,200); // Bad - won't compile

But you can do the following:

    Image imgGood;  // Not instantiated object!
    // Now you can do this
    imgGood = new Bitmap(200, 200);

You can now use imgGood as you would the same bitmap object if you had done the following:

    Bitmap bmpGood = new Bitmap(200,200);

The nice thing here is you can draw the imgGood object using a Graphics object

    Graphics gr = default(Graphics);
    gr = Graphics.FromImage(new Bitmap(1000, 1000));
    Rectangle rect = new Rectangle(50, 50, imgGood.Width, imgGood.Height); // where to draw
    gr.DrawImage(imgGood, rect);

Here imgGood can be any Image object - Bitmap, Metafile, or anything else that inherits from Image!

Changing navigation title programmatically

Swift 5.1

// Set NavigationBar Title Programmatically and Dynamic

Note : First add NavigationControllerItem to Your ViewController then goto their ViewController.swift file and Just Copy and Paste this in viewDidLoad().

navigationItem.title = "Your Title Here"

Curl and PHP - how can I pass a json through curl by PUT,POST,GET

PUT

$data = array('username'=>'dog','password'=>'tall');
$data_json = json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json','Content-Length: ' . strlen($data_json)));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

POST

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

GET See @Dan H answer

DELETE

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_POSTFIELDS,$data_json);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response  = curl_exec($ch);
curl_close($ch);

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

Make sure you import csv file using Pandas

import pandas as pd

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

MySQL date formats - difficulty Inserting a date

Put the date in single quotes and move the parenthesis (after the 'yes') to the end:

INSERT INTO custorder 
  VALUES ('Kevin', 'yes' , STR_TO_DATE('1-01-2012', '%d-%m-%Y') ) ;
                        ^                                     ^
---parenthesis removed--|                and added here ------|

But you can always use dates without STR_TO_DATE() function, just use the (Y-m-d) '20120101' or '2012-01-01' format. Check the MySQL docs: Date and Time Literals

INSERT INTO custorder 
  VALUES ('Kevin', 'yes', '2012-01-01') ;

How to show a running progress bar while page is loading

I have copied the relevant code below from This page. Hope this might help you.

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
        console.log(percentComplete);
      }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
        console.log(percentComplete);
      }
    }, false);
    return xhr;
  },
  type: 'POST',
  url: "/",
  data: {},
  success: function(data) {
    //Do something success-ish
  }
});

How to add onload event to a div element

Try this! And never use trigger twice on div!

You can define function to call before the div tag.

$(function(){
    $('div[onload]').trigger('onload');
});

DEMO: jsfiddle

How can I set Image source with base64

Try using setAttribute instead:

document.getElementById('img')
    .setAttribute(
        'src', 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='
    );

Real answer: (And make sure you remove the line-breaks in the base64.)

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

How to create an Observable from static data similar to http one in Angular?

As of July 2018 and the release of RxJS 6, the new way to get an Observable from a value is to import the of operator like so:

import { of } from 'rxjs';

and then create the observable from the value, like so:

of(someValue);

Note, that you used to have to do Observable.of(someValue) like in the currently accepted answer. There is a good article on the other RxJS 6 changes here.

ALTER TABLE ADD COLUMN IF NOT EXISTS in SQLite

You can alternatively use the CASE-WHEN TSQL statement in combination with pragma_table_info to know if a column exists:

select case(CNT) 
    WHEN 0 then printf('not found')
    WHEN 1 then printf('found')
    END
FROM (SELECT COUNT(*) AS CNT FROM pragma_table_info('myTableName') WHERE name='columnToCheck') 

How can I create a two dimensional array in JavaScript?

var _field = (function()
{
    var array = [];
    for(var y = 0; y != 3; y++) { array[y] = new Array(5); }
    return array;
})();

// var item = _field[2][4];

A python class that acts like dict

A python class that acts like dict

By request - adding slots to a dict subclass.

Why add slots? A builtin dict instance doesn't have arbitrary attributes:

>>> d = dict()
>>> d.foo = 'bar'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'dict' object has no attribute 'foo'

If we create a subclass the way most are doing it here on this answer, we see we don't get the same behavior, because we'll have a __dict__ attribute, causing our dicts to take up to potentially twice the space:

my_dict(dict):
    """my subclass of dict""" 

md = my_dict()
md.foo = 'bar'

Since there's no error created by the above, the above class doesn't actually act, "like dict."

We can make it act like dict by giving it empty slots:

class my_dict(dict):
    __slots__ = ()

md = my_dict()

So now attempting to use arbitrary attributes will fail:

>>> md.foo = 'bar'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'my_dict' object has no attribute 'foo'

And this Python class acts more like a dict.

For more on how and why to use slots, see this Q&A: Usage of __slots__?

Select second last element with css

In CSS3 you have:

:nth-last-child(2)

See: https://developer.mozilla.org/en-US/docs/Web/CSS/:nth-last-child

nth-last-child Browser Support:

  • Chrome 2
  • Firefox 3.5
  • Opera 9.5, 10
  • Safari 3.1, 4
  • Internet Explorer 9

Combining COUNT IF AND VLOOK UP EXCEL

You can combine this all into one formula, but you need to use a regular IF first to find out if the VLOOKUP came back with something, then use your COUNTIF if it did.

=IF(ISERROR(VLOOKUP(B1,Sheet2!A1:A9,1,FALSE)),"Not there",COUNTIF(Sheet2!A1:A9,B1))

In this case, Sheet2-A1:A9 is the range I was searching, and Sheet1-B1 had the value I was looking for ("To retire" in your case).

apache ProxyPass: how to preserve original IP address

The answer of JasonW is fine. But since apache httpd 2.4.6 there is a alternative: mod_remoteip

All what you must do is:

  1. May be you must install the mod_remoteip package
  2. Enable the module:

    LoadModule remoteip_module modules/mod_remoteip.so
    
  3. Add the following to your apache httpd config. Note that you must add this line not into the configuration of the proxy server. You must add this to the configuration of the proxy target httpd server (the server behind the proxy):

    RemoteIPHeader X-Forwarded-For
    

See at http://httpd.apache.org/docs/trunk/mod/mod_remoteip.html for more informations and more options.

How to serve static files in Flask

By default folder named "static" contains all static files Here's code sample:

_x000D_
_x000D_
<link href="{{ url_for('static', filename='vendor/bootstrap/css/bootstrap.min.css') }}" rel="stylesheet">
_x000D_
_x000D_
_x000D_

What's an Aggregate Root?

In another world, in Event Sourcing, an Aggregate(Root) is a different concept. Event Sourcing might be encountered together with CQRS, DDD etc.

In Event Sourcing an Aggregate is an object for which the state (fields) is not mapped to a record in a database as we are used to think in SQL/JPA world.

Is not a group of related entities.

It is a group of related records like in a history table.

GiftCard.amount is one field in a GiftCard Aggregate, but this field is mapped to all the events, like card-redeemed (take money from the card) ever created.

So the source of data for your Aggregate is not a record in a database but the complete list of events ever created for that specific aggregate. We say we event sourced the aggregate.

Now we can ask ourselves how is it done? Who is aggregating these events so we are operating still with one field e.g GiftCard.amount? We might be expecting that amount to be a Collection and not a big-decimal type.

Is the event sourcing engine, doing the work, who might simply replay all the events in the creation order. But this is out of the scope for this thread.

How to convert a single char into an int

#include<iostream>
#include<stdlib>
using namespace std;

void main()
{
     char ch;
     int x;
     cin >> ch;
     x = char (ar[1]);
     cout << x;
}

Hibernate: ids for this class must be manually assigned before calling save()

your id attribute is not set. this MAY be due to the fact that the DB field is not set to auto increment? what DB are you using? MySQL? is your field set to AUTO INCREMENT?

How to find sum of multiple columns in a table in SQL Server 2005?

SELECT Emp_cd, Val1, Val2, Val3, SUM(Val1 + Val2 + Val3) AS TOTAL 
FROM Emp
GROUP BY Emp_cd, Val1, Val2, Val3

How do I install Composer on a shared hosting?

SIMPLE SOLUTION (tested on Red Hat):

run command: curl -sS https://getcomposer.org/installer | php

to use it: php composer.phar

SYSTEM WIDE SOLLUTION (tested on Red Hat):

run command: mv composer.phar /usr/local/bin/composer

to use it: composer update

now you can call composer from any directory.

Source: http://www.agix.com.au/install-composer-on-centosredhat/

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

What others have posted about running the function repeatedly in a loop is correct.

For Linux (and BSD) you want to use clock_gettime().

#include <sys/time.h>

int main()
{
   timespec ts;
   // clock_gettime(CLOCK_MONOTONIC, &ts); // Works on FreeBSD
   clock_gettime(CLOCK_REALTIME, &ts); // Works on Linux
}

For windows you want to use the QueryPerformanceCounter. And here is more on QPC

Apparently there is a known issue with QPC on some chipsets, so you may want to make sure you do not have those chipset. Additionally some dual core AMDs may also cause a problem. See the second post by sebbbi, where he states:

QueryPerformanceCounter() and QueryPerformanceFrequency() offer a bit better resolution, but have different issues. For example in Windows XP, all AMD Athlon X2 dual core CPUs return the PC of either of the cores "randomly" (the PC sometimes jumps a bit backwards), unless you specially install AMD dual core driver package to fix the issue. We haven't noticed any other dual+ core CPUs having similar issues (p4 dual, p4 ht, core2 dual, core2 quad, phenom quad).

EDIT 2013/07/16:

It looks like there is some controversy on the efficacy of QPC under certain circumstances as stated in http://msdn.microsoft.com/en-us/library/windows/desktop/ee417693(v=vs.85).aspx

...While QueryPerformanceCounter and QueryPerformanceFrequency typically adjust for multiple processors, bugs in the BIOS or drivers may result in these routines returning different values as the thread moves from one processor to another...

However this StackOverflow answer https://stackoverflow.com/a/4588605/34329 states that QPC should work fine on any MS OS after Win XP service pack 2.

This article shows that Windows 7 can determine if the processor(s) have an invariant TSC and falls back to an external timer if they don't. http://performancebydesign.blogspot.com/2012/03/high-resolution-clocks-and-timers-for.html Synchronizing across processors is still an issue.

Other fine reading related to timers:

See the comments for more details.

C++ floating point to integer type conversions

What you are looking for is 'type casting'. typecasting (putting the type you know you want in brackets) tells the compiler you know what you are doing and are cool with it. The old way that is inherited from C is as follows.

float var_a = 9.99;
int   var_b = (int)var_a;

If you had only tried to write

int var_b = var_a;

You would have got a warning that you can't implicitly (automatically) convert a float to an int, as you lose the decimal.

This is referred to as the old way as C++ offers a superior alternative, 'static cast'; this provides a much safer way of converting from one type to another. The equivalent method would be (and the way you should do it)

float var_x = 9.99;
int   var_y = static_cast<int>(var_x);

This method may look a bit more long winded, but it provides much better handling for situations such as accidentally requesting a 'static cast' on a type that cannot be converted. For more information on the why you should be using static cast, see this question.

Stop fixed position at footer

This worked for me -

HTML -

<div id="sideNote" class="col-sm-3" style="float:right;">

</div> 
<div class="footer-wrap">
        <div id="footer-div">
        </div>      
</div>

CSS -

#sideNote{right:0; margin-top:10px; position:fixed; bottom:0; margin-bottom:5px;}

#footer-div{margin:0 auto; text-align:center; min-height:300px; margin-top:100px; padding:100px 50px;}

JQuery -

function isVisible(elment) {
    var vpH = $(window).height(), // Viewport Height
        st = $(window).scrollTop(), // Scroll Top
        y = $(elment).offset().top;

    return y <= (vpH + st);
}

function setSideNotePos(){
    $(window).scroll(function() {
        if (isVisible($('.footer-wrap'))) {
            $('#sideNote').css('position','absolute');
            $('#sideNote').css('top',$('.footer-wrap').offset().top - $('#sideNote').outerHeight() - 100);
        } else {
            $('#sideNote').css('position','fixed');
            $('#sideNote').css('top','auto');
        }
    });
}

Now call this function like this -

$(document).ready(function() {
    setSideNotePos();
});

PS - The Jquery functions are copied from an answer to another similar question on stackoverflow, but it wasn't working for me fully. So I modified it to these functions, as they are shown here. I think the position etc attributes to your divs will depend on how the divs are structured, who their parents and siblings are.

The above function works when both sideNote and footer-wraps are direct siblings.

Swift: Reload a View Controller

View Life Cycle

it will load ViewWillAppear everytime you open the view. above is the link to the picture View Controller Lifecycle.

viewWillAppear()—Called just before the view controller’s content view is added to the app’s view hierarchy. Use this method to trigger any operations that need to occur before the content view is presented onscreen. Despite the name, just because the system calls this method, it does not guarantee that the content view will become visible. The view may be obscured by other views or hidden. This method simply indicates that the content view is about to be added to the app’s view hierarchy.

https://developer.apple.com/library/archive/referencelibrary/GettingStarted/DevelopiOSAppsSwift/WorkWithViewControllers.html

List passed by ref - help me explain this behaviour

This link will help you in understanding pass by reference in C#. Basically,when an object of reference type is passed by value to an method, only methods which are available on that object can modify the contents of object.

For example List.sort() method changes List contents but if you assign some other object to same variable, that assignment is local to that method. That is why myList remains unchanged.

If we pass object of reference type by using ref keyword then we can assign some other object to same variable and that changes entire object itself.

(Edit: this is the updated version of the documentation linked above.)

How to select true/false based on column value?

You can try something like

SELECT  e.EntityId, 
        e.EntityName, 
        CASE 
            WHEN ep.EntityId IS NULL THEN 'False' 
            ELSE 'TRUE' 
        END AS HasProfile 
FROM    Entities e LEFT JOIN 
        EntityProfiles ep ON e.EntityID = ep.EntityID

Or

SELECT e.EntityId, 
        e.EntityName, 
        CASE 
            WHEN e.EntityProfile IS NULL THEN 'False' 
            ELSE 'TRUE' 
        END AS HasProfile 

FROM    Entities e

How to make an inline-block element fill the remainder of the line?

I've used flex-grow property to achieve this goal. You'll have to set display: flex for parent container, then you need to set flex-grow: 1 for the block you want to fill remaining space, or just flex: 1 as tanius mentioned in the comments.

No 'Access-Control-Allow-Origin' header in Angular 2 app

Unfortunately, that's not an Angular2 error, that's an error your browser is running into (i.e. outside of your app).

That CORS header will have to be added to that endpoint on the server before you can make ANY requests.

How to manually set an authenticated user in Spring Security / SpringMVC

The new filtering feature in Servlet 2.4 basically alleviates the restriction that filters can only operate in the request flow before and after the actual request processing by the application server. Instead, Servlet 2.4 filters can now interact with the request dispatcher at every dispatch point. This means that when a Web resource forwards a request to another resource (for instance, a servlet forwarding the request to a JSP page in the same application), a filter can be operating before the request is handled by the targeted resource. It also means that should a Web resource include the output or function from other Web resources (for instance, a JSP page including the output from multiple other JSP pages), Servlet 2.4 filters can work before and after each of the included resources. .

To turn on that feature you need:

web.xml

<filter>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class> 
</filter>  
<filter-mapping>   
    <filter-name>springSecurityFilterChain</filter-name>   
    <url-pattern>/<strike>*</strike></url-pattern>
    <dispatcher>REQUEST</dispatcher>
    <dispatcher>FORWARD</dispatcher>
</filter-mapping>

RegistrationController

return "forward:/login?j_username=" + registrationModel.getUserEmail()
        + "&j_password=" + registrationModel.getPassword();

round() doesn't seem to be rounding properly

The problem is only when last digit is 5. Eg. 0.045 is internally stored as 0.044999999999999... You could simply increment last digit to 6 and round off. This will give you the desired results.

import re


def custom_round(num, precision=0):
    # Get the type of given number
    type_num = type(num)
    # If the given type is not a valid number type, raise TypeError
    if type_num not in [int, float, Decimal]:
        raise TypeError("type {} doesn't define __round__ method".format(type_num.__name__))
    # If passed number is int, there is no rounding off.
    if type_num == int:
        return num
    # Convert number to string.
    str_num = str(num).lower()
    # We will remove negative context from the number and add it back in the end
    negative_number = False
    if num < 0:
        negative_number = True
        str_num = str_num[1:]
    # If number is in format 1e-12 or 2e+13, we have to convert it to
    # to a string in standard decimal notation.
    if 'e-' in str_num:
        # For 1.23e-7, e_power = 7
        e_power = int(re.findall('e-[0-9]+', str_num)[0][2:])
        # For 1.23e-7, number = 123
        number = ''.join(str_num.split('e-')[0].split('.'))
        zeros = ''
        # Number of zeros = e_power - 1 = 6
        for i in range(e_power - 1):
            zeros = zeros + '0'
        # Scientific notation 1.23e-7 in regular decimal = 0.000000123
        str_num = '0.' + zeros + number
    if 'e+' in str_num:
        # For 1.23e+7, e_power = 7
        e_power = int(re.findall('e\+[0-9]+', str_num)[0][2:])
        # For 1.23e+7, number_characteristic = 1
        # characteristic is number left of decimal point.
        number_characteristic = str_num.split('e+')[0].split('.')[0]
        # For 1.23e+7, number_mantissa = 23
        # mantissa is number right of decimal point.
        number_mantissa = str_num.split('e+')[0].split('.')[1]
        # For 1.23e+7, number = 123
        number = number_characteristic + number_mantissa
        zeros = ''
        # Eg: for this condition = 1.23e+7
        if e_power >= len(number_mantissa):
            # Number of zeros = e_power - mantissa length = 5
            for i in range(e_power - len(number_mantissa)):
                zeros = zeros + '0'
            # Scientific notation 1.23e+7 in regular decimal = 12300000.0
            str_num = number + zeros + '.0'
        # Eg: for this condition = 1.23e+1
        if e_power < len(number_mantissa):
            # In this case, we only need to shift the decimal e_power digits to the right
            # So we just copy the digits from mantissa to characteristic and then remove
            # them from mantissa.
            for i in range(e_power):
                number_characteristic = number_characteristic + number_mantissa[i]
            number_mantissa = number_mantissa[i:]
            # Scientific notation 1.23e+1 in regular decimal = 12.3
            str_num = number_characteristic + '.' + number_mantissa
    # characteristic is number left of decimal point.
    characteristic_part = str_num.split('.')[0]
    # mantissa is number right of decimal point.
    mantissa_part = str_num.split('.')[1]
    # If number is supposed to be rounded to whole number,
    # check first decimal digit. If more than 5, return
    # characteristic + 1 else return characteristic
    if precision == 0:
        if mantissa_part and int(mantissa_part[0]) >= 5:
            return type_num(int(characteristic_part) + 1)
        return type_num(characteristic_part)
    # Get the precision of the given number.
    num_precision = len(mantissa_part)
    # Rounding off is done only if number precision is
    # greater than requested precision
    if num_precision <= precision:
        return num
    # Replace the last '5' with 6 so that rounding off returns desired results
    if str_num[-1] == '5':
        str_num = re.sub('5$', '6', str_num)
    result = round(type_num(str_num), precision)
    # If the number was negative, add negative context back
    if negative_number:
        result = result * -1
    return result

JQuery datepicker language

Include js files of datepicker and language (locales)

'resource/bower_components/bootstrap-datepicker/dist/js/bootstrap-datepicker.min.js',
'resource/bower_components/bootstrap-datepicker/dist/locales/bootstrap-datepicker.sv.min.js',

In the options of the datepicker, set the language as below:

$('.datepicker').datepicker({'language' : 'sv'});

Removing a non empty directory programmatically in C or C++

The easiest way to do this is with remove_all function of the Boost.Filesystem library. Besides, the resulting code will be portable.

If you want to write something specific for Unix (rmdir) or for Windows (RemoveDirectory) then you'll have to write a function that deletes are subfiles and subfolders recursively.

EDIT

Looks like this question was already asked, in fact someone already recommended Boost's remove_all. So please don't upvote my answer.

No serializer found for class org.hibernate.proxy.pojo.javassist.Javassist?

Or you could configure mapper as :

// custom configuration for lazy loading

public static class HibernateLazyInitializerSerializer extends JsonSerializer<JavassistLazyInitializer> {

    @Override
    public void serialize(JavassistLazyInitializer initializer, JsonGenerator jsonGenerator,
            SerializerProvider serializerProvider)
            throws IOException, JsonProcessingException {
        jsonGenerator.writeNull();
    }
}

and configure mapper:

    mapper = new JacksonMapper();
    SimpleModule simpleModule = new SimpleModule(
            "SimpleModule", new Version(1,0,0,null)
    );
    simpleModule.addSerializer(
            JavassistLazyInitializer.class,
            new HibernateLazyInitializerSerializer()
    );
    mapper.registerModule(simpleModule);

git - Server host key not cached

The message means that the host key of origin is not present in your trusted hosts file.

To get around this, open a plain SSH connection to origin and SSH will ask you if you want to trust the remote host (from the Git console):

$ ssh 127.0.0.1
The authenticity of host '127.0.0.1 (127.0.0.1)' can't be established.
RSA key fingerprint is <FINGERPRINT>.
Are you sure you want to continue connecting (yes/no)?

If you trust the remote host (i.e. type yes), SSH will add its key to the list of known hosts.

After that, you should be able to do your git push origin.

As an alternative, you could also manually add the key of origin to .ssh/known_hosts but this requires that you adhere to the format of the known_hosts file as described in the man page of sshd (Section AUTHORIZED_KEYS FILE FORMAT).

What's the difference between map() and flatMap() methods in Java 8?

This is very confusing for beginners. The basic difference is map emits one item for each entry in the list and flatMap is basically a map + flatten operation. To be more clear, use flatMap when you require more than one value, eg when you are expecting a loop to return arrays, flatMap will be really helpful in this case.

I have written a blog about this, you can check it out here.

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

enter image description here

How about just > Format only cells that contain - in the drop down box select Blanks

Draw in Canvas by finger, Android

I think it's important to add a thing, if you use the layout inflation that constructor in the drawview is not correct, add these constructors in the class:

public DrawingView(Context c, AttributeSet attrs) {
    super(c, attrs);
    ...
}

public DrawingView(Context c, AttributeSet attrs, int defStyle) {
    super(c, attrs, defStyle);
    ...
}

or the android system fails to inflate the layout file. I hope this could to help.

Changing CSS for last <li>

I usually combine CSS and JavaScript approaches, so that it works without JavaScript in all browsers but IE6/7, and in IE6/7 with JavaScript on (but not off), since they does not support the :last-child pseudo-class.

$("li:last-child").addClass("last-child");

li:last-child,li.last-child{ /* ... */ }

Check whether an array is empty

<?php
if(empty($myarray))
echo"true";
else
echo "false";
?>

Oracle: not a valid month

1.

To_Date(To_Char(MaxDate, 'DD/MM/YYYY')) = REP_DATE

is causing the issue. when you use to_date without the time format, oracle will use the current sessions NLS format to convert, which in your case might not be "DD/MM/YYYY". Check this...

SQL> select sysdate from dual;

SYSDATE
---------
26-SEP-12

Which means my session's setting is DD-Mon-YY

SQL> select to_char(sysdate,'MM/DD/YYYY') from dual;

TO_CHAR(SY
----------
09/26/2012


SQL> select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual;
select to_date(to_char(sysdate,'MM/DD/YYYY')) from dual
               *
ERROR at line 1:
ORA-01843: not a valid month

SQL> select to_date(to_char(sysdate,'MM/DD/YYYY'),'MM/DD/YYYY') from dual;

TO_DATE(T
---------
26-SEP-12

2.

More importantly, Why are you converting to char and then to date, instead of directly comparing

MaxDate = REP_DATE

If you want to ignore the time component in MaxDate before comparision, you should use..

trunc(MaxDate ) = rep_date

instead.

==Update : based on updated question.

Rep_Date = 01/04/2009 Rep_Time = 01/01/1753 13:00:00

I think the problem is more complex. if rep_time is intended to be only time, then you cannot store it in the database as a date. It would have to be a string or date to time interval or numerically as seconds (thanks to Alex, see this) . If possible, I would suggest using one column rep_date that has both the date and time and compare it to the max date column directly.

If it is a running system and you have no control over repdate, you could try this.

trunc(rep_date) = trunc(maxdate) and 
to_char(rep_date,'HH24:MI:SS') = to_char(maxdate,'HH24:MI:SS')

Either way, the time is being stored incorrectly (as you can tell from the year 1753) and there could be other issues going forward.

Setting up enviromental variables in Windows 10 to use java and javac

  • Right click Computer
  • Click the properties
  • On the left pane select Advanced System Settings
  • Select Environment Variables
  • Under the System Variables, Select PATH and click edit,
    and then click new and add path as C:\Program
    Files\Java\jdk1.8.0_131\bin
    (depending on your installation path)
    and finally click ok
  • Next restart your command prompt and open it and try javac

How to export data from Excel spreadsheet to Sql Server 2008 table

There are several tools which can import Excel to SQL Server.

I am using DbTransfer (http://www.dbtransfer.com/Products/DbTransfer) to do the job. It's primarily focused on transfering data between databases and excel, xml, etc...

I have tried the openrowset method and the SQL Server Import / Export Assitant before. But I found these methods to be unnecessary complicated and error prone in constrast to doing it with one of the available dedicated tools.

Get MD5 hash of big files in Python

Here's my version of @Piotr Czapla's method:

def md5sum(filename):
    md5 = hashlib.md5()
    with open(filename, 'rb') as f:
        for chunk in iter(lambda: f.read(128 * md5.block_size), b''):
            md5.update(chunk)
    return md5.hexdigest()

history.replaceState() example?

history.pushState pushes the current page state onto the history stack, and changes the URL in the address bar. So, when you go back, that state (the object you passed) are returned to you.

Currently, that is all it does. Any other page action, such as displaying the new page or changing the page title, must be done by you.

The W3C spec you link is just a draft, and browser may implement it differently. Firefox, for example, ignores the title parameter completely.

Here is a simple example of pushState that I use on my website.

(function($){
    // Use AJAX to load the page, and change the title
    function loadPage(sel, p){
        $(sel).load(p + ' #content', function(){
            document.title = $('#pageData').data('title');
        });
    }

    // When a link is clicked, use AJAX to load that page
    // but use pushState to change the URL bar
    $(document).on('click', 'a', function(e){
        e.preventDefault();
        history.pushState({page: this.href}, '', this.href);
        loadPage('#frontPage', this.href);
    });

    // This event is triggered when you visit a page in the history
    // like when yu push the "back" button
    $(window).on('popstate', function(e){
        loadPage('#frontPage', location.pathname);
        console.log(e.originalEvent.state);
    });
}(jQuery));

How to fix "ImportError: No module named ..." error in Python?

Here is a step-by-step solution:

  1. Add a script called run.py in /home/bodacydo/work/project and edit it like this:

    import programs.my_python_program
    programs.my_python_program.main()
    

    (replace main() with your equivalent method in my_python_program.)

  2. Go to /home/bodacydo/work/project
  3. Run run.py

Explanation: Since python appends to PYTHONPATH the path of the script from which it runs, running run.py will append /home/bodacydo/work/project. And voilà, import foo.tasks will be found.

Find location of a removable SD card

Environment.getExternalStorageState() returns path to internal SD mount point like "/mnt/sdcard"

No, Environment.getExternalStorageDirectory() refers to whatever the device manufacturer considered to be "external storage". On some devices, this is removable media, like an SD card. On some devices, this is a portion of on-device flash. Here, "external storage" means "the stuff accessible via USB Mass Storage mode when mounted on a host machine", at least for Android 1.x and 2.x.

But the question is about external SD. How to get a path like "/mnt/sdcard/external_sd" (it may differ from device to device)?

Android has no concept of "external SD", aside from external storage, as described above.

If a device manufacturer has elected to have external storage be on-board flash and also has an SD card, you will need to contact that manufacturer to determine whether or not you can use the SD card (not guaranteed) and what the rules are for using it, such as what path to use for it.


UPDATE

Two recent things of note:

First, on Android 4.4+, you do not have write access to removable media (e.g., "external SD"), except for any locations on that media that might be returned by getExternalFilesDirs() and getExternalCacheDirs(). See Dave Smith's excellent analysis of this, particularly if you want the low-level details.

Second, lest anyone quibble on whether or not removable media access is otherwise part of the Android SDK, here is Dianne Hackborn's assessment:

...keep in mind: until Android 4.4, the official Android platform has not supported SD cards at all except for two special cases: the old school storage layout where external storage is an SD card (which is still supported by the platform today), and a small feature added to Android 3.0 where it would scan additional SD cards and add them to the media provider and give apps read-only access to their files (which is also still supported in the platform today).

Android 4.4 is the first release of the platform that has actually allowed applications to use SD cards for storage. Any access to them prior to that was through private, unsupported APIs. We now have a quite rich API in the platform that allows applications to make use of SD cards in a supported way, in better ways than they have been able to before: they can make free use of their app-specific storage area without requiring any permissions in the app, and can access any other files on the SD card as long as they go through the file picker, again without needing any special permissions.

difference between width auto and width 100 percent

Width 100% : It will make content with 100%. margin, border, padding will be added to this width and element will overflow if any of these added.

Width auto : It will fit the element in available space including margin, border and padding. space remaining after adjusting margin + padding + border will be available width/ height.

Width 100% + box-sizing: border box : It will also fits the element in available space including border, padding (margin will make it overflow the container).

Define a global variable in a JavaScript function

If you are making a startup function, you can define global functions and variables this way:

function(globalScope)
{
    // Define something
    globalScope.something()
    {
        alert("It works");
    };
}(window)

Because the function is invoked globally with this argument, this is global scope here. So, the something should be a global thing.

How to check if array is not empty?

I can't comment yet, but it should be mentioned that if you use numpy array with more than one element this will fail:

if l:
    print "list has items"

elif not l:
    print "list is empty"

the error will be:

ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

How do you make a LinearLayout scrollable?

 <LinearLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        tools:context=".MainActivity">

        <ScrollView
            android:layout_width="match_parent"
            android:layout_height="match_parent">

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical">
                <---------Content Here --------------->
            </LinearLayout>
       </ScrollView>
    </LinearLayout>

Allow click on twitter bootstrap dropdown toggle link?

For those of you complaining about "the submenus don't drop down", I solved it this way, which looks clean to me:

1) Besides your

<a class="dropdown-toggle disabled" href="http://google.com">
     Dropdown <b class="caret"></b>
</a>

put a new

<a class="dropdown-toggle"><b class="caret"></b></a>

and remove the <b class="caret"></b> tag, so it will look like

<a class="dropdown-toggle disabled" href="http://google.com">
Dropdown</a><a class="dropdown-toggle"><b class="caret"></b></a>

2) Style them with the following css rules:

.caret1 {
    position: absolute !important; top: 0; right: 0;
}

.dropdown-toggle.disabled {
    padding-right: 40px;
}

The style in .caret1 class is for positioning it absolutely inside your li, at the right corner.

The second style is for adding some padding to the right of the dropdown to place the caret, preventing overlapping the text of the menu item.

Now you have a nice responsive menu item which looks nice both in desktop and mobile versions and that is both clickable and dropdownable depending on whether you click on the text or on the caret.

How to downgrade Node version

In Mac there is a fast method with brew:

brew search node

You see some version, for example: node@10 node@12 ... Then

brew unlink node

And now select a before version for example node@12

brew link --overwrite --force node@12

Ready, you have downgraded you node version.

Replace a character at a specific index in a string?

String is an immutable class in java. Any method which seems to modify it always returns a new string object with modification.

If you want to manipulate a string, consider StringBuilder or StringBuffer in case you require thread safety.

String replacement in Objective-C

If you want multiple string replacement:

NSString *s = @"foo/bar:baz.foo";
NSCharacterSet *doNotWant = [NSCharacterSet characterSetWithCharactersInString:@"/:."];
s = [[s componentsSeparatedByCharactersInSet: doNotWant] componentsJoinedByString: @""];
NSLog(@"%@", s); // => foobarbazfoo

How to localise a string inside the iOS info.plist file?

I would highly recommend reading Apple's guides, and viewing the WWDC resources listed here: Internationalization and Localization Topics

To specifically answer your question, when you add a new language to your projectenter image description here, you get an opportunity to choose what InfoPlist files to include (if you have multiple targets, you'll have multiple Info plist files). All you need to do to get the following screen is hit the + under Localizations and choose a new language to add support for. enter image description here

Once you've added, it will create the necessary string files in the appropriate lproj directories for the given language.

--EDIT--

Just to be clear, iOS will swap out the string for your Plist file based upon the user's currently selected language using the plist entry's key as the key in the localized strings file.

HTML/JavaScript: Simple form validation on submit

You have several errors there.

First, you have to return a value from the function in the HTML markup: <form name="ff1" method="post" onsubmit="return validateForm();">

Second, in the JSFiddle, you place the code inside onLoad which and then the form won't recognize it - and last you have to return true from the function if all validation is a success - I fixed some issues in the update:

https://jsfiddle.net/mj68cq0b/

function validateURL(url) {
    var reurl = /^(http[s]?:\/\/){0,1}(www\.){0,1}[a-zA-Z0-9\.\-]+\.[a-zA-Z]{2,5}[\.]{0,1}/;
    return reurl.test(url);
}

function validateForm()
{
    // Validate URL
    var url = $("#frurl").val();
    if (validateURL(url)) { } else {
        alert("Please enter a valid URL, remember including http://");
        return false;
    }

    // Validate Title
    var title = $("#frtitle").val();
    if (title=="" || title==null) {
        alert("Please enter only alphanumeric values for your advertisement title");
        return false;
    }

    // Validate Email
    var email = $("#fremail").val();
    if ((/(.+)@(.+){2,}\.(.+){2,}/.test(email)) || email=="" || email==null) { } else {
        alert("Please enter a valid email");
        return false;
    }
  return true;
}

What's the difference between TRUNCATE and DELETE in SQL

Here is my detailed answer on the difference between DELETE and TRUNCATE in SQL Server

Remove Data : First thing first, both can be used to remove the rows from table.
But a DELETE can be used to remove the rows not only from a Table but also from a VIEW or the result of an OPENROWSET or OPENQUERY subject to provider capabilities.

FROM Clause : With DELETE you can also delete rows from one table/view/rowset_function_limited based on rows from another table by using another FROM clause. In that FROM clause you can also write normal JOIN conditions. Actually you can create a DELETE statement from a SELECT statement that doesn’t contain any aggregate functions by replacing SELECT with DELETE and removing column names.
With TRUNCATE you can’t do that.

WHERE : A TRUNCATE cannot have WHERE Conditions, but a DELETE can. That means with TRUNCATE you can’t delete a specific row or specific group of rows. TRUNCATE TABLE is similar to the DELETE statement with no WHERE clause.

Performance : TRUNCATE TABLE is faster and uses fewer system and transaction log resources. And one of the reason is locks used by either statements. The DELETE statement is executed using a row lock, each row in the table is locked for deletion. TRUNCATE TABLE always locks the table and page but not each row.

Transaction log : DELETE statement removes rows one at a time and makes individual entries in the transaction log for each row.
TRUNCATE TABLE removes the data by deallocating the data pages used to store the table data and records only the page deallocations in the transaction log.

Pages : After a DELETE statement is executed, the table can still contain empty pages. TRUNCATE removes the data by deallocating the data pages used to store the table data.

Trigger : TRUNCATE does not activate the delete triggers on the table. So you must be very careful while using TRUNCATE. One should never use a TRUNCATE if delete Trigger is defined on the table to do some automatic cleanup or logging action when rows are deleted.

Identity Column : With TRUNCATE if the table contains an identity column, the counter for that column is reset to the seed value defined for the column. If no seed was defined, the default value 1 is used. DELETE doesn’t reset the identity counter. So if you want to retain the identity counter, use DELETE instead.

Replication : DELETE can be used against table used in transactional replication or merge replication.
While TRUNCATE cannot be used against the tables involved in transactional replication or merge replication.

Rollback : DELETE statement can be rolled back.
TRUNCATE can also be rolled back provided it is enclosed in a TRANSACTION block and session is not closed. Once session is closed you won't be able to Rollback TRUNCATE.

Restrictions : The DELETE statement may fail if it violates a trigger or tries to remove a row referenced by data in another table with a FOREIGN KEY constraint. If the DELETE removes multiple rows, and any one of the removed rows violates a trigger or constraint, the statement is canceled, an error is returned, and no rows are removed.
And if DELETE is used against View, that View must be an Updatable view. TRUNCATE cannot be used against the table used in Indexed view.
TRUNCATE cannot be used against the table referenced by a FOREIGN KEY constraint, unless a table that has a foreign key that references itself.

How to create enum like type in TypeScript?

As of TypeScript 0.9 (currently an alpha release) you can use the enum definition like this:

enum TShirtSize {
  Small,
  Medium,
  Large
}

var mySize = TShirtSize.Large;

By default, these enumerations will be assigned 0, 1 and 2 respectively. If you want to explicitly set these numbers, you can do so as part of the enum declaration.

Listing 6.2 Enumerations with explicit members

enum TShirtSize {
  Small = 3,
  Medium = 5,
  Large = 8
}

var mySize = TShirtSize.Large;

Both of these examples lifted directly out of TypeScript for JavaScript Programmers.

Note that this is different to the 0.8 specification. The 0.8 specification looked like this - but it was marked as experimental and likely to change, so you'll have to update any old code:

Disclaimer - this 0.8 example would be broken in newer versions of the TypeScript compiler.

enum TShirtSize {
  Small: 3,
  Medium: 5,
  Large: 8
}

var mySize = TShirtSize.Large;

Genymotion Android emulator - adb access?

You can get IP Genymotion Virtual Device Manager,then use the command like this

adb connect your ip

Evaluate list.contains string in JSTL

Another way of doing this is using a Map (HashMap) with Key, Value pairs representing your object.

Map<Long, Object> map = new HashMap<Long, Object>();
map.put(new Long(1), "one");
map.put(new Long(2), "two");

In JSTL

<c:if test="${not empty map[1]}">

This should return true if the pair exist in the map

Export JAR with Netbeans

  1. Right click your project folder.
  2. Select Properties.
  3. Expand Build option.
  4. Select Packaging.
  5. Now Clean and Build your project (Shift +F11).
  6. jar file will be created at your_project_folder\dist folder.

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

  1. @SpringBootApplication: checked, didn't work.
  2. spring-boot-starter-web in Pom file: checked, didn't work.
  3. Switch from IntelliJ CE to IntelliJ Ultimate, problem solved.

SSL Proxy/Charles and Android trouble

I wasted 1 day finding the issue , my system was not asking connection "allow" or "reject". i though it was due to some certiifcate issue . tried all methods mentioned above but none of them worked . in the end i found "Firewall was real culprit ". if firewall settings is ON , they will not allow charles to connect with your laptop via proxy IP . make them off and all things will work smoothly .Not sure if that was relevent answer but just want to share.

Sort objects in an array alphabetically on one property of the array

objArray.sort( (a, b) => a.id.localeCompare(b.id, 'en', {'sensitivity': 'base'}));

This sorts them alphabetically AND is case insensitive. It's also super clean and easy to read :D

Setting Elastic search limit to "unlimited"

Another approach is to first do a searchType: 'count', then and then do a normal search with size set to results.count.

The advantage here is it avoids depending on a magic number for UPPER_BOUND as suggested in this similar SO question, and avoids the extra overhead of building too large of a priority queue that Shay Banon describes here. It also lets you keep your results sorted, unlike scan.

The biggest disadvantage is that it requires two requests. Depending on your circumstance, this may be acceptable.

getch and arrow codes

The keypad will allow the keyboard of the user's terminal to allow for function keys to be interpreted as a single value (i.e. no escape sequence).

As stated in the man page:

The keypad option enables the keypad of the user's terminal. If enabled (bf is TRUE), the user can press a function key (such as an arrow key) and wgetch returns a single value representing the function key, as in KEY_LEFT. If disabled (bf is FALSE), curses does not treat function keys specially and the program has to interpret the escape sequences itself. If the keypad in the terminal can be turned on (made to transmit) and off (made to work locally), turning on this option causes the terminal keypad to be turned on when wgetch is called. The default value for keypad is false.

How to send list of file in a folder to a txt file in Linux

If only names of regular files immediately contained within a directory (assume it's ~/dirs) are needed, you can do

find ~/docs -type f -maxdepth 1 > filenames.txt

How can I perform a short delay in C# without using sleep?

You can probably use timers : http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx

Timers can provide you a precision up to 1 millisecond. Depending on the tick interval an event will be generated. Do your stuff inside the tick event.

How the int.TryParse actually works

TryParse is the best way for parse or validate in single line:

int nNumber = int.TryParse("InputString", out nNumber) ? nNumber : 1;

Short description:

  1. nNumber will initialize with zero,
  2. int.TryParse() try parse "InputString" and validate it, if succeed set into nNumber.
  3. short if ?: checking int.TryParse() result, that return nNumber or 1 as default value.

Can't drop table: A foreign key constraint fails

But fortunately, with the MySQL FOREIGN_KEY_CHECKS variable, you don't have to worry about the order of your DROP TABLE statements at all, and you can write them in any order you like -- even the exact opposite -- like this:

SET FOREIGN_KEY_CHECKS = 0;
drop table if exists customers;
drop table if exists orders;
drop table if exists order_details;
SET FOREIGN_KEY_CHECKS = 1;

For more clarification, check out the link below:

http://alvinalexander.com/blog/post/mysql/drop-mysql-tables-in-any-order-foreign-keys/

Escaping quotation marks in PHP

Use a backslash as such

"From time to \"time\"";

Backslashes are used in PHP to escape special characters within quotes. As PHP does not distinguish between strings and characters, you could also use this

'From time to "time"';

The difference between single and double quotes is that double quotes allows for string interpolation, meaning that you can reference variables inline in the string and their values will be evaluated in the string like such

$name = 'Chris';
$greeting = "Hello my name is $name"; //equals "Hello my name is Chris"

As per your last edit of your question I think the easiest thing you may be able to do that this point is to use a 'heredoc.' They aren't commonly used and honestly I wouldn't normally recommend it but if you want a fast way to get this wall of text in to a single string. The syntax can be found here: http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.heredoc and here is an example:

$someVar = "hello";
$someOtherVar = "goodbye";
$heredoc = <<<term
This is a long line of text that include variables such as $someVar
and additionally some other variable $someOtherVar. It also supports having
'single quotes' and "double quotes" without terminating the string itself.
heredocs have additional functionality that most likely falls outside
the scope of what you aim to accomplish.
term;

Eclipse copy/paste entire line keyboard shortcut

Ctrl+Alt+Down Copies current line to below like notepad++ (Ctrl+D)

If your whole screen is 180° rotted then you should disable your hotkey settings.

Right Click -> Graphics Options -> Hot Keys -> Disable

enter image description here

That it now you done try shortcut Ctrl+Alt+Down

Bash integer comparison

I know this has been answered, but here's mine just because I think case is an under-appreciated tool. (Maybe because people think it is slow, but it's at least as fast as an if, sometimes faster.)

case "$1" in
    0|1) xinput set-prop 12 "Device Enabled" $1 ;;
      *) echo "This script requires a 1 or 0 as first parameter." ;;
esac

pthread_join() and pthread_exit()

The typical use is

void* ret = NULL;
pthread_t tid = something; /// change it suitably
if (pthread_join (tid, &ret)) 
   handle_error();
// do something with the return value ret

Java: Finding the highest value in an array

If you don't want to use any java predefined libraries then below is the

simplest way

   public class Test {

    public static void main(String[] args) {
        double[] decMax = {-2.8, -8.8, 2.3, 7.9, 4.1, -1.4, 11.3, 10.4,
            8.9, 8.1, 5.8, 5.9, 7.8, 4.9, 5.7, -0.9, -0.4, 7.3, 8.3, 6.5, 9.2,
            3.5, 3, 1.1, 6.5, 5.1, -1.2, -5.1, 2, 5.2, 2.1};

        double maxx = decMax[0];

        for (int i = 0; i < decMax.length; i++) {
            if (maxx < decMax[i]) {
                maxx = decMax[i];
            }
        }
        System.out.println(maxx);

    }
}

How do you create a Spring MVC project in Eclipse?

You don't necessarily have to create a Spring project. Almost all Java web applications have he same project structure. In almost every project I create, I automatically add these source folder:

  • src/main/java
  • src/main/resources
  • src/test/java
  • src/test/resources
  • src/main/webapp*

src/main/webapp isn't actually a source folder. The web.xml file under src/main/webapp/WEB-INF will allow you to run your java application on any Java enabled web server (Tomcat, Jetty, etc.). I typically add the Jetty Plugin to my POM (assuming you use Maven), and launch the web app in development using mvn clean jetty:run.

Java reverse an int value without using array

If you wanna reverse any number like 1234 and you want to revers this number to let it looks like 4321. First of all, initialize 3 variables int org ; int reverse = 0; and int reminder ; then put your logic like

    Scanner input = new Scanner (System.in);
    System.out.println("Enter number to reverse ");
    int org = input.nextInt();
    int getReminder;
    int r = 0;
    int count = 0;

    while (org !=0){
        getReminder = org%10;
         r = 10 * r + getReminder;
         org = org/10;



    }
        System.out.println(r);

    }

How do I create a slug in Django?

Use prepopulated_fields in your admin class:

class ArticleAdmin(admin.ModelAdmin):
    prepopulated_fields = {"slug": ("title",)}

admin.site.register(Article, ArticleAdmin)

disable viewport zooming iOS 10+ safari?

Unintentional zooming tends to happen when:

  • A user double taps on a component of the interface
  • A user interacts with the viewport using two or more digits (pinch)

To prevent the double tap behaviour I have found two very simple workarounds:

<button onclick='event.preventDefault()'>Prevent Default</button>
<button style='touch-action: manipulation'>Touch Action Manipulation</button>

Both of these prevent Safari (iOS 10.3.2) from zooming in on the button. As you can see one is JavaScript only, the other is CSS only. Use appropriately.

Here is a demo: https://codepen.io/lukejacksonn/pen/QMELXQ

I have not attempted to prevent the pinch behaviour (yet), primarily because I tend not to create multi touch interfaces for the web and secondly I have come round to the idea that perhaps all interfaces including native app UI should be "pinch to zoom"-able in places. I'd still design to avoid the user having to do this to make your UI accessible to them, at all costs.

Why does git perform fast-forward merges by default?

Let me expand a bit on a VonC's very comprehensive answer:


First, if I remember it correctly, the fact that Git by default doesn't create merge commits in the fast-forward case has come from considering single-branch "equal repositories", where mutual pull is used to sync those two repositories (a workflow you can find as first example in most user's documentation, including "The Git User's Manual" and "Version Control by Example"). In this case you don't use pull to merge fully realized branch, you use it to keep up with other work. You don't want to have ephemeral and unimportant fact when you happen to do a sync saved and stored in repository, saved for the future.

Note that usefulness of feature branches and of having multiple branches in single repository came only later, with more widespread usage of VCS with good merging support, and with trying various merge-based workflows. That is why for example Mercurial originally supported only one branch per repository (plus anonymous tips for tracking remote branches), as seen in older revisions of "Mercurial: The Definitive Guide".


Second, when following best practices of using feature branches, namely that feature branches should all start from stable version (usually from last release), to be able to cherry-pick and select which features to include by selecting which feature branches to merge, you are usually not in fast-forward situation... which makes this issue moot. You need to worry about creating a true merge and not fast-forward when merging a very first branch (assuming that you don't put single-commit changes directly on 'master'); all other later merges are of course in non fast-forward situation.

HTH

How to split CSV files as per number of rows specified?

I have a one-liner answer (this example gives you 999 lines of data and one header row per file)

cat bigFile.csv | parallel --header : --pipe -N999 'cat >file_{#}.csv'

https://stackoverflow.com/a/53062251/401226

Transfer files to/from session I'm logged in with PuTTY

If you have to do private key validation; at Command Prompt(cmd), run

First;

set PATH=C:\PuttySetupLocation

Second;

pscp -i C:/MyPrivateKeyFile.ppk C:/MySourceFile.jar [email protected]:/home/ubuntu

Also, if you need extra options look at the following link. https://the.earth.li/~sgtatham/putty/0.60/htmldoc/Chapter5.html

Find provisioning profile in Xcode 5

I wrote a simple bash script to get around this stupid problem. Pass in the path to a named copy of your provision (downloaded from developer.apple.com) and it will identify the matching GUID-renamed file in your provision library:

#!/bin/bash

if [ -z "$1" ] ; then
  echo -e "\nUsage: $0 <myprovision>\n"
  exit
fi

if [ ! -f "$1" ] ; then
  echo -e "\nFile not found: $1\n"
  exit
fi

provisionpath="$HOME/Library/MobileDevice/Provisioning Profiles"
provisions=$( ls "$provisionpath" )

for i in $provisions ; do
  match=$( diff "$1" "$provisionpath/$i" )
  if [ "$match" = "" ] ; then
    echo -e "\nmatch: $provisionpath/$i\n"
  fi
done

comparing strings in vb

If String.Compare(string1,string2,True) Then

    'perform operation

EndIf

How to change lowercase chars to uppercase using the 'keyup' event?

Plain ol' javascript:

var input = document.getElementById('inputID');

input.onkeyup = function(){
    this.value = this.value.toUpperCase();
}

Javascript with jQuery:

$('#inputID').keyup(function(){
    this.value = this.value.toUpperCase();
});

Angular 5, HTML, boolean on checkbox is checked

Here is my answer,

In row.model.ts

export interface Row {
   otherProperty : type;
   checked : bool;
   otherProperty : type;
   ...
}

In .html

<tr class="even" *ngFor="let item of rows">
   <input [checked]="item.checked" type="checkbox">
</tr>

In .ts

rows : Row[] = [];

update the rows in component.ts

Passing a string with spaces as a function argument in bash

Your definition of myFunction is wrong. It should be:

myFunction()
{
    # same as before
}

or:

function myFunction
{
    # same as before
}

Anyway, it looks fine and works fine for me on Bash 3.2.48.

Convert .pem to .crt and .key

I was able to convert pem to crt using this:

openssl x509 -outform der -in your-cert.pem -out your-cert.crt

How to end a session in ExpressJS

req.session.destroy(); 

The above did not work for me so I did this.

req.session.cookie.expires = new Date().getTime();

By setting the expiration of the cookie to the current time, the session expired on its own.

How to obtain the last index of a list?

len(list1)-1 is definitely the way to go, but if you absolutely need a list that has a function that returns the last index, you could create a class that inherits from list.

class MyList(list):
    def last_index(self):
        return len(self)-1


>>> l=MyList([1, 2, 33, 51])
>>> l.last_index()
3

How to use shell commands in Makefile

With:

FILES = $(shell ls)

indented underneath all like that, it's a build command. So this expands $(shell ls), then tries to run the command FILES ....

If FILES is supposed to be a make variable, these variables need to be assigned outside the recipe portion, e.g.:

FILES = $(shell ls)
all:
        echo $(FILES)

Of course, that means that FILES will be set to "output from ls" before running any of the commands that create the .tgz files. (Though as Kaz notes the variable is re-expanded each time, so eventually it will include the .tgz files; some make variants have FILES := ... to avoid this, for efficiency and/or correctness.1)

If FILES is supposed to be a shell variable, you can set it but you need to do it in shell-ese, with no spaces, and quoted:

all:
        FILES="$(shell ls)"

However, each line is run by a separate shell, so this variable will not survive to the next line, so you must then use it immediately:

        FILES="$(shell ls)"; echo $$FILES

This is all a bit silly since the shell will expand * (and other shell glob expressions) for you in the first place, so you can just:

        echo *

as your shell command.

Finally, as a general rule (not really applicable to this example): as esperanto notes in comments, using the output from ls is not completely reliable (some details depend on file names and sometimes even the version of ls; some versions of ls attempt to sanitize output in some cases). Thus, as l0b0 and idelic note, if you're using GNU make you can use $(wildcard) and $(subst ...) to accomplish everything inside make itself (avoiding any "weird characters in file name" issues). (In sh scripts, including the recipe portion of makefiles, another method is to use find ... -print0 | xargs -0 to avoid tripping over blanks, newlines, control characters, and so on.)


1The GNU Make documentation notes further that POSIX make added ::= assignment in 2012. I have not found a quick reference link to a POSIX document for this, nor do I know off-hand which make variants support ::= assignment, although GNU make does today, with the same meaning as :=, i.e., do the assignment right now with expansion.

Note that VAR := $(shell command args...) can also be spelled VAR != command args... in several make variants, including all modern GNU and BSD variants as far as I know. These other variants do not have $(shell) so using VAR != command args... is superior in both being shorter and working in more variants.

Response Content type as CSV

I suggest to insert an '/' character in front of 'myfilename.cvs'

Response.AddHeader("Content-Disposition", "attachment;filename=/myfilename.csv");

I hope you get better results.

Disable Proximity Sensor during call

I have been researching this for a while, tested and wrote apps.

If you have no option in Settings ? Phone ? Use proximity sensor, then the only choice, seem to be to disable or modify its settings in rooted devices.

Also consider, that if you plug the headset, the screen will remain on :D

#pragma mark in Swift?

Pragma mark is a way to improve the readability of your code. The pragma comments would appear like tags on the Xcode jumpbar.

//MARK:  <Your comment goes here>

Example: In the code,

//MARK: Properties

// MARK: View Life cycle

//MARK: Helper methods

This is how it would appear in the Xcode jump bar.

enter image description here

Digital Certificate: How to import .cer file in to .truststore file using?

Instead of using sed to filter out the certificate, you can also pipe the openssl s_client output through openssl x509 -out certfile.txt, for example:

echo "" | openssl s_client -connect my.server.com:443 -showcerts 2>/dev/null | openssl x509 -out certfile.txt

How to process a file in PowerShell line-by-line as a stream

If you want to use straight PowerShell check out the below code.

$content = Get-Content C:\Users\You\Documents\test.txt
foreach ($line in $content)
{
    Write-Host $line
}

Why doesn't git recognize that my file has been changed, therefore git add not working

When you edit a file in Visual Studio it gets listed in git changes instantly even if the file is not saved. So all you need to do is just to save the file manually (Ctrl+S for the currently displayed file or Ctrl+Shift+S for all project files) and git bash will pick them up.

How can I generate Unix timestamps?

First of all, the Unix 'epoch' or zero-time is 1970-01-01 00:00:00Z (meaning midnight of 1st January 1970 in the Zulu or GMT or UTC time zone). A Unix time stamp is the number of seconds since that time - not accounting for leap seconds.

Generating the current time in Perl is rather easy:

perl -e 'print time, "\n"'

Generating the time corresponding to a given date/time value is rather less easy. Logically, you use the strptime() function from POSIX. However, the Perl POSIX::strptime module (which is separate from the POSIX module) has the signature:

($sec, $min, $hour, $mday, $mon, $year, $wday, $yday) = 
                                     POSIX::strptime("string", "Format");

The function mktime in the POSIX module has the signature:

mktime(sec, min, hour, mday, mon, year, wday = 0, yday = 0, isdst = 0)

So, if you know the format of your data, you could write a variant on:

perl -MPOSIX -MPOSIX::strptime -e \
    'print mktime(POSIX::strptime("2009-07-30 04:30", "%Y-%m-%d %H:%M")), "\n"'

What is the default access modifier in Java?

From a book named OCA Java SE 7 Programmer I:

The members of a class defined without using any explicit access modifier are defined with package accessibility (also called default accessibility). The members with package access are only accessible to classes and interfaces defined in the same package.

Jquery click not working with ipad

I found that when I made my binding more specific, it began to work on iOS. I had:

$(document).on('click tap', 'span.clickable', function(e){ ... });

When I changed it to:

$("div.content").on('click tap', 'span.clickable', function(e){ ... });

iOS began responding.

Insert a string at a specific index

another solution, cut the string in 2 and put a string in between.

var str = jQuery('#selector').text();

var strlength = str.length;

strf = str.substr(0 , strlength - 5);
strb = str.substr(strlength - 5 , 5);

jQuery('#selector').html(strf + 'inserted' + strb);

Installing mcrypt extension for PHP on OSX Mountain Lion

Solution with brew worked only after the following: in your php.ini

nano /private/etc/php.ini

add this line:

extension="/usr/local/Cellar/php53-mcrypt/5.3.26/mcrypt.so"

Warning! Set the correct PHP version.

Is there any sizeof-like method in Java?

No. There is no such method in the standard Java SE class library.

The designers' view is that it is not needed in Java, since the language removes the need for an application1 to know about how much space needs to be reserved for a primitive value, an object or an array with a given number of elements.

You might think that a sizeof operator would be useful for people that need to know how much space their data structures take. However you can also get this information and more, simply and reliably using a Java memory profiler, so there is no need for a sizeof method.


Previous commenters made the point that sizeof(someType) would be more readable than 4. If you accept that readability argument, then the remedy is in your hands. Simply define a class like this ...

public class PrimitiveSizes {
    public static int sizeof(byte b) { return 1; } 
    public static int sizeof(short s) { return 2; }
    // etcetera
}

... and statically import it ...

import static PrimitiveSizes.*;

Or define some named constants; e.g.

public static final int SIZE_OF_INT = 4;

Or (Java 8 and later) use the Integer.BYTES constant, and so on.


Why haven't the Java designers implemented this in standard libraries? My guess is that:

  • they don't think there is a need for it,
  • they don't think there is sufficient demand for it, and
  • they don't think it is worth the effort.

There is also the issue that the next demand would be for a sizeof(Object o) method, which is fraught with technical difficulties.

The key word in the above is "they"!


1 - A programmer may need to know in order to design space efficient data structures. However, I can't imagine why that information would be needed in application code at runtime via a method call.

Where is the web server root directory in WAMP?

To check what is your root directory go to httpd.conf file of apache and search for "DocumentRoot".The location following it is your root directory

How do I extend a class with c# extension methods?

Unfortunately, you can't do that. I believe it would be useful, though. It is more natural to type:

DateTime.Tomorrow

than:

DateTimeUtil.Tomorrow

With a Util class, you have to check for the existence of a static method in two different classes, instead of one.

What's the difference between align-content and align-items?

Having read some of the answers, they identify correctly that align-content takes no affect if the flex content is not wrapped. However what they don't understand is align-items still plays an important role when there is wrapped content:

In the following two examples, align-items is used to center the items within each row, then we change align-content to see it's effect.

Example 1:

align-content: flex-start;

enter image description here

Example 2:

    align-content: flex-end;

enter image description here

Here's the code:

<div class="container">
    <div class="child" style="height: 30px;">1</div>
    <div class="child" style="height: 50px;">2</div>
    <div class="child" style="height: 60px;">3</div>
    <div class="child" style="height: 40px;">4</div>
    <div class="child" style="height: 50px;">5</div>
    <div class="child" style="height: 20px;">6</div>
    <div class="child" style="height: 90px;">7</div>
    <div class="child" style="height: 50px;">8</div>
    <div class="child" style="height: 30px;">9</div>
    <div class="child" style="height: 40px;">10</div>
    <div class="child" style="height: 30px;">11</div>
    <div class="child" style="height: 60px;">12</div>
</div>

<style>
.container {
    display: flex;
    width: 300px;
    flex-flow: row wrap;
    justify-content: space-between;
    align-items: center;
    align-content: flex-end;
    background: lightgray;
    height: 400px;
}
.child {
    padding: 12px;
    background: red;
    border: solid 1px black;
}
</style>

Difference between Arrays.asList(array) and new ArrayList<Integer>(Arrays.asList(array))

I am pretty late here, anyways felt an explanation with doc references would be better for someone looking for answer.

  1. java.util.Arrays
  • This is a utility class with bunch of static methods to operate on given array
  • asList is one such static method that takes input array and returns an object of java.util.Arrays.ArrayList which is a static nested class that extends AbstractList which inturn implements List interface.
  • So Arrays.asList(inarray) returns a List wrapper around the input array but this wrapper is java.util.Arrays.ArrayList and not java.util.ArrayList and it refers to the same array so adding more elements to List wrapped array would affect orignal one too and also we cannot change the length.
  1. java.util.ArrayList
  • ArrayList has bunch of overloaded constructors

    public ArrayList() - //returns arraylist with default capacity 10

    public ArrayList(Collection c)

    public ArrayList(int initialCapacity)

  • So when we pass Arrays.asList returned object i.e. List(AbstractList) to second constructor above, it will create a new dynamic array(this array size increases as we add more elements than its capacity and also the new elements will not affect the orignal array) shallow copying the original array(shallow copy means it copies over the references only and does not create a new set of same objects as in orignal array)

"You have mail" message in terminal, os X

I was also having this issue of "You have mail" coming up every time I started Terminal.

What I discovered is this.

Something I'd installed (not entirely sure what, but possibly a script or something associated with an Alfred Workflow [at a guess]) made a change to the OS X system to start presenting Terminal bash notifications. Prior to that, it appears Wordpress had attempted to use the Local Mail system to send a message. The message bounced, due to it having an invalid Recipient address. The bounced message then ended up in the local system mail inbox. So Terminal (bash) was then notifying me that "You have mail".

You can access the mail by simply using the command

mail

This launches you into Mail, and it will right away show you a list of messages that are stored there. If you want to see the content of the first message, use

t

This will show you the content of the first message, in full. You'll need to scroll down through the message to view it all, by hitting the down-arrow key.

If you want to jump to the end of the message, use the

spacebar

If you want to abort viewing the message, use

q 

To view the next message in the queue use

n

... assuming there's more than one message.

NOTE: You need to use these commands at the mail ? command prompt. They won't work whilst you are in the process of viewing a message. Hitting n whilst viewing a message will just cause an error message related to regular expressions. So, if in the midst of viewing a message, hit q to quit from that, or hit spacebar to jump to the end of the message, and then at the ? prompt, hit n.

Viewing the content of the messages in this way may help you identify what attempted to send the message(s).

You can also view a specific message by just inputting its number at the ? prompt. 3, for instance, will show you the content of the third message (if there are that many in there).

DELETING MESSAGES

Use the d command (at the ? command prompt )

d [message number]

To delete each message when you are done looking at them. For example, d 2 will delete message number 2. Or you can delete a list of messages, such as d 1 2 5 7. Or you can delete a range of messages with (for example), d 3-10. You can find the message numbers in the list of messages mail shows you.

To delete all the messages, from the mail prompt (?) use the command d *.

As per a comment on this post, you will need to use q to quit mail, which also saves any changes.

If you'd like to see the mail all in one output, use this command at the bash prompt (i.e. not from within mail, but from your regular command prompt):

cat /var/mail/<username>

And, if you wish to delete the emails all in one hit, use this command

sudo rm /var/mail/<username>

In my particular case, there were a number of messages. It looks like the one was a returned message that bounced. It was sent by a local Wordpress installation. It was a notification for when user "Admin" (me) changed its password. Two additional messages where there. Both seemed to be to the same incident.

What I don't know, and can't answer for you either, is WHY I only recently started seeing this mail notification each time I open Terminal. The mails were generated a couple of months ago, and yet I only noticed this "you have mail" appearing in the last few weeks. I suspect it's the result of something a workflow I installed in Alfred, and that workflow using Terminal bash to provide notifications... or something along those lines.

Simply deleting the messages

If you have no interest in determining the source of the messages, and just wish to get rid of them, it may be easier to do so without using the mail command (which can be somewhat fiddly). As pointed out by a few other people, you can use this command instead:

sudo rm /var/mail/YOURUSERNAME

How to overplot a line on a scatter plot in python?

A one-line version of this excellent answer to plot the line of best fit is:

plt.plot(np.unique(x), np.poly1d(np.polyfit(x, y, 1))(np.unique(x)))

Using np.unique(x) instead of x handles the case where x isn't sorted or has duplicate values.

The call to poly1d is an alternative to writing out m*x + b like in this other excellent answer.

Cannot install packages inside docker Ubuntu image

Add following command in Dockerfile:

RUN apt-get update

Python - IOError: [Errno 13] Permission denied:

This happened to me when I was using 'shutil.copyfile' instead of 'shutil.copy'. The permissions were messed up.

How to use continue in jQuery each() loop?

$('.submit').filter(':checked').each(function() {
    //This is same as 'continue'
    if(something){
        return true;
    }
    //This is same as 'break'
    if(something){
        return false;
    }
});

Select Last Row in the Table

Use the latest scope provided by Laravel out of the box.

Model::latest()->first();

That way you're not retrieving all the records. A nicer shortcut to orderBy.

How do I replace all line breaks in a string with <br /> elements?

Regardless of the system:

my_multiline_text.replace(/$/mg,'<br>');

Operation is not valid due to the current state of the object, when I select a dropdown list

This can happen if you call

 .SingleOrDefault() 

on an IEnumerable with 2 or more elements.

How to round down to nearest integer in MySQL?

SUBSTR will be better than FLOOR in some cases because FLOOR has a "bug" as follow:

SELECT 25 * 9.54 + 0.5 -> 239.00

SELECT FLOOR(25 * 9.54 + 0.5) -> 238  (oops!)

SELECT SUBSTR((25*9.54+0.5),1,LOCATE('.',(25*9.54+0.5)) - 1) -> 239

Difference between wait and sleep

This is a very simple question, because both these methods have a totally different use.

The major difference is to wait to release the lock or monitor while sleep doesn't release any lock or monitor while waiting. Wait is used for inter-thread communication while sleep is used to introduce pause on execution.

This was just a clear and basic explanation, if you want more than that then continue reading.

In case of wait() method thread goes in waiting state and it won't come back automatically until we call the notify() method (or notifyAll() if you have more then one thread in waiting state and you want to wake all of those thread). And you need synchronized or object lock or class lock to access the wait() or notify() or notifyAll() methods. And one more thing, the wait() method is used for inter-thread communication because if a thread goes in waiting state you'll need another thread to wake that thread.

But in case of sleep() this is a method which is used to hold the process for few seconds or the time you wanted. Because you don't need to provoke any notify() or notifyAll() method to get that thread back. Or you don't need any other thread to call back that thread. Like if you want something should happen after few seconds like in a game after user's turn you want the user to wait until the computer plays then you can mention the sleep() method.

And one more important difference which is asked often in interviews: sleep() belongs to Thread class and wait() belongs to Object class.

These are all the differences between sleep() and wait().

And there is a similarity between both methods: they both are checked statement so you need try catch or throws to access these methods.

I hope this will help you.

Indent multiple lines quickly in vi

Also try this for C-indenting indentation. Do :help = for more information:

={

That will auto-indent the current code block you're in.

Or just:

==

to auto-indent the current line.

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

I was getting this error when using Laravel and eloquent, trying to make a foreign key link would cause a 1452. The problem was lack of data in the linked table.

Please see here for an example: http://mstd.eu/index.php/2016/12/02/laravel-eloquent-integrity-constraint-violation-1452-foreign-key-constraint/

How to call a method daily, at specific time, in C#?

The best method that I know of and probably the simplest is to use the Windows Task Scheduler to execute your code at a specific time of day or have you application run permanently and check for a particular time of day or write a windows service that does the same.

Is there a way to access an iteration-counter in Java's for-each loop?

The easiest solution is to just run your own counter thus:

int i = 0;
for (String s : stringArray) {
    doSomethingWith(s, i);
    i++;
}

The reason for this is because there's no actual guarantee that items in a collection (which that variant of for iterates over) even have an index, or even have a defined order (some collections may change the order when you add or remove elements).

See for example, the following code:

import java.util.*;

public class TestApp {
  public static void AddAndDump(AbstractSet<String> set, String str) {
    System.out.println("Adding [" + str + "]");
    set.add(str);
    int i = 0;
    for(String s : set) {
        System.out.println("   " + i + ": " + s);
        i++;
    }
  }

  public static void main(String[] args) {
    AbstractSet<String> coll = new HashSet<String>();
    AddAndDump(coll, "Hello");
    AddAndDump(coll, "My");
    AddAndDump(coll, "Name");
    AddAndDump(coll, "Is");
    AddAndDump(coll, "Pax");
  }
}

When you run that, you can see something like:

Adding [Hello]
   0: Hello
Adding [My]
   0: Hello
   1: My
Adding [Name]
   0: Hello
   1: My
   2: Name
Adding [Is]
   0: Hello
   1: Is
   2: My
   3: Name
Adding [Pax]
   0: Hello
   1: Pax
   2: Is
   3: My
   4: Name

indicating that, rightly so, order is not considered a salient feature of a set.

There are other ways to do it without a manual counter but it's a fair bit of work for dubious benefit.

MVC: How to Return a String as JSON

You just need to return standard ContentResult and set ContentType to "application/json". You can create custom ActionResult for it:

public class JsonStringResult : ContentResult
{
    public JsonStringResult(string json)
    {
        Content = json;
        ContentType = "application/json";
    }
}

And then return it's instance:

[HttpPost]
public JsonResult UpdateBatchSearchMembers()
{
    string returntext;
    if (!System.IO.File.Exists(path))
        returntext = Properties.Settings.Default.EmptyBatchSearchUpdate;
    else
        returntext = Properties.Settings.Default.ResponsePath;

    return new JsonStringResult(returntext);
}

How to pass a URI to an intent?

If you want to use standard extra data field, you would do something like this:

private Uri imageUri;
....
Intent intent = new Intent(this, GoogleActivity.class);
intent.putExtra(Intent.EXTRA_STREAM, imageUri.toString());
startActivity(intent);
this.finish();

The documentation for Intent says:

EXTRA_STREAM   added in API level 1 
String EXTRA_STREAM
A content: URI holding a stream of data associated with the Intent,
used with ACTION_SEND to supply the data being sent. 

Constant Value: "android.intent.extra.STREAM"

You don't have to use the built-in standard names, but it's probably good practice and more reusable. Take a look at the developer documentation for a list of all the built-in standard extra data fields.

How to provide user name and password when connecting to a network share

I searched lots of methods and i did it my own way. You have to open a connection between two machine via command prompt NET USE command and after finishing your work clear the connection with command prompt NET USE "myconnection" /delete.

You must use Command Prompt process from code behind like this:

var savePath = @"\\servername\foldername\myfilename.jpg";
var filePath = @"C:\\temp\myfileTosave.jpg";

Usage is simple:

SaveACopyfileToServer(filePath, savePath);

Here is functions:

using System.IO
using System.Diagnostics;


public static void SaveACopyfileToServer(string filePath, string savePath)
    {
        var directory = Path.GetDirectoryName(savePath).Trim();
        var username = "loginusername";
        var password = "loginpassword";
        var filenameToSave = Path.GetFileName(savePath);

        if (!directory.EndsWith("\\"))
            filenameToSave = "\\" + filenameToSave;

        var command = "NET USE " + directory + " /delete";
        ExecuteCommand(command, 5000);

        command = "NET USE " + directory + " /user:" + username + " " + password;
        ExecuteCommand(command, 5000);

        command = " copy \"" + filePath + "\"  \"" + directory + filenameToSave + "\"";

        ExecuteCommand(command, 5000);


        command = "NET USE " + directory + " /delete";
        ExecuteCommand(command, 5000);
    }

And also ExecuteCommand function is:

public static int ExecuteCommand(string command, int timeout)
    {
        var processInfo = new ProcessStartInfo("cmd.exe", "/C " + command)
                              {
                                  CreateNoWindow = true, 
                                  UseShellExecute = false, 
                                  WorkingDirectory = "C:\\",
                              };

        var process = Process.Start(processInfo);
        process.WaitForExit(timeout);
        var exitCode = process.ExitCode;
        process.Close();
        return exitCode;
    } 

This functions worked very fast and stable for me.

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Use directions service of Google Maps API v3. It's basically the same as directions API, but nicely packed in Google Maps API which also provides convenient way to easily render the route on the map.

Information and examples about rendering the directions route on the map can be found in rendering directions section of Google Maps API v3 documentation.

How to highlight text using javascript

The solutions offered here are quite bad.

  1. You can't use regex, because that way, you search/highlight in the html tags.
  2. You can't use regex, because it doesn't work properly with UTF* (anything with non-latin/English characters).
  3. You can't just do an innerHTML.replace, because this doesn't work when the characters have a special HTML notation, e.g. &amp; for &, &lt; for <, &gt; for >, &auml; for ä, &ouml; for ö &uuml; for ü &szlig; for ß, etc.

What you need to do:

Loop through the HTML document, find all text nodes, get the textContent, get the position of the highlight-text with indexOf (with an optional toLowerCase if it should be case-insensitive), append everything before indexof as textNode, append the matched Text with a highlight span, and repeat for the rest of the textnode (the highlight string might occur multiple times in the textContent string).

Here is the code for this:

var InstantSearch = {

    "highlight": function (container, highlightText)
    {
        var internalHighlighter = function (options)
        {

            var id = {
                container: "container",
                tokens: "tokens",
                all: "all",
                token: "token",
                className: "className",
                sensitiveSearch: "sensitiveSearch"
            },
            tokens = options[id.tokens],
            allClassName = options[id.all][id.className],
            allSensitiveSearch = options[id.all][id.sensitiveSearch];


            function checkAndReplace(node, tokenArr, classNameAll, sensitiveSearchAll)
            {
                var nodeVal = node.nodeValue, parentNode = node.parentNode,
                    i, j, curToken, myToken, myClassName, mySensitiveSearch,
                    finalClassName, finalSensitiveSearch,
                    foundIndex, begin, matched, end,
                    textNode, span, isFirst;

                for (i = 0, j = tokenArr.length; i < j; i++)
                {
                    curToken = tokenArr[i];
                    myToken = curToken[id.token];
                    myClassName = curToken[id.className];
                    mySensitiveSearch = curToken[id.sensitiveSearch];

                    finalClassName = (classNameAll ? myClassName + " " + classNameAll : myClassName);

                    finalSensitiveSearch = (typeof sensitiveSearchAll !== "undefined" ? sensitiveSearchAll : mySensitiveSearch);

                    isFirst = true;
                    while (true)
                    {
                        if (finalSensitiveSearch)
                            foundIndex = nodeVal.indexOf(myToken);
                        else
                            foundIndex = nodeVal.toLowerCase().indexOf(myToken.toLowerCase());

                        if (foundIndex < 0)
                        {
                            if (isFirst)
                                break;

                            if (nodeVal)
                            {
                                textNode = document.createTextNode(nodeVal);
                                parentNode.insertBefore(textNode, node);
                            } // End if (nodeVal)

                            parentNode.removeChild(node);
                            break;
                        } // End if (foundIndex < 0)

                        isFirst = false;


                        begin = nodeVal.substring(0, foundIndex);
                        matched = nodeVal.substr(foundIndex, myToken.length);

                        if (begin)
                        {
                            textNode = document.createTextNode(begin);
                            parentNode.insertBefore(textNode, node);
                        } // End if (begin)

                        span = document.createElement("span");
                        span.className += finalClassName;
                        span.appendChild(document.createTextNode(matched));
                        parentNode.insertBefore(span, node);

                        nodeVal = nodeVal.substring(foundIndex + myToken.length);
                    } // Whend

                } // Next i 
            }; // End Function checkAndReplace 

            function iterator(p)
            {
                if (p === null) return;

                var children = Array.prototype.slice.call(p.childNodes), i, cur;

                if (children.length)
                {
                    for (i = 0; i < children.length; i++)
                    {
                        cur = children[i];
                        if (cur.nodeType === 3)
                        {
                            checkAndReplace(cur, tokens, allClassName, allSensitiveSearch);
                        }
                        else if (cur.nodeType === 1)
                        {
                            iterator(cur);
                        }
                    }
                }
            }; // End Function iterator

            iterator(options[id.container]);
        } // End Function highlighter
        ;


        internalHighlighter(
            {
                container: container
                , all:
                    {
                        className: "highlighter"
                    }
                , tokens: [
                    {
                        token: highlightText
                        , className: "highlight"
                        , sensitiveSearch: false
                    }
                ]
            }
        ); // End Call internalHighlighter 

    } // End Function highlight

};

Then you can use it like this:

function TestTextHighlighting(highlightText)
{
    var container = document.getElementById("testDocument");
    InstantSearch.highlight(container, highlightText);
}

Here's an example HTML document

<!DOCTYPE html>
<html>
    <head>
        <title>Example of Text Highlight</title>
        <style type="text/css" media="screen">
            .highlight{ background: #D3E18A;}
            .light{ background-color: yellow;}
        </style>
    </head>
    <body>
        <div id="testDocument">
            This is a test
            <span> This is another test</span>
            äöüÄÖÜäöüÄÖÜ
            <span>Test123&auml;&ouml;&uuml;&Auml;&Ouml;&Uuml;</span>
        </div>
    </body>
</html>

By the way, if you search in a database with LIKE,
e.g. WHERE textField LIKE CONCAT('%', @query, '%') [which you shouldn't do, you should use fulltext-search or Lucene], then you can escape every character with \ and add an SQL-escape-statement, that way you'll find special characters that are LIKE-expressions.

e.g.

WHERE textField LIKE CONCAT('%', @query, '%') ESCAPE '\'

and the value of @query is not '%completed%' but '%\c\o\m\p\l\e\t\e\d%'

(tested, works with SQL-Server and PostgreSQL, and every other RDBMS system that supports ESCAPE)


A revised typescript-version:

namespace SearchTools 
{


    export interface IToken
    {
        token: string;
        className: string;
        sensitiveSearch: boolean;
    }


    export class InstantSearch 
    {

        protected m_container: Node;
        protected m_defaultClassName: string;
        protected m_defaultCaseSensitivity: boolean;
        protected m_highlightTokens: IToken[];


        constructor(container: Node, tokens: IToken[], defaultClassName?: string, defaultCaseSensitivity?: boolean)
        {
            this.iterator = this.iterator.bind(this);
            this.checkAndReplace = this.checkAndReplace.bind(this);
            this.highlight = this.highlight.bind(this);
            this.highlightNode = this.highlightNode.bind(this);    

            this.m_container = container;
            this.m_defaultClassName = defaultClassName || "highlight";
            this.m_defaultCaseSensitivity = defaultCaseSensitivity || false;
            this.m_highlightTokens = tokens || [{
                token: "test",
                className: this.m_defaultClassName,
                sensitiveSearch: this.m_defaultCaseSensitivity
            }];
        }


        protected checkAndReplace(node: Node)
        {
            let nodeVal: string = node.nodeValue;
            let parentNode: Node = node.parentNode;
            let textNode: Text = null;

            for (let i = 0, j = this.m_highlightTokens.length; i < j; i++)
            {
                let curToken: IToken = this.m_highlightTokens[i];
                let textToHighlight: string = curToken.token;
                let highlightClassName: string = curToken.className || this.m_defaultClassName;
                let caseSensitive: boolean = curToken.sensitiveSearch || this.m_defaultCaseSensitivity;

                let isFirst: boolean = true;
                while (true)
                {
                    let foundIndex: number = caseSensitive ?
                        nodeVal.indexOf(textToHighlight)
                        : nodeVal.toLowerCase().indexOf(textToHighlight.toLowerCase());

                    if (foundIndex < 0)
                    {
                        if (isFirst)
                            break;

                        if (nodeVal)
                        {
                            textNode = document.createTextNode(nodeVal);
                            parentNode.insertBefore(textNode, node);
                        } // End if (nodeVal)

                        parentNode.removeChild(node);
                        break;
                    } // End if (foundIndex < 0)

                    isFirst = false;


                    let begin: string = nodeVal.substring(0, foundIndex);
                    let matched: string = nodeVal.substr(foundIndex, textToHighlight.length);

                    if (begin)
                    {
                        textNode = document.createTextNode(begin);
                        parentNode.insertBefore(textNode, node);
                    } // End if (begin)

                    let span: HTMLSpanElement = document.createElement("span");

                    if (!span.classList.contains(highlightClassName))
                        span.classList.add(highlightClassName);

                    span.appendChild(document.createTextNode(matched));
                    parentNode.insertBefore(span, node);

                    nodeVal = nodeVal.substring(foundIndex + textToHighlight.length);
                } // Whend

            } // Next i 

        } // End Sub checkAndReplace 


        protected iterator(p: Node)
        {
            if (p == null)
                return;

            let children: Node[] = Array.prototype.slice.call(p.childNodes);

            if (children.length)
            {
                for (let i = 0; i < children.length; i++)
                {
                    let cur: Node = children[i];

                    // https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType
                    if (cur.nodeType === Node.TEXT_NODE) 
                    {
                        this.checkAndReplace(cur);
                    }
                    else if (cur.nodeType === Node.ELEMENT_NODE) 
                    {
                        this.iterator(cur);
                    }
                } // Next i 

            } // End if (children.length) 

        } // End Sub iterator


        public highlightNode(n:Node)
        {
            this.iterator(n);
        } // End Sub highlight 


        public highlight()
        {
            this.iterator(this.m_container);
        } // End Sub highlight 


    } // End Class InstantSearch 


} // End Namespace SearchTools 

Usage:

let searchText = document.getElementById("txtSearchText");
let searchContainer = document.body; // document.getElementById("someTable");
let highlighter = new SearchTools.InstantSearch(searchContainer, [
    {
        token: "this is the text to highlight" // searchText.value,
        className: "highlight", // this is the individual highlight class
        sensitiveSearch: false
    }
]);


// highlighter.highlight(); // this would highlight in the entire table
// foreach tr - for each td2 
highlighter.highlightNode(td2); // this highlights in the second column of table

How to generate random number in Bash?

Reading from /dev/random or /dev/urandom character special files is the way to go.

These devices return truly random numbers when read and are designed to help application software choose secure keys for encryption. Such random numbers are extracted from an entropy pool that is contributed by various random events. {LDD3, Jonathan Corbet, Alessandro Rubini, and Greg Kroah-Hartman]

These two files are interface to kernel randomization, in particular

void get_random_bytes_arch(void* buf, int nbytes)

which draws truly random bytes from hardware if such function is by hardware implemented (usually is), or it draws from entropy pool (comprised of timings between events like mouse and keyboard interrupts and other interrupts that are registered with SA_SAMPLE_RANDOM).

dd if=/dev/urandom count=4 bs=1 | od -t d

This works, but writes unneeded output from dd to stdout. The command below gives just the integer I need. I can even get specified number of random bits as I need by adjustment of the bitmask given to arithmetic expansion:

me@mymachine:~/$ x=$(head -c 1 /dev/urandom > tmp && hexdump 
                         -d tmp | head -n 1 | cut -c13-15) && echo $(( 10#$x & 127 ))

Classes residing in App_Code is not accessible

I haven't figured out yet why this occurs, but I had classes that were in my App_Code folder that were calling methods in each other, and were fine in doing this when I built a .NET 4.5.2 project, but then I had to revert it to 4.0 as the target server wasn't getting upgraded. That's when I found this problem (after fixing the langversion in my web.config from 6 to 5... another story)....

One of my methods kept having an error like:

The type X.Y conflicts with the imported type X.Y in MyProject.DLL

All of my classes were already set to "Compile" in their properties, as suggested on the accepted answer here, and each had a common namespace that was the same, and each had using MyNamespace; at the top of each class.

I found that if I just moved the offending classes that had to call methods in each other to another, standard folder named something other than "App_Code", they stopped having this conflict issue.

Note: If you create a standard folder called "AppCode", move your classes into it, delete the "App_Code" folder, then rename "AppCode" to "App_Code", your problems will return. It doesn't matter if you use the "New Folder" or "Add ASP .NET Folder" option to create "App_Code" - it seems to key in on the name.

Maybe this is just a .NET 4.0 (and possibly earlier) issue... I was just fine in 4.5.2 before having to revert!

How to add 10 minutes to my (String) time?

I would use Joda Time, parse the time as a LocalTime, and then use

time = time.plusMinutes(10);

Short but complete program to demonstrate this:

import org.joda.time.*;
import org.joda.time.format.*;

public class Test {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormat.forPattern("HH:mm");
        LocalTime time = formatter.parseLocalTime("14:10");
        time = time.plusMinutes(10);
        System.out.println(formatter.print(time));
    }       
}

Note that I would definitely use Joda Time instead of java.util.Date/Calendar if you possibly can - it's a much nicer API.

JS jQuery - check if value is in array

As to your bonus question, try if (jQuery.inArray(jQuery("input:first").val(), ar) < 0)

How can I get a list of Git branches, ordered by most recent commit?

Git v2.19 introduces branch.sort config option (see branch.sort).

So git branch will sort by committer date (desc) by default with

# gitconfig
[branch]
    sort = -committerdate     # desc

script:

$ git config --global branch.sort -committerdate

Update:

So,

$ git branch
* dev
  master
  _

and

$ git branch -v
* dev    0afecf5 Merge branch 'oc' into dev
  master 652428a Merge branch 'dev'
  _      7159cf9 Merge branch 'bashrc' into dev

The ALTER TABLE statement conflicted with the FOREIGN KEY constraint

It is possible to create the foreign key using ALTER TABLE tablename WITH NOCHECK ..., which will allow data that violates the foreign key.

"ALTER TABLE tablename WITH NOCHECK ..." option to add the FK -- This solution worked for me.

Listen to port via a Java socket

What do you actually want to achieve? What your code does is it tries to connect to a server located at 192.168.1.104:4000. Is this the address of a server that sends the messages (because this looks like a client-side code)? If I run fake server locally:

$ nc -l 4000

...and change socket address to localhost:4000, it will work and try to read something from nc-created server.

What you probably want is to create a ServerSocket and listen on it:

ServerSocket serverSocket = new ServerSocket(4000);
Socket socket = serverSocket.accept();

The second line will block until some other piece of software connects to your machine on port 4000. Then you can read from the returned socket. Look at this tutorial, this is actually a very broad topic (threading, protocols...)

How to Solve the XAMPP 1.7.7 - PHPMyAdmin - MySQL Error #2002 in Ubuntu

Go to config.inc.php file using terminal by typing the following:

sudo gedit /opt/lampp/phpmyadmin/config.inc.php

The file will open in gedit.

Now open the file and edit

$cfg['Servers'][$i]['auth_type'] = 'localhost';

to

$cfg['Servers'][$i]['auth_type'] = 'cookie';

and keep the username as: root password:

Also make sure that the lines with username and password are not commented:

//$cfg['Servers'][$i]['user'] = 'root'; //$cfg['Servers'][$i]['password'] = '';

Make sure that // is removed from the above lines.

WARNING: Exception encountered during context initialization - cancelling refresh attempt

I was having the problem as a beginner..........

There was issue in the path of the xml file I have saved.

403 Forbidden error when making an ajax Post request in Django framework

You must change your folder chmod 755 and file(.php ,.html) chmod 644.

how to get the first and last days of a given month

You might want to look at the strtotime and date functions.

<?php

$query_date = '2010-02-04';

// First day of the month.
echo date('Y-m-01', strtotime($query_date));

// Last day of the month.
echo date('Y-m-t', strtotime($query_date));

error C2065: 'cout' : undeclared identifier

I came here because I had the same problem, but when I did #include "stdafx.h" it said it did not find that file.
What did the trick for me was: #include <algorithm>.
I use Microsoft Visual Studio 2008.
These are the things that you can use then, incl. 'count': Link

using lodash .groupBy. how to add your own keys for grouped output?

Highest voted answer uses Lodash _.chain function which is considered a bad practice now "Why using _.chain is a mistake."

Here is a fewliner that approaches the problem from functional programming perspective:

import tap from "lodash/fp/tap";
import flow from "lodash/fp/flow";
import groupBy from "lodash/fp/groupBy";

const map = require('lodash/fp/map').convert({ 'cap': false });

const result = flow(
      groupBy('color'),
      map((users, color) => ({color, users})),
      tap(console.log)
    )(input)

Where input is an array that you want to convert.

How to convert an array of key-value tuples into an object

With Object.fromEntries, you can convert from Array to Object:

_x000D_
_x000D_
var entries = [_x000D_
  ['cardType', 'iDEBIT'],_x000D_
  ['txnAmount', '17.64'],_x000D_
  ['txnId', '20181'],_x000D_
  ['txnType', 'Purchase'],_x000D_
  ['txnDate', '2015/08/13 21:50:04'],_x000D_
  ['respCode', '0'],_x000D_
  ['isoCode', '0'],_x000D_
  ['authCode', ''],_x000D_
  ['acquirerInvoice', '0'],_x000D_
  ['message', ''],_x000D_
  ['isComplete', 'true'],_x000D_
  ['isTimeout', 'false']_x000D_
];_x000D_
var obj = Object.fromEntries(entries);_x000D_
console.log(obj);
_x000D_
_x000D_
_x000D_

Returning an empty array

I'm pretty sure you should go with bar(); because with foo(); it creates a List (for nothing) since you create a new File[0] in the end anyway, so why not go with directly returning it!

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

I use XAMPP and had the same error. I used Paul Gobée solution above and it worked for me. I navigated to C:\xampp\mysql\bin\mysqld-debug.exe and upon starting the .exe my Windows Firewall popped up asking for permission. Once I allowed it, it worked fine. I would have commented under his post but I do not have that much rep yet... sry! Just wanted to let everyone know this worked for me as well.

How to align absolutely positioned element to center?

If you set both left and right to zero, and left and right margins to auto you can center an absolutely positioned element.

position:absolute;
left:0;
right:0;
margin-left:auto;
margin-right:auto;

How to add headers to OkHttp request interceptor?

Faced similar issue with other samples, this Kotlin class worked for me

import okhttp3.Interceptor
import okhttp3.Response

class CustomInterceptor : Interceptor {
    override fun intercept(chain: Interceptor.Chain) : Response {               
        val request = chain.request().newBuilder()
            .header("x-custom-header", "my-value")
            .build()
        return chain.proceed(request)
    }
}

How to update /etc/hosts file in Docker image during "docker build"

Complete Answer

  1. Prepare your own hosts file you wish to add to docker container;
1.2.3.4 abc.tv
5.6.7.8 domain.xyz
1.3.5.7 odd.org
2.4.6.8 even.net
  1. COPY your hosts file into the container by adding the following line in the Dockerfile
COPY hosts /etc/hosts_extra
  1. If you know how to use ENTRYPOINT or CMD or CRON job then incorporate the following command line into it or at least run this inside the running container:
cat /etc/hosts_extra >> etc/hosts;
  1. You cannot add the following in the Dockerfile because the modification will be lost:
RUN cat /etc/hosts_extra >> etc/hosts;

Controlling fps with requestAnimationFrame?

How to easily throttle to a specific FPS:

// timestamps are ms passed since document creation.
// lastTimestamp can be initialized to 0, if main loop is executed immediately
var lastTimestamp = 0,
    maxFPS = 30,
    timestep = 1000 / maxFPS; // ms for each frame

function main(timestamp) {
    window.requestAnimationFrame(main);

    // skip if timestep ms hasn't passed since last frame
    if (timestamp - lastTimestamp < timestep) return;

    lastTimestamp = timestamp;

    // draw frame here
}

window.requestAnimationFrame(main);

Source: A Detailed Explanation of JavaScript Game Loops and Timing by Isaac Sukin

How to find files modified in last x minutes (find -mmin does not work as expected)

This may work for you. I used it for cleaning folders during deployments for deleting old deployment files.

clean_anyfolder() {
    local temp2="$1/**"; //PATH
    temp3=( $(ls -d $temp2 -t | grep "`date | awk '{print $2" "$3}'`") )
    j=0;
    while [ $j -lt ${#temp3[@]} ]
    do
            echo "to be removed ${temp3[$j]}"
            delete_file_or_folder ${temp3[$j]} 0 //DELETE HERE
        fi
        j=`expr $j + 1`
    done
}

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Minimal settings to prevent resize events

form1.FormBorderStyle = FormBorderStyle.FixedDialog;
form1.MaximizeBox = false;

How to get current class name including package name in Java?

Use this.getClass().getCanonicalName() to get the full class name.

Note that a package / class name ("a.b.C") is different from the path of the .class files (a/b/C.class), and that using the package name / class name to derive a path is typically bad practice. Sets of class files / packages can be in multiple different class paths, which can be directories or jar files.

Formatting DataBinder.Eval data

You can use it this way in aspx page

<%# DataBinder.Eval(Container.DataItem, "DateColoumnName", "{0:dd-MMM-yyyy}") %>

Creating a select box with a search option

You can use select2 . it is the best js for this job.
https://select2.org/dropdown

_x000D_
_x000D_
$(document).ready(function () {_x000D_
//change selectboxes to selectize mode to be searchable_x000D_
   $("select").select2();_x000D_
});
_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/select2.min.css" rel="stylesheet" />_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/select2.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
  <select id="select_page" style="width:200px;" class="operator"> _x000D_
         <option value="">Select a Page...</option>_x000D_
         <option value="alpha">alpha</option> _x000D_
         <option value="beta">beta</option>_x000D_
         <option value="theta">theta</option>_x000D_
         <option value="omega">omega</option>_x000D_
  </select>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

"Could not find Developer Disk Image"

1) I have experienced same issue, my Xcode version was 7.0.1, and I updated my iPhone to version 9.2, then upon using Xcode, my iPhone was shown in the section of unavailable device. Just like in image below:

enter image description here

2) But then I somehow managed to select my iPhone by clicking at
Product -> Destination -> Unavailable Device

enter image description here

3) But that didn't solved my problem, and it started showing:

Could not find Developer Disk Image

enter image description here

Solution) Then finally I downloaded latest version of Xcode version 7.2 from here and everything has worked fine for me.

Update: Whenever version of iPhone device is higher than version of Xcode, you may experience same issue, so you should update your Xcode version to remove this error.

how to convert from int to char*?

You can use boost

#include <boost/lexical_cast.hpp>
string s = boost::lexical_cast<string>( number );

How can I get session id in php and show it?

Before getting a session id you need to start a session and that is done by using: session_start() function.

Now that you have started a session you can get a session id by using: session_id().

/* A small piece of code for setting, displaying and destroying session in PHP */

<?php
session_start();
$r=session_id();

/* SOME PIECE OF CODE TO AUTHENTICATE THE USER, MOSTLY SQL QUERY... */

/* now registering a session for an authenticated user */
$_SESSION['username']=$username;

/* now displaying the session id..... */
echo "the session id id: ".$r;
echo " and the session has been registered for: ".$_SESSION['username'];


/* now destroying the session id */

if(isset($_SESSION['username']))
{
    $_SESSION=array();
    unset($_SESSION);
    session_destroy();
    echo "session destroyed...";
}
?>

Calculating Covariance with Python and Numpy

Thanks to unutbu for the explanation. By default numpy.cov calculates the sample covariance. To obtain the population covariance you can specify normalisation by the total N samples like this:

Covariance = numpy.cov(a, b, bias=True)[0][1]
print(Covariance)

or like this:

Covariance = numpy.cov(a, b, ddof=0)[0][1]
print(Covariance)

Start HTML5 video at a particular position when loading?

Using a #t=10,20 fragment worked for me.

Understanding Spring @Autowired usage

Nothing in the example says that the "classes implementing the same interface". MovieCatalog is a type and CustomerPreferenceDao is another type. Spring can easily tell them apart.

In Spring 2.x, wiring of beans mostly happened via bean IDs or names. This is still supported by Spring 3.x but often, you will have one instance of a bean with a certain type - most services are singletons. Creating names for those is tedious. So Spring started to support "autowire by type".

What the examples show is various ways that you can use to inject beans into fields, methods and constructors.

The XML already contains all the information that Spring needs since you have to specify the fully qualified class name in each bean. You need to be a bit careful with interfaces, though:

This autowiring will fail:

 @Autowired
 public void prepare( Interface1 bean1, Interface1 bean2 ) { ... }

Since Java doesn't keep the parameter names in the byte code, Spring can't distinguish between the two beans anymore. The fix is to use @Qualifier:

 @Autowired
 public void prepare( @Qualifier("bean1") Interface1 bean1,
     @Qualifier("bean2")  Interface1 bean2 ) { ... }

How do I make a WinForms app go Full Screen

I don't know if it will work on .NET 2.0, but it worked me on .NET 4.5.2. Here is the code:

using System;
using System.Drawing;
using System.Windows.Forms;

public partial class Your_Form_Name : Form
{
    public Your_Form_Name()
    {
        InitializeComponent();
    }

    // CODE STARTS HERE

    private System.Drawing.Size oldsize = new System.Drawing.Size(300, 300);
    private System.Drawing.Point oldlocation = new System.Drawing.Point(0, 0);
    private System.Windows.Forms.FormWindowState oldstate = System.Windows.Forms.FormWindowState.Normal;
    private System.Windows.Forms.FormBorderStyle oldstyle = System.Windows.Forms.FormBorderStyle.Sizable;
    private bool fullscreen = false;
    /// <summary>
    /// Goes to fullscreen or the old state.
    /// </summary>
    private void UpgradeFullscreen()
    {
        if (!fullscreen)
        {
            oldsize = this.Size;
            oldstate = this.WindowState;
            oldstyle = this.FormBorderStyle;
            oldlocation = this.Location;
            this.WindowState = System.Windows.Forms.FormWindowState.Normal;
            this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
            this.Bounds = System.Windows.Forms.Screen.PrimaryScreen.Bounds;
            fullscreen = true;
        }
        else
        {
            this.Location = oldlocation;
            this.WindowState = oldstate;
            this.FormBorderStyle = oldstyle;
            this.Size = oldsize;
            fullscreen = false;
        }
    }

    // CODE ENDS HERE
}

Usage:

UpgradeFullscreen(); // Goes to fullscreen
UpgradeFullscreen(); // Goes back to normal state
// You don't need arguments.

Notice: You MUST place it inside your Form's class (Example: partial class Form1 : Form { /* Code goes here */ } ) or it will not work because if you don't place it on any form, code this will create an exception.

How can I print out all possible letter combinations a given phone number can represent?

This is a recursive algorithm in C++11.

#include <iostream>
#include <array>
#include <list>

std::array<std::string, 10> pm = {
    "0", "1", "ABC", "DEF", "GHI", "JKL", "MNO", "PQRS", "TUV", "WXYZ"
};

void generate_mnemonic(const std::string& numbers, size_t i, std::string& m,
    std::list<std::string>& mnemonics)
{
    // Base case
    if (numbers.size() == i) {
        mnemonics.push_back(m);
        return;
    }

    for (char c : pm[numbers[i] - '0']) {
        m[i] = c;
        generate_mnemonic(numbers, i + 1, m, mnemonics);
    }
}

std::list<std::string> phone_number_mnemonics(const std::string& numbers)
{
    std::list<std::string> mnemonics;
    std::string m(numbers.size(), 0);
    generate_mnemonic(numbers, 0, m, mnemonics);
    return mnemonics;
}

int main() {
    std::list<std::string> result = phone_number_mnemonics("2276696");
    for (const std::string& s : result) {
        std::cout << s << std::endl;
    }
    return 0;
}

Javascript close alert box

I want to be able to close an alert box automatically using javascript after a certain amount of time or on a specific event (i.e. onkeypress)

A sidenote: if you have an Alert("data"), you won't be able to keep code running in background (AFAIK)... . the dialog box is a modal window, so you can't lose focus too. So you won't have any keypress or timer running...