Programs & Examples On #Windows embedded

Module 'tensorflow' has no attribute 'contrib'

If you want to use tf.contrib, you need to now copy and paste the source code from github into your script/notebook. It's annoying and doesn't always work. But that's the only workaround I've found. For example, if you wanted to use tf.contrib.opt.AdamWOptimizer, you have to copy and paste from here. https://github.com/tensorflow/tensorflow/blob/590d6eef7e91a6a7392c8ffffb7b58f2e0c8bc6b/tensorflow/contrib/opt/python/training/weight_decay_optimizers.py#L32

Email address validation in C# MVC 4 application: with or without using Regex

Don't.

Use a regex for a quick sanity check, something like .@.., but almost all langauges / frameworks have better methods for checking an e-mail address. Use that.

It is possible to validate an e-mail address with a regex, but it is a long regex. Very long.
And in the end you will be none the wiser. You'll only know that the format is valid, but you still don't know if it's an active e-mail address. The only way to find out, is by sending a confirmation e-mail.

How do you use Intent.FLAG_ACTIVITY_CLEAR_TOP to clear the Activity Stack?

For this, I use FLAG_ACTIVITY_CLEAR_TOP flag for starting Intent
(without FLAG_ACTIVITY_NEW_TASK)

and launchMode = "singleTask" in manifest for launched activity.

Seems like it works as I need - activity does not restart and all other activities are closed.

CSS Printing: Avoiding cut-in-half DIVs between pages?

@media print{
    /* use your css selector */    
    div{ 
        page-break-inside: avoid;
    }
}

For all new browser this solution works. See caniuse.com/#search=page-break-inside

Set port for php artisan.php serve

You can use many ports together for each project,

  php artisan serve --port=8000

  php artisan serve --port=8001   

  php artisan serve --port=8002

  php artisan serve --port=8003

ConcurrentModificationException for ArrayList

While iterating through the loop, you are trying to change the List value in the remove() operation. This will result in ConcurrentModificationException.

Follow the below code, which will achieve what you want and yet will not throw any exceptions

private String toString(List aDrugStrengthList) {
        StringBuilder str = new StringBuilder();
    List removalList = new ArrayList();
    for (DrugStrength aDrugStrength : aDrugStrengthList) {
        if (!aDrugStrength.isValidDrugDescription()) {
            removalList.add(aDrugStrength);
        }
    }
    aDrugStrengthList.removeAll(removalList);
    str.append(aDrugStrengthList);
    if (str.indexOf("]") != -1) {
        str.insert(str.lastIndexOf("]"), "\n          " );
    }
    return str.toString();
}

How can I find out if I have Xcode commandline tools installed?

First of all, be sure that you have downloaded it or not. Open up your terminal application, and enter $ gcc if you have not installed it you will get an alert. You can verify that you have installed it by

$ xcode-select -p
/Library/Developer/CommandLineTools

And to be sure then enter $ gcc --version

You can read more about the process here: Xcode command line tools for Mavericks

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

This works for me...

  • go to GenyMotion settings -> ADB tab
  • instead of Use Genymotion Android tools, choose custom Android SDK Tools and then browse your installed SDK.

Could not instantiate mail function. Why this error occurring

I just had this problem and found in my apache error log that sendmail was'nt installed, after installation it was all working as it should!

root@web1:~$ tail /var/log/apache2/error.log
sh: 1: /usr/sbin/sendmail: not found

[] and {} vs list() and dict(), which is better?

A box bracket pair denotes one of a list object, or an index subscript, my_List[x].

A curly brace pair denotes a dictionary object.

a_list = ['on', 'off', 1, 2]

a_dict = { on: 1, off: 2 }

How to resize Twitter Bootstrap modal dynamically based on the content

This worked for me, none of the above worked.

.modal-dialog{
    position: relative;
    display: table; /* This is important */ 
    overflow-y: auto;    
    overflow-x: auto;
    width: auto;
    min-width: 300px;   
}

How can I disable a specific LI element inside a UL?

If you still want to show the item but make it not clickable and look disabled with CSS:

CSS:

.disabled {
    pointer-events:none; //This makes it not clickable
    opacity:0.6;         //This grays it out to look disabled
}

HTML:

<li class="disabled">Disabled List Item</li>

Also, if you are using BootStrap, they already have a class called disabled for this purpose. See this example.

As @LV98 pointed out, users could change this on the client side and submit a selection you weren't expecting. You will want to validate at the server as well.

Python Variable Declaration

This might be 6 years late, but in Python 3.5 and above, you declare a variable type like this:

variable_name: type_name

or this:

variable_name # type: shinyType

So in your case(if you have a CustomObject class defined), you can do:

customObj: CustomObject

See this or that for more info.

Python: Figure out local timezone

For simple things, the following tzinfo implementation can be used, which queries the OS for time zone offsets:

import datetime
import time

class LocalTZ(datetime.tzinfo):
    _unixEpochOrdinal = datetime.datetime.utcfromtimestamp(0).toordinal()

    def dst(self, dt):
        return datetime.timedelta(0)

    def utcoffset(self, dt):
        t = (dt.toordinal() - self._unixEpochOrdinal)*86400 + dt.hour*3600 + dt.minute*60 + dt.second + time.timezone
        utc = datetime.datetime(*time.gmtime(t)[:6])
        local = datetime.datetime(*time.localtime(t)[:6])
        return local - utc


print datetime.datetime.now(LocalTZ())
print datetime.datetime(2010, 4, 27, 12, 0, 0, tzinfo=LocalTZ())

# If you're in the EU, the following datetimes are right on the DST change.
print datetime.datetime(2013, 3, 31, 0, 59, 59, tzinfo=LocalTZ())
print datetime.datetime(2013, 3, 31, 1, 0, 0, tzinfo=LocalTZ())
print datetime.datetime(2013, 3, 31, 1, 59, 59, tzinfo=LocalTZ())

# The following datetime is invalid, as the clock moves directly from
# 01:59:59 standard time to 03:00:00 daylight savings time.
print datetime.datetime(2013, 3, 31, 2, 0, 0, tzinfo=LocalTZ())

print datetime.datetime(2013, 10, 27, 0, 59, 59, tzinfo=LocalTZ())
print datetime.datetime(2013, 10, 27, 1, 0, 0, tzinfo=LocalTZ())
print datetime.datetime(2013, 10, 27, 1, 59, 59, tzinfo=LocalTZ())

# The following datetime is ambigous, as 02:00 can be either DST or standard
# time. (It is interpreted as standard time.)
print datetime.datetime(2013, 10, 27, 2, 0, 0, tzinfo=LocalTZ())

How to restart Postgresql

You can also restart postgresql by using this command, should work on both the versions :

sudo service postgresql start

What does -z mean in Bash?

The expression -z string is true if the length of string is zero.

Is it possible to use Visual Studio on macOS?

I guess you can install it via Parallel or in any other Virtual machine with windows in it

Postgresql : syntax error at or near "-"

I have reproduced the issue in my system,

postgres=# alter user my-sys with password 'pass11';
ERROR:  syntax error at or near "-"
LINE 1: alter user my-sys with password 'pass11';
                       ^

Here is the issue,

psql is asking for input and you have given again the alter query see postgres-#That's why it's giving error at alter

postgres-# alter user "my-sys" with password 'pass11';
ERROR:  syntax error at or near "alter"
LINE 2: alter user "my-sys" with password 'pass11';
        ^

Solution is as simple as the error,

postgres=# alter user "my-sys" with password 'pass11';
ALTER ROLE

Error: Cannot find module html

I am assuming that test.html is a static file.To render static files use the static middleware like so.

app.use(express.static(path.join(__dirname, 'public')));

This tells express to look for static files in the public directory of the application.

Once you have specified this simply point your browser to the location of the file and it should display.

If however you want to render the views then you have to use the appropriate renderer for it.The list of renderes is defined in consolidate.Once you have decided which library to use just install it.I use mustache so here is a snippet of my config file

var engines = require('consolidate');

app.set('views', __dirname + '/views');
app.engine('html', engines.mustache);
app.set('view engine', 'html');

What this does is tell express to

  • look for files to render in views directory

  • Render the files using mustache

  • The extension of the file is .html(you can use .mustache too)

Android ListView with Checkbox and all clickable

Below code will help you:

public class DeckListAdapter extends BaseAdapter{

      private LayoutInflater mInflater;
        ArrayList<String> teams=new ArrayList<String>();
        ArrayList<Integer> teamcolor=new ArrayList<Integer>();


        public DeckListAdapter(Context context) {
            // Cache the LayoutInflate to avoid asking for a new one each time.
            mInflater = LayoutInflater.from(context);

            teams.add("Upload");
            teams.add("Download");
            teams.add("Device Browser");
            teams.add("FTP Browser");
            teams.add("Options");

            teamcolor.add(Color.WHITE);
            teamcolor.add(Color.LTGRAY);
            teamcolor.add(Color.WHITE);
            teamcolor.add(Color.LTGRAY);
            teamcolor.add(Color.WHITE);


        }



        public int getCount() {
            return teams.size();
        }


        public Object getItem(int position) {
            return position;
        }


        public long getItemId(int position) {
            return position;
        }

       @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final ViewHolder holder;


            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.decklist, null);

                holder = new ViewHolder();
                holder.icon = (ImageView) convertView.findViewById(R.id.deckarrow);
                holder.text = (TextView) convertView.findViewById(R.id.textname);

             .......here you can use holder.text.setonclicklistner(new View.onclick.

                        for each textview


                System.out.println(holder.text.getText().toString());

                convertView.setTag(holder);
            } else {

                holder = (ViewHolder) convertView.getTag();
            }



             holder.text.setText(teams.get(position));

             if(position<teamcolor.size())
             holder.text.setBackgroundColor(teamcolor.get(position));

             holder.icon.setImageResource(R.drawable.arraocha);







            return convertView;
        }

        class ViewHolder {
            ImageView icon;
            TextView text;



        }
}

Hope this helps.

How to get DATE from DATETIME Column in SQL?

Try this:

SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)

The GETDATE() function returns the current date and time from the SQL Server.

Printing column separated by comma using Awk command line

If your only requirement is to print the third field of every line, with each field delimited by a comma, you can use cut:

cut -d, -f3 file
  • -d, sets the delimiter to a comma
  • -f3 specifies that only the third field is to be printed

How to save MySQL query output to excel or .txt file?

From Save MySQL query results into a text or CSV file:

MySQL provides an easy mechanism for writing the results of a select statement into a text file on the server. Using extended options of the INTO OUTFILE nomenclature, it is possible to create a comma separated value (CSV) which can be imported into a spreadsheet application such as OpenOffice or Excel or any other application which accepts data in CSV format.

Given a query such as

SELECT order_id,product_name,qty FROM orders

which returns three columns of data, the results can be placed into the file /tmp/orders.txt using the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.txt'

This will create a tab-separated file, each row on its own line. To alter this behavior, it is possible to add modifiers to the query:

SELECT order_id,product_name,qty FROM orders
INTO OUTFILE '/tmp/orders.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'

In this example, each field will be enclosed in double quotes, the fields will be separated by commas, and each row will be output on a new line separated by a newline (\n). Sample output of this command would look like:

"1","Tech-Recipes sock puppet","14.95" "2","Tech-Recipes chef's hat","18.95"

Keep in mind that the output file must not already exist and that the user MySQL is running as has write permissions to the directory MySQL is attempting to write the file to.

Syntax

   SELECT Your_Column_Name
    FROM Your_Table_Name
    INTO OUTFILE 'Filename.csv'
    FIELDS TERMINATED BY ','
    ENCLOSED BY '"'
    LINES TERMINATED BY '\n'

Or you could try to grab the output via the client:

You could try executing the query from the your local client and redirect the output to a local file destination:

mysql -user -pass -e "select cols from table where cols not null" > /tmp/output

Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv' or INTO OUTFILE './output.csv', it will store the output file to the directory specified by show variables like 'datadir';.

Recursive query in SQL Server

Something like this (not tested)

with match_groups as (

  select product_id, 
         matching_product_id,
         product_id as group_id
  from matches
  where product_id not in (select matching_product_id from matches)

  union all

  select m.product_id, m.matching_product_id, p.group_id
  from matches m
    join match_groups p on m.product_id = p.matching_product_id
)
select group_id, product_id
from match_groups
order by group_id;

How can I create a simple message box in Python?

On Mac, the python standard library has a module called EasyDialogs. There is also a (ctypes based) windows version at http://www.averdevelopment.com/python/EasyDialogs.html

If it matters to you: it uses native dialogs and doesn't depend on Tkinter like the already mentioned easygui, but it might not have as much features.

How to escape a JSON string containing newline characters using JavaScript?

Looks like this is an ancient post really :-) But guys, the best workaround I have for this, to be 100% that it works without complicated code, is to use both functions of encoding/decoding to base64. These are atob() and btoa(). By far the easiest and best way, no need to worry if you missed any characters to be escaped.

George

Node Version Manager install - nvm command not found

First add following lines in ~/.bashrc file

export NVM_DIR="$HOME/.nvm"
[ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh"  # This loads nvm
[ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion"  # This loads nvm bash_completion

then open terminal and source the nvm.sh script

source ~/.nvm/nvm.sh

How to convert list of numpy arrays into single numpy array?

In general you can concatenate a whole sequence of arrays along any axis:

numpy.concatenate( LIST, axis=0 )

but you do have to worry about the shape and dimensionality of each array in the list (for a 2-dimensional 3x5 output, you need to ensure that they are all 2-dimensional n-by-5 arrays already). If you want to concatenate 1-dimensional arrays as the rows of a 2-dimensional output, you need to expand their dimensionality.

As Jorge's answer points out, there is also the function stack, introduced in numpy 1.10:

numpy.stack( LIST, axis=0 )

This takes the complementary approach: it creates a new view of each input array and adds an extra dimension (in this case, on the left, so each n-element 1D array becomes a 1-by-n 2D array) before concatenating. It will only work if all the input arrays have the same shape—even along the axis of concatenation.

vstack (or equivalently row_stack) is often an easier-to-use solution because it will take a sequence of 1- and/or 2-dimensional arrays and expand the dimensionality automatically where necessary and only where necessary, before concatenating the whole list together. Where a new dimension is required, it is added on the left. Again, you can concatenate a whole list at once without needing to iterate:

numpy.vstack( LIST )

This flexible behavior is also exhibited by the syntactic shortcut numpy.r_[ array1, ...., arrayN ] (note the square brackets). This is good for concatenating a few explicitly-named arrays but is no good for your situation because this syntax will not accept a sequence of arrays, like your LIST.

There is also an analogous function column_stack and shortcut c_[...], for horizontal (column-wise) stacking, as well as an almost-analogous function hstack—although for some reason the latter is less flexible (it is stricter about input arrays' dimensionality, and tries to concatenate 1-D arrays end-to-end instead of treating them as columns).

Finally, in the specific case of vertical stacking of 1-D arrays, the following also works:

numpy.array( LIST )

...because arrays can be constructed out of a sequence of other arrays, adding a new dimension to the beginning.

Java heap terminology: young, old and permanent generations?

The Heap is divided into young and old generations as follows :

Young Generation : It is place where lived for short period and divided into two spaces:

  • Eden Space : When object created using new keyword memory allocated on this space.
  • Survivor Space : This is the pool which contains objects which have survived after java garbage collection from Eden space.

Old Generation : This pool basically contains tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from Young Generation.

  • Tenured Space: This memory pool contains objects which survived after multiple garbage collection means object which survived after garbage collection from Survivor space.

Permanent Generation : This memory pool as name also says contain permanent class metadata and descriptors information so PermGen space always reserved for classes and those that is tied to the classes for example static members.

Java8 Update: PermGen is replaced with Metaspace which is very similar.
Main difference is that Metaspace re-sizes dynamically i.e., It can expand at runtime.
Java Metaspace space: unbounded (default)

Code Cache (Virtual or reserved) : If you are using HotSpot Java VM this includes code cache area that containing memory which will be used for compilation and storage of native code.

enter image description here

Courtesy

Print out the values of a (Mat) matrix in OpenCV C++

#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <iostream>
#include <iomanip>

using namespace cv;
using namespace std;

int main(int argc, char** argv)
{
    double data[4] = {-0.0000000077898273846583732, -0.03749374753019832, -0.0374787251930463, -0.000000000077893623846343843};
    Mat src = Mat(1, 4, CV_64F, &data);
    for(int i=0; i<4; i++)
        cout << setprecision(3) << src.at<double>(0,i) << endl;

    return 0;
}

Invoke-WebRequest, POST with parameters

For some picky web services, the request needs to have the content type set to JSON and the body to be a JSON string. For example:

Invoke-WebRequest -UseBasicParsing http://example.com/service -ContentType "application/json" -Method POST -Body "{ 'ItemID':3661515, 'Name':'test'}"

or the equivalent for XML, etc.

How to disable the back button in the browser using JavaScript

Our approach is simple, but it works! :)

When a user clicks our LogOut button, we simply open the login page (or any page) and close the page we are on...simulating opening in new browser window without any history to go back to.

<input id="btnLogout" onclick="logOut()" class="btn btn-sm btn-warning" value="Logout" type="button"/>
<script>
    function logOut() {
        window.close = function () { 
            window.open('Default.aspx', '_blank'); 
        };
    }
</script>

Bootstrap 4 multiselect dropdown

Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3

NOTE: this component only works in since version 1.13.0

_x000D_
_x000D_
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
  <option>Mustard</option>_x000D_
  <option>Ketchup</option>_x000D_
  <option>Relish</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

SVN repository backup strategies

Here is a Perl script that will:

  1. Backup the repo
  2. Copy it to another server via SCP
  3. Retrieve the backup
  4. Create a test repository from the backup
  5. Do a test checkout
  6. Email you with any errors (via cron)

The script:

my $svn_repo = "/var/svn";  
my $bkup_dir = "/home/backup_user/backups";
my $bkup_file = "my_backup-";
my $tmp_dir = "/home/backup_user/tmp";   
my $bkup_svr = "my.backup.com";
my $bkup_svr_login = "backup";

$bkup_file = $bkup_file . `date +%Y%m%d-%H%M`;
chomp $bkup_file;
my $youngest = `svnlook youngest $svn_repo`;
chomp $youngest;

my $dump_command = "svnadmin  -q dump $svn_repo > $bkup_dir/$bkup_file ";
print "\nDumping Subversion repo $svn_repo to $bkup_file...\n";
print `$dump_command`;
print "Backing up through revision $youngest... \n";
print "\nCompressing dump file...\n";
print `gzip -9 $bkup_dir/$bkup_file\n`;
chomp $bkup_file;
my $zipped_file = $bkup_dir . "/" . $bkup_file . ".gz";
print "\nCreated $zipped_file\n";
print `scp $zipped_file $bkup_svr_login\@$bkup_svr:/home/backup/`;
print "\n$bkup_file.gz transfered to $bkup_svr\n";

#Test Backup
print "\n---------------------------------------\n";
print "Testing Backup";
print "\n---------------------------------------\n";
print "Downloading $bkup_file.gz from $bkup_svr\n";
print `scp $bkup_svr_login\@$bkup_svr:/home/backup/$bkup_file.gz $tmp_dir/`;
print "Unzipping $bkup_file.gz\n";
print `gunzip $tmp_dir/$bkup_file.gz`;
print "Creating test repository\n";
print `svnadmin create $tmp_dir/test_repo`;
print "Loading repository\n";
print `svnadmin -q load $tmp_dir/test_repo < $tmp_dir/$bkup_file`;
print "Checking out repository\n";
print `svn -q co file://$tmp_dir/test_repo $tmp_dir/test_checkout`;
print "Cleaning up\n";
print `rm -f $tmp_dir/$bkup_file`;
print `rm -rf $tmp_dir/test_checkout`;
print `rm -rf $tmp_dir/test_repo`;

Script source and more details about the rational for this type of backup.

else & elif statements not working in Python

Besides that your indention is wrong. The code wont work. I know you are using python 3. something. I am using python 2.7.3 the code that will actually work for what you trying accomplish is this.

number = str(23)
guess =  input('Enter a number: ')
if guess == number:
   print('Congratulations! You guessed it.')
elif guess < number:
     print('Wrong Number')
elif guess < number:
     print("Wrong Number')

The only difference I would tell python that number is a string of character for the code to work. If not is going to think is a Integer. When somebody runs the code they are inputing a string not an integer. There are many ways of changing this code but this is the easy solution I wanted to provide there is another way that I cant think of without making the 23 into a string. Or you could of "23" put quotations or you could of use int() function in the input. that would transform anything they input into and integer a number.

What does <a href="#" class="view"> mean?

It probably works with Javascript. When you click the link, nothing happens because it points to the current site. The javascript will then load a window or an url. It's used a lot in AJAX web apps.

Difference between @Mock and @InjectMocks

@Mock annotation mocks the concerned object.

@InjectMocks annotation allows to inject into the underlying object the different (and relevant) mocks created by @Mock.

Both are complementary.

Function stoi not declared

In comments under another answer, you indicated you are using a dodgy version of g++ under MS Windows.

In this case, -std=c++11 as suggested by the top answer would still not fix the problem.

Please see the following thread which does discuss your situation: std::stoi doesn't exist in g++ 4.6.1 on MinGW

Error With Port 8080 already in use

if you are running from inside eclipse with wtp, you should be able to change the port from the "servers" view (window -> show view -> servers)

How to get a pixel's x,y coordinate color from an image?

Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:

getPixel from HTML Canvas?

Some code that would serve you specifically as well:

var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;

for (var i = 0, n = pix.length; i < n; i += 4) {
  console.log pix[i+3]
}

This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.

Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:

$('el').click(function(e){
   console.log(e.clientX, e.clientY)
}

Those should grab your x and y values.

Run react-native on android emulator

You probably haven't run the Android SDK in forever. So you probably just have to update it. If you open the Android Studio Software it'll probably let you know that and ask to update it for you. Otherwise refer to following link: Update Android SDK

Add default value of datetime field in SQL Server to a timestamp

While the marked answer is correct with:

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn

You should always be aware of timezones when adding default datetime values in to a column.

Say for example, this datetime value is designed to indicate when a member joined a website and you want it to be displayed back to the user, GETDATE() will give you the server time so could show discrepancies if the user is in a different locale to the server.

If you expect to deal with international users, it is better in some cases to use GETUTCDATE(), which:

Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETUTCDATE() FOR YourColumn

When retrieving the values, the front end application/website should transform this value from UTC time to the locale/culture of the user requesting it.

How to get the name of the current Windows user in JavaScript

Working for me on IE:

<script type="text/javascript">
  var WinNetwork = new ActiveXObject("WScript.Network");
  document.write(WinNetwork.UserName);
</script>

...but ActiveX controls needs to be on in security settings.

How to capture UIView to UIImage without loss of quality on retina display

For Swift 5.1 you can use this extension:

extension UIView {

    func asImage() -> UIImage {
        let renderer = UIGraphicsImageRenderer(bounds: bounds)

        return renderer.image {
            rendererContext in

            layer.render(in: rendererContext.cgContext)
        }
    }
}

Percentage width in a RelativeLayout

Update 1

As pointed by @EmJiHash PercentRelativeLayout is deprecated in API level 26.0.0

Below quoting google comment:

This class was deprecated in API level 26.0.0. consider using ConstraintLayout and associated layouts instead. The following shows how to replicate the functionality of percentage layouts with a ConstraintLayout


Google introduced new API called android.support.percent

Then you can just specify percentage to take by view

Add compile dependency like

implementation 'com.android.support:percent:22.2.0

in that, PercentRelativeLayout is what we can do a percentage wise layout

 <android.support.percent.PercentRelativeLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:app="http://schemas.android.com/apk/res-auto"
     android:layout_width="match_parent"
     android:layout_height="match_parent">
     <ImageView
         app:layout_widthPercent="50%"
         app:layout_heightPercent="50%"
         app:layout_marginTopPercent="25%"
         app:layout_marginLeftPercent="25%"/>
 </android.support.percent.PercentRelativeLayout>

conversion from infix to prefix

(a–b)/c*(d + e – f / g)

remember scanning the expression from leftmost to right most start on parenthesized terms follow the WHICH COMES FIRST rule... *, /, % are on the same level and higher than + and -.... so (a-b) = -bc prefix (a-b) = bc- for postfix another parenthesized term: (d + e - f / g) = do move the / first then plus '+' comes first before minus sigh '-' (remember they are on the same level..) (d + e - f / g) move / first (d + e - (/fg)) = prefix (d + e - (fg/)) = postfix followed by + then - ((+de) - (/fg)) = prefix ((de+) - (fg/)) = postfix

(-(+de)(/fg)) = prefix so the new expression is now -+de/fg (1) ((de+)(fg/)-) = postfix so the new expression is now de+fg/- (2)

(a–b)/c* hence

  1. (a-b)/c*(d + e – f / g) = -bc prefix [-ab]/c*[-+de/fg] ---> taken from (1) / c * do not move yet so '/' comes first before '*' because they on the same level, move '/' to the rightmost : /[-ab]c * [-+de/fg] then move '*' to the rightmost

    • / [-ab]c[-+de/fg] = remove the grouping symbols = */-abc-+de/fg --> Prefix
  2. (a-b)/c*(d + e – f / g) = bc- for postfix [ab-]/c*[de+fg/-]---> taken from (2) so '/' comes first before '' because they on the same level, move '/' to the leftmost: [ab-]c[de+fg/-]/ then move '' to the leftmost [ab-] c [de+fg/-]/ = remove the grouping symbols= a b - c d e + f g / - / * --> Postfix

Base table or view not found: 1146 Table Laravel 5

I also had this problem when doing migration => after performing php artisan migrate:refresh --seed command

"Base table or view not found: 1146 Table posts do not exist" and I solved it, I was using "soft deletes" in a separate migration file, and my original migration for "posts" table which was responsible for creating the "posts" table was performing after the "soft deletes" migration in the database\migration folder, I simply needed to rename the "posts" migration file name and put it before "softdeletes" migration to perform sooner. the do the migration again => php artisan migrate:refresh --seed it's done.

How can I get the day of a specific date with PHP

$date = '2009-10-22';
$sepparator = '-';
$parts = explode($sepparator, $date);
$dayForDate = date("l", mktime(0, 0, 0, $parts[1], $parts[2], $parts[0]));

How to prevent a double-click using jQuery?

In my case, jQuery one had some side effects (in IE8) and I ended up using the following :

$(document).ready(function(){
  $("*").dblclick(function(e){
    e.preventDefault();
  });
});

which works very nicely and looks simpler. Found it there: http://www.jquerybyexample.net/2013/01/disable-mouse-double-click-using-javascript-or-jquery.html

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

Angelika Langers Secrets of equals gets into that with a long and detailed discussion for a few common and well-known examples, including by Josh Bloch and Barbara Liskov, discovering a couple of problems in most of them. She also gets into the instanceof vs getClass. Some quote from it

Conclusions

Having dissected the four arbitrarily chosen examples of implementations of equals() , what do we conclude?

First of all: there are two substantially different ways of performing the check for type match in an implementation of equals() . A class can allow mixed-type comparison between super- and subclass objects by means of the instanceof operator, or a class can treat objects of different type as non-equal by means of the getClass() test. The examples above illustrated nicely that implementations of equals() using getClass() are generally more robust than those implementations using instanceof .

The instanceof test is correct only for final classes or if at least method equals() is final in a superclass. The latter essentially implies that no subclass must extend the superclass's state, but can only add functionality or fields that are irrelevant for the object's state and behavior, such as transient or static fields.

Implementations using the getClass() test on the other hand always comply to the equals() contract; they are correct and robust. They are, however, semantically very different from implementations that use the instanceof test. Implementations using getClass() do not allow comparison of sub- with superclass objects, not even when the subclass does not add any fields and would not even want to override equals() . Such a "trivial" class extension would for instance be the addition of a debug-print method in a subclass defined for exactly this "trivial" purpose. If the superclass prohibits mixed-type comparison via the getClass() check, then the trivial extension would not be comparable to its superclass. Whether or not this is a problem fully depends on the semantics of the class and the purpose of the extension.

How to import data from one sheet to another

VLookup

You can do it with a simple VLOOKUP formula. I've put the data in the same sheet, but you can also reference a different worksheet. For the price column just change the last value from 2 to 3, as you are referencing the third column of the matrix "A2:C4". VLOOKUP example

External Reference

To reference a cell of the same Workbook use the following pattern:

<Sheetname>!<Cell>

Example:

Table1!A1

To reference a cell of a different Workbook use this pattern:

[<Workbook_name>]<Sheetname>!<Cell>

Example:

[MyWorkbook]Table1!A1

How to check if IEnumerable is null or empty?

Here's the code from Marc Gravell's answer, along with an example of using it.

using System;
using System.Collections.Generic;
using System.Linq;

public static class Utils
{
    public static bool IsAny<T>(this IEnumerable<T> data)
    {
        return data != null && data.Any();
    }
}

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> items;
        //items = null;
        //items = new String[0];
        items = new String[] { "foo", "bar", "baz" };

        /*** Example Starts Here ***/
        if (items.IsAny())
        {
            foreach (var item in items)
            {
                Console.WriteLine(item);
            }
        }
        else
        {
            Console.WriteLine("No items.");
        }
    }
}

As he says, not all sequences are repeatable, so that code may sometimes cause problems, because IsAny() starts stepping through the sequence. I suspect what Robert Harvey's answer meant was that you often don't need to check for null and empty. Often, you can just check for null and then use foreach.

To avoid starting the sequence twice and take advantage of foreach, I just wrote some code like this:

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        IEnumerable<string> items;
        //items = null;
        //items = new String[0];
        items = new String[] { "foo", "bar", "baz" };

        /*** Example Starts Here ***/
        bool isEmpty = true;
        if (items != null)
        {
            foreach (var item in items)
            {
                isEmpty = false;
                Console.WriteLine(item);
            }
        }
        if (isEmpty)
        {
            Console.WriteLine("No items.");
        }
    }
}

I guess the extension method saves you a couple of lines of typing, but this code seems clearer to me. I suspect that some developers wouldn't immediately realize that IsAny(items) will actually start stepping through the sequence. (Of course if you're using a lot of sequences, you quickly learn to think about what steps through them.)

ROW_NUMBER() in MySQL

Check out this Article, it shows how to mimic SQL ROW_NUMBER() with a partition by in MySQL. I ran into this very same scenario in a WordPress Implementation. I needed ROW_NUMBER() and it wasn't there.

http://www.explodybits.com/2011/11/mysql-row-number/

The example in the article is using a single partition by field. To partition by additional fields you could do something like this:

  SELECT  @row_num := IF(@prev_value=concat_ws('',t.col1,t.col2),@row_num+1,1) AS RowNumber
         ,t.col1 
         ,t.col2
         ,t.Col3
         ,t.col4
         ,@prev_value := concat_ws('',t.col1,t.col2)
    FROM table1 t,
         (SELECT @row_num := 1) x,
         (SELECT @prev_value := '') y
   ORDER BY t.col1,t.col2,t.col3,t.col4 

Using concat_ws handles null's. I tested this against 3 fields using an int, date, and varchar. Hope this helps. Check out the article as it breaks this query down and explains it.

CSS to make HTML page footer stay at bottom of the page with a minimum height, but not overlap the page

I have used in my many projects and never got any single issue :)

for your reference, Code are in snippet

_x000D_
_x000D_
* {_x000D_
 margin: 0;_x000D_
}_x000D_
html, body {_x000D_
 height: 100%;_x000D_
}_x000D_
.wrapper {_x000D_
 min-height: 100%;_x000D_
 height: auto !important; /* This line and the next line are not necessary unless you need IE6 support */_x000D_
 height: 100%;_x000D_
 margin: 0 auto -50px; /* the bottom margin is the negative value of the footer's height */_x000D_
  background:green;_x000D_
}_x000D_
.footer, .push {_x000D_
 height: 50px; /* .push must be the same height as .footer */_x000D_
}_x000D_
_x000D_
.footer{_x000D_
  background:gold;_x000D_
  }
_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<title>Untitled Document</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="wrapper">_x000D_
    Content Area_x000D_
    </div>_x000D_
  _x000D_
  <div class="push">_x000D_
    </div>_x000D_
  _x000D_
  <div class="footer">_x000D_
    Footer Area_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Using node.js as a simple web server

This is one of the fastest solutions i use to quickly see web pages

sudo npm install ripple-emulator -g

From then on just enter the directory of your html files and run

ripple emulate

then change the device to Nexus 7 landscape.

Convert YYYYMMDD string date to a datetime value

You should have to use DateTime.TryParseExact.

var newDate = DateTime.ParseExact("20111120", 
                                  "yyyyMMdd", 
                                   CultureInfo.InvariantCulture);

OR

string str = "20111021";
string[] format = {"yyyyMMdd"};
DateTime date;

if (DateTime.TryParseExact(str, 
                           format, 
                           System.Globalization.CultureInfo.InvariantCulture,
                           System.Globalization.DateTimeStyles.None, 
                           out date))
{
     //valid
}

Android SDK location should not contain whitespace, as this cause problems with NDK tools

Just change

C:\Users\Giacomo B\AppData\Local\Android\sdk

to

C:\Users\Giacomo_B\AppData\Local\Android\sdk

Set an empty DateTime variable

The method you used (AddWithValue) doesn't convert null values to database nulls. You should use DBNull.Value instead:

myCommand.Parameters.AddWithValue(
    "@SurgeryDate", 
    someDate == null ? DBNull.Value : (object)someDate
);

This will pass the someDate value if it is not null, or DBNull.Value otherwise. In this case correct value will be passed to the database.

How to add number of days in postgresql datetime

For me I had to put the whole interval in single quotes not just the value of the interval.

select id,  
   title,
   created_at + interval '1 day' * claim_window as deadline from projects   

Instead of

select id,  
   title,
   created_at + interval '1' day * claim_window as deadline from projects   

Postgres Date/Time Functions

What is the difference between parseInt(string) and Number(string) in JavaScript?

The parseInt function allows you to specify a radix for the input string and is limited to integer values.

parseInt('Z', 36) === 35

The Number constructor called as a function will parse the string with a grammar and is limited to base 10 and base 16.

StringNumericLiteral :::
    StrWhiteSpaceopt 
    StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt

StrWhiteSpace :::
    StrWhiteSpaceChar StrWhiteSpaceopt

StrWhiteSpaceChar :::
    WhiteSpace 
    LineTerminator

StrNumericLiteral :::
    StrDecimalLiteral 
    HexIntegerLiteral

StrDecimalLiteral :::
    StrUnsignedDecimalLiteral 
    + StrUnsignedDecimalLiteral 
    - StrUnsignedDecimalLiteral

StrUnsignedDecimalLiteral :::
    Infinity 
    DecimalDigits . DecimalDigitsopt ExponentPartopt 
    . DecimalDigits ExponentPartopt     
    DecimalDigits ExponentPartopt

DecimalDigits :::
    DecimalDigit 
    DecimalDigits DecimalDigit

DecimalDigit ::: one of
    0 1 2 3 4 5 6 7 8 9

ExponentPart :::
    ExponentIndicator SignedInteger

ExponentIndicator ::: one of
    e E

SignedInteger :::
    DecimalDigits 
    + DecimalDigits 
    - DecimalDigits

HexIntegerLiteral :::
    0x HexDigit 
    0X HexDigit 
    HexIntegerLiteral HexDigit

HexDigit ::: one of
    0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

Init function in javascript and how it works

In simple word you can understand that whenever page load, by this second pair of brackets () function will have called default.We need not call the function.It is known as anonymous function.

i.e.

(function(a,b){
//Do your code here
})(1,2);

It same like as

var test = function(x,y) {
  // Do your code here
}
test(1,2);

Can I run javascript before the whole page is loaded?

You can run javascript code at any time. AFAIK it is executed at the moment the browser reaches the <script> tag where it is in. But you cannot access elements that are not loaded yet.

So if you need access to elements, you should wait until the DOM is loaded (this does not mean the whole page is loaded, including images and stuff. It's only the structure of the document, which is loaded much earlier, so you usually won't notice a delay), using the DOMContentLoaded event or functions like $.ready in jQuery.

How can I load Partial view inside the view?

If you do it with a @Html.ActionLink() then loading the PartialView is handled as a normal request when clicking a anchor-element, i.e. load new page with the reponse of the PartialViewResult method.
If you want to load it immedialty, then you use @Html.RenderPartial("_LoadView") or @Html.RenderAction("Load").
If you want to do it upon userinteraction (i.e. clicking a link) then you need to use AJAX --> @Ajax.ActionLink()

String to HtmlDocument

You could try with OpenNew and then with Write but that's a bit strange use of that class. More info on MSDN.

How to compare if two structs, slices or maps are equal?

You can use reflect.DeepEqual, or you can implement your own function (which performance wise would be better than using reflection):

http://play.golang.org/p/CPdfsYGNy_

m1 := map[string]int{   
    "a":1,
    "b":2,
}
m2 := map[string]int{   
    "a":1,
    "b":2,
}
fmt.Println(reflect.DeepEqual(m1, m2))

Java generics - ArrayList initialization

The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.

ArrayList<A> a = new ArrayList<A>();

Here a is a reference to an instance of a specific type - exactly an array list of As. More explicitly, a is a reference to an array list that will accept As and will produce As. new ArrayList<A>() is an instance of an array list of As, that is, an array list that will accept As and will produce As.

ArrayList<Integer> a = new ArrayList<Number>(); 

Here, a is a reference to exactly an array list of Integers, i.e. exactly an array list that can accept Integers and will produce Integers. It cannot point to an array list of Numbers. That array list of Numbers can not meet all the promises of ArrayList<Integer> a (i.e. an array list of Numbers may produce objects that are not Integers, even though its empty right then).

ArrayList<Number> a = new ArrayList<Integer>(); 

Here, declaration of a says that a will refer to exactly an array list of Numbers, that is, exactly an array list that will accept Numbers and will produce Numbers. It cannot point to an array list of Integers, because the type declaration of a says that a can accept any Number, but that array list of Integers cannot accept just any Number, it can only accept Integers.

ArrayList<? extends Object> a= new ArrayList<Object>();

Here a is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family. However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic). In this case, a is a reference to an array list that will produce Objects. But, unlike a type-specific list reference, this a reference cannot accept any Object. (i.e. not every member of the family of types that a can point to can accept any Object, e.g. an array list of Integers can only accept Integers.)

ArrayList<? super Integer> a = new ArrayList<Number>();

Again, a is a reference to a family of types (rather than a single specific type). Since the wildcard uses super, this list reference can accept Integers, but it cannot produce Integers. Said another way, we know that any and every member of the family of types that a can point to can accept an Integer. However, not every member of that family can produce Integers.

PECS - Producer extends, Consumer super - This mnemonic helps you remember that using extends means the generic type can produce the specific type (but cannot accept it). Using super means the generic type can consume (accept) the specific type (but cannot produce it).

ArrayList<ArrayList<?>> a

An array list that holds references to any list that is a member of a family of array lists types.

= new ArrayList<ArrayList<?>>(); // correct

An instance of an array list that holds references to any list that is a member of a family of array lists types.

ArrayList<?> a

An reference to any array list (a member of the family of array list types).

= new ArrayList<?>()

ArrayList<?> refers to any type from a family of array list types, but you can only instantiate a specific type.


See also How can I add to List<? extends Number> data structures?

oracle - what statements need to be committed?

DML (Data Manipulation Language) commands need to be commited/rolled back. Here is a list of those commands.

Data Manipulation Language (DML) statements are used for managing data within schema objects. Some examples:

INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes records from a table, the space for the records remain
MERGE - UPSERT operation (insert or update)
CALL - call a PL/SQL or Java subprogram
EXPLAIN PLAN - explain access path to data
LOCK TABLE - control concurrency

javascript regex for password containing at least 8 characters, 1 number, 1 upper and 1 lowercase

Your regular expression should look like:

/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])[0-9a-zA-Z]{8,}$/

Here is an explanation:

/^
  (?=.*\d)          // should contain at least one digit
  (?=.*[a-z])       // should contain at least one lower case
  (?=.*[A-Z])       // should contain at least one upper case
  [a-zA-Z0-9]{8,}   // should contain at least 8 from the mentioned characters
$/

Adding a leading zero to some values in column in MySQL

A previous answer using LPAD() is optimal. However, in the event you want to do special or advanced processing, here is a method that allows more iterative control over the padding. Also serves as an example using other constructs to achieve the same thing.

UPDATE
    mytable
SET
    mycolumn = CONCAT(
        REPEAT(
            "0",
            8 - LENGTH(mycolumn)
        ),
        mycolumn
    )
WHERE
    LENGTH(mycolumn) < 8;

How to insert a picture into Excel at a specified cell position with VBA

If it's simply about inserting and resizing a picture, try the code below.

For the specific question you asked, the property TopLeftCell returns the range object related to the cell where the top left corner is parked. To place a new image at a specific place, I recommend creating an image at the "right" place and registering its top and left properties values of the dummy onto double variables.

Insert your Pic assigned to a variable to easily change its name. The Shape Object will have that same name as the Picture Object.

Sub Insert_Pic_From_File(PicPath as string, wsDestination as worksheet)
    Dim Pic As Picture, Shp as Shape
    Set Pic = wsDestination.Pictures.Insert(FilePath)
    Pic.Name = "myPicture"
    'Strongly recommend using a FileSystemObject.FileExists method to check if the path is good before executing the previous command
    Set Shp = wsDestination.Shapes("myPicture")
    With Shp
        .Height = 100
        .Width = 75
        .LockAspectRatio = msoTrue  'Put this later so that changing height doesn't change width and vice-versa)
        .Placement = 1
        .Top = 100
        .Left = 100
    End with
End Sub

Good luck!

Laravel Eloquent: Ordering results of all()

You instruction require call to get, because is it bring the records and orderBy the catalog

$results = Project::orderBy('name')
           ->get();

Example:

$results = Result::where ('id', '>=', '20')
->orderBy('id', 'desc')
->get();

In the example the data is filtered by "where" and bring records greater than 20 and orderBy catalog by order from high to low.

SQL Server: Attach incorrect version 661

SQL Server 2008 databases are version 655. SQL Server 2008 R2 databases are 661. You are trying to attach an 2008 R2 database (v. 661) to an 2008 instance and this is not supported. Once the database has been upgraded to an 2008 R2 version, it cannot be downgraded. You'll have to either upgrade your 2008 SP2 instance to R2, or you have to copy out the data in that database into an 2008 database (eg using the data migration wizard, or something equivalent).

The message is misleading, to say the least, it says 662 because SQL Server 2008 SP2 does support 662 as a database version, this is when 15000 partitions are enabled in the database, see Support for 15000 Partitions.docx. Enabling the support bumps the DB version to 662, disabling it moves it back to 655. But SQL Server 2008 SP2 does not support 661 (the R2 version).

BeanFactory not initialized or already closed - call 'refresh' before

In my case, this error was due to the Network connection error that i was noticed in log.

HTTP Range header

Contrary to Mark Novakowski answer, which for some reason has been upvoted by many, yes, it is a valid and satisfiable request.

In fact the standard, as Wrikken pointed out, makes just such an example. In practice, Apache responds to such requests as expected (with a 206 code), and this is exactly what I use to implement progressive download, that is, only get the tail of a long log file which grows in real time with polling.

Sending data through POST request from a node.js server to a node.js server

You can also use Requestify, a really cool and very simple HTTP client I wrote for nodeJS + it supports caching.

Just do the following for executing a POST request:

var requestify = require('requestify');

requestify.post('http://example.com', {
    hello: 'world'
})
.then(function(response) {
    // Get the response body (JSON parsed or jQuery object for XMLs)
    response.getBody();
});

Jersey Exception : SEVERE: A message body reader for Java class

If you are building an uberjar or "shaded jar", make sure your meta inf service files are merged. (This bit me multiple times on a dropwizard project.)

If you are using the gradle shadowJar plugin, you want to call mergeServiceFiles() in your shadowJar target: https://github.com/johnrengelman/shadow#merging-service-files

Not sure what the analogous commands are for maven or other build systems.

Laravel Unknown Column 'updated_at'

Setting timestamps to false means you are going to lose both created_at and updated_at whereas you could set both of the keys in your model.

Case 1:

You have created_at column but not update_at you could simply set updated_at to false in your model

class ABC extends Model {

const UPDATED_AT = null;

Case 2:

You have both created_at and updated_at columns but with different column names

You could simply do:

class ABC extends Model {

const CREATED_AT = 'name_of_created_at_column';
const UPDATED_AT = 'name_of_updated_at_column';

Finally ignoring timestamps completely:

class ABC extends Model {

public $timestamps = false;

Compute row average in pandas

You can specify a new column. You also need to compute the mean along the rows, so use axis=1.

df['mean'] = df.mean(axis=1)
>>> df
       Y1961      Y1962      Y1963      Y1964      Y1965 Region       mean
0  82.567307  83.104757  83.183700  83.030338  82.831958     US  82.943612
1   2.699372   2.610110   2.587919   2.696451   2.846247     US   2.688020
2  14.131355  13.690028  13.599516  13.649176  13.649046     US  13.743824
3   0.048589   0.046982   0.046583   0.046225   0.051750     US   0.048026
4   0.553377   0.548123   0.582282   0.577811   0.620999     US   0.576518

Remove all multiple spaces in Javascript and replace with single space

There are a lot of options for regular expressions you could use to accomplish this. One example that will perform well is:

str.replace( /\s\s+/g, ' ' )

See this question for a full discussion on this exact problem: Regex to replace multiple spaces with a single space

How to URL encode a string in Ruby

str = "\x12\x34\x56\x78\x9a\xbc\xde\xf1\x23\x45\x67\x89\xab\xcd\xef\x12\x34\x56\x78\x9a"
require 'cgi'
CGI.escape(str)
# => "%124Vx%9A%BC%DE%F1%23Eg%89%AB%CD%EF%124Vx%9A"

Taken from @J-Rou's comment

the getSource() and getActionCommand()

Assuming you are talking about the ActionEvent class, then there is a big difference between the two methods.

getActionCommand() gives you a String representing the action command. The value is component specific; for a JButton you have the option to set the value with setActionCommand(String command) but for a JTextField if you don't set this, it will automatically give you the value of the text field. According to the javadoc this is for compatability with java.awt.TextField.

getSource() is specified by the EventObject class that ActionEvent is a child of (via java.awt.AWTEvent). This gives you a reference to the object that the event came from.

Edit:

Here is a example. There are two fields, one has an action command explicitly set, the other doesn't. Type some text into each then press enter.

public class Events implements ActionListener {

  private static JFrame frame; 

  public static void main(String[] args) {

    frame = new JFrame("JTextField events");
    frame.getContentPane().setLayout(new FlowLayout());

    JTextField field1 = new JTextField(10);
    field1.addActionListener(new Events());
    frame.getContentPane().add(new JLabel("Field with no action command set"));
    frame.getContentPane().add(field1);

    JTextField field2 = new JTextField(10);
    field2.addActionListener(new Events());
    field2.setActionCommand("my action command");
    frame.getContentPane().add(new JLabel("Field with an action command set"));
    frame.getContentPane().add(field2);


    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setSize(220, 150);
    frame.setResizable(false);
    frame.setVisible(true);
  }

  @Override
  public void actionPerformed(ActionEvent evt) {
    String cmd = evt.getActionCommand();
    JOptionPane.showMessageDialog(frame, "Command: " + cmd);
  }

}

What does void do in java?

When the return type is void, your method doesn't return anything.

Look again at your code: There's no return in that method. You print to the console and exit.

JavaScript Nested function

It is called closure.

Basically, the function defined within other function is accessible only within this function. But may be passed as a result and then this result may be called.

It is a very powerful feature. You can see more explanation here:

javascript_closures_for_dummies.html mirror on Archive.org

Handling click events on a drawable within an EditText

That last contribution's use of contains(x,y) won't work directly on the result of getBounds() (except, by coincidence, when using "left" drawables). The getBounds method only provides the Rect defining points of the drawable item normalized with origin at 0,0 - so, you actually need to do the math of the original post to find out if the click is in the area of the drawable in the context of the containing EditText's dimensions, but change it for top, right, left etc. Alternatively you could describe a Rect that has coordinates actually relative to its position in the EditText container and use contains(), although in the end you're doing the same math.

Combining them both gives you a pretty complete solution, I only added an instance attribute consumesEvent that lets the API user decide if the click event should be passed on or not by using its result to set ACTION_CANCEL or not.

Also, I can't see why the bounds and actionX, actionY values are instance attributes rather than just local on the stack.

Here's a cutout from an implementation based on the above that I put together. It fixes an issue that to properly consume the event you need to return false. It adds a "fuzz" factor to. In my use case of a Voice control icon in an EditText field, I found it hard to click, so the fuzz increases the effective bounds that are considered clicking the drawable. For me 15 worked well. I only needed drawableRight so I didn't plug the math in the others, to save some space, but you see the idea.

package com.example.android;

import android.content.Context;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.widget.EditText;
import android.graphics.Rect;

import com.example.android.DrawableClickListener;

public class ClickableButtonEditText extends EditText {
  public static final String LOG_TAG = "ClickableButtonEditText";

  private Drawable drawableRight;
  private Drawable drawableLeft;
  private Drawable drawableTop;
  private Drawable drawableBottom;
  private boolean consumeEvent = false;
  private int fuzz = 0;

  private DrawableClickListener clickListener;

  public ClickableButtonEditText(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
  }

  public ClickableButtonEditText(Context context, AttributeSet attrs) {
    super(context, attrs);
  }

  public ClickableButtonEditText(Context context) {
    super(context);
  }

  public void consumeEvent() {
    this.setConsumeEvent(true);
  }

  public void setConsumeEvent(boolean b) {
    this.consumeEvent = b;
  }

  public void setFuzz(int z) {
    this.fuzz = z;
  }

  public int getFuzz() {
    return fuzz;
  }

  @Override
  public void setCompoundDrawables(Drawable left, Drawable top, Drawable right, Drawable bottom) {
    if (right != null) {
      drawableRight = right;
    }

    if (left != null) {
      drawableLeft = left;
    }
    super.setCompoundDrawables(left, top, right, bottom);
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    if (event.getAction() == MotionEvent.ACTION_DOWN) {
      int x, y;
      Rect bounds;
      x = (int) event.getX();
      y = (int) event.getY();
      // this works for left since container shares 0,0 origin with bounds
      if (drawableLeft != null) {
        bounds = drawableLeft.getBounds();
        if (bounds.contains(x - fuzz, y - fuzz)) {
          clickListener.onClick(DrawableClickListener.DrawablePosition.LEFT);
          if (consumeEvent) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            return false;
          }
        }
      } else if (drawableRight != null) {
        bounds = drawableRight.getBounds();
        if (x >= (this.getRight() - bounds.width() - fuzz) && x <= (this.getRight() - this.getPaddingRight() + fuzz) 
              && y >= (this.getPaddingTop() - fuzz) && y <= (this.getHeight() - this.getPaddingBottom()) + fuzz) {

          clickListener.onClick(DrawableClickListener.DrawablePosition.RIGHT);
          if (consumeEvent) {
            event.setAction(MotionEvent.ACTION_CANCEL);
            return false;
          }
        }
      } else if (drawableTop != null) {
        // not impl reader exercise :)
      } else if (drawableBottom != null) {
        // not impl reader exercise :)
      }
    }

    return super.onTouchEvent(event);
  }

  @Override
  protected void finalize() throws Throwable {
    drawableRight = null;
    drawableBottom = null;
    drawableLeft = null;
    drawableTop = null;
    super.finalize();
  }

  public void setDrawableClickListener(DrawableClickListener listener) {
    this.clickListener = listener;
  }
}

How to maintain state after a page refresh in React.js?

I consider state to be for view only information and data that should persist beyond the view state is better stored as props. URL params are useful when you want to be able to link to a page or share the URL deep in to the app but otherwise clutter the address bar.

Take a look at Redux-Persist (if you're using redux) https://github.com/rt2zz/redux-persist

Undefined behavior and sequence points

I am guessing there is a fundamental reason for the change, it isn't merely cosmetic to make the old interpretation clearer: that reason is concurrency. Unspecified order of elaboration is merely selection of one of several possible serial orderings, this is quite different to before and after orderings, because if there is no specified ordering, concurrent evaluation is possible: not so with the old rules. For example in:

f (a,b)

previously either a then b, or, b then a. Now, a and b can be evaluated with instructions interleaved or even on different cores.

Resize image proportionally with CSS?

If it's a background image, use background-size:contain.

Example css:

#your-div {
  background: url('image.jpg') no-repeat;
  background-size:contain;
}

Correct way to load a Nib for a UIView subclass

In Swift:

For example, name of your custom class is InfoView

At first, you create files InfoView.xib and InfoView.swiftlike this:

import Foundation
import UIKit

class InfoView: UIView {
    class func instanceFromNib() -> UIView {
    return UINib(nibName: "InfoView", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as! UIView
}

Then set File's Owner to UIViewController like this:

enter image description here

Rename your View to InfoView:

enter image description here

Right-click to File's Owner and connect your view field with your InfoView:

enter image description here

Make sure that class name is InfoView:

enter image description here

And after this you can add the action to button in your custom class without any problem:

enter image description here

And usage of this custom class in your MainViewController:

func someMethod() {
    var v = InfoView.instanceFromNib()
    v.frame = self.view.bounds
    self.view.addSubview(v)
}

When should I use uuid.uuid1() vs. uuid.uuid4() in python?

One thing to note when using uuid1, if you use the default call (without giving clock_seq parameter) you have a chance of running into collisions: you have only 14 bit of randomness (generating 18 entries within 100ns gives you roughly 1% chance of a collision see birthday paradox/attack). The problem will never occur in most use cases, but on a virtual machine with poor clock resolution it will bite you.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

There is a way to accomplish this. The magic is to create a combined jacoco.exec file. And with maven 3.3.1 there is an easy way to get this. Here my profile:

<profile>
    <id>runSonar</id>
    <activation>
        <property>
            <name>runSonar</name>
            <value>true</value>
        </property>
    </activation>
    <properties>
        <sonar.language>java</sonar.language>
        <sonar.host.url>http://sonar.url</sonar.host.url>
        <sonar.login>tokenX</sonar.login>
        <sonar.jacoco.reportMissing.force.zero>true</sonar.jacoco.reportMissing.force.zero>
        <sonar.jacoco.reportPath>${jacoco.destFile}</sonar.jacoco.reportPath>
        <jacoco.destFile>${maven.multiModuleProjectDirectory}/target/jacoco_analysis/jacoco.exec</jacoco.destFile>
    </properties>
    <build>
        <plugins>
            <plugin>
                <groupId>org.jacoco</groupId>
                <artifactId>jacoco-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <id>default-prepare-agent</id>
                        <goals>
                            <goal>prepare-agent</goal>
                        </goals>
                        <configuration>
                            <append>true</append>
                            <destFile>${jacoco.destFile}</destFile>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
        <pluginManagement>
            <plugins>
                <plugin>
                    <groupId>org.sonarsource.scanner.maven</groupId>
                    <artifactId>sonar-maven-plugin</artifactId>
                    <version>3.2</version>
                </plugin>
                <plugin>
                    <groupId>org.jacoco</groupId>
                    <artifactId>jacoco-maven-plugin</artifactId>
                    <version>0.7.8</version>
                </plugin>
            </plugins>
        </pluginManagement>
    </build>
</profile>

If you add this profile to your parent pom and call mvn clean install sonar:sonar -DrunSonar you get the complete coverage.

The magic here is maven.multiModuleProjectDirectory. This folder is always the folder where you started your maven build.

How to use SQL Order By statement to sort results case insensitive?

You can also do ORDER BY TITLE COLLATE NOCASE.

Edit: If you need to specify ASC or DESC, add this after NOCASE like

ORDER BY TITLE COLLATE NOCASE ASC

or

ORDER BY TITLE COLLATE NOCASE DESC

Conversion hex string into ascii in bash command line

You can use xxd:

$cat hex.txt
68 65 6c 6c 6f
$cat hex.txt | xxd -r -p
hello

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The use-case for CORS is simple. Imagine the site alice.com has some data that the site bob.com wants to access. This type of request traditionally wouldn’t be allowed under the browser’s same origin policy. However, by supporting CORS requests, alice.com can add a few special response headers that allows bob.com to access the data. In order to understand it well, please visit this nice tutorial.. How to solve the issue of CORS

Better naming in Tuple classes than "Item1", "Item2"

Just to add to @MichaelMocko answer. Tuples have couple of gotchas at the moment:

You can't use them in EF expression trees

Example:

public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        // Selecting as Tuple
        .Select(person => (person.Name, person.Surname))
        .First();
}

This will fail to compile with "An expression tree may not contain a tuple literal" error. Unfortunately, the expression trees API wasn't expanded with support for tuples when these were added to the language.

Track (and upvote) this issue for the updates: https://github.com/dotnet/roslyn/issues/12897

To get around the problem, you can cast it to anonymous type first and then convert the value to tuple:

// Will work
public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => new { person.Name, person.Surname })
        .ToList()
        .Select(person => (person.Name, person.Surname))
        .First();
}

Another option is to use ValueTuple.Create:

// Will work
public static (string name, string surname) GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => ValueTuple.Create(person.Name, person.Surname))
        .First();
}

References:

You can't deconstruct them in lambdas

There's a proposal to add the support: https://github.com/dotnet/csharplang/issues/258

Example:

public static IQueryable<(string name, string surname)> GetPersonName(this PersonContext ctx, int id)
{
    return ctx.Persons
        .Where(person => person.Id == id)
        .Select(person => ValueTuple.Create(person.Name, person.Surname));
}

// This won't work
ctx.GetPersonName(id).Select((name, surname) => { return name + surname; })

// But this will
ctx.GetPersonName(id).Select(t => { return t.name + t.surname; })

References:

They won't serialize nicely

using System;
using Newtonsoft.Json;

public class Program
{
    public static void Main() {
        var me = (age: 21, favoriteFood: "Custard");
        string json = JsonConvert.SerializeObject(me);

        // Will output {"Item1":21,"Item2":"Custard"}
        Console.WriteLine(json); 
    }
}

Tuple field names are only available at compile time and are completely wiped out at runtime.

References:

Python: Removing list element while iterating over list

Another way of doing so is:

while i<len(your_list):
    if #condition :
        del your_list[i]
    else:
        i+=1

So, you delete the elements side by side while checking

PHP script to loop through all of the files in a directory?

You can use the DirectoryIterator. Example from php Manual:

<?php
$dir = new DirectoryIterator(dirname(__FILE__));
foreach ($dir as $fileinfo) {
    if (!$fileinfo->isDot()) {
        var_dump($fileinfo->getFilename());
    }
}
?>

Add multiple items to a list

Another useful way is with Concat.
More information in the official documentation.

List<string> first = new List<string> { "One", "Two", "Three" };
List<string> second = new List<string>() { "Four", "Five" };
first.Concat(second);

The output will be.

One
Two
Three
Four
Five

And there is another similar answer.

Description Box using "onmouseover"

I'd try doing this with jQuery's .hover() event handler system, it makes it easy to show a div with the tooltip when the mouse is over the text, and hide it once it's gone.

Here's a simple example.

HTML:

?<p id="testText">Some Text</p>
<div id="tooltip">Tooltip Hint Text</div>???????????????????????????????????????????

Basic CSS:

?#?tooltip {
display:none;
border:1px solid #F00;
width:150px;
}?

jQuery:

$("#testText").hover(
   function(e){
       $("#tooltip").show();
   },
   function(e){
       $("#tooltip").hide();
  });??????????

How to access shared folder without giving username and password

You need to go to user accounts and enable Guest Account, its default disabled. Once you do this, you share any folder and add the guest account to the list of users who can accesss that specific folder, this also includes to Turn off password Protected Sharing in 'Advanced Sharing Settings'

The other way to do this where you only enter a password once is to join a Homegroup. if you have a network of 2 or more computers, they can all connect to a homegroup and access all the files they need from each other, and anyone outside the group needs a 1 time password to be able to access your network, this was introduced in windows 7.

How can I write a byte array to a file in Java?

         File file = ...
         byte[] data = ...
         try{
            FileOutputStream fos = FileOutputStream(file);
            fos.write(data);
            fos.flush();
            fos.close();
         }catch(Exception e){
          }

but if the bytes array length is more than 1024 you should use loop to write the data.

CodeIgniter: Create new helper?

Some code that allows you to use CI instance inside the helper:

function yourHelperFunction(){
    $ci=& get_instance();
    $ci->load->database(); 

    $sql = "select * from table"; 
    $query = $ci->db->query($sql);
    $row = $query->result();
}

remove double quotes from Json return data using Jquery

What you are doing is making a JSON string in your example. Either don't use the JSON.stringify() or if you ever do have JSON data coming back and you don't want quotations, Simply use JSON.parse() to remove quotations around JSON responses! Don't use regex, there's no need to.

Git status shows files as changed even though contents are the same

The only suspect entry in your config looks to me to be core.ignorecase. You could try unsetting that with:

  git config --unset core.ignorecase

... and see if the output from git status or git diff is different.

How can I nullify css property?

like say a class .c1 has height:40px; how do I get rid of this height property?

Sadly, you can't. CSS doesn't have a "default" placeholder.

In that case, you would reset the property using

 height: auto;

as @Ben correctly points out, in some cases, inherit is the correct way to go, for example when resetting the text colour of an a element (that property is inherited from the parent element):

a { color: inherit }

nodeJS - How to create and read session with express

Steps I did:

  1. Include the angular-cookies.js file in the HTML!
  2. Init cookies as being NOT http-only in server-side app.'s:

    app.configure(function(){
       //a bunch of stuff
       app.use(express.cookieSession({secret: 'mySecret', store: store, cookie: cookieSettings}));```
    
  3. Then in client-side services.jss I put ['ngCookies'] in like this:

    angular.module('swrp', ['ngCookies']).//etc

  4. Then in controller.js, in my function UserLoginCtrl, I have $cookies in there with $scope at the top like so:

    function UserLoginCtrl($scope, $cookies, socket) {

  5. Lastly, to get the value of a cookie inside the controller function I did:

    var mySession = $cookies['connect.sess'];

Now you can send that back to the server from the client. Awesome. Wish they would've put this in the Angular.js documentation. I figured it out by just reading the actual code for angular-cookies.js directly.

jQuery select child element by class with unknown path

Try this

$('#thisElement .classToSelect').each(function(i){
         // do stuff
});

Hope it will help

How to print the current Stack Trace in .NET without any exception?

   private void ExceptionTest()
    {
        try
        {
            int j = 0;
            int i = 5;
            i = 1 / j;
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: " + ex.Message);
            var stList = ex.StackTrace.ToString().Split('\\');
            Console.WriteLine("Exception occurred at " + stList[stList.Count() - 1]);
        }
    }

Seems to work for me

"Operation must use an updateable query" error in MS Access

This is a shot in the dark but try putting the two operands for the AND in parentheses

On ((A = B) And (C = D))

AngularJS - Any way for $http.post to send request parameters instead of JSON?

I think the params config parameter won't work here since it adds the string to the url instead of the body but to add to what Infeligo suggested here is an example of the global override of a default transform (using jQuery param as an example to convert the data to param string).

Set up global transformRequest function:

var app = angular.module('myApp');

app.config(function ($httpProvider) {
    $httpProvider.defaults.transformRequest = function(data){
        if (data === undefined) {
            return data;
        }
        return $.param(data);
    }
});

That way all calls to $http.post will automatically transform the body to the same param format used by the jQuery $.post call.

Note you may also want to set the Content-Type header per call or globally like this:

$httpProvider.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded; charset=UTF-8';

Sample non-global transformRequest per call:

    var transform = function(data){
        return $.param(data);
    }

    $http.post("/foo/bar", requestData, {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
        transformRequest: transform
    }).success(function(responseData) {
        //do stuff with response
    });

makefile:4: *** missing separator. Stop

The key point was "HARD TAB" 1. Check whether you used TAB instead of whitespace 2. Check your .vimrc for "set tabstop=X"

How to show hidden divs on mouseover?

You could wrap the hidden div in another div that will toggle the visibility with onMouseOver and onMouseOut event handlers in JavaScript:

<style type="text/css">
  #div1, #div2, #div3 {  
    visibility: hidden;  
  }
</style>
<script>
  function show(id) {
    document.getElementById(id).style.visibility = "visible";
  }
  function hide(id) {
    document.getElementById(id).style.visibility = "hidden";
  }
</script>

<div onMouseOver="show('div1')" onMouseOut="hide('div1')">
  <div id="div1">Div 1 Content</div>
</div>
<div onMouseOver="show('div2')" onMouseOut="hide('div2')">
  <div id="div2">Div 2 Content</div>
</div>
<div onMouseOver="show('div3')" onMouseOut="hide('div3')">
  <div id="div3">Div 3 Content</div>
</div>

Unable to read repository at http://download.eclipse.org/releases/indigo

In my case, I discovered that the major issue why my eclipse won't connect to internet is my Internet Service Provider. I was only able to browse some websites but unable to browse other website. Fixing the issue with the ISP worked.

how to deal with google map inside of a hidden div (Updated picture)

 $("#map_view").show("slow"); // use id of div which you want to show.
     var script = document.createElement("script");
     script.type = "text/javascript";
     script.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize";
     document.body.appendChild(script);

How do I left align these Bootstrap form items?

Just my two cents. If you are using Bootstrap 3 then I would just add an extra style into your own site's stylesheet which controls the text-left style of the control-label.

If you were to add text-left to the label, by default there is another style which overrides this .form-horizontal .control-label. So if you add:

.form-horizontal .control-label.text-left{
    text-align: left;
}

Then the built in text-left style is applied to the label correctly.

How to replace multiple white spaces with one white space

A fast extra whitespace remover by Felipe Machado. (Modified by RW for multi-space removal)

static string DuplicateWhiteSpaceRemover(string str)
{
    var len = str.Length;
    var src = str.ToCharArray();
    int dstIdx = 0;
    bool lastWasWS = false; //Added line
    for (int i = 0; i < len; i++)
    {
        var ch = src[i];
        switch (ch)
        {
            case '\u0020': //SPACE
            case '\u00A0': //NO-BREAK SPACE
            case '\u1680': //OGHAM SPACE MARK
            case '\u2000': // EN QUAD
            case '\u2001': //EM QUAD
            case '\u2002': //EN SPACE
            case '\u2003': //EM SPACE
            case '\u2004': //THREE-PER-EM SPACE
            case '\u2005': //FOUR-PER-EM SPACE
            case '\u2006': //SIX-PER-EM SPACE
            case '\u2007': //FIGURE SPACE
            case '\u2008': //PUNCTUATION SPACE
            case '\u2009': //THIN SPACE
            case '\u200A': //HAIR SPACE
            case '\u202F': //NARROW NO-BREAK SPACE
            case '\u205F': //MEDIUM MATHEMATICAL SPACE
            case '\u3000': //IDEOGRAPHIC SPACE
            case '\u2028': //LINE SEPARATOR
            case '\u2029': //PARAGRAPH SEPARATOR
            case '\u0009': //[ASCII Tab]
            case '\u000A': //[ASCII Line Feed]
            case '\u000B': //[ASCII Vertical Tab]
            case '\u000C': //[ASCII Form Feed]
            case '\u000D': //[ASCII Carriage Return]
            case '\u0085': //NEXT LINE
                if (lastWasWS == false) //Added line
                {
                    src[dstIdx++] = ' '; // Updated by Ryan
                    lastWasWS = true; //Added line
                }
                continue;
            default:
                lastWasWS = false; //Added line 
                src[dstIdx++] = ch;
                break;
        }
    }
    return new string(src, 0, dstIdx);
}

The benchmarks...

|                           | Time  |   TEST 1    |   TEST 2    |   TEST 3    |   TEST 4    |   TEST 5    |
| Function Name             |(ticks)| dup. spaces | spaces+tabs | spaces+CR/LF| " " -> " "  | " " -> " " |
|---------------------------|-------|-------------|-------------|-------------|-------------|-------------|
| SwitchStmtBuildSpaceOnly  |   5.2 |    PASS     |    FAIL     |    FAIL     |    PASS     |    PASS     |
| InPlaceCharArraySpaceOnly |   5.6 |    PASS     |    FAIL     |    FAIL     |    PASS     |    PASS     |
| DuplicateWhiteSpaceRemover|   7.0 |    PASS     |    PASS     |    PASS     |    PASS     |    PASS     |
| SingleSpacedTrim          |  11.8 |    PASS     |    PASS     |    PASS     |    FAIL     |    FAIL     |
| Fubo(StringBuilder)       |    13 |    PASS     |    FAIL     |    FAIL     |    PASS     |    PASS     |
| User214147                |    19 |    PASS     |    PASS     |    PASS     |    FAIL     |    FAIL     | 
| RegExWithCompile          |    28 |    PASS     |    FAIL     |    FAIL     |    PASS     |    PASS     |
| SwitchStmtBuild           |    34 |    PASS     |    FAIL     |    FAIL     |    PASS     |    PASS     |
| SplitAndJoinOnSpace       |    55 |    PASS     |    FAIL     |    FAIL     |    FAIL     |    FAIL     |
| RegExNoCompile            |   120 |    PASS     |    PASS     |    PASS     |    PASS     |    PASS     |
| RegExBrandon              |   137 |    PASS     |    FAIL     |    PASS     |    PASS     |    PASS     |

Benchmark notes: Release Mode, no-debugger attached, i7 processor, avg of 4 runs, only short strings tested

SwitchStmtBuildSpaceOnly by Felipe Machado 2015 and modified by Sunsetquest

InPlaceCharArraySpaceOnly by Felipe Machado 2015 and modified by Sunsetquest

SwitchStmtBuild by Felipe Machado 2015 and modified by Sunsetquest

SwitchStmtBuild2 by Felipe Machado 2015 and modified by Sunsetquest

SingleSpacedTrim by David S 2013

Fubo(StringBuilder) by fubo 2014

SplitAndJoinOnSpace by Jon Skeet 2009

RegExWithCompile by Jon Skeet 2009

User214147 by user214147

RegExBrandon by Brandon

RegExNoCompile by Tim Hoolihan

Benchmark code is on Github

How to Verify if file exist with VB script

There is no built-in functionality in VBS for that, however, you can use the FileSystemObject FileExists function for that :

Option Explicit
DIM fso    
Set fso = CreateObject("Scripting.FileSystemObject")

If (fso.FileExists("C:\Program Files\conf")) Then
  WScript.Echo("File exists!")
  WScript.Quit()
Else
  WScript.Echo("File does not exist!")
End If

WScript.Quit()

How to get the mysql table columns data type?

You can use the information_schema columns table:

SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS 
  WHERE table_name = 'tbl_name' AND COLUMN_NAME = 'col_name';

How can I enable CORS on Django REST Framework

You can do by using a custom middleware, even though knowing that the best option is using the tested approach of the package django-cors-headers. With that said, here is the solution:

create the following structure and files:

-- myapp/middleware/__init__.py

from corsMiddleware import corsMiddleware

-- myapp/middleware/corsMiddleware.py

class corsMiddleware(object):
    def process_response(self, req, resp):
        resp["Access-Control-Allow-Origin"] = "*"
        return resp

add to settings.py the marked line:

MIDDLEWARE_CLASSES = (
    "django.contrib.sessions.middleware.SessionMiddleware",
    "django.middleware.common.CommonMiddleware",
    "django.middleware.csrf.CsrfViewMiddleware",

    # Now we add here our custom middleware
     'app_name.middleware.corsMiddleware' <---- this line
)

How to auto adjust table td width from the content

Use this style attribute for no word wrapping:

white-space: nowrap;

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

If file = open(filename, encoding="utf8") doesn't work, try
file = open(filename, errors="ignore"), if you want to remove unneeded characters.

How do I change the language of moment.js?

This one just works by auto detecting the current user location.

import moment from "moment/min/moment-with-locales";

// Then use it as you always do. 
moment(yourDate).format("MMMM Do YYYY, h:mm a")

Regular expression for matching HH:MM time format

The best would be for HH:MM without taking any risk.

^(0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$

Call a "local" function within module.exports from another function in module.exports?

You can also save a reference to module's global scope outside the (module.)exports.somemodule definition:

var _this = this;

exports.somefunction = function() {
   console.log('hello');
}

exports.someotherfunction = function() {
   _this.somefunction();
}

How to disable/enable select field using jQuery?

To be able to disable/enable selects first of all your selects need an ID or class. Then you could do something like this:

Disable:

$('#id').attr('disabled', 'disabled');

Enable:

$('#id').removeAttr('disabled');

Is there a way to get a list of column names in sqlite?

Quick, interactive way to see column names

If you're working interactively in Python and just want to quickly 'see' the column names, I found cursor.description to work.

import sqlite3
conn = sqlite3.connect('test-db.db')
cursor = conn.execute('select * from mytable')
cursor.description

Outputs something like this:

(('Date', None, None, None, None, None, None),
 ('Object-Name', None, None, None, None, None, None),
 ('Object-Count', None, None, None, None, None, None))

Or, quick way to access and print them out.

colnames = cursor.description
for row in colnames:
    print row[0]

Outputs something like this:

Date
Object-Name
Object-Count

Get all inherited classes of an abstract class

This is such a common problem, especially in GUI applications, that I'm surprised there isn't a BCL class to do this out of the box. Here's how I do it.

public static class ReflectiveEnumerator
{
    static ReflectiveEnumerator() { }

    public static IEnumerable<T> GetEnumerableOfType<T>(params object[] constructorArgs) where T : class, IComparable<T>
    {
        List<T> objects = new List<T>();
        foreach (Type type in 
            Assembly.GetAssembly(typeof(T)).GetTypes()
            .Where(myType => myType.IsClass && !myType.IsAbstract && myType.IsSubclassOf(typeof(T))))
        {
            objects.Add((T)Activator.CreateInstance(type, constructorArgs));
        }
        objects.Sort();
        return objects;
    }
}

A few notes:

  • Don't worry about the "cost" of this operation - you're only going to be doing it once (hopefully) and even then it's not as slow as you'd think.
  • You need to use Assembly.GetAssembly(typeof(T)) because your base class might be in a different assembly.
  • You need to use the criteria type.IsClass and !type.IsAbstract because it'll throw an exception if you try to instantiate an interface or abstract class.
  • I like forcing the enumerated classes to implement IComparable so that they can be sorted.
  • Your child classes must have identical constructor signatures, otherwise it'll throw an exception. This typically isn't a problem for me.

Ternary operator in PowerShell

If you're just looking for a syntactically simple way to assign/return a string or numeric based on a boolean condition, you can use the multiplication operator like this:

"Condition is "+("true"*$condition)+("false"*!$condition)
(12.34*$condition)+(56.78*!$condition)

If you're only ever interested in the result when something is true, you can just omit the false part entirely (or vice versa), e.g. a simple scoring system:

$isTall = $true
$isDark = $false
$isHandsome = $true

$score = (2*$isTall)+(4*$isDark)+(10*$isHandsome)
"Score = $score"
# or
# "Score = $((2*$isTall)+(4*$isDark)+(10*$isHandsome))"

Note that the boolean value should not be the leading term in the multiplication, i.e. $condition*"true" etc. won't work.

PHP Multidimensional Array Searching (Find key by specific value)

For the next visitor coming along: use the recursive array walk; it visits every "leaf" in the multidimensional array. Here's for inspiration:

function getMDArrayValueByKey($a, $k) {
    $r = [];
    array_walk_recursive ($a, 
                          function ($item, $key) use ($k, &$r) {if ($key == $k) $r[] = $item;}
                          );
    return $r;
}

How to change workspace and build record Root Directory on Jenkins?

You can modify the path on the config.xml file in the default directory

<projectNamingStrategy class="jenkins.model.ProjectNamingStrategy$DefaultProjectNamingStrategy"/>
<workspaceDir>D:/Workspace/${ITEM_FULL_NAME}</workspaceDir>
<buildsDir>D:/Logs/${ITEM_ROOTDIR}/Build</buildsDir>

How many spaces will Java String.trim() remove?

From java docs(String class source),

/**
 * Returns a copy of the string, with leading and trailing whitespace
 * omitted.
 * <p>
 * If this <code>String</code> object represents an empty character
 * sequence, or the first and last characters of character sequence
 * represented by this <code>String</code> object both have codes
 * greater than <code>'&#92;u0020'</code> (the space character), then a
 * reference to this <code>String</code> object is returned.
 * <p>
 * Otherwise, if there is no character with a code greater than
 * <code>'&#92;u0020'</code> in the string, then a new
 * <code>String</code> object representing an empty string is created
 * and returned.
 * <p>
 * Otherwise, let <i>k</i> be the index of the first character in the
 * string whose code is greater than <code>'&#92;u0020'</code>, and let
 * <i>m</i> be the index of the last character in the string whose code
 * is greater than <code>'&#92;u0020'</code>. A new <code>String</code>
 * object is created, representing the substring of this string that
 * begins with the character at index <i>k</i> and ends with the
 * character at index <i>m</i>-that is, the result of
 * <code>this.substring(<i>k</i>,&nbsp;<i>m</i>+1)</code>.
 * <p>
 * This method may be used to trim whitespace (as defined above) from
 * the beginning and end of a string.
 *
 * @return  A copy of this string with leading and trailing white
 *          space removed, or this string if it has no leading or
 *          trailing white space.
 */
public String trim() {
int len = count;
int st = 0;
int off = offset;      /* avoid getfield opcode */
char[] val = value;    /* avoid getfield opcode */

while ((st < len) && (val[off + st] <= ' ')) {
    st++;
}
while ((st < len) && (val[off + len - 1] <= ' ')) {
    len--;
}
return ((st > 0) || (len < count)) ? substring(st, len) : this;
}

Note that after getting start and length it calls the substring method of String class.

What is a web service endpoint?

A endpoint is a URL for web service.And Endpoints also is a distributed API.

The Simple Object Access Protocol (SOAP) endpoint is a URL. It identifies the location on the built-in HTTP service where the web services listener listens for incoming requests.

Reference: https://www.ibm.com/support/knowledgecenter/SSSHYH_7.1.0.4/com.ibm.netcoolimpact.doc/dsa/imdsa_web_netcool_impact_soap_endpoint_c.html

login to remote using "mstsc /admin" with password

Save your username, password and sever name in an RDP file and run the RDP file from your script

Using sendmail from bash script for multiple recipients

Use option -t for sendmail.

in your case - echo -e $mail | /usr/sbin/sendmail -t and add yout Recepient list to message itself like To: [email protected] [email protected] right after the line From:.....

-t option means - Read message for recipients. To:, Cc:, and Bcc: lines will be scanned for recipient addresses. The Bcc: line will be deleted before transmission.

How to specify non-default shared-library path in GCC Linux? Getting "error while loading shared libraries" when running

Should it be LIBRARY_PATH instead of LD_LIBRARY_PATH. gcc checks for LIBRARY_PATH which can be seen with -v option

What's the best way to store a group of constants that my program uses?

IMO using a class full of constants is fine for constants. If they will change semi-occasionally I recommend using AppSettings in your config and the ConfigurationManager class instead.

When I have "constants" that are actually pulled in from AppSettings or similar I still will always have a "constants" class that wraps the reading from configuration manager. It's always more meaningful to have Constants.SomeModule.Setting instead of having to resort directly to ConfigurationManager.AppSettings["SomeModule/Setting"] on any place that wants to consume said setting value.

Bonus points for this setup, since SomeModule would likely be a nested class inside the Constants file, you could easily use Dependency Injection to inject either SomeModule directly into classes that depend on it. You could also even extract an interface on top of SomeModule and then create a depenedency to ISomeModuleConfiguration in your consuming code, this would then allow you to decouple the dependency to the Constants files, and even potentially make testing easier, especially if these settings come from AppSettings and you change them using config transformations because the settings are environment specific.

org.json.simple cannot be resolved

The jar file is missing. You can download the jar file and add it as external libraries in your project . You can download this from

http://www.findjar.com/jar/com/googlecode/json-simple/json-simple/1.1/json-simple-1.1.jar.html

Using Javascript can you get the value from a session attribute set by servlet in the HTML page

<%
String session_val = (String)session.getAttribute("sessionval"); 
System.out.println("session_val"+session_val);
%>
<html>
<head>
<script type="text/javascript">
var session_obj= '<%=session_val%>';
alert("session_obj"+session_obj);
</script>
</head>
</html>

'do...while' vs. 'while'

Here's my theory why most people (including me) prefer while(){} loops to do{}while(): A while(){} loop can easily be adapted to perform like a do..while() loop while the opposite is not true. A while loop is in a certain way "more general". Also programmers like easy to grasp patterns. A while loop says right at start what its invariant is and this is a nice thing.

Here's what I mean about the "more general" thing. Take this do..while loop:

do {
 A;
 if (condition) INV=false; 
 B;
} while(INV);

Transforming this in to a while loop is straightforward:

INV=true;
while(INV) {
 A;
 if (condition) INV=false; 
 B;
}

Now, we take a model while loop:

while(INV) {
     A;
     if (condition) INV=false; 
     B;
}

And transform this into a do..while loop, yields this monstrosity:

if (INV) {
 do
 {
         A;
         if (condition) INV=false; 
         B;

 } while(INV)
}

Now we have two checks on opposite ends and if the invariant changes you have to update it on two places. In a certain way do..while is like the specialized screwdrivers in the tool box which you never use, because the standard screwdriver does everything you need.

Pass Multiple Parameters to jQuery ajax call

Just to add on [This line perfectly work in Asp.net& find web-control Fields in jason Eg:<%Fieldname%>]

 data: "{LocationName:'" + document.getElementById('<%=txtLocationName.ClientID%>').value + "',AreaID:'" + document.getElementById('<%=DropDownArea.ClientID%>').value + "'}",

Is it possible to pass parameters programmatically in a Microsoft Access update query?

Many thanks for the information about using the QueryDefs collection! I have been wondering about this for a while.

I did it a different way, without using VBA, by using a table containing the query parameters.

E.g:

SELECT a_table.a_field 
FROM QueryParameters, a_table 
WHERE a_table.a_field BETWEEN QueryParameters.a_field_min 
AND QueryParameters.a_field_max

Where QueryParameters is a table with two fields, a_field_min and a_field_max

It can even be used with GROUP BY, if you include the query parameter fields in the GROUP BY clause, and the FIRST operator on the parameter fields in the HAVING clause.

Could not connect to React Native development server on Android

I got the same problem and resolve it by deleting node module package and then again install yarn. Simply on some changes we need to clear our.

WITH CHECK ADD CONSTRAINT followed by CHECK CONSTRAINT vs. ADD CONSTRAINT

Foreign key and check constraints have the concept of being trusted or untrusted, as well as being enabled and disabled. See the MSDN page for ALTER TABLE for full details.

WITH CHECK is the default for adding new foreign key and check constraints, WITH NOCHECK is the default for re-enabling disabled foreign key and check constraints. It's important to be aware of the difference.

Having said that, any apparently redundant statements generated by utilities are simply there for safety and/or ease of coding. Don't worry about them.

Jackson enum Serializing and DeSerializer

I've found a very nice and concise solution, especially useful when you cannot modify enum classes as it was in my case. Then you should provide a custom ObjectMapper with a certain feature enabled. Those features are available since Jackson 1.6. So you only need to write toString() method in your enum.

public class CustomObjectMapper extends ObjectMapper {
    @PostConstruct
    public void customConfiguration() {
        // Uses Enum.toString() for serialization of an Enum
        this.enable(WRITE_ENUMS_USING_TO_STRING);
        // Uses Enum.toString() for deserialization of an Enum
        this.enable(READ_ENUMS_USING_TO_STRING);
    }
}

There are more enum-related features available, see here:

https://github.com/FasterXML/jackson-databind/wiki/Serialization-Features https://github.com/FasterXML/jackson-databind/wiki/Deserialization-Features

Dynamically change bootstrap progress bar value when checkboxes checked

Try this maybe :

Bootply : http://www.bootply.com/106527

Js :

$('input').on('click', function(){
  var valeur = 0;
  $('input:checked').each(function(){
       if ( $(this).attr('value') > valeur )
       {
           valeur =  $(this).attr('value');
       }
  });
  $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    
});

HTML :

 <div class="progress progress-striped active">
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">
        </div>
    </div>
<div class="row tasks">
        <div class="col-md-6">
          <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>
        </div>
        <div class="col-md-2">
          <label>2014-01-29</label>
        </div>
        <div class="col-md-2">
          <input name="progress" class="progress" type="checkbox" value="10">
        </div>
        <div class="col-md-2">
          <input name="done" class="done" type="checkbox" value="20">
        </div>
      </div><!-- tasks -->

<div class="row tasks">
        <div class="col-md-6">
          <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be
sure that you’ll have tangible results to share with the world (or your
boss) at the end of your campaign.</p>
        </div>
        <div class="col-md-2">
          <label>2014-01-25</label>
        </div>
        <div class="col-md-2">
          <input name="progress" class="progress" type="checkbox" value="30">
        </div>
        <div class="col-md-2">
          <input name="done" class="done" type="checkbox" value="40">
        </div>
      </div><!-- tasks -->

Css

.tasks{
    background-color: #F6F8F8;
    padding: 10px;
    border-radius: 5px;
    margin-top: 10px;
}
.tasks span{
    font-weight: bold;
}
.tasks input{
    display: block;
    margin: 0 auto;
    margin-top: 10px;
}
.tasks a{
    color: #000;
    text-decoration: none;
    border:none;
}
.tasks a:hover{
    border-bottom: dashed 1px #0088cc;
}
.tasks label{
    display: block;
    text-align: center;
}

_x000D_
_x000D_
$(function(){_x000D_
$('input').on('click', function(){_x000D_
  var valeur = 0;_x000D_
  $('input:checked').each(function(){_x000D_
       if ( $(this).attr('value') > valeur )_x000D_
       {_x000D_
           valeur =  $(this).attr('value');_x000D_
       }_x000D_
  });_x000D_
  $('.progress-bar').css('width', valeur+'%').attr('aria-valuenow', valeur);    _x000D_
});_x000D_
_x000D_
});
_x000D_
.tasks{_x000D_
 background-color: #F6F8F8;_x000D_
 padding: 10px;_x000D_
 border-radius: 5px;_x000D_
 margin-top: 10px;_x000D_
}_x000D_
.tasks span{_x000D_
 font-weight: bold;_x000D_
}_x000D_
.tasks input{_x000D_
 display: block;_x000D_
 margin: 0 auto;_x000D_
 margin-top: 10px;_x000D_
}_x000D_
.tasks a{_x000D_
 color: #000;_x000D_
 text-decoration: none;_x000D_
 border:none;_x000D_
}_x000D_
.tasks a:hover{_x000D_
 border-bottom: dashed 1px #0088cc;_x000D_
}_x000D_
.tasks label{_x000D_
 display: block;_x000D_
 text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
 <div class="progress progress-striped active">_x000D_
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">_x000D_
        </div>_x000D_
    </div>_x000D_
<div class="row tasks">_x000D_
        <div class="col-md-6">_x000D_
          <p><span>Identify your campaign audience.</span>Who are we talking to here? Understand your buyer persona before launching into a campaign, so you can target them correctly.</p>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <label>2014-01-29</label>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="progress" class="progress" type="checkbox" value="10">_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="done" class="done" type="checkbox" value="20">_x000D_
        </div>_x000D_
      </div><!-- tasks -->_x000D_
_x000D_
<div class="row tasks">_x000D_
        <div class="col-md-6">_x000D_
          <p><span>Set your goals + benchmarks</span>Having SMART goals can help you be_x000D_
sure that you’ll have tangible results to share with the world (or your_x000D_
boss) at the end of your campaign.</p>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <label>2014-01-25</label>_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="progress" class="progress" type="checkbox" value="30">_x000D_
        </div>_x000D_
        <div class="col-md-2">_x000D_
          <input name="done" class="done" type="checkbox" value="40">_x000D_
        </div>_x000D_
      </div><!-- tasks -->
_x000D_
_x000D_
_x000D_

PostgreSQL: Show tables in PostgreSQL

The most straightforward way to list all tables at command line is, for my taste :

psql -a -U <user> -p <port> -h <server> -c "\dt"

For a given database just add the database name :

psql -a -U <user> -p <port> -h <server> -c "\dt" <database_name>

It works on both Linux and Windows.

MySQL Select Query - Get only first 10 characters of a value

Have a look at either Left or Substring if you need to chop it up even more.

Google and the MySQL docs are a good place to start - you'll usually not get such a warm response if you've not even tried to help yourself before asking a question.

How to add option to select list in jQuery

$('#dropListBuilding').append('<option>'+val+'</option>');

How to force reloading a page when using browser back button?

Just use jquery :

jQuery( document ).ready(function( $ ) {

   //Use this inside your document ready jQuery 
   $(window).on('popstate', function() {
      location.reload(true);
   });

});

The above will work 100% when back or forward button has been clicked using ajax as well.

if it doesn't, there must be a misconfiguration in a different part of the script.

For example it might not reload if something like one of the example in the previous post is used window.history.pushState('', null, './');

so when you do use history.pushState(); make sure you use it properly.

Suggestion in most cases you will just need:

history.pushState(url, '', url); 

No window.history... and make sure url is defined.

Hope that helps..

Use of Java's Collections.singletonList()?

singletonList can hold instance of any object. Object state can be modify.

List<Character> list = new ArrayList<Character>();
list.add('X');
list.add('Y');
System.out.println("Initial list: "+ list);
List<List<Character>> list2 = Collections.singletonList(list);
list.add('Z');
System.out.println(list);
System.out.println(list2);

We can not define unmodifiableList like above.

What does a circled plus mean?

It is XOR. Another name for the XOR function is addition without carry. I suppose that's how the symbol might make sense.

Print raw string from variable? (not getting the answers)

try this. Based on what type of output you want. sometime you may not need single quote around printed string.

test = "qweqwe\n1212as\t121\\2asas"
print(repr(test)) # output: 'qweqwe\n1212as\t121\\2asas'
print( repr(test).strip("'"))  # output: qweqwe\n1212as\t121\\2asas

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

Not this exact problem, but this is the top result when googling for almost the exact same error:

If you see this problem calling a WCF Service hosted on the same machine, you may need to populate the BackConnectionHostNames registry key

  1. In regedit, locate and then click the following registry subkey: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa\MSV1_0
  2. Right-click MSV1_0, point to New, and then click Multi-String Value.
  3. In the Name column, type BackConnectionHostNames, and then press ENTER.
  4. Right-click BackConnectionHostNames, and then click Modify. In the Value data box, type the CNAME or the DNS alias, that is used for the local shares on the computer, and then click OK.
    • Type each host name on a separate line.

See Calling WCF service hosted in IIS on the same machine as client throws authentication error for details.

Youtube autoplay not working on mobile devices with embedded HTML5 player

Preview The official statement "Due to this restriction, functions and parameters such as autoplay, playVideo(), loadVideoById() won't work in all mobile environments.

Reference: https://developers.google.com/youtube/iframe_api_reference

XML Parser for C

My personal preference is libxml2. It's very easy to use but I never bothered to benchmark it, as I've only used it for configuration file parsing.

Provide static IP to docker containers via docker-compose

Note that I don't recommend a fixed IP for containers in Docker unless you're doing something that allows routing from outside to the inside of your container network (e.g. macvlan). DNS is already there for service discovery inside of the container network and supports container scaling. And outside the container network, you should use exposed ports on the host. With that disclaimer, here's the compose file you want:

version: '2'

services:
  mysql:
    container_name: mysql
    image: mysql:latest
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=root
    ports:
     - "3306:3306"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.5

  apigw-tomcat:
    container_name: apigw-tomcat
    build: tomcat/.
    ports:
     - "8080:8080"
     - "8009:8009"
    networks:
      vpcbr:
        ipv4_address: 10.5.0.6
    depends_on:
     - mysql

networks:
  vpcbr:
    driver: bridge
    ipam:
     config:
       - subnet: 10.5.0.0/16
         gateway: 10.5.0.1

Unicode character in PHP string

Because JSON directly supports the \uxxxx syntax the first thing that comes into my mind is:

$unicodeChar = '\u1000';
echo json_decode('"'.$unicodeChar.'"');

Another option would be to use mb_convert_encoding()

echo mb_convert_encoding('&#x1000;', 'UTF-8', 'HTML-ENTITIES');

or make use of the direct mapping between UTF-16BE (big endian) and the Unicode codepoint:

echo mb_convert_encoding("\x10\x00", 'UTF-8', 'UTF-16BE');

How to fill in proxy information in cntlm config file?

Update your user, domain, and proxy information in cntlm.ini, then test your proxy with this command (run in your Cntlm installation folder):

cntlm -c cntlm.ini -I -M http://google.ro

It will ask for your password, and hopefully print your required authentication information, which must be saved in your cntlm.ini

Sample cntlm.ini:

Username            user
Domain              domain

# provide actual value if autodetection fails
# Workstation         pc-name

Proxy               my_proxy_server.com:80
NoProxy             127.0.0.*, 192.168.*

Listen              127.0.0.1:54321
Listen              192.168.1.42:8080
Gateway             no

SOCKS5Proxy         5000
# provide socks auth info if you want it
# SOCKS5User          socks-user:socks-password

# printed authentication info from the previous step
Auth            NTLMv2
PassNTLMv2      98D6986BCFA9886E41698C1686B58A09

Note: on linux the config file is cntlm.conf

Changing website favicon dynamically

Why not?

var link = document.querySelector("link[rel~='icon']");
if (!link) {
    link = document.createElement('link');
    link.rel = 'icon';
    document.getElementsByTagName('head')[0].appendChild(link);
}
link.href = 'https://stackoverflow.com/favicon.ico';

Java: how to import a jar file from command line

you can try to export as "Runnable jar" in eclipse. I have also problems, when i export as "jar", but i have never problems when i export as "Runnable jar".

Google Maps API v3: How do I dynamically change the marker icon?

You can try this code

    <script src="http://maps.googleapis.com/maps/api/js"></script>
<script type="text/javascript" src="http://google-maps-utility-library-v3.googlecode.com/svn/trunk/infobox/src/infobox.js"></script>

<script>

    function initialize()
    {
        var map;
        var bounds = new google.maps.LatLngBounds();
        var mapOptions = {
                            zoom: 10,
                            mapTypeId: google.maps.MapTypeId.ROADMAP    
                         };
        map = new google.maps.Map(document.getElementById("mapDiv"), mapOptions);
        var markers = [
            ['title-1', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.120850, '<p> Hello - 1 </p>'],
            ['title-2', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.420850, '<p> Hello - 2 </p>'],
            ['title-3', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -0.720850, '<p> Hello - 3 </p>'],
            ['title-4', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -1.020850, '<p> Hello - 4 </p>'],
            ['title-5', '<img style="width:100%;" src="canberra_hero_image.jpg"></img>', 51.508742, -1.320850, '<p> Hello - 5 </p>']
        ];

        var infoWindow = new google.maps.InfoWindow(), marker, i;
        var testMarker = [];
        var status = [];
        for( i = 0; i < markers.length; i++ ) 
        {
            var title = markers[i][0];
            var loan = markers[i][1];
            var lat = markers[i][2];
            var long = markers[i][3];
            var add = markers[i][4];


            var iconGreen = 'img/greenMarker.png'; //green marker
            var iconRed = 'img/redMarker.png';     //red marker

            var infoWindowContent = loan + "\n" + placeId + add;

            var position = new google.maps.LatLng(lat, long);
            bounds.extend(position);

            marker = new google.maps.Marker({
                map: map,
                title: title,
                position: position,
                icon: iconGreen
            });
            testMarker[i] = marker;
            status[i] = 1;
            google.maps.event.addListener(marker, 'click', ( function toggleBounce( i,status,testMarker) 
            {
                return function() 
                {
                    infoWindow.setContent(markers[i][1]+markers[i][4]);
                    if( status[i] === 1 )
                    {
                        testMarker[i].setIcon(iconRed);
                        status[i] = 0;

                    }
                    for( var k = 0; k <  markers.length ; k++ )
                    {
                        if(k != i)
                        {
                            testMarker[k].setIcon(iconGreen);
                            status[i] = 1;

                        }
                    }
                    infoWindow.open(map, testMarker[i]);
                }
            })( i,status,testMarker));
            map.fitBounds(bounds);
        }
        var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event)
        {
            this.setZoom(8);
            google.maps.event.removeListener(boundsListener);
        });
    }
    google.maps.event.addDomListener(window, 'load', initialize);

</script>

<div id="mapDiv" style="width:820px; height:300px"></div>

Uninstall Node.JS using Linux command line?

if you want to just update node, there's a neat updater too

https://github.com/creationix/nvm

to use,

git clone git://github.com/creationix/nvm.git ~/.nvm

source ~/.nvm/nvm.sh

nvm install v0.4.1

Android Studio Emulator and "Process finished with exit code 0"

I was getting the following error when starting the emulator and none of the answers fixed it.

Emulator: Process finished with exit code -1073741515 (0xC0000135)

Finally I found that Visual C++ is not installed in my system. If it is not installed please install Visual C++ and check.

Please find the link below to download latest Visual C++.

https://support.microsoft.com/en-in/help/2977003/the-latest-supported-visual-c-downloads

Java Pass Method as Parameter

Example of solution with reflection, passed method must be public

import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;

public class Program {
    int i;

    public static void main(String[] args) {
        Program   obj = new Program();    //some object

        try {
            Method method = obj.getClass().getMethod("target");
            repeatMethod( 5, obj, method );
        } 
        catch ( NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
            System.out.println( e ); 
        }
    }

    static void repeatMethod (int times, Object object, Method method)
        throws IllegalAccessException, InvocationTargetException {

        for (int i=0; i<times; i++)
            method.invoke(object);
    }
    public void target() {                 //public is necessary
        System.out.println("target(): "+ ++i);
    }
}

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

The OSHI project provides platform-independent hardware utilities.

Maven dependency:

<dependency>
    <groupId>com.github.oshi</groupId>
    <artifactId>oshi-core</artifactId>
    <version>LATEST</version>
</dependency>

For instance, you could use something like the following code to identify a machine uniquely:

import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.hardware.ComputerSystem;
import oshi.hardware.HardwareAbstractionLayer;
import oshi.software.os.OperatingSystem;

class ComputerIdentifier
{
    static String generateLicenseKey()
    {
        SystemInfo systemInfo = new SystemInfo();
        OperatingSystem operatingSystem = systemInfo.getOperatingSystem();
        HardwareAbstractionLayer hardwareAbstractionLayer = systemInfo.getHardware();
        CentralProcessor centralProcessor = hardwareAbstractionLayer.getProcessor();
        ComputerSystem computerSystem = hardwareAbstractionLayer.getComputerSystem();

        String vendor = operatingSystem.getManufacturer();
        String processorSerialNumber = computerSystem.getSerialNumber();
        String processorIdentifier = centralProcessor.getIdentifier();
        int processors = centralProcessor.getLogicalProcessorCount();

        String delimiter = "#";

        return vendor +
                delimiter +
                processorSerialNumber +
                delimiter +
                processorIdentifier +
                delimiter +
                processors;
    }

    public static void main(String[] arguments)
    {
        String identifier = generateLicenseKey();
        System.out.println(identifier);
    }
}

Output for my machine:

Microsoft#57YRD12#Intel64 Family 6 Model 60 Stepping 3#8

Your output will be different since at least the processor serial number will differ.

failed to find target with hash string android-23

For me the problem was in that I wrote compileSdkVersion '23' instead of 23. The quotes were the problem.

How to get full file path from file name?

Directory.GetCurrentDirectory

string dirpath = Directory.GetCurrentDirectory();

Prepend this dirpath to the filename to get the complete path.

As @Dan Puzey indicated in the comments, it would be better to use Path.Combine

Path.Combine(Directory.GetCurrentDirectory(), filename)

Generating a WSDL from an XSD file

Personally (and given what I know, i.e., Java and axis), I'd generate a Java data model from the .xsd files (Axis 2 can do this), and then add an interface to describe my web service that uses that model, and then generate a WSDL from that interface.

Because .NET has all these features as well, it must be possible to do all this in that ecosystem as well.

How to calculate the sum of all columns of a 2D numpy array (efficiently)

Check out the documentation for numpy.sum, paying particular attention to the axis parameter. To sum over columns:

>>> import numpy as np
>>> a = np.arange(12).reshape(4,3)
>>> a.sum(axis=0)
array([18, 22, 26])

Or, to sum over rows:

>>> a.sum(axis=1)
array([ 3, 12, 21, 30])

Other aggregate functions, like numpy.mean, numpy.cumsum and numpy.std, e.g., also take the axis parameter.

From the Tentative Numpy Tutorial:

Many unary operations, such as computing the sum of all the elements in the array, are implemented as methods of the ndarray class. By default, these operations apply to the array as though it were a list of numbers, regardless of its shape. However, by specifying the axis parameter you can apply an operation along the specified axis of an array:

Java converting int to hex and back again

Using Integer.toHexString(...) is a good answer. But personally prefer to use String.format(...).

Try this sample as a test.

byte[] values = new byte[64];
Arrays.fill(values, (byte)8);  //Fills array with 8 just for test
String valuesStr = "";
for(int i = 0; i < values.length; i++)
    valuesStr += String.format("0x%02x", values[i] & 0xff) + " ";
valuesStr.trim();

get the value of input type file , and alert if empty

<script type="text/javascript">
$(document).ready(function() {
    $('#upload').bind("click",function() 
    { 
        var imgVal = $('#uploadImage').val(); 
        if(imgVal=='') 
        { 
            alert("empty input file"); 

        } 
        return false; 

    }); 
});
</script> 

<input type="file" name="image" id="uploadImage" size="30" /> 
<input type="submit" name="upload" id="upload"  class="send_upload" value="upload" /> 

String method cannot be found in a main class method

It seem like your Resort method doesn't declare a compareTo method. This method typically belongs to the Comparable interface. Make sure your class implements it.

Additionally, the compareTo method is typically implemented as accepting an argument of the same type as the object the method gets invoked on. As such, you shouldn't be passing a String argument, but rather a Resort.

Alternatively, you can compare the names of the resorts. For example

if (resortList[mid].getResortName().compareTo(resortName)>0)  

CodeIgniter Select Query

Here is the example of the code:

public function getItemName()
{
    $this->db->select('Id,Name');
    $this->db->from('item');
    $this->db->where(array('Active' => 1));
    return $this->db->get()->result();
}

Run ssh and immediately execute command

ssh -t 'command; bash -l'

will execute the command and then start up a login shell when it completes. For example:

ssh -t [email protected] 'cd /some/path; bash -l'

How can I mix LaTeX in with Markdown?

yes, but you'll have to hack it a little yourself. I've written a filter that replaces latex tags $\some\inline\latex$ or $$\some\equation$$ with appropriate image tags to a mimetex.cgi script. It took all of 5 minutes.

Warning: spectacularly ugly...

#!/usr/bin/env python
import sys, markdown,re

MIMETEX_LOC="http://some.server.com/cgi-bin/mimetex.cgi"

def sanitizeLatex(text):
    return re.sub(r"\\",r"%5C", text)

def wrapLatexBlock(text):
    return '<img alt="equation" class="block" src="%s?%s"></img>'%(MIMETEX_LOC,text)

def wrapLatexInline(text):
    return '<img alt="equation" class="inline" src="%s?%s"></img>'%(MIMETEX_LOC,text)

def prepLatexBlock(matchobj):
    return wrapLatexBlock(sanitizeLatex(matchobj.group()[2:-2]))

def prepLatexInline(matchobj):
    return wrapLatexInline(sanitizeLatex(matchobj.group()[1:-1]))


if __name__ == "__main__":
    # initialise markdown
    md=markdown.Markdown()
    raw_md=open(sys.argv[1],"r").read()

    ##
    # deal with embedded latex
    ##
    raw_md=re.sub(r'\$\$(.*?)\$\$',prepLatexBlock, raw_md)
    raw_md=re.sub(r'\$(.*?)\$',prepLatexInline, raw_md)

    ##
    # once latex is parsed, convert md to html
    ##
    main_html=md.convert(raw_md)

    # hey presto!
    print(main_html)

Of course, you have to define the appropriate css yourself for .block and .inline images...

Test for multiple cases in a switch, like an OR (||)

Forget switch and break, lets play with if. And instead of asserting

if(pageid === "listing-page" || pageid === "home-page")

lets create several arrays with cases and check it with Array.prototype.includes()

var caseA = ["listing-page", "home-page"];
var caseB = ["details-page", "case04", "case05"];

if(caseA.includes(pageid)) {
    alert("hello");
}
else if (caseB.includes(pageid)) {
    alert("goodbye");
}
else {
    alert("there is no else case");
}

JPA OneToMany and ManyToOne throw: Repeated column in mapping for entity column (should be mapped with insert="false" update="false")

I am not really sure about your question (the meaning of "empty table" etc, or how mappedBy and JoinColumn were not working).

I think you were trying to do a bi-directional relationships.

First, you need to decide which side "owns" the relationship. Hibernate is going to setup the relationship base on that side. For example, assume I make the Post side own the relationship (I am simplifying your example, just to keep things in point), the mapping will look like:

(Wish the syntax is correct. I am writing them just by memory. However the idea should be fine)

public class User{
    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    private List<Post> posts;
}


public class Post {
    @ManyToOne(fetch=FetchType.LAZY)
    @JoinColumn(name="user_id")
    private User user;
}

By doing so, the table for Post will have a column user_id which store the relationship. Hibernate is getting the relationship by the user in Post (Instead of posts in User. You will notice the difference if you have Post's user but missing User's posts).

You have mentioned mappedBy and JoinColumn is not working. However, I believe this is in fact the correct way. Please tell if this approach is not working for you, and give us a bit more info on the problem. I believe the problem is due to something else.


Edit:

Just a bit extra information on the use of mappedBy as it is usually confusing at first. In mappedBy, we put the "property name" in the opposite side of the bidirectional relationship, not table column name.

How do I include a Perl module that's in a different directory?

Most likely the reason your push did not work is order of execution.

use is a compile time directive. You push is done at execution time:

push ( @INC,"directory_path/more_path");
use Foo.pm;  # In directory path/more_path

You can use a BEGIN block to get around this problem:

BEGIN {
    push ( @INC,"directory_path/more_path");
}
use Foo.pm;  # In directory path/more_path

IMO, it's clearest, and therefore best to use lib:

use lib "directory_path/more_path";
use Foo.pm;  # In directory path/more_path

See perlmod for information about BEGIN and other special blocks and when they execute.

Edit

For loading code relative to your script/library, I strongly endorse File::FindLib

You can say use File::FindLib 'my/test/libs'; to look for a library directory anywhere above your script in the path.

Say your work is structured like this:

   /home/me/projects/
    |- shared/
    |   |- bin/
    |   `- lib/
    `- ossum-thing/
       `- scripts 
           |- bin/
           `- lib/

Inside a script in ossum-thing/scripts/bin:

use File::FindLib 'lib/';
use File::FindLib 'shared/lib/';

Will find your library directories and add them to your @INC.

It's also useful to create a module that contains all the environment set-up needed to run your suite of tools and just load it in all the executables in your project.

use File::FindLib 'lib/MyEnvironment.pm'

A Space between Inline-Block List Items

Actually, this is not specific to display:inline-block, but also applies to display:inline. Thus, in addition to David Horák's solution, this also works:

ul {
    font-size: 0;
}
ul li {
    font-size: 14px;
    display: inline;
}

go to link on button click - jquery

you can get the current url with window.location.href but I think you will need the jQuery query plugin to manipulate the query string: http://plugins.jquery.com/project/query-object

How to trim a string to N chars in Javascript?

Copying Will's comment into an answer, because I found it useful:

var string = "this is a string";
var length = 20;
var trimmedString = string.length > length ? 
                    string.substring(0, length - 3) + "..." : 
                    string;

Thanks Will.

And a jsfiddle for anyone who cares https://jsfiddle.net/t354gw7e/ :)

How to change Android version and code version number?

You can easily auto increase versionName and versionCode programmatically.

For Android add this to your gradle script and also create a file version.properties with VERSION_CODE=555

android {
        compileSdkVersion 30
        buildToolsVersion "30.0.3"
    
        def versionPropsFile = file('version.properties')
        if (versionPropsFile.canRead()) {
            def Properties versionProps = new Properties()
    
            versionProps.load(new FileInputStream(versionPropsFile))
    
            def code = versionProps['VERSION_CODE'].toInteger() + 1
    
            versionProps['VERSION_CODE'] = code.toString()
            versionProps.store(versionPropsFile.newWriter(), null)
    
    
            defaultConfig {
                applicationId "app.umanusorn.playground"
                minSdkVersion 29
                targetSdkVersion 30
                versionCode code
                versionName code.toString()

Browser Caching of CSS files

It does depend on the HTTP headers sent with the CSS files as both of the previous answers state - as long as you don't append any cachebusting stuff to the href. e.g.

<link href="/stylesheets/mycss.css?some_var_to_bust_cache=24312345" rel="stylesheet" type="text/css" />

Some frameworks (e.g. rails) put these in by default.

However If you get something like firebug or fiddler, you can see exactly what your browser is downloading on each request - which is expecially useful for finding out what your browser is doing, as opposed to just what it should be doing.

All browsers should respect the cache headers in the same way, unless configured to ignore them (but there are bound to be exceptions)

Delayed rendering of React components

We can solve this using Hooks:

First we'll need a timeout hook for the delay.

This one is inspired by Dan Abramov's useInterval hook (see Dan's blog post for an in depth explanation), the differences being:

  1. we use we setTimeout not setInterval
  2. we return a reset function allowing us to restart the timer at any time

_x000D_
_x000D_
import { useEffect, useRef, useCallback } from 'react';_x000D_
_x000D_
const useTimeout = (callback, delay) => {_x000D_
  // save id in a ref_x000D_
  const timeoutId = useRef('');_x000D_
_x000D_
  // save callback as a ref so we can update the timeout callback without resetting the clock_x000D_
  const savedCallback = useRef();_x000D_
  useEffect(_x000D_
    () => {_x000D_
      savedCallback.current = callback;_x000D_
    },_x000D_
    [callback],_x000D_
  );_x000D_
_x000D_
  // clear the timeout and start a new one, updating the timeoutId ref_x000D_
  const reset = useCallback(_x000D_
    () => {_x000D_
      clearTimeout(timeoutId.current);_x000D_
_x000D_
      const id = setTimeout(savedCallback.current, delay);_x000D_
      timeoutId.current = id;_x000D_
    },_x000D_
    [delay],_x000D_
  );_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      if (delay !== null) {_x000D_
        reset();_x000D_
_x000D_
        return () => clearTimeout(timeoutId.current);_x000D_
      }_x000D_
    },_x000D_
    [delay, reset],_x000D_
  );_x000D_
_x000D_
  return { reset };_x000D_
};
_x000D_
_x000D_
_x000D_

and now we need a hook which will capture previous children and use our useTimeout hook to swap in the new children after a delay

_x000D_
_x000D_
import { useState, useEffect } from 'react';_x000D_
_x000D_
const useDelayNextChildren = (children, delay) => {_x000D_
  const [finalChildren, setFinalChildren] = useState(children);_x000D_
_x000D_
  const { reset } = useTimeout(() => {_x000D_
    setFinalChildren(children);_x000D_
  }, delay);_x000D_
_x000D_
  useEffect(_x000D_
    () => {_x000D_
      reset();_x000D_
    },_x000D_
    [reset, children],_x000D_
  );_x000D_
_x000D_
  return finalChildren || children || null;_x000D_
};
_x000D_
_x000D_
_x000D_

Note that the useTimeout callback will always have the latest children, so even if we attempt to render multiple different new children within the delay time, we'll always get the latest children once the timeout finally completes.

Now in your case, we want to also delay the initial render, so we make this change:

_x000D_
_x000D_
const useDelayNextChildren = (children, delay) => {_x000D_
  const [finalChildren, setFinalChildren] = useState(null); // initial state set to null_x000D_
_x000D_
  // ... stays the same_x000D_
_x000D_
  return finalChildren || null;  // remove children from return_x000D_
};
_x000D_
_x000D_
_x000D_

and using the above hook, your entire child component becomes

_x000D_
_x000D_
import React, { memo } from 'react';_x000D_
import { useDelayNextChildren } from 'hooks';_x000D_
_x000D_
const Child = ({ delay }) => useDelayNextChildren(_x000D_
  <div>_x000D_
    ... Child JSX goes here_x000D_
    ... etc_x000D_
  </div>_x000D_
  , delay_x000D_
);_x000D_
_x000D_
export default memo(Child);
_x000D_
_x000D_
_x000D_

or if you prefer: ( dont say i havent given you enough code ;) )

_x000D_
_x000D_
const Child = ({ delay }) => {_x000D_
  const render = <div>... Child JSX goes here ... etc</div>;_x000D_
_x000D_
  return useDelayNextChildren(render, delay);_x000D_
};
_x000D_
_x000D_
_x000D_

which will work exactly the same in the Parent render function as in the accepted answer

...

except the delay will be the same on every subsequent render too,

AND we used hooks, so that stateful logic is reusable across any component

...

...

use hooks. :D

Can't create handler inside thread that has not called Looper.prepare()

I was running into the same issue when my callbacks would try to show a dialog.

I solved it with dedicated methods in the Activity - at the Activity instance member level - that use runOnUiThread(..)

public void showAuthProgressDialog() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mAuthProgressDialog = DialogUtil.getVisibleProgressDialog(SignInActivity.this, "Loading ...");
        }
    });
}

public void dismissAuthProgressDialog() {
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            if (mAuthProgressDialog == null || ! mAuthProgressDialog.isShowing()) {
                return;
            }
            mAuthProgressDialog.dismiss();
        }
    });
}

How to generate a random number between a and b in Ruby?

UPDATE: Ruby 1.9.3 Kernel#rand also accepts ranges

rand(a..b)

http://www.rubyinside.com/ruby-1-9-3-introduction-and-changes-5428.html

Converting to array may be too expensive, and it's unnecessary.


(a..b).to_a.sample

Or

[*a..b].sample

Array#sample

Standard in Ruby 1.8.7+.
Note: was named #choice in 1.8.7 and renamed in later versions.

But anyway, generating array need resources, and solution you already wrote is the best, you can do.

How do I POST JSON data with cURL?

Try to put your data in a file, say body.json and then use

curl -H "Content-Type: application/json" --data @body.json http://localhost:8080/ui/webapp/conf

scp from remote host to local host

There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.

And then you can copy for example the file "test.txt" from a remote host to the local host

scp [email protected]:test.txt /local/dir


@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.

In UNIX, absolute paths must start with '/'.

Meaning of 'const' last in a function declaration of a class?

The const means that the method promises not to alter any members of the class. You'd be able to execute the object's members that are so marked, even if the object itself were marked const:

const foobar fb;
fb.foo();

would be legal.

See How many and which are the uses of “const” in C++? for more information.

Java, Shifting Elements in an Array

Instead of shifting by one position you can make this function more general using module like this.

int[] original = { 1, 2, 3, 4, 5, 6 };
int[] reordered = new int[original.length];
int shift = 1;

for(int i=0; i<original.length;i++)
     reordered[i] = original[(shift+i)%original.length];

How to check if element in groovy array/hash/collection/list?

def fruitBag = ["orange","banana","coconut"]
def fruit = fruitBag.collect{item -> item.contains('n')}

I did it like this so it works if someone is looking for it.

How to change the port number for Asp.Net core app?

Maybe it's because I am not using Core yet. My project didn't have a LaunchSettings.json file but that did prompt me to look in the project properties. I found it under the Web tab and simply changed the project url: enter image description here

How can I suppress all output from a command using Bash?

An alternative that may fit in some situations is to assign the result of a command to a variable:

$ DUMMY=$( grep root /etc/passwd 2>&1 )
$ echo $?
0
$ DUMMY=$( grep r00t /etc/passwd 2>&1 )
$ echo $?
1

Since Bash and other POSIX commandline interpreters does not consider variable assignments as a command, the present command's return code is respected.

Note: assignement with the typeset or declare keyword is considered as a command, so the evaluated return code in case is the assignement itself and not the command executed in the sub-shell:

$ declare DUMMY=$( grep r00t /etc/passwd 2>&1 )
$ echo $?
0

Excel 2010 VBA Referencing Specific Cells in other worksheets

I am going to give you a simplistic answer that hopefully will help you with VBA in general. The easiest way to learn how VBA works and how to reference and access elements is to record your macro then edit it in the VBA editor. This is how I learned VBA. It is based on visual basic so all the programming conventions of VB apply. Recording the macro lets you see how to access and do things.

you could use something like this:

var result = 0
Sheets("Sheet1").Select
result = Range("A1").Value * Range("B1").Value
Sheets("Sheet2").Select
Range("D1").Value = result

Alternatively you can also reference a cell using Cells(1,1).Value This way you can set variables and increment them as you wish. I think I am just not clear on exactly what you are trying to do but i hope this helps.

How to create a sticky left sidebar menu using bootstrap 3?

Bootstrap 3

Here is a working left sidebar example:

http://bootply.com/90936 (similar to the Bootstrap docs)

The trick is using the affix component along with some CSS to position it:

  #sidebar.affix-top {
    position: static;
    margin-top:30px;
    width:228px;
  }

  #sidebar.affix {
    position: fixed;
    top:70px;
    width:228px;
  }

EDIT- Another example with footer and affix-bottom


Bootstrap 4

The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top class is explained in this answer.

Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?

Write Array to Excel Range

This is an excerpt from method of mine, which converts a DataTable (the dt variable) into an array and then writes the array into a Range on a worksheet (wsh var). You can also change the topRow variable to whatever row you want the array of strings to be placed at.

object[,] arr = new object[dt.Rows.Count, dt.Columns.Count];
for (int r = 0; r < dt.Rows.Count; r++)
{
    DataRow dr = dt.Rows[r];
    for (int c = 0; c < dt.Columns.Count; c++)
    {
        arr[r, c] = dr[c];
    }
}
Excel.Range c1 = (Excel.Range)wsh.Cells[topRow, 1];
Excel.Range c2 = (Excel.Range)wsh.Cells[topRow + dt.Rows.Count - 1, dt.Columns.Count];
Excel.Range range = wsh.get_Range(c1, c2);
range.Value = arr;

Of course you do not need to use an intermediate DataTable like I did, the code excerpt is just to demonstrate how an array can be written to worksheet in single call.

codeigniter model error: Undefined property

It solved throung second parameter in Model load:

$this->load->model('user','User');

first parameter is the model's filename, and second it defining the name of model to be used in the controller:

function alluser() 
{
$this->load->model('User');
$result = $this->User->showusers();
}

automating telnet session using bash scripts

Telnet is often used when you learn HTTP protocol. I used to use that script as a part of my web-scraper:

echo "open www.example.com 80" 
sleep 2 
echo "GET /index.html HTTP/1.1" 
echo "Host: www.example.com" 
echo 
echo 
sleep 2

let's say the name of the script is get-page.sh then:

get-page.sh | telnet

will give you a html document.

Hope it will be helpful to someone ;)

Create a custom event in Java

What you want is an implementation of the observer pattern. You can do it yourself completely, or use java classes like java.util.Observer and java.util.Observable

How to use boolean datatype in C?

C99 introduced _Bool as intrinsic pure boolean type. No #includes needed:

int main(void)
{
  _Bool b = 1;
  b = 0;
}

On a true C99 (or higher) compliant C compiler the above code should compile perfectly fine.