Programs & Examples On #Joomla template

Joomla is an open source content management system for web sites which includes a powerful template system.

TypeError: unsupported operand type(s) for -: 'str' and 'int'

For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str to int) so you must do this yourself. You'll like that in the long-run, trust me!

How do I check if a number is positive or negative in C#?

Of course no-one's actually given the correct answer,

num != 0   // num is positive *or* negative!

ASP.Net MVC 4 Form with 2 submit buttons/actions

That's what we have in our applications:
Attribute

public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
    public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
    {
        if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
            return true;

        var request = controllerContext.RequestContext.HttpContext.Request;
        return request[methodInfo.Name] != null;
    }
}

Actions decorated with it:


[HttpParamAction]
public ActionResult Save(MyModel model)
{
    // ...
}

[HttpParamAction]
public ActionResult Publish(MyModel model)
{
    // ...
}

HTML/Razor

@using (@Html.BeginForm())
{
    <!-- form content here -->
    <input type="submit" name="Save" value="Save" />
    <input type="submit" name="Publish" value="Publish" />
}

name attribute of submit button should match action/method name

This way you do not have to hard-code urls in javascript

Add / remove input field dynamically with jQuery

In your click function, you can write:

function addMoreRows(frm) {
   rowCount ++;
   var recRow = '<p id="rowCount'+rowCount+'"><tr><td><input name="" type="text" size="17%"  maxlength="120" /></td><td><input name="" type="text"  maxlength="120" style="margin: 4px 5px 0 5px;"/></td><td><input name="" type="text" maxlength="120" style="margin: 4px 10px 0 0px;"/></td></tr> <a href="javascript:void(0);" onclick="removeRow('+rowCount+');">Delete</a></p>';
   jQuery('#addedRows').append(recRow);
}

Or follow this link: http://www.discussdesk.com/add-remove-more-rows-dynamically-using-jquery.htm

How to open a file / browse dialog using javascript?

Unfortunately, there isn't a good way to browse for files with a JavaScript API. Fortunately, it's easy to create a file input in JavaScript, bind an event handler to its change event, and simulate a user clicking on it. We can do this without modifications to the page itself:

$('<input type="file" multiple>').on('change', function () {
  console.log(this.files);
}).click();

this.files on the second line is an array that contains filename, timestamps, size, and type.

Open a Web Page in a Windows Batch FIle

You can use the start command to do much the same thing as ShellExecute. For example

 start "" http://www.stackoverflow.com

This will launch whatever browser is the default browser, so won't necessarily launch Internet Explorer.

Why does flexbox stretch my image rather than retaining aspect ratio?

The key attribute is align-self: center:

_x000D_
_x000D_
.container {_x000D_
  display: flex;_x000D_
  flex-direction: column;_x000D_
}_x000D_
_x000D_
img {_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
img.align-self {_x000D_
  align-self: center;_x000D_
}
_x000D_
<div class="container">_x000D_
    <p>Without align-self:</p>_x000D_
    <img src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
    <p>With align-self:</p>_x000D_
    <img class="align-self" src="http://i.imgur.com/NFBYJ3hs.jpg" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Set font-weight using Bootstrap classes

In Bootstrap 4:

class="font-weight-bold"

Or:

<strong>text</strong>

Bulk Insert Correctly Quoted CSV File in SQL Server

I know this is an old topic but this feature has now been implemented since SQL Server 2017. The parameter you're looking for is FIELDQUOTE= which defaults to '"'. See more on https://docs.microsoft.com/en-us/sql/t-sql/statements/bulk-insert-transact-sql?view=sql-server-2017

Implementing a simple file download servlet

And to send a largFile

byte[] pdfData = getPDFData();

String fileType = "";

res.setContentType("application/pdf");

httpRes.setContentType("application/.pdf");
httpRes.addHeader("Content-Disposition", "attachment; filename=IDCards.pdf");
httpRes.setStatus(HttpServletResponse.SC_OK);
OutputStream out = res.getOutputStream();
System.out.println(pdfData.length);
         
out.write(pdfData);
System.out.println("sendDone");
out.flush();

How to clean up R memory (without the need to restart my PC)?

There is only so much you can do with rm() and gc(). As suggested by Gavin Simpson, even if you free the actual memory in R, Windows often won't reclaim it until you close R or it is needed because all the apparent Windows memory fills up.

This usually isn't a problem. However, if you are running large loops this can sometimes lead to fragmented memory in the long term, such that even if you free the memory and restart R - the fragmented memory may prevent you allocating large chunks of memory. Especially if other applications were allocated fragmented memory while you were running R. rm() and gc() may delay the inevitable, but more RAM is better.

Is it good practice to use the xor operator for boolean checks?

I think you've answered your own question - if you get strange looks from people, it's probably safer to go with the more explicit option.

If you need to comment it, then you're probably better off replacing it with the more verbose version and not making people ask the question in the first place.

How to install SimpleJson Package for Python

I would recommend EasyInstall, a package management application for Python.

Once you've installed EasyInstall, you should be able to go to a command window and type:

easy_install simplejson

This may require putting easy_install.exe on your PATH first, I don't remember if the EasyInstall setup does this for you (something like C:\Python25\Scripts).

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

Following the steps in the accepted answer didn't work for me. I followed the steps in this guide with an image running 5.0.0, and it got the job done. It's a step-wise process just like the accepted answer for adding Google Play support to genymotion images.

The most important differences are that in the guide I linked to, they mention that installing Google Play Services on images running higher than 5.0.0 may not work, and they say to change the ADB tool connection settings in the Genymotion desktop application's settings window to: Use custom Android SDK tools. Also, the gapps zips seem to be different.

The guide also uses GIFs to illustrate the steps in the process, so it leaves much less room for doubt.

Link to gapps zip for Android 5.0 used in the guide -- requires Genymotion 2.4.0+

Link to ARM Translation Installer v1.1 used in the guide -- this is provided for convenience. it doesn't seem any different than the one provided in the accepted answer at first glance

Moment JS - check if a date is today or in the future

i wanted it for something else but eventually found a trick which you can try

somedate.calendar(compareDate, { sameDay: '[Today]'})=='Today'

_x000D_
_x000D_
var d = moment();_x000D_
 var today = moment();_x000D_
 _x000D_
 console.log("Usign today's date, is Date is Today? ",d.calendar(today, {_x000D_
    sameDay: '[Today]'})=='Today');_x000D_
    _x000D_
 var someRondomDate = moment("2012/07/13","YYYY/MM/DD");_x000D_
 _x000D_
 console.log("Usign Some Random Date, is Today ?",someRondomDate.calendar(today, {_x000D_
    sameDay: '[Today]'})=='Today');_x000D_
    _x000D_
  _x000D_
 var anotherRandomDate =  moment("2012/07/13","YYYY/MM/DD");_x000D_
 _x000D_
 console.log("Two Random Date are same date ? ",someRondomDate.calendar(anotherRandomDate, {_x000D_
    sameDay: '[Today]'})=='Today');
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

What does bundle exec rake mean?

When you directly run the rake task or execute any binary file of a gem, there is no guarantee that the command will behave as expected. Because it might happen that you already have the same gem installed on your system which have a version say 1.0 but in your project you have higher version say 2.0. In this case you can not predict which one will be used.

To enforce the desired gem version you take the help of bundle exec command which would execute the binary in context of current bundle. That means when you use bundle exec, bundler checks the gem version configured for the current project and use that to perform the task.

I have also written a post about it which also shows how we can avoid using it using bin stubs.

CSS: stretching background image to 100% width and height of screen?

html, body {
    min-height: 100%;
}

Will do the trick.

By default, even html and body are only as big as the content they hold, but never more than the width/height of the windows. This can often lead to quite strange results.

You might also want to read http://css-tricks.com/perfect-full-page-background-image/

There are some great ways do achieve a very good and scalable full background image.

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I had the same problem, and my solving was to replace :

return redirect(url_for('index'))

with

return render_template('indexo.html',data=Todos.query.all())

in my POST and DELETE route.

What does the 'Z' mean in Unix timestamp '120314170138Z'?

"Z" doesn't stand for "Zulu"

I don't have any more information than the Wikipedia article cited by the two existing answers, but I believe the interpretation that "Z" stands for "Zulu" is incorrect. UTC time is referred to as "Zulu time" because of the use of Z to identify it, not the other way around. The "Z" seems to have been used to mark the time zone as the "zero zone", in which case "Z" unsurprisingly stands for "zero" (assuming the following information from Wikipedia is accurate):

Around 1950, a letter suffix was added to the zone description, assigning Z to the zero zone, and A–M (except J) to the east and N–Y to the west (J may be assigned to local time in non-nautical applications — zones M and Y have the same clock time but differ by 24 hours: a full day). These can be vocalized using the NATO phonetic alphabet which pronounces the letter Z as Zulu, leading to the use of the term "Zulu Time" for Greenwich Mean Time, or UT1 from January 1, 1972 onward.

How to add Action bar options menu in Android Fragments

I am late for the answer but I think this is another solution which is not mentioned here so posting.

Step 1: Make a xml of menu which you want to add like I have to add a filter action on my action bar so I have created a xml filter.xml. The main line to notice is android:orderInCategory this will show the action icon at first or last wherever you want to show. One more thing to note down is the value, if the value is less then it will show at first and if value is greater then it will show at last.

filter.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools" >


    <item
        android:id="@+id/action_filter"
        android:title="@string/filter"
        android:orderInCategory="10"
        android:icon="@drawable/filter"
        app:showAsAction="ifRoom" />


</menu>

Step 2: In onCreate() method of fragment just put the below line as mentioned, which is responsible for calling back onCreateOptionsMenu(Menu menu, MenuInflater inflater) method just like in an Activity.

@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);
    }

Step 3: Now add the method onCreateOptionsMenu which will be override as:

@Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.filter, menu);  // Use filter.xml from step 1
    }

Step 4: Now add onOptionsItemSelected method by which you can implement logic whatever you want to do when you select the added action icon from actionBar:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if(id == R.id.action_filter){
            //Do whatever you want to do 
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

How do I find out what type each object is in a ArrayList<Object>?

Instanceof works if you don't depend on specific classes, but also keep in mind that you can have nulls in the list, so obj.getClass() will fail, but instanceof always returns false on null.

How can I set size of a button?

Try with setPreferredSize instead of setSize.

UPDATE: GridLayout take up all space in its container, and BoxLayout seams to take up all the width in its container, so I added some glue-panels that are invisible and just take up space when the user stretches the window. I have just done this horizontally, and not vertically, but you could implement that in the same way if you want it.

Since GridLayout make all cells in the same size, it doesn't matter if they have a specified size. You have to specify a size for its container instead, as I have done.

import javax.swing.*;
import java.awt.*;

public class PanelModel {
    public static void main(String[] args) {
        JFrame frame = new JFrame("Colored Trails");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        JPanel mainPanel = new JPanel();
        mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

        JPanel firstPanel = new JPanel(new GridLayout(4, 4));
        firstPanel.setPreferredSize(new Dimension(4*100, 4*100));
        for (int i=1; i<=4; i++) {
            for (int j=1; j<=4; j++) {
                firstPanel.add(new JButton());
            }
        }

        JPanel firstGluePanel = new JPanel(new BorderLayout());
        firstGluePanel.add(firstPanel, BorderLayout.WEST);
        firstGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
        firstGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);

        JPanel secondPanel = new JPanel(new GridLayout(13, 5));
        secondPanel.setPreferredSize(new Dimension(5*40, 13*40));
        for (int i=1; i<=5; i++) {
            for (int j=1; j<=13; j++) {
                secondPanel.add(new JButton());
            }
        }

        JPanel secondGluePanel = new JPanel(new BorderLayout());
        secondGluePanel.add(secondPanel, BorderLayout.WEST);
        secondGluePanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
        secondGluePanel.add(Box.createVerticalGlue(), BorderLayout.SOUTH);

        mainPanel.add(firstGluePanel);
        mainPanel.add(secondGluePanel);
        frame.getContentPane().add(mainPanel);

        //frame.setSize(400,600);
        frame.pack();
        frame.setVisible(true);
    }
}

program cant start because php5.dll is missing

What you can do to solve this is:

  1. Download PHP5.dll or PHP7.dll from: http://windows.php.net/download/.
  2. Copy the downloaded php5.dll or php7.dll to C:\xampp\php.
  3. Start Apache and MySQL from XAMPP Control Panel.

Select rows with same id but different value in another column

Select A.ARIDNR,A.LIEFNR
from Table A
join Table B
on A.ARIDNR = B.ARIDNR
and A.LIEFNR<> B.LIEFNR
group by A.ARIDNR,A.LIEFNR

CREATE TABLE LIKE A1 as A2

For MySQL, you can do it like this:

CREATE TABLE New_Users   SELECT * FROM Old_Users group by ID;

Left/Right float button inside div

You can use justify-content: space-between in .test like so:

_x000D_
_x000D_
.test {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


For those who want to use Bootstrap 4 can use justify-content-between:

_x000D_
_x000D_
div {_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to use Angular4 to set focus by element id

One of the answers in the question referred to by @Z.Bagley gave me the answer. I had to import Renderer2 from @angular/core into my component. Then:

const element = this.renderer.selectRootElement('#input1');

// setTimeout(() => element.focus, 0);
setTimeout(() => element.focus(), 0);

Thank you @MrBlaise for the solution!

Mercurial stuck "waiting for lock"

I had the same problem. Got the following message when I tried to commit:

waiting for lock on working directory of <MyProject> held by '...'

hg debuglock showed this:

lock:  free
wlock:  (66722s)

So I did the following command, and that fixed the problem for me:

hg debuglocks -W

Using Win7 and TortoiseHg 4.8.7.

Tomcat base URL redirection

What i did:

I added the following line inside of ROOT/index.jsp

 <meta http-equiv="refresh" content="0;url=/somethingelse/index.jsp"/>

Remove all special characters with RegExp

Plain Javascript regex does not handle Unicode letters.

Do not use [^\w\s], this will remove letters with accents (like àèéìòù), not to mention to Cyrillic or Chinese, letters coming from such languages will be completed removed.

You really don't want remove these letters together with all the special characters. You have two chances:

  • Add in your regex all the special characters you don't want remove,
    for example: [^èéòàùì\w\s].
  • Have a look at xregexp.com. XRegExp adds base support for Unicode matching via the \p{...} syntax.

_x000D_
_x000D_
var str = "????::: résd,$%& adùf"
var search = XRegExp('([^?<first>\\pL ]+)');
var res = XRegExp.replace(str, search, '',"all");

console.log(res); // returns "????::: resd,adf"
console.log(str.replace(/[^\w\s]/gi, '') ); // returns " rsd adf"
console.log(str.replace(/[^\wèéòàùì\s]/gi, '') ); // returns " résd adùf"
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.js"></script>
_x000D_
_x000D_
_x000D_

What does "Table does not support optimize, doing recreate + analyze instead" mean?

That's really an informational message.

Likely, you're doing OPTIMIZE on an InnoDB table (table using the InnoDB storage engine, rather than the MyISAM storage engine).

InnoDB doesn't support the OPTIMIZE the way MyISAM does. It does something different. It creates an empty table, and copies all of the rows from the existing table into it, and essentially deletes the old table and renames the new table, and then runs an ANALYZE to gather statistics. That's the closest that InnoDB can get to doing an OPTIMIZE.

The message you are getting is basically MySQL server repeating what the InnoDB storage engine told MySQL server:

Table does not support optimize is the InnoDB storage engine saying...

"I (the InnoDB storage engine) don't do an OPTIMIZE operation like my friend (the MyISAM storage engine) does."

"doing recreate + analyze instead" is the InnoDB storage engine saying...

"I have decided to perform a different set of operations which will achieve an equivalent result."

Get keys of a Typescript interface as array of strings

Can't. Interfaces don't exist at runtime.

workaround

Create a variable of the type and use Object.keys on it

How to plot an array in python?

if you give a 2D array to the plot function of matplotlib it will assume the columns to be lines:

If x and/or y is 2-dimensional, then the corresponding columns will be plotted.

In your case your shape is not accepted (100, 1, 1, 8000). As so you can using numpy squeeze to solve the problem quickly:

np.squeez doc: Remove single-dimensional entries from the shape of an array.

import numpy as np
import matplotlib.pyplot as plt

data = np.random.randint(3, 7, (10, 1, 1, 80))
newdata = np.squeeze(data) # Shape is now: (10, 80)
plt.plot(newdata) # plotting by columns
plt.show()

But notice that 100 sets of 80 000 points is a lot of data for matplotlib. I would recommend that you look for an alternative. The result of the code example (run in Jupyter) is:

Jupyter matplotlib plot

How to remove all characters after a specific character in python?

Assuming your separator is '...', but it can be any string.

text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')

>>> print head
some string

If the separator is not found, head will contain all of the original string.

The partition function was added in Python 2.5.

partition(...) S.partition(sep) -> (head, sep, tail)

Searches for the separator sep in S, and returns the part before it,
the separator itself, and the part after it.  If the separator is not
found, returns S and two empty strings.

Change a HTML5 input's placeholder color with CSS

I don't remember where I've found this code snippet on the Internet (it wasn't written by me, don't remember where I've found it, nor who wrote it).

$('[placeholder]').focus(function() {
        var input = $(this);
        if (input.val() == input.attr('placeholder')) {
            input.val('');
            input.removeClass('placeholder');
        }
    }).blur(function() {
        var input = $(this);
        if (input.val() == '' || input.val() == input.attr('placeholder')) {
            input.addClass('placeholder');
            input.val(input.attr('placeholder'));
        }
    }).blur();
    $('[placeholder]').parents('form').submit(function() {
        $(this).find('[placeholder]').each(function() {
            var input = $(this);
            if (input.val() == input.attr('placeholder')) {
                input.val('');
            }
        })
    });

Just load this JavaScript code and then edit your placeholder with CSS by calling this rule:

form .placeholder {
   color: #222;
   font-size: 25px;
   /* etc. */
}

Google Maps setCenter()

For me above solutions didn't work then I tried

map.setCenter(new google.maps.LatLng(lat, lng));

and it worked as expected.

How to set character limit on the_content() and the_excerpt() in wordpress

Or even easier and without the need to create a filter: use PHP's mb_strimwidth to truncate a string to a certain width (length). Just make sure you use one of the get_ syntaxes. For example with the content:

<?php $content = get_the_content(); echo mb_strimwidth($content, 0, 400, '...');?>

This will cut the string at 400 characters and close it with .... Just add a "read more"-link to the end by pointing to the permalink with get_permalink().

<a href="<?php the_permalink() ?>">Read more </a>

Of course you could also build the read more in the first line. Than just replace '...' with '<a href="' . get_permalink() . '">[Read more]</a>'

ORA-00979 not a group by expression

Too bad Oracle has limitations like these. Sure, the result for a column not in the GROUP BY would be random, but sometimes you want that. Silly Oracle, you can do this in MySQL/MSSQL.

BUT there is a work around for Oracle:

While the following line does not work

SELECT unique_id_col, COUNT(1) AS cnt FROM yourTable GROUP BY col_A;

You can trick Oracle with some 0's like the following, to keep your column in scope, but not group by it (assuming these are numbers, otherwise use CONCAT)

SELECT MAX(unique_id_col) AS unique_id_col, COUNT(1) AS cnt 
FROM yourTable GROUP BY col_A, (unique_id_col*0 + col_A);

How do I check if string contains substring?

ECMAScript 6 introduces String.prototype.includes, previously named contains.

It can be used like this:

'foobar'.includes('foo'); // true
'foobar'.includes('baz'); // false

It also accepts an optional second argument which specifies the position at which to begin searching:

'foobar'.includes('foo', 1); // false
'foobar'.includes('bar', 1); // true

It can be polyfilled to make it work on old browsers.

How to draw border on just one side of a linear layout?

I was able to achieve the effect with the following code

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:left="0dp" android:right="-5dp" android:top="-5dp" android:bottom="-5dp">
        <shape
        android:shape="rectangle">
            <stroke android:width="1dp" android:color="#123456" />
        </shape>
    </item>
</layer-list>

You can adjust to your needs for border position by changing the direction of displacement

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

In bootstrap 3, this works well for me:

.btn-link.btn-anchor {
    outline: none !important;
    padding: 0;
    border: 0;
    vertical-align: baseline;
}

Used like:

<button type="button" class="btn-link btn-anchor">My Button</button>

Demo

SQL Query for Logins

Select * From Master..SysUsers Where IsSqlUser = 1

Count table rows

Because nobody mentioned it:

show table status;

lists all tables along with some additional information, including estimated rows for each table. This is what phpMyAdmin is using for its database page.

This information is available in MySQL 4, probably in MySQL 3.23 too - long time prior information schema database.

UPDATE:

Because there was down-vote, I want to clarify that the number shown is estimated for InnoDB and TokuDB and it is absolutely correct for MyISAM and Aria (Maria) storage engines.

Per the documentation:

The number of rows. Some storage engines, such as MyISAM, store the exact count. For other storage engines, such as InnoDB, this value is an approximation, and may vary from the actual value by as much as 40% to 50%. In such cases, use SELECT COUNT(*) to obtain an accurate count.

This also is fastest way to see the row count on MySQL, because query like:

select count(*) from table;

Doing full table scan what could be very expensive operation that might take hours on large high load server. It also increase disk I/O.

The same operation might block the table for inserts and updates - this happen only on exotic storage engines.

InnoDB and TokuDB are OK with table lock, but need full table scan.

Why is my toFixed() function not working?

Example simple (worked):

var a=Number.parseFloat($("#budget_project").val()); // from input field
var b=Number.parseFloat(html); // from ajax
var c=a-b;
$("#result").html(c.toFixed(2)); // put to id='result' (div or others)

jQuery - Getting the text value of a table cell in the same row as a clicked element

so you can use parent() to reach to the parent tr and then use find to gather the td with class two

var Something = $(this).parent().find(".two").html();

or

var Something = $(this).parent().parent().find(".two").html();

use as much as parent() what ever the depth of the clicked object according to the tr row

hope this works...

What is the use of WPFFontCache Service in WPF? WPFFontCache_v0400.exe taking 100 % CPU all the time this exe is running, why?

After installing Free BitDefender AntiVirus the services related to the AntiVirus used about 80 MB of my computer's Memory. I also noticed that after installing BitDefender the service related to windows Presentation Font Cache was also installed: "WPFFontCache_v0300.exe". I disabled the service from stating automatically and now BitDefender Free AntiVirus use only 15-20 MB (!!!) of my computer's Memory! As far as I concern, this service affected negatively the memory usage of my PC inother services. I recommend you to disable it.

HTTP POST and GET using cURL in Linux

*nix provides a nice little command which makes our lives a lot easier.

GET:

with JSON:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource

with XML:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource

POST:

For posting data:

curl --data "param1=value1&param2=value2" http://hostname/resource

For file upload:

curl --form "[email protected]" http://hostname/resource

RESTful HTTP Post:

curl -X POST -d @filename http://hostname/resource

For logging into a site (auth):

curl -d "username=admin&password=admin&submit=Login" --dump-header headers http://localhost/Login
curl -L -b headers http://localhost/

Pretty-printing the curl results:

For JSON:

If you use npm and nodejs, you can install json package by running this command:

npm install -g json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | json

If you use pip and python, you can install pjson package by running this command:

pip install pjson

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | pjson

If you use Python 2.6+, json tool is bundled within.

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | python -m json.tool

If you use gem and ruby, you can install colorful_json package by running this command:

gem install colorful_json

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource | cjson

If you use apt-get (aptitude package manager of your Linux distro), you can install yajl-tools package by running this command:

sudo apt-get install yajl-tools

Usage:

curl -i -H "Accept: application/json" -H "Content-Type: application/json" -X GET http://hostname/resource |  json_reformat

For XML:

If you use *nix with Debian/Gnome envrionment, install libxml2-utils:

sudo apt-get install libxml2-utils

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | xmllint --format -

or install tidy:

sudo apt-get install tidy

Usage:

curl -H "Accept: application/xml" -H "Content-Type: application/xml" -X GET http://hostname/resource | tidy -xml -i -

Saving the curl response to a file

curl http://hostname/resource >> /path/to/your/file

or

curl http://hostname/resource -o /path/to/your/file

For detailed description of the curl command, hit:

man curl

For details about options/switches of the curl command, hit:

curl -h

jQuery check if an input is type checkbox?

$('#myinput').is(':checkbox')

this is the only work, to solve the issue to detect if checkbox checked or not. It returns true or false, I search it for hours and try everything, now its work to be clear I use EDG as browser and W2UI

HTML SELECT - Change selected option by VALUE using JavaScript

document.getElementById('drpSelectSourceLibrary').value = 'Seven';

Change Row background color based on cell value DataTable

OK I was able to solve this myself:

$(document).ready(function() {
  $('#tid_css').DataTable({
    "iDisplayLength": 100,
    "bFilter": false,
    "aaSorting": [
      [2, "desc"]
    ],
    "fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {
      if (aData[2] == "5") {
        $('td', nRow).css('background-color', 'Red');
      } else if (aData[2] == "4") {
        $('td', nRow).css('background-color', 'Orange');
      }
    }
  });
})

jsonify a SQLAlchemy result set in Flask

Here's what's usually sufficient for me:

I create a serialization mixin which I use with my models. The serialization function basically fetches whatever attributes the SQLAlchemy inspector exposes and puts it in a dict.

from sqlalchemy.inspection import inspect

class Serializer(object):

    def serialize(self):
        return {c: getattr(self, c) for c in inspect(self).attrs.keys()}

    @staticmethod
    def serialize_list(l):
        return [m.serialize() for m in l]

All that's needed now is to extend the SQLAlchemy model with the Serializer mixin class.

If there are fields you do not wish to expose, or that need special formatting, simply override the serialize() function in the model subclass.

class User(db.Model, Serializer):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String)
    password = db.Column(db.String)

    # ...

    def serialize(self):
        d = Serializer.serialize(self)
        del d['password']
        return d

In your controllers, all you have to do is to call the serialize() function (or serialize_list(l) if the query results in a list) on the results:

def get_user(id):
    user = User.query.get(id)
    return json.dumps(user.serialize())

def get_users():
    users = User.query.all()
    return json.dumps(User.serialize_list(users))

How can I get onclick event on webview in android?

I have tried almost all the answers and some of them almost worked for me but none of these answers work perfectly. So here is my solution. For this solution, you will need to add onclick attribute in the HTML body tag. So if you can not modify the HTML file then this solution won't work for you.

Step 1: add onclick attribute in the HTML body tag like this:

<body onclick="ok.performClick(this.value);">
    <h1>This is heading 1</h1>
    <p>This is para 1</p>
</body>

Step 2: implement addJavascriptInterface in your app to handle click listener:

webView.addJavascriptInterface(new Object() {
    @JavascriptInterface
    public void performClick(String string) {
        handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 0);
    }
}, "ok");

Step 3: We can not perform any action on main thread from performClick method so need to add Handler class:

private final Handler handler = new Handler(this); // class-level variable 
private static final int CLICK_ON_WEBVIEW = 1; // class-level variable 

implement Handler.Callback to your class and the override handleMessage

@Override
public boolean handleMessage(Message message) {
    if (message.what == CLICK_ON_WEBVIEW) {
        Toast.makeText(getActivity(), "WebView clicked", Toast.LENGTH_SHORT).show();
        return true;
    }
    return false;
}

Install / upgrade gradle on Mac OS X

Two Method

  • using homebrew auto install:
    • Steps:
      • brew install gradle
    • Pros and cons
      • Pros: easy
      • Cons: (probably) not latest version
  • manually install (for latest version):
    • Pros and cons
      • Pros: use your expected any (or latest) version
      • Cons: need self to do it
    • Steps
      • download latest version binary (gradle-6.0.1) from Gradle | Releases
      • unzip it (gradle-6.0.1-all.zip) and added gradle path into environment variable PATH
        • normally is edit and add following config into your startup script( ~/.bashrc or ~/.zshrc etc.):
export GRADLE_HOME=/path_to_your_gradle/gradle-6.0.1
export PATH=$GRADLE_HOME/bin:$PATH

some other basic note

Q: How to make PATH take effect immediately?

A: use source:

source ~/.bashrc

it will make/execute your .bashrc, so make PATH become your expected latest values, which include your added gradle path.

Q: How to check PATH is really take effect/working now?

A: use echo to see your added path in indeed in your PATH

?  ~ echo $PATH
xxx:/Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin:xxx

you can see we added /Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin into your PATH

Q: How to verify gradle is installed correctly on my Mac ?

A: use which to make sure can find gradle

?  ~ which gradle
/Users/crifan/dev/dev_tool/java/gradle/gradle-6.0.1/bin/gradle

AND to check and see gradle version

?  ~ gradle --version

------------------------------------------------------------
Gradle 6.0.1
------------------------------------------------------------

Build time:   2019-11-18 20:25:01 UTC
Revision:     fad121066a68c4701acd362daf4287a7c309a0f5

Kotlin:       1.3.50
Groovy:       2.5.8
Ant:          Apache Ant(TM) version 1.10.7 compiled on September 1 2019
JVM:          1.8.0_112 (Oracle Corporation 25.112-b16)
OS:           Mac OS X 10.14.6 x86_64

this means the (latest) gradle is correctly installed on your mac ^_^.

for more detail please refer my (Chinese) post ?????mac???maven

How to push a docker image to a private repository

There are two options:

  1. Go into the hub, and create the repository first, and mark it as private. Then when you push to that repo, it will be private. This is the most common approach.

  2. log into your docker hub account, and go to your global settings. There is a setting that allows you to set what your default visability is for the repositories that you push. By default it is set to public, but if you change it to private, all of your repositories that you push will be marked as private by default. It is important to note that you will need to have enough private repos available on your account, or else the repo will be locked until you upgrade your plan.

Get the height and width of the browser viewport without scrollbars using jquery?

Don't use jQuery, just use javascript for correct result:

This includes scrollbar width/height:

_x000D_
_x000D_
var windowWidth = window.innerWidth;_x000D_
var windowHeight = window.innerHeight;_x000D_
_x000D_
alert('viewport width is: '+ windowWidth + ' and viewport height is:' + windowHeight);
_x000D_
_x000D_
_x000D_

This excludes scrollbar width/height:

_x000D_
_x000D_
var widthWithoutScrollbar = document.body.clientWidth;_x000D_
var heightWithoutScrollbar = document.body.clientHeight;_x000D_
_x000D_
alert('viewport width is: '+ widthWithoutScrollbar + ' and viewport height is:' + heightWithoutScrollbar);
_x000D_
_x000D_
_x000D_

How to replace local branch with remote branch entirely in Git?

git branch -D <branch-name>
git fetch <remote> <branch-name>
git checkout -b <branch-name> --track <remote>/<branch-name>

Column/Vertical selection with Keyboard in SublimeText 3

Commenting just so people can have a solution to the intended question.

You can do what you are wanting but it isn't quite as nice as Notepad++ but it may work for small solutions decently enough.

In sublime if you hold ctrl, or mac equiv., and select the word/characters you want on a single line with the mouse and still holding ctrl go to another line and select the word/characters you want on that line it will be additive and you will build your selection. I mainly use notepadd++ as my extractor and data cleanup and sublime for actual development.

The other way is if your columns are in perfect alignment you can simply middle click on windows or option + click on mac and this enables you to select text in a square like fashion, Columns, inside the lines of text.

How to fix Array indexOf() in JavaScript for Internet Explorer browsers

Alternatively, you could use the jQuery 1.2 inArray function, which should work across browsers:

jQuery.inArray( value, array [, fromIndex ] )

Aligning rotated xticklabels with their respective xticks

If you dont want to modify the xtick labels, you can just use:

plt.xticks(rotation=45)

Reset IntelliJ UI to Default

check, if this works for you.

File -> Settings -> (type appe in search box) and select Appearance -> Select Intellij from dropdown option of Theme on the right (under UI Options).

Hope this helps someone.

Format date and time in a Windows batch script

This batch script will do exactly what the O.P. wants (tested on Windows XP SP3).

I also used that clever registry trick described by "jph" previously which IMHO is the simplest way of getting 100% consistent formatting of the date to "yyyy_MM_dd" on any Windows system new or old. The change to one Registry value for doing this is instantaneous temporary and trivial; it only lasts a few milliseconds before it is immediately reverted back.

Double-click this batch file for an instant demo, Command Prompt window will pop up and display your timestamp . . . . .

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: generates a custom formatted timestamp string using date and time.
:: run this batch file for an instant demo.
::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

@ECHO OFF
SETLOCAL & MODE CON:COLS=80 LINES=15 & COLOR 0A

:: --- CHANGE THE COMPUTER DATE FORMAT TEMPORARILY TO MY PREFERENCE "yyyy_MM_dd",
REG COPY "HKCU\Control Panel\International" "HKCU\Control Panel\International-Temp" /f 2>nul >nul
REG ADD "HKCU\Control Panel\International" /v sShortDate /d "yyyy_MM_dd" /f 2>nul >nul

SET MYDATE=%date%

:: --- REVERT COMPUTER DATE BACK TO SYSTEM PREFERENCE
REG COPY "HKCU\Control Panel\International-Temp" "HKCU\Control Panel\International" /f 2>nul >nul
REG DELETE "HKCU\Control Panel\International-Temp" /f 2>nul >nul

:: --- SPLIT THE TIME [HH:MM:SS.SS] TO THREE SEPARATE VARIABLES [HH] [MM] [SS.SS]
FOR /F "tokens=1-3 delims=:" %%A IN ('echo %time%') DO (
SET HOUR=%%A
SET MINUTES=%%B
SET SECONDS=%%C
)

:: --- CHOOSE ONE OF THESE TWO OPTIONS :
:: --- FOR 4 DIGIT SECONDS        //REMOVES THE DOT FROM THE SECONDS VARIABLE [SS.SS]
:: SET SECONDS=%SECONDS:.=%
:: --- FOR 2 DIGIT SECONDS        //GETS THE FIRST TWO DIGITS FROM THE SECONDS VARIABLE [SS.SS]
SET SECONDS=%SECONDS:~0,2% 

:: --- FROM 12 AM TO 9 AM, THE HOUR VARIABLE WE EXTRACTED FROM %TIME% RETURNS A SINGLE DIGIT, 
:: --- WE PREFIX A ZERO CHARACTER TO THOSE CASES, SO THAT OUR WANTED TIMESTAMP
:: --- ALWAYS GENERATES DOUBLE-DIGIT HOURS (24-HOUR CLOCK TIME SYSTEM).
IF %HOUR%==0 (SET HOUR=00)
IF %HOUR%==1 (SET HOUR=01)
IF %HOUR%==2 (SET HOUR=02)
IF %HOUR%==3 (SET HOUR=03)
IF %HOUR%==4 (SET HOUR=04)
IF %HOUR%==5 (SET HOUR=05)
IF %HOUR%==6 (SET HOUR=06)
IF %HOUR%==7 (SET HOUR=07)
IF %HOUR%==8 (SET HOUR=08)
IF %HOUR%==9 (SET HOUR=09)

:: --- GENERATE OUR WANTED TIMESTAMP
SET TIMESTAMP=%MYDATE%__%HOUR%_%MINUTES%_%SECONDS%

:: --- VIEW THE RESULT IN THE CONSOLE SCREEN
ECHO.
ECHO    Generate a custom formatted timestamp string using date and time.
ECHO.
ECHO    Your timestamp is:    %TIMESTAMP%
ECHO.
ECHO.
ECHO    Job is done. Press any key to exit . . .
PAUSE > NUL

EXIT

getting the error: expected identifier or ‘(’ before ‘{’ token

you need to place the opening brace after main , not before it

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

int main(void)
{

Access restriction on class due to restriction on required library rt.jar?

I just had this problem too. Apparently I had set the JRE to 1.5 instead of 1.6 in my build path.

JavaScript: Object Rename Key

You could wrap the work in a function and assign it to the Object prototype. Maybe use the fluent interface style to make multiple renames flow.

Object.prototype.renameProperty = function (oldName, newName) {
     // Do nothing if the names are the same
     if (oldName === newName) {
         return this;
     }
    // Check for the old property name to avoid a ReferenceError in strict mode.
    if (this.hasOwnProperty(oldName)) {
        this[newName] = this[oldName];
        delete this[oldName];
    }
    return this;
};

ECMAScript 5 Specific

I wish the syntax wasn't this complex but it is definitely nice having more control.

Object.defineProperty(
    Object.prototype, 
    'renameProperty',
    {
        writable : false, // Cannot alter this property
        enumerable : false, // Will not show up in a for-in loop.
        configurable : false, // Cannot be deleted via the delete operator
        value : function (oldName, newName) {
            // Do nothing if the names are the same
            if (oldName === newName) {
                return this;
            }
            // Check for the old property name to 
            // avoid a ReferenceError in strict mode.
            if (this.hasOwnProperty(oldName)) {
                this[newName] = this[oldName];
                delete this[oldName];
            }
            return this;
        }
    }
);

How to Deep clone in javascript

var newDate = new Date(this.oldDate); I was passing oldDate to function and generating newDate from this.oldDate, but it was changing this.oldDate also.So i used that solution and it worked.

Using bind variables with dynamic SELECT INTO clause in PL/SQL

Bind variable can be used in Oracle SQL query with "in" clause.

Works in 10g; I don't know about other versions.

Bind variable is varchar up to 4000 characters.

Example: Bind variable containing comma-separated list of values, e.g.

:bindvar = 1,2,3,4,5

select * from mytable
  where myfield in
    (
      SELECT regexp_substr(:bindvar,'[^,]+', 1, level) items
      FROM dual
      CONNECT BY regexp_substr(:bindvar, '[^,]+', 1, level) is not null
    );

(Same info as I posted here: How do you specify IN clause in a dynamic query using a variable? )

Can someone explain __all__ in Python?

I'm just adding this to be precise:

All other answers refer to modules. The original question explicitely mentioned __all__ in __init__.py files, so this is about python packages.

Generally, __all__ only comes into play when the from xxx import * variant of the import statement is used. This applies to packages as well as to modules.

The behaviour for modules is explained in the other answers. The exact behaviour for packages is described here in detail.

In short, __all__ on package level does approximately the same thing as for modules, except it deals with modules within the package (in contrast to specifying names within the module). So __all__ specifies all modules that shall be loaded and imported into the current namespace when us use from package import *.

The big difference is, that when you omit the declaration of __all__ in a package's __init__.py, the statement from package import * will not import anything at all (with exceptions explained in the documentation, see link above).

On the other hand, if you omit __all__ in a module, the "starred import" will import all names (not starting with an underscore) defined in the module.

Writing a VLOOKUP function in vba

Please find the code below for Vlookup:

Function vlookupVBA(lookupValue, rangeString, colOffset)
vlookupVBA = "#N/A"
On Error Resume Next
Dim table_lookup As range
Set table_lookup = range(rangeString)
vlookupVBA = Application.WorksheetFunction.vlookup(lookupValue, table_lookup, colOffset, False)
End Function

How to increase the Java stack size?

I assume you calculated the "depth of 1024" by the recurring lines in the stack trace?

Obviously, the stack trace array length in Throwable seems to be limited to 1024. Try the following program:

public class Test {

    public static void main(String[] args) {

        try {
            System.out.println(fact(1 << 15));
        }
        catch (StackOverflowError e) {
            System.err.println("true recursion level was " + level);
            System.err.println("reported recursion level was " +
                               e.getStackTrace().length);
        }
    }

    private static int level = 0;
    public static long fact(int n) {
        level++;
        return n < 2 ? n : n * fact(n - 1);
    }
}

How to create Windows EventLog source from command line?

you can create your own custom event by using diagnostics.Event log class. Open a windows application and on a button click do the following code.

System.Diagnostics.EventLog.CreateEventSource("ApplicationName", "MyNewLog");

"MyNewLog" means the name you want to give to your log in event viewer.

for more information check this link [ http://msdn.microsoft.com/en-in/library/49dwckkz%28v=vs.90%29.aspx]

How to set a single, main title above all the subplots with Pyplot?

A few points I find useful when applying this to my own plots:

  • I prefer the consistency of using fig.suptitle(title) rather than plt.suptitle(title)
  • When using fig.tight_layout() the title must be shifted with fig.subplots_adjust(top=0.88)
  • See answer below about fontsizes

Example code taken from subplots demo in matplotlib docs and adjusted with a master title.

A nice 4x4 plot

import matplotlib.pyplot as plt
import numpy as np

# Simple data to display in various forms
x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)

fig, axarr = plt.subplots(2, 2)
fig.suptitle("This Main Title is Nicely Formatted", fontsize=16)

axarr[0, 0].plot(x, y)
axarr[0, 0].set_title('Axis [0,0] Subtitle')
axarr[0, 1].scatter(x, y)
axarr[0, 1].set_title('Axis [0,1] Subtitle')
axarr[1, 0].plot(x, y ** 2)
axarr[1, 0].set_title('Axis [1,0] Subtitle')
axarr[1, 1].scatter(x, y ** 2)
axarr[1, 1].set_title('Axis [1,1] Subtitle')

# # Fine-tune figure; hide x ticks for top plots and y ticks for right plots
plt.setp([a.get_xticklabels() for a in axarr[0, :]], visible=False)
plt.setp([a.get_yticklabels() for a in axarr[:, 1]], visible=False)

# Tight layout often produces nice results
# but requires the title to be spaced accordingly
fig.tight_layout()
fig.subplots_adjust(top=0.88)

plt.show()

Python recursive folder read

Agree with Dave Webb, os.walk will yield an item for each directory in the tree. Fact is, you just don't have to care about subFolders.

Code like this should work:

import os
import sys

rootdir = sys.argv[1]

for folder, subs, files in os.walk(rootdir):
    with open(os.path.join(folder, 'python-outfile.txt'), 'w') as dest:
        for filename in files:
            with open(os.path.join(folder, filename), 'r') as src:
                dest.write(src.read())

How can the size of an input text box be defined in HTML?

You could set its width:

<input type="text" id="text" name="text_name" style="width: 300px;" />

or even better define a class:

<input type="text" id="text" name="text_name" class="mytext" />

and in a separate CSS file apply the necessary styling:

.mytext {
    width: 300px;
}

If you want to limit the number of characters that the user can type into this textbox you could use the maxlength attribute:

<input type="text" id="text" name="text_name" class="mytext" maxlength="25" />

How to force Chrome browser to reload .css file while debugging in Visual Studio?

Why is it needed to refresh the whole page? Just refresh only css files without reloading the page. It is very helpful when, for example, you have to wait a long response from DB. Once you get data from DB and populate the page, then edit your css files and reload them in Chrome (or in Firefox). To do that you need to install CSS Reloader extension. Firefox version is also available.

Pass row number as variable in excel sheet

An alternative is to use OFFSET:

Assuming the column value is stored in B1, you can use the following

C1 = OFFSET(A1, 0, B1 - 1)

This works by:

a) taking a base cell (A1)
b) adding 0 to the row (keeping it as A)
c) adding (A5 - 1) to the column

You can also use another value instead of 0 if you want to change the row value too.

How to pass a Javascript Array via JQuery Post so that all its contents are accessible via the PHP $_POST array?

This is fairly straightforward. In your JS, all you would do is this or something similar:

var array = ["thing1", "thing2", "thing3"];

var parameters = {
  "array1[]": array,
  ...
};

$.post(
  'your/page.php',
  parameters
)
.done(function(data, statusText) {
    // This block is optional, fires when the ajax call is complete
});

In your php page, the values in array form will be available via $_POST['array1'].

references

Regex in JavaScript for validating decimal numbers

Does this work?

[0-9]{2}.[0-9]{2}

Install-Module : The term 'Install-Module' is not recognized as the name of a cmdlet

Run the below commands as admin to install NuGet using Powershell:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Install-PackageProvider -Name NuGet

Print a file's last modified date in Bash

EDITED: turns out that I had forgotten the quotes needed for $entry in order to print correctly and not give the "no such file or directory" error. Thank you all so much for helping me!

Here is my final code:

    echo "Please type in the directory you want all the files to be listed with last modified dates" #bash can't find file creation dates

read directory

for entry in "$directory"/*

do
modDate=$(stat -c %y "$entry") #%y = last modified. Qoutes are needed otherwise spaces in file name with give error of "no such file"
modDate=${modDate%% *} #%% takes off everything off the string after the date to make it look pretty
echo $entry:$modDate

Prints out like this:

/home/joanne/Dropbox/cheat sheet.docx:2012-03-14
/home/joanne/Dropbox/Comp:2013-05-05
/home/joanne/Dropbox/Comp 150 java.zip:2013-02-11
/home/joanne/Dropbox/Comp 151 Java 2.zip:2013-02-11
/home/joanne/Dropbox/Comp 162 Assembly Language.zip:2013-02-11
/home/joanne/Dropbox/Comp 262 Comp Architecture.zip:2012-12-12
/home/joanne/Dropbox/Comp 345 Image Processing.zip:2013-02-11
/home/joanne/Dropbox/Comp 362 Operating Systems:2013-05-05
/home/joanne/Dropbox/Comp 447 Societal Issues.zip:2013-02-11

JDK on OSX 10.7 Lion

You can download the 10.7 Lion JDK from http://connect.apple.com.

  1. Sign in and click the java section on the right.

  2. The jdk is installed into a different location then previous. This will result in IDEs (such as Eclipse) being unable to locate source code and javadocs.

  3. At the time of writing the JDK ended up here:

    /Library/Java/JavaVirtualMachines/1.6.0_26-b03-383.jdk/Contents/Home

  4. Open up eclipse preferences and go to Java --> Installed JREs page

  5. Rather than use the "JVM Contents (MacOS X Default) we will need to use the JDK location

  6. At the time of writing Search is not aware of the new JDK location; we we will need to click on the Add button

  7. From the Add JRE wizard choose "MacOS X VM" for the JRE Type

  8. For the JRE Definition Page we need to fill in the following:

    • JRE Home: /Library/Java/JavaVirtualMachines/1.6.0_26-b03-383.jdk/Contents/Home
  9. The other fields will now auto fill, with the default JRE name being "Home". You can quickly correct this to something more meaningful:

    • JRE name: System JDK
  10. Finish the wizard and return to the Installed JREs page

  11. Choose "System JDK" from the list

  12. You can now develop normally with:

    • javadocs correctly shown for base classes
    • source code correctly shown when debugging

How to return multiple values?

You can only return one value, but it can be an object that has multiple fields - ie a "value object". Eg

public class MyResult {
    int returnCode;
    String errorMessage;
    // etc
}

public MyResult someMethod() {
    // impl here
}

unix - count of columns in file

awk -F'|' '{print NF; exit}' stores.dat 

Just quit right after the first line.

What is the difference between 'protected' and 'protected internal'?

I have read out very clear definitions for these terms.

Protected : Access is limited to within the class definition and any class that inherits from the class. The type or member can be accessed only by code in the same class or struct or in a class that is derived from that class.

Internal : Access is limited to exclusively to classes defined within the current project assembly. The type or member can be accessed only by code in same class.

Protected-Internal : Access is limited to current assembly or types derived from containing class.

Writing BMP image in pure c/c++ without other libraries

this is a example code copied from https://en.wikipedia.org/wiki/User:Evercat/Buddhabrot.c

void drawbmp (char * filename) {

unsigned int headers[13];
FILE * outfile;
int extrabytes;
int paddedsize;
int x; int y; int n;
int red, green, blue;

extrabytes = 4 - ((WIDTH * 3) % 4);                 // How many bytes of padding to add to each
                                                    // horizontal line - the size of which must
                                                    // be a multiple of 4 bytes.
if (extrabytes == 4)
   extrabytes = 0;

paddedsize = ((WIDTH * 3) + extrabytes) * HEIGHT;

// Headers...
// Note that the "BM" identifier in bytes 0 and 1 is NOT included in these "headers".
                     
headers[0]  = paddedsize + 54;      // bfSize (whole file size)
headers[1]  = 0;                    // bfReserved (both)
headers[2]  = 54;                   // bfOffbits
headers[3]  = 40;                   // biSize
headers[4]  = WIDTH;  // biWidth
headers[5]  = HEIGHT; // biHeight

// Would have biPlanes and biBitCount in position 6, but they're shorts.
// It's easier to write them out separately (see below) than pretend
// they're a single int, especially with endian issues...

headers[7]  = 0;                    // biCompression
headers[8]  = paddedsize;           // biSizeImage
headers[9]  = 0;                    // biXPelsPerMeter
headers[10] = 0;                    // biYPelsPerMeter
headers[11] = 0;                    // biClrUsed
headers[12] = 0;                    // biClrImportant

outfile = fopen(filename, "wb");

//
// Headers begin...
// When printing ints and shorts, we write out 1 character at a time to avoid endian issues.
//

fprintf(outfile, "BM");

for (n = 0; n <= 5; n++)
{
   fprintf(outfile, "%c", headers[n] & 0x000000FF);
   fprintf(outfile, "%c", (headers[n] & 0x0000FF00) >> 8);
   fprintf(outfile, "%c", (headers[n] & 0x00FF0000) >> 16);
   fprintf(outfile, "%c", (headers[n] & (unsigned int) 0xFF000000) >> 24);
}

// These next 4 characters are for the biPlanes and biBitCount fields.

fprintf(outfile, "%c", 1);
fprintf(outfile, "%c", 0);
fprintf(outfile, "%c", 24);
fprintf(outfile, "%c", 0);

for (n = 7; n <= 12; n++)
{
   fprintf(outfile, "%c", headers[n] & 0x000000FF);
   fprintf(outfile, "%c", (headers[n] & 0x0000FF00) >> 8);
   fprintf(outfile, "%c", (headers[n] & 0x00FF0000) >> 16);
   fprintf(outfile, "%c", (headers[n] & (unsigned int) 0xFF000000) >> 24);
}

//
// Headers done, now write the data...
//

for (y = HEIGHT - 1; y >= 0; y--)     // BMP image format is written from bottom to top...
{
   for (x = 0; x <= WIDTH - 1; x++)
   {

      red = reduce(redcount[x][y] + COLOUR_OFFSET) * red_multiplier;
      green = reduce(greencount[x][y] + COLOUR_OFFSET) * green_multiplier;
      blue = reduce(bluecount[x][y] + COLOUR_OFFSET) * blue_multiplier;
      
      if (red > 255) red = 255; if (red < 0) red = 0;
      if (green > 255) green = 255; if (green < 0) green = 0;
      if (blue > 255) blue = 255; if (blue < 0) blue = 0;
      
      // Also, it's written in (b,g,r) format...

      fprintf(outfile, "%c", blue);
      fprintf(outfile, "%c", green);
      fprintf(outfile, "%c", red);
   }
   if (extrabytes)      // See above - BMP lines must be of lengths divisible by 4.
   {
      for (n = 1; n <= extrabytes; n++)
      {
         fprintf(outfile, "%c", 0);
      }
   }
}

fclose(outfile);
return;
}


drawbmp(filename);

List comprehension vs map

I find list comprehensions are generally more expressive of what I'm trying to do than map - they both get it done, but the former saves the mental load of trying to understand what could be a complex lambda expression.

There's also an interview out there somewhere (I can't find it offhand) where Guido lists lambdas and the functional functions as the thing he most regrets about accepting into Python, so you could make the argument that they're un-Pythonic by virtue of that.

Working with SQL views in Entity Framework Core

EF Core supports the views, here is the details.

This feature was added in EF Core 2.1 under the name of query types. In EF Core 3.0 the concept was renamed to keyless entity types. The [Keyless] Data Annotation became available in EFCore 5.0.

It is working not that much different than normal entities; but has some special points. According documentation:

  • Cannot have a key defined.
  • Are never tracked for changes in the DbContext and therefore are never inserted, updated or deleted on the database.
  • Are never discovered by convention.
  • Only support a subset of navigation mapping capabilities, specifically:
  • They may never act as the principal end of a relationship.
  • They may not have navigations to owned entities
  • They can only contain reference navigation properties pointing to regular entities.
  • Entities cannot contain navigation properties to keyless entity types.
  • Need to be configured with a [Keyless] data annotation or a .HasNoKey() method call.
  • May be mapped to a defining query. A defining query is a query declared in the model that acts as a data source for a keyless entity type

It is working like below:

public class Blog
{
   public int BlogId { get; set; }
   public string Name { get; set; }
   public string Url { get; set; }
   public ICollection<Post> Posts { get; set; }
}

public class Post
{
   public int PostId { get; set; }
   public string Title { get; set; }
   public string Content { get; set; }
   public int BlogId { get; set; }
}

If you don't have an existing View at database you should create like below:

db.Database.ExecuteSqlRaw(
@"CREATE VIEW View_BlogPostCounts AS 
    SELECT b.Name, Count(p.PostId) as PostCount 
    FROM Blogs b
    JOIN Posts p on p.BlogId = b.BlogId
    GROUP BY b.Name");

And than you should have a class to hold the result from the database view:

  public class BlogPostsCount
  {
     public string BlogName { get; set; }
     public int PostCount { get; set; }
  }

And than configure the keyless entity type in OnModelCreating using the HasNoKey:

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
      modelBuilder
          .Entity<BlogPostsCount>(eb =>
          {
             eb.HasNoKey();
             eb.ToView("View_BlogPostCounts");
             eb.Property(v => v.BlogName).HasColumnName("Name");
          });
    }

And just configure the DbContext to include the DbSet:

public DbSet<BlogPostsCount> BlogPostCounts { get; set; }

Java 8 stream map to list of keys sorted by values

You can use this as an example of your problem

    Map<Integer, String> map = new HashMap<>();
    map.put(10, "apple");
    map.put(20, "orange");
    map.put(30, "banana");
    map.put(40, "watermelon");
    map.put(50, "dragonfruit");

    // split a map into 2 List
    List<Integer> resultSortedKey = new ArrayList<>();
    List<String> resultValues = map.entrySet().stream()
            //sort a Map by key and stored in resultSortedKey
            .sorted(Map.Entry.<Integer, String>comparingByKey().reversed())
            .peek(e -> resultSortedKey.add(e.getKey()))
            .map(x -> x.getValue())
            // filter banana and return it to resultValues
            .filter(x -> !"banana".equalsIgnoreCase(x))
            .collect(Collectors.toList());

    resultSortedKey.forEach(System.out::println);
    resultValues.forEach(System.out::println);

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

JSON Post with Customized HTTPHeader Field

I tried as you mentioned, but only first parameter is going through and rest all are appearing in the server as undefined. I am passing JSONWebToken as part of header.

.ajax({
    url: 'api/outletadd',
    type: 'post',
    data: { outletname:outletname , addressA:addressA , addressB:addressB, city:city , postcode:postcode , state:state , country:country , menuid:menuid },
    headers: {
        authorization: storedJWT
    },
    dataType: 'json',
    success: function (data){
        alert("Outlet Created");
    },
    error: function (data){
        alert("Outlet Creation Failed, please try again.");        
    }

    });

How to trigger jQuery change event in code

The parameterless form of the change() method triggers a change event. You can write something like:

$(document).ready(function() {
    $("#yourInitialElementID").change(function() {
        // Do something here...
        $(".yourDropDownClass").change();
    });
});

Return multiple values from a SQL Server function

Here's the Query Analyzer template for an in-line function - it returns 2 values by default:

-- =============================================  
-- Create inline function (IF)  
-- =============================================  
IF EXISTS (SELECT *   
   FROM   sysobjects   
   WHERE  name = N'<inline_function_name, sysname, test_function>')  
DROP FUNCTION <inline_function_name, sysname, test_function>  
GO  

CREATE FUNCTION <inline_function_name, sysname, test_function>   
(<@param1, sysname, @p1> <data_type_for_param1, , int>,   
 <@param2, sysname, @p2> <data_type_for_param2, , char>)  
RETURNS TABLE   
AS  
RETURN SELECT   @p1 AS c1,   
        @p2 AS c2  
GO  

-- =============================================  
-- Example to execute function  
-- =============================================  
SELECT *   
FROM <owner, , dbo>.<inline_function_name, sysname, test_function>   
    (<value_for_@param1, , 1>,   
     <value_for_@param2, , 'a'>)  
GO  

how to get value of selected item in autocomplete

To answer the question more generally, the answer is:

select: function( event , ui ) {
    alert( "You selected: " + ui.item.label );
}

Complete example :

_x000D_
_x000D_
$('#test').each(function(i, el) {_x000D_
    var that = $(el);_x000D_
    that.autocomplete({_x000D_
        source: ['apple','banana','orange'],_x000D_
        select: function( event , ui ) {_x000D_
            alert( "You selected: " + ui.item.label );_x000D_
        }_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />_x000D_
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>_x000D_
_x000D_
Type a fruit here: <input type="text" id="test" />
_x000D_
_x000D_
_x000D_

Is there a way to return a list of all the image file names from a folder using only Javascript?

IMHO, Edizkan Adil Ata's idea is actually the most proper way. It extracts the URLs of anchor tags and puts them in a different tag. And if you don't want to let the anchors being seen by the page visitor then just .hide() them all with JQuery or display: none; in CSS.

Also you can perform prefetching, like this:

<link rel="prefetch" href="imagefolder/clouds.jpg" />

That way you don't have to hide it and still can extract the path to the image.

Active Menu Highlight CSS

Maybe it is very very bad way and just for lazy person but I decided to say it.

I used PHP and bootstrap and fontawsome too

for simple I have 2 pages: 1.index and 2.create-user

put this code above your code

<?php
$name=basename($_SERVER["REQUEST_URI"]);
$name=str_replace(".php","",$name);
switch ($name) {
    case "create-user":
        $a = 2;
        break;
    case "index":
        $a = 1;
        break;
    default:
        $a=1;
}
?>

and in menu you add <?php if($a==1){echo "active";} ?> in class for menu1 and for menu2 you add <?php if($a==2){echo "active";} ?>

<ul id="menu" class="navbar-nav  flex-column text-right mt-3 p-1">
                        <li class="nav-item mb-2">
                            <a href="index.php" class="nav-link text-white customlihamid <?php if($a==1){echo "active";} ?>"><i
                                        class="fas fa-home fa-lg text-light ml-3"></i>dashbord</a>
                        </li>
                        <li class="nav-item mb-2">
                            <a href="#" href="javascript:" data-parent="#menu" data-toggle="collapse"
                               class="accordion-toggle nav-link text-white customlihamid <?php if($a==2){echo "active";} ?>" data-target="#tickets">
                                <i class="fas fa-user fa-lg text-light ml-3"></i>manage users
                                <span class="float-left"><i class="fas fa-angle-down"></i></span>
                            </a>

                            <ul class="collapse list-unstyled mt-2 mr-1 pr-2" id="tickets">
                                <li class="nav-item mb-2">
                                    <a href="create-user.php" class="nav-link text-white customlihamid"><i class="fas fa-user-plus fa-lg text-light ml-3"></i>add user</a>
                                </li>

                                <li class="nav-item mb-2">
                                    <a href="#" class="nav-link text-white customlihamid"><i class="fas fa-user-times fa-lg text-light ml-3"></i>delete user</a>
                                </li>

                            </ul>
                        </li>

                    </ul>

and add in css

.customlihamid {
    transition: all .4s;
}

.customlihamid:hover {
    background-color: #8a8a8a;
    border-radius: 5px;
    color: #00cc99;
}
.nav-item > .nav-link.active  {
    background-color: #00cc99;
    border-radius: 7px;
    box-shadow: 5px 7px 10px #111;
    transition: all .3s;
}
.nav-item > .nav-link.active:hover  {
    background-color: #8eccc1;
    border-radius: 7px;
    box-shadow: 5px 7px 20px #111;
    transform: translateY(-1px);
}

and in js add

$(document).ready(function () {
   $('.navbar-nav .nav-link').click(function(){
      $('.navbar-nav .nav-link').removeClass('active');
      $(this).addClass('active');
   })
});

first check your work without js code to understand js code for what

How to pass object from one component to another in Angular 2?

you could also store your data in an service with an setter and get it over a getter

import { Injectable } from '@angular/core';

@Injectable()
export class StorageService {

    public scope: Array<any> | boolean = false;

    constructor() {
    }

    public getScope(): Array<any> | boolean {
        return this.scope;
    }

    public setScope(scope: any): void {
        this.scope = scope;
    }
}

Why is Android Studio reporting "URI is not registered"?

I had this problem now - I created a new folder under the layout folder which would contain all the xml relate to my "home" page of my app and then another folder that would relate to my "settings" page as I wanted to organise my xml.

However, android only recognises the layout folder for xmls, not the layout/home or layout/settings folder so that is why it was giving me the error.

Thanks to Mazen Kasser answer, he assisted me in figuring this out.

"Could not find or load main class" Error while running java program using cmd prompt

For a lot of us, at least for me, I think the class path hierarchy is not intuitive since I'm working inside a directory structure and it feels like that ought to be it.

Java is looking at the name of the class based on it's package path, not just the file path.

It doesn't matter if: i'm in the local directory ./packagefoo/MainClass, or a directory up ./packagefoo/, or one down ./packagefoo/MainClass/foo.

The command "java packagefoo.MainClass" is running off the root %CLASSPATH% which means something significant to Java. Then from there it traverses package names, not path names like us lay coders would expect.

So if my CLASSPATH is set to %CWD%/, then "java packagefoo.MainClass" will work. If I set the CLASSPATH to %CWD%/packagefoo/ then packagefoo.MainClass can't be found. Always "java MainClass" means nothing, if it is a member of "package", until I rip out the java code "package packagefoo;" and move the Class File up a directory.

In fact if I change "package packagefoo;" to "package foopackage;" I have to create a subfolder under CLASSPATH/foopackage or foopackage.MainClass stops working again.

To make matters worse, Between PATH, CLASSPATH, JAVAHOME, for Windows, JDeveloper, Oracle Database, and every user name it was installed under, I think a coder trying to just get something up fast ends up brute forcing path variables and structure until something works without understanding what it means.

at least i did.

Android overlay a view ontop of everything?

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/root_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
    android:id = "@+id/Everything"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <!-- other actual layout stuff here EVERYTHING HERE -->

   </LinearLayout>

<LinearLayout
    android:id="@+id/overlay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="right" >
</LinearLayout>

Now any view you add under LinearLayout with android:id = "@+id/overlay" will appear as overlay with gravity = right on Linear Layout with android:id="@+id/Everything"

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

It is because the framework requires that two objects that are the same must have the same hashcode. If you override the equals method to do a special comparison of two objects and the two objects are considered the same by the method, then the hash code of the two objects must also be the same. (Dictionaries and Hashtables rely on this principle).

Retrieve last 100 lines logs

len=`cat filename | wc -l`
len=$(( $len + 1 ))
l=$(( $len - 99 ))
sed -n "${l},${len}p" filename

first line takes the length (Total lines) of file then +1 in the total lines after that we have to fatch 100 records so, -99 from total length then just put the variables in the sed command to fetch the last 100 lines from file

I hope this will help you.

Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource

Its a CORS issue, your api cannot be accessed directly from remote or different origin, In order to allow other ip address or other origins from accessing you api, you should add the 'Access-Control-Allow-Origin' on the api's header, you can set its value to '*' if you want it to be accessible to all, or you can set specific domain or ips like 'http://siteA.com' or 'http://192. ip address ';

Include this on your api's header, it may vary depending on how you are displaying json data,

if your using ajax, to retrieve and display data your header would look like this,

$.ajax({
   url: '',
   headers: {  'Access-Control-Allow-Origin': 'http://The web site allowed to access' },
   data: data,
   type: 'dataType',
   /* etc */
   success: function(jsondata){

   }
})

malloc for struct and pointer in C

First malloc allocates memory for struct, including memory for x (pointer to double). Second malloc allocates memory for double value wtich x points to.

LINQ: Distinct values

Are you trying to be distinct by more than one field? If so, just use an anonymous type and the Distinct operator and it should be okay:

var query = doc.Elements("whatever")
               .Select(element => new {
                             id = (int) element.Attribute("id"),
                             category = (int) element.Attribute("cat") })
               .Distinct();

If you're trying to get a distinct set of values of a "larger" type, but only looking at some subset of properties for the distinctness aspect, you probably want DistinctBy as implemented in MoreLINQ in DistinctBy.cs:

 public static IEnumerable<TSource> DistinctBy<TSource, TKey>(
     this IEnumerable<TSource> source,
     Func<TSource, TKey> keySelector,
     IEqualityComparer<TKey> comparer)
 {
     HashSet<TKey> knownKeys = new HashSet<TKey>(comparer);
     foreach (TSource element in source)
     {
         if (knownKeys.Add(keySelector(element)))
         {
             yield return element;
         }
     }
 }

(If you pass in null as the comparer, it will use the default comparer for the key type.)

What programming language does facebook use?

Facebook uses the LAMP stack, so if you want to get a career with them you're going to want to focus on that. In addition they often have C++ and/or Java listed in their requirements as well.

One of the postings includes the following requirements:

  • Expertise with C++ and/or Java
  • Knowledge of Perl or PHP or Python
  • Knowledge of relational databases and SQL, preferably MySQL and Oracle

Another:

  • Expertise in PHP, JavaScript, and CSS.

Another:

  • Knowledge of Perl or PHP or Python
  • Knowledge of relational databases and
  • SQL, preferably MySQL Knowledge of
  • web technologies: XHTML, JavaScript Experience with C, C++ a plus

Source

http://www.facebook.com/careers/#!/careers/department.php?dept=engineering

Also, do any other social networking sites use the same language?

Some other companys that use PHP/LAMP Stack:

Convert from lowercase to uppercase all values in all character variables in dataframe

From the dplyr package you can also use the mutate_all() function in combination with toupper(). This will affect both character and factor classes.

library(dplyr)
df <- mutate_all(df, funs=toupper)

How to split the screen with two equal LinearLayouts?

Just putting it out there:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#FF0000"
    android:weightSum="4"
    android:padding="5dp"> <!-- to show what the parent is -->
    <LinearLayout
        android:background="#0000FF"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="2" />
    <LinearLayout
        android:background="#00FF00"
        android:layout_height="0dp"
        android:layout_width="match_parent"
        android:layout_weight="1" />
</LinearLayout>

How to perform Unwind segue programmatically?

FYI: In order for @Vadim's answer to work with a manual unwind seque action called from within a View Controller you must place the command:

[self performSegueWithIdentifier:(NSString*) identifier sender:(id) sender];

inside of the overriden class method viewDidAppear like so:

-(void) viewDidAppear:(BOOL) animated
{
    [super viewDidAppear: animated];

    [self performSegueWithIdentifier:@"SomeSegueIdentifier" sender:self];
}

If you put it in other ViewController methods like viewDidLoad or viewWillAppear it will be ignored.

How to check object is nil or not in swift?

Normally, I just want to know if the object is nil or not.

So i use this function that just returns true when the object entered is valid and false when its not.

func isNotNil(someObject: Any?) -> Bool {
        if someObject is String {
            if (someObject as? String) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is Array<Any> {
            if (someObject as? Array<Any>) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is Dictionary<AnyHashable, Any> {
            if (someObject as? Dictionary<String, Any>) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is Data {
            if (someObject as? Data) != nil {
                return true
            }else {
                return false
            }
        }else if someObject is NSNumber {
            if (someObject as? NSNumber) != nil{
                return true
            }else {
                return false
            }
        }else if someObject is UIImage {
            if (someObject as? UIImage) != nil {
                return true
            }else {
                return false
            }
        }
        return false
 }

Accessing a local website from another computer inside the local network in IIS 7

Add two bindings to your website, one for local access and another for LAN access like so:

Open IIS and select your local website (that you want to access from your local network) from the left panel:

Connections > server (user-pc) > sites > local site

Open Bindings on the right panel under Actions tab add these bindings:

  1. Local:

    Type: http
    Ip Address: All Unassigned
    Port: 80
    Host name: samplesite.local
    
  2. LAN:

    Type: http
    Ip Address: <Network address of the hosting machine ex. 192.168.0.10>
    Port: 80
    Host name: <Leave it blank>
    

Voila, you should be able to access the website from any machine on your local network by using the host's LAN IP address (192.168.0.10 in the above example) as the site url.

NOTE:

if you want to access the website from LAN using a host name (like samplesite.local) instead of an ip address, add the host name to the hosts file on the local network machine (The hosts file can be found in "C:\Windows\System32\drivers\etc\hosts" in windows, or "/etc/hosts" in ubuntu):

192.168.0.10 samplesite.local

Print text instead of value from C enum

Enumerations in C are numbers that have convenient names inside your code. They are not strings, and the names assigned to them in the source code are not compiled into your program, and so they are not accessible at runtime.

The only way to get what you want is to write a function yourself that translates the enumeration value into a string. E.g. (assuming here that you move the declaration of enum Days outside of main):

const char* getDayName(enum Days day) 
{
   switch (day) 
   {
      case Sunday: return "Sunday";
      case Monday: return "Monday";
      /* etc... */
   }
}

/* Then, later in main: */
printf("%s", getDayName(TheDay));

Alternatively, you could use an array as a map, e.g.

const char* dayNames[] = {"Sunday", "Monday", "Tuesday", /* ... etc ... */ };

/* ... */

printf("%s", dayNames[TheDay]);

But here you would probably want to assign Sunday = 0 in the enumeration to be safe... I'm not sure if the C standard requires compilers to begin enumerations from 0, although most do (I'm sure someone will comment to confirm or deny this).

Wait one second in running program

.Net Core seems to be missing the DispatcherTimer.

If we are OK with using an async method, Task.Delay will meet our needs. This can also be useful if you want to wait inside of a for loop for rate-limiting reasons.

public async Task DoTasks(List<Items> items)
{
    foreach (var item in items)
    {
        await Task.Delay(2 * 1000);
        DoWork(item);
    }
}

You can await the completion of this method as follows:

public async void TaskCaller(List<Item> items)
{
    await DoTasks(items);
}

PHP Email sending BCC

You have $headers .= '...'; followed by $headers = '...';; the second line is overwriting the first.

Just put the $headers .= "Bcc: $emailList\r\n"; say after the Content-type line and it should be fine.

On a side note, the To is generally required; mail servers might mark your message as spam otherwise.

$headers  = "From: [email protected]\r\n" .
  "X-Mailer: php\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "Bcc: $emailList\r\n";

Java stack overflow error - how to increase the stack size in Eclipse?

Open the Run Configuration for your application (Run/Run Configurations..., then look for the applications entry in 'Java application').

The arguments tab has a text box Vm arguments, enter -Xss1m (or a bigger parameter for the maximum stack size). The default value is 512 kByte (SUN JDK 1.5 - don't know if it varies between vendors and versions).

Spool Command: Do not output SQL statement to file

My shell script calls the sql file and executes it. The spool output had the SQL query at the beginning followed by the query result.

This did not resolve my problem:

set echo off

This resolved my problem:

set verify off

Usage of the backtick character (`) in JavaScript

You can make a template of templates too, and reach private variable.

var a= {e:10, gy:'sfdsad'}; //global object

console.log(`e is ${a.e} and gy is ${a.gy}`); 
//e is 10 and gy is sfdsad

var b = "e is ${a.e} and gy is ${a.gy}" // template string
console.log( `${b}` );
//e is ${a.e} and gy is ${a.gy}

console.log( eval(`\`${b}\``) ); // convert template string to template
//e is 10 and gy is sfdsad

backtick( b );   // use fonction's variable
//e is 20 and gy is fghj

function backtick( temp ) {
  var a= {e:20, gy:'fghj'}; // local object
  console.log( eval(`\`${temp}\``) );
}

forcing web-site to show in landscape mode only

@Golmaal really answered this, I'm just being a bit more verbose.

<style type="text/css">
    #warning-message { display: none; }
    @media only screen and (orientation:portrait){
        #wrapper { display:none; }
        #warning-message { display:block; }
    }
    @media only screen and (orientation:landscape){
        #warning-message { display:none; }
    }
</style>

....

<div id="wrapper">
    <!-- your html for your website -->
</div>
<div id="warning-message">
    this website is only viewable in landscape mode
</div>

You have no control over the user moving the orientation however you can at least message them. This example will hide the wrapper if in portrait mode and show the warning message and then hide the warning message in landscape mode and show the portrait.

I don't think this answer is any better than @Golmaal , only a compliment to it. If you like this answer, make sure to give @Golmaal the credit.

Update

I've been working with Cordova a lot recently and it turns out you CAN control it when you have access to the native features.

Another Update

So after releasing Cordova it is really terrible in the end. It is better to use something like React Native if you want JavaScript. It is really amazing and I know it isn't pure web but the pure web experience on mobile kind of failed.

3D Plotting from X, Y, Z Data, Excel or other Tools

You can use r libraries for 3 D plotting.

Steps are:

First create a data frame using data.frame() command.

Create a 3D plot by using scatterplot3D library.

Or You can also rotate your chart using rgl library by plot3d() command.

Alternately you can use plot3d() command from rcmdr library.

In MATLAB, you can use surf(), mesh() or surfl() command as per your requirement.

[http://in.mathworks.com/help/matlab/examples/creating-3-d-plots.html]

Match line break with regular expression

By default . (any character) does not match newline characters.

This means you can simply match zero or more of any character then append the end tag.

Find: <li><a href="#">.* Replace: $0</a>

Tomcat is web server or application server?

It runs Java compiled code, it can maintain database connection pools, it can log errors of various types. I'd call it an application server, in fact I do. In our environment we have Apache as the webserver fronting a number of different application servers, including Tomcat and Coldfusion, and others.

How to dynamically add a style for text-align using jQuery

function add_question(){ var count=document.getElementById("nofquest").value; var container = document.getElementById("container"); // Clear previous contents of the container while (container.hasChildNodes()) { container.removeChild(container.lastChild); } for (i=1;i

how to set center of the textboxes

How do I draw a set of vertical lines in gnuplot?

alternatively you can also do this:

p '< echo "x y"' w impulse

x and y are the coordinates of the point to which you draw a vertical bar

python 3.x ImportError: No module named 'cStringIO'

From Python 3.0 changelog;

The StringIO and cStringIO modules are gone. Instead, import the io module and use io.StringIO or io.BytesIO for text and data respectively.

From the Python 3 email documentation it can be seen that io.StringIO should be used instead:

from io import StringIO
from email.generator import Generator
fp = StringIO()
g = Generator(fp, mangle_from_=True, maxheaderlen=60)
g.flatten(msg)
text = fp.getvalue()

Reference: https://docs.python.org/3/library/io.html

if else condition in blade file (laravel 5.3)

I think you are putting one too many curly brackets. Try this

 @if($user->status=='waiting')
            <td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{!! $user->travel_id !!}" data-toggle="modal" data-target="#myModal">Approve/Reject</a> </td>
            @else
            <td>{!! $user->status !!}</td>
        @endif

How to pick just one item from a generator?

I believe the only way is to get a list from the iterator then get the element you want from that list.

l = list(myfunct())
l[4]

What causes a java.lang.StackOverflowError

I was having the same issue

Role.java

 @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY,cascade = CascadeType.ALL)
 Set<BusinessUnitMaster> businessUnits =new HashSet<>();

BusinessUnitMaster.java

@ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(
        name = "BusinessUnitRoles",
        joinColumns = {@JoinColumn(name = "unit_id", referencedColumnName = "record_id")},
        inverseJoinColumns = {@JoinColumn(name = "role_id", referencedColumnName = "record_id")}
)
private Set<Role> roles=new HashSet<>();

the problem is that when you create BusinessUnitMaster and Role you have to save the object for both sides for RoleService.java

roleRepository.save(role);

for BusinessUnitMasterService.java

businessUnitMasterRepository.save(businessUnitMaster);

Maven home (M2_HOME) not being picked up by IntelliJ IDEA

Another option is to add the M2_HOME variable at: IntelliJ IDEA=>Preferences=>IDE Settings=>Path Variables

After a restart of IntelliJ, IntelliJ IDEA=>Preferences=>Project Settings=>Maven=>Maven home directory should be set to your M2_HOME variable.

Force hide address bar in Chrome on Android

window.scrollTo(0,1);

this will help you but this javascript is may not work in all browsers

Java - get pixel array from image

Something like this?

int[][] pixels = new int[w][h];

for( int i = 0; i < w; i++ )
    for( int j = 0; j < h; j++ )
        pixels[i][j] = img.getRGB( i, j );

How to use order by with union all in sql?

SELECT  * 
FROM 
        (
            SELECT * FROM TABLE_A 
            UNION ALL 
            SELECT * FROM TABLE_B
        ) dum
-- ORDER BY .....

but if you want to have all records from Table_A on the top of the result list, the you can add user define value which you can use for ordering,

SELECT  * 
FROM 
        (
            SELECT *, 1 sortby FROM TABLE_A 
            UNION ALL 
            SELECT *, 2 sortby FROM TABLE_B
        ) dum
ORDER   BY sortby 

"No Content-Security-Policy meta tag found." error in my phonegap application

For me it was enough to reinstall whitelist plugin:

cordova plugin remove cordova-plugin-whitelist

and then

cordova plugin add cordova-plugin-whitelist

It looks like updating from previous versions of Cordova was not succesful.

cursor.fetchall() vs list(cursor) in Python

list(cursor) works because a cursor is an iterable; you can also use cursor in a loop:

for row in cursor:
    # ...

A good database adapter implementation will fetch rows in batches from the server, saving on the memory footprint required as it will not need to hold the full result set in memory. cursor.fetchall() has to return the full list instead.

There is little point in using list(cursor) over cursor.fetchall(); the end effect is then indeed the same, but you wasted an opportunity to stream results instead.

C# : Converting Base Class to Child Class

As long as the object is actually a SkyfilterClient, then a cast should work. Here is a contrived example to prove this:

using System;

class Program
{
    static void Main()
    {
        NetworkClient net = new SkyfilterClient();
        var sky = (SkyfilterClient)net;
    }
}

public class NetworkClient{}
public class SkyfilterClient : NetworkClient{}

However, if it is actually a NetworkClient, then you cannot magically make it become the subclass. Here is an example of that:

using System;

class Program
{
    static void Main()
    {
        NetworkClient net = new NetworkClient();
        var sky = (SkyfilterClient)net;
    }
}

public class NetworkClient{}
public class SkyfilterClient : NetworkClient{}

HOWEVER, you could create a converter class. Here is an example of that, also:

using System;

class Program
{
    static void Main()
    {
        NetworkClient net = new NetworkClient();
        var sky = SkyFilterClient.CopyToSkyfilterClient(net);
    }
}

public class NetworkClient
{  
  public int SomeVal {get;set;}
}

public class SkyfilterClient : NetworkClient
{
    public int NewSomeVal {get;set;}
    public static SkyfilterClient CopyToSkyfilterClient(NetworkClient networkClient)
    {
        return new SkyfilterClient{NewSomeVal = networkClient.SomeVal};
    }
}

But, keep in mind that there is a reason you cannot convert this way. You may be missing key information that the subclass needs.

Finally, if you just want to see if the attempted cast will work, then you can use is:

if(client is SkyfilterClient)
    cast

Meaning of end='' in the statement print("\t",end='')?

The default value of end is \n meaning that after the print statement it will print a new line. So simply stated end is what you want to be printed after the print statement has been executed

Eg: - print ("hello",end=" +") will print hello +

Convert array to JSON

One other way could be this:

        var json_arr = {};
        json_arr["name1"] = "value1";
        json_arr["name2"] = "value2";
        json_arr["name3"] = "value3";

        var json_string = JSON.stringify(json_arr);

PHP file_get_contents() and setting request headers

Here is what worked for me (Dominic was just one line short).

$url = "";

$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n" .  // check function.stream-context-create on php.net
              "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad 
  )
);

$context = stream_context_create($options);
$file = file_get_contents($url, false, $context);

The Use of Multiple JFrames: Good or Bad Practice?

It is not a good practice but even though you wish to use it you can use the singleton pattern as its good. I have used the singleton patterns in most of my project its good.

Calling a JSON API with Node.js

I'm using get-json very simple to use:

$ npm install get-json --save

Import get-json

var getJSON = require('get-json')

To do a GET request you would do something like:

getJSON('http://api.listenparadise.org', function(error, response){
    console.log(response);
})

How to update (append to) an href in jquery?

jQuery 1.4 has a new feature for doing this, and it rules. I've forgotten what it's called, but you use it like this:

$("a.directions-link").attr("href", function(i, href) {
  return href + '?q=testing';
});

That loops over all the elements too, so no need for $.each

How can I one hot encode in Python?

You can use numpy.eye function.

import numpy as np

def one_hot_encode(x, n_classes):
    """
    One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
    : x: List of sample Labels
    : return: Numpy array of one-hot encoded labels
     """
    return np.eye(n_classes)[x]

def main():
    list = [0,1,2,3,4,3,2,1,0]
    n_classes = 5
    one_hot_list = one_hot_encode(list, n_classes)
    print(one_hot_list)

if __name__ == "__main__":
    main()

Result

D:\Desktop>python test.py
[[ 1.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 0.  0.  0.  1.  0.]
 [ 0.  0.  0.  0.  1.]
 [ 0.  0.  0.  1.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 1.  0.  0.  0.  0.]]

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

They both work the same way, but $_POST should be used as it is cleaner. You can add isset() to it to check it exists.

Close dialog on click (anywhere)

This post may help:

http://www.jensbits.com/2010/06/16/jquery-modal-dialog-close-on-overlay-click/

See also How to close a jQuery UI modal dialog by clicking outside the area covered by the box? for explanation of when and how to apply overlay click or live event depending on how you are using dialog on page.

What is a smart pointer and when should I use one?

A smart pointer is like a regular (typed) pointer, like "char*", except when the pointer itself goes out of scope then what it points to is deleted as well. You can use it like you would a regular pointer, by using "->", but not if you need an actual pointer to the data. For that, you can use "&*ptr".

It is useful for:

  • Objects that must be allocated with new, but that you'd like to have the same lifetime as something on that stack. If the object is assigned to a smart pointer, then they will be deleted when the program exits that function/block.

  • Data members of classes, so that when the object is deleted all the owned data is deleted as well, without any special code in the destructor (you will need to be sure the destructor is virtual, which is almost always a good thing to do).

You may not want to use a smart pointer when:

  • ... the pointer shouldn't actually own the data... i.e., when you are just using the data, but you want it to survive the function where you are referencing it.
  • ... the smart pointer isn't itself going to be destroyed at some point. You don't want it to sit in memory that never gets destroyed (such as in an object that is dynamically allocated but won't be explicitly deleted).
  • ... two smart pointers might point to the same data. (There are, however, even smarter pointers that will handle that... that is called reference counting.)

See also:

Remove specific characters from a string in Javascript

Regexp solution:

ref = ref.replace(/^F0/, "");

plain solution:

if (ref.substr(0, 2) == "F0")
     ref = ref.substr(2);

is there any alternative for ng-disabled in angular2?

To set the disabled property to true or false use

<button [disabled]="!nextLibAvailable" (click)="showNext('library')" class=" btn btn-info btn-xs" title="Next Lib"> {{libraries.name}}">
    <i class="fa fa-chevron-right fa-fw"></i>
</button>

versionCode vs versionName in Android Manifest

Version Code - It's a positive integer that's used for comparison with other version codes. It's not shown to the user, it's just for record-keeping in a way. You can set it to any integer you like but it's suggested that you linearly increment it for successive versions.

Version Name - This is the version string seen by the user. It isn't used for internal comparisons or anything, it's just for users to see.

For example: Say you release an app, its initial versionCode could be 1 and versionName could also be 1. Once you make some small changes to the app and want to publish an update, you would set versionName to "1.1" (since the changes aren't major) while logically your versionCode should be 2 (regardless of size of changes).

Say in another condition you release a completely revamped version of your app, you could set versionCode and versionName to "2".

Hope that helps.

You can read more about it here

Properties private set;

The two common approaches are either that the class should have a constructor for the DAL to use, or the DAL should use reflection to hydrate objects.

Get the Last Inserted Id Using Laravel Eloquent

After

$data->save()

$data->id will give you the inserted id,

Note: If your autoincrement column name is sno then you should use $data->sno and not $data->id

String escape into XML

Using a third-party library (Newtonsoft.Json) as alternative:

public static string XmlEscape(string unescaped)
{
    if (unescaped == null) return null;
    return JsonConvert.SerializeObject(unescaped); ;
}

public static string XmlUnescape(string escaped)
{
    if (escaped == null) return null;
    return JsonConvert.DeserializeObject(escaped, typeof(string)).ToString();
}

Examples of escaped string:

a<b ==> "a&lt;b"

<foo></foo> ==> "foo&gt;&lt;/foo&gt;"

NOTE: In newer versions, the code written above may not work with escaping, so you need to specify how the strings will be escaped:

public static string XmlEscape(string unescaped)
{
    if (unescaped == null) return null;
    return JsonConvert.SerializeObject(unescaped, new JsonSerializerSettings()
    {
        StringEscapeHandling = StringEscapeHandling.EscapeHtml
    });
}

Examples of escaped string:

a<b ==> "a\u003cb"

<foo></foo> ==> "\u003cfoo\u003e\u003c/foo\u003e"

Which passwordchar shows a black dot (•) in a winforms textbox?

One more solution to use this Unicode black circle >>

Start >> All Programs >> Accessories >> System Tools >> Character Map

Then select Arial font and choose the Black circle copy it and paste it into PasswordChar property of the textbox.

That's it....

Add and remove a class on click using jQuery?

Try this in your Head section of the site:

$(function() {
    $('.menu_box_list li').click(function() {
        $('.menu_box_list li.active').removeClass('active');
        $(this).addClass('active');
    });
});

Calling virtual functions inside constructors

Do you know the crash error from Windows explorer?! "Pure virtual function call ..."
Same problem ...

class AbstractClass 
{
public:
    AbstractClass( ){
        //if you call pureVitualFunction I will crash...
    }
    virtual void pureVitualFunction() = 0;
};

Because there is no implemetation for the function pureVitualFunction() and the function is called in the constructor the program will crash.

Resizing an image in an HTML5 canvas

Try pica - that's a highly optimized resizer with selectable algorythms. See demo.

For example, original image from first post is resized in 120ms with Lanczos filter and 3px window or 60ms with Box filter and 0.5px window. For huge 17mb image 5000x3000px resize takes ~1s on desktop and 3s on mobile.

All resize principles were described very well in this thread, and pica does not add rocket science. But it's optimized very well for modern JIT-s, and is ready to use out of box (via npm or bower). Also, it use webworkers when available to avoid interface freezes.

I also plan to add unsharp mask support soon, because it's very useful after downscale.

How to stop a vb script running in windows

Running scripts can be terminated from the Task Manager.

However, scripts that perpetually focus program windows using .AppActivate may make it very difficult to get to the task manager -i.e you and the script will be fighting for control. Hence i recommend writing a script (which i call self destruct for obvious reasons) and make a keyboard shortcut key to activate the script.

Self destruct script:

Option Explicit
Dim WshShell
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "taskkill /f /im Cscript.exe", , True 
WshShell.Run "taskkill /f /im wscript.exe", , True  

Keyboard shortcut: rightclick on the script icon, select create shortcut, rightclick on script shortcut icon, select properties, click in shortcutkey and make your own.

type your shortcut key and all scripts end. Cheers

Make a link in the Android browser start up my app?

This method doesn't call the disambiguation dialog asking you to open either your app or a browser.

If you register the following in your Manifest

<manifest package="com.myApp" .. >
  <application ...>
    <activity ...>
      <intent-filter>
        <action android:name="android.intent.action.VIEW" />
        <category android:name="android.intent.category.DEFAULT" />
        <category android:name="android.intent.category.BROWSABLE" />
        <data
          android:host="gallery"
          android:scheme="myApp" />
      </intent-filter>
    </activity>
    ..

and click this url from an email on your phone for example

<a href="intent://gallery?directLink=true#Intent;scheme=myApp;package=com.myApp;end"> 
  Click me 
</a>

then android will try to find an app with the package com.myApp that responds to your gallery intent and has a myApp scheme. In case it can't, it will take you to the store, looking for com.myApp, which should be your app.

Delete ActionLink with confirm dialog

Try this :

<button> @Html.ActionLink(" ", "DeletePhoto", "PhotoAndVideo", new { id = item.Id }, new { @class = "modal-link1", @OnClick = "return confirm('Are you sure you to delete this Record?');" })</button>

How to auto adjust the <div> height according to content in it?

Just write "min-height: XXX;" And "overflow: hidden;" & you will be out of this problem Like this

min-height: 100px;
overflow: hidden;

Remove large .pack file created by git

The issue is that, even though you removed the files, they are still present in previous revisions. That's the whole point of git, is that even if you delete something, you can still get it back by accessing the history.

What you are looking to do is called rewriting history, and it involved the git filter-branch command.

GitHub has a good explanation of the issue on their site. https://help.github.com/articles/remove-sensitive-data

To answer your question more directly, what you basically need to run is this command with unwanted_filename_or_folder replaced accordingly:

git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch unwanted_filename_or_folder' --prune-empty

This will remove all references to the files from the active history of the repo.

Next step, to perform a GC cycle to force all references to the file to be expired and purged from the packfile. Nothing needs to be replaced in these commands.

git for-each-ref --format='delete %(refname)' refs/original | git update-ref --stdin
# or, for older git versions (e.g. 1.8.3.1) which don't support --stdin
# git update-ref $(git for-each-ref --format='delete %(refname)' refs/original)
git reflog expire --expire=now --all
git gc --aggressive --prune=now

Best cross-browser method to capture CTRL+S with JQuery?

I would like Web applications to not override my default shortcut keys, honestly. Ctrl+S already does something in browsers. Having that change abruptly depending on the site I'm viewing is disruptive and frustrating, not to mention often buggy. I've had sites hijack Ctrl+Tab because it looked the same as Ctrl+I, both ruining my work on the site and preventing me from switching tabs as usual.

If you want shortcut keys, use the accesskey attribute. Please don't break existing browser functionality.

Why does the Google Play store say my Android app is incompatible with my own device?

I ran into this as well - I did all of my development on a Lenovo IdeaTab A2107A-F and could run development builds on it, and even release signed APKs (installed with adb install) with no issues. Once it was published in Alpha test mode and available on Google Play I received the "incompatible with your device" error message.

It turns out I had placed in my AndroidManifest.xml the following from a tutorial:

<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA" />

Well, the Lenovo IdeaTab A2107A-F doesn't have an autofocusing camera on it (which I learned from http://www.phonearena.com/phones/Lenovo-IdeaTab-A2107_id7611, under Cons: lacks autofocus camera). Regardless of whether I was using that feature, Google Play said no. Once that was removed I rebuilt my APK, uploaded it to Google Play, and sure enough my IdeaTab was now in the compatible devices list.

So, double-check every <uses-feature> and if you've been doing some copy-paste from the web check again. Odds are you requested some feature you aren't even using.

How to match a line not containing a word

This should work:

/^((?!PART).)*$/

If you only wanted to exclude it from the beginning of the line (I know you don't, but just FYI), you could use this:

/^(?!PART)/

Edit (by request): Why this pattern works

The (?!...) syntax is a negative lookahead, which I've always found tough to explain. Basically, it means "whatever follows this point must not match the regular expression /PART/." The site I've linked explains this far better than I can, but I'll try to break this down:

^         #Start matching from the beginning of the string.    
(?!PART)  #This position must not be followed by the string "PART".
.         #Matches any character except line breaks (it will include those in single-line mode).
$         #Match all the way until the end of the string.

The ((?!xxx).)* idiom is probably hardest to understand. As we saw, (?!PART) looks at the string ahead and says that whatever comes next can't match the subpattern /PART/. So what we're doing with ((?!xxx).)* is going through the string letter by letter and applying the rule to all of them. Each character can be anything, but if you take that character and the next few characters after it, you'd better not get the word PART.

The ^ and $ anchors are there to demand that the rule be applied to the entire string, from beginning to end. Without those anchors, any piece of the string that didn't begin with PART would be a match. Even PART itself would have matches in it, because (for example) the letter A isn't followed by the exact string PART.

Since we do have ^ and $, if PART were anywhere in the string, one of the characters would match (?=PART). and the overall match would fail. Hope that's clear enough to be helpful.

Is there a way to cast float as a decimal without rounding and preserving its precision?

Have you tried:

SELECT Cast( 2.555 as decimal(53,8))

This would return 2.55500000. Is that what you want?

UPDATE:

Apparently you can also use SQL_VARIANT_PROPERTY to find the precision and scale of a value. Example:

SELECT SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Precision'),
SQL_VARIANT_PROPERTY(Cast( 2.555 as decimal(8,7)),'Scale')

returns 8|7

You may be able to use this in your conversion process...

How to add custom method to Spring Data JPA

There is another issue to be considered here. Some people expect that adding custom method to your repository will automatically expose them as REST services under '/search' link. This is unfortunately not the case. Spring doesn't support that currently.

This is 'by design' feature, spring data rest explicitly checks if method is a custom method and doesn't expose it as a REST search link:

private boolean isQueryMethodCandidate(Method method) {    
  return isQueryAnnotationPresentOn(method) || !isCustomMethod(method) && !isBaseClassMethod(method);
}

This is a qoute of Oliver Gierke:

This is by design. Custom repository methods are no query methods as they can effectively implement any behavior. Thus, it's currently impossible for us to decide about the HTTP method to expose the method under. POST would be the safest option but that's not in line with the generic query methods (which receive GET).

For more details see this issue: https://jira.spring.io/browse/DATAREST-206

Format decimal for percentage values?

Use the P format string. This will vary by culture:

String.Format("Value: {0:P2}.", 0.8526) // formats as 85.26 % (varies by culture)

How to configure Eclipse build path to use Maven dependencies?

Typically, you can copy the .classpath file from a working project since there isn’t anything project specific here assuming you’re structured as a standard Maven project.

Including all the jars in a directory within the Java classpath

Using Java 6 or later, the classpath option supports wildcards. Note the following:

  • Use straight quotes (")
  • Use *, not *.jar

Windows

java -cp "Test.jar;lib/*" my.package.MainClass

Unix

java -cp "Test.jar:lib/*" my.package.MainClass

This is similar to Windows, but uses : instead of ;. If you cannot use wildcards, bash allows the following syntax (where lib is the directory containing all the Java archive files):

java -cp "$(printf %s: lib/*.jar)"

(Note that using a classpath is incompatible with the -jar option. See also: Execute jar file with multiple classpath libraries from command prompt)

Understanding Wildcards

From the Classpath document:

Class path entries can contain the basename wildcard character *, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry foo/* specifies all JAR files in the directory named foo. A classpath entry consisting simply of * expands to a list of all the jar files in the current directory.

A class path entry that contains * will not match class files. To match both classes and JAR files in a single directory foo, use either foo;foo/* or foo/*;foo. The order chosen determines whether the classes and resources in foo are loaded before JAR files in foo, or vice versa.

Subdirectories are not searched recursively. For example, foo/* looks for JAR files only in foo, not in foo/bar, foo/baz, etc.

The order in which the JAR files in a directory are enumerated in the expanded class path is not specified and may vary from platform to platform and even from moment to moment on the same machine. A well-constructed application should not depend upon any particular order. If a specific order is required then the JAR files can be enumerated explicitly in the class path.

Expansion of wildcards is done early, prior to the invocation of a program's main method, rather than late, during the class-loading process itself. Each element of the input class path containing a wildcard is replaced by the (possibly empty) sequence of elements generated by enumerating the JAR files in the named directory. For example, if the directory foo contains a.jar, b.jar, and c.jar, then the class path foo/* is expanded into foo/a.jar;foo/b.jar;foo/c.jar, and that string would be the value of the system property java.class.path.

The CLASSPATH environment variable is not treated any differently from the -classpath (or -cp) command-line option. That is, wildcards are honored in all these cases. However, class path wildcards are not honored in the Class-Path jar-manifest header.

Note: due to a known bug in java 8, the windows examples must use a backslash preceding entries with a trailing asterisk: https://bugs.openjdk.java.net/browse/JDK-8131329

Is it possible to specify a different ssh port when using rsync?

use the "rsh option" . e.g.:

rsync -avz --rsh='ssh -p3382' root@remote_server_name:/opt/backups

refer to: http://www.linuxquestions.org/questions/linux-software-2/rsync-ssh-on-different-port-448112/

How do I add Git version control (Bitbucket) to an existing source code folder?

The commands are given in your Bitbucket account. When you open the repository in Bitbucket, it gives you the entire list of commands you need to execute in the order. What is missing is where exactly you need to execute those commands (Git CLI, SourceTree terminal).

I struggled with these commands as I was writing these in Git CLI, but we need to execute the commands in the SourceTree terminal window and the repository will be added to Bitbucket.

Download file through an ajax call php

AJAX isn't for downloading files. Pop up a new window with the download link as its address, or do document.location = ....

Django Rest Framework File Upload

models.py

from django.db import models

import uuid

class File(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    file = models.FileField(blank=False, null=False)
    
    def __str__(self):
        return self.file.name

serializers.py

from rest_framework import serializers
from .models import File

class FileSerializer(serializers.ModelSerializer):
    class Meta:
        model = File
        fields = "__all__"

views.py

from django.shortcuts import render
from rest_framework.parsers import FileUploadParser
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status

from .serializers import FileSerializer


class FileUploadView(APIView):
    permission_classes = []
    parser_class = (FileUploadParser,)

    def post(self, request, *args, **kwargs):

      file_serializer = FileSerializer(data=request.data)

      if file_serializer.is_valid():
          file_serializer.save()
          return Response(file_serializer.data, status=status.HTTP_201_CREATED)
      else:
          return Response(file_serializer.errors, status=status.HTTP_400_BAD_REQUEST)

urls.py

from apps.files import views as FileViews

urlpatterns = [
    path('api/files', FileViews.FileUploadView.as_view()),
]

settings.py

# file uload parameters
MEDIA_URL =  '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')

Send a post request to api/files with a your file attached to a form-data field file. The file will be uploaded to /media folder and a db record will be added with id and file name.

Tablix: Repeat header rows on each page not working - Report Builder 3.0

It depends on the tablix structure you are using. In a table, for example, you do not have column groups, so Reporting Services does not recognize which textboxes are the column headers and setting RepeatColumnHeaders property to True doesn't work.

Instead, you need to:

  1. Open Advanced Mode in the Groupings pane. (Click the arrow to the right of the Column Groups and select Advanced Mode.)
    • Screenshot
  2. In the Row Groups area (not Column Groups), click on a Static group, which highlights the corresponding textbox in the tablix. Click through each Static group until it highlights the leftmost column header. This is generally the first Static group listed.
  3. In the Properties window, set the RepeatOnNewPage property to True.
    • Screenshot
  4. Make sure that the KeepWithGroup property is set to After.

The KeepWithGroup property specifies which group to which the static member needs to stick. If set to After then the static member sticks with the group after it, or below it, acting as a group header. If set to Before, then the static member sticks with the group before, or above it, acting as a group footer. If set to None, Reporting Services decides where to put the static member.

Now when you view the report, the column headers repeat on each page of the tablix.

This video shows how to set it exactly as the answer described.

rails 3.1.0 ActionView::Template::Error (application.css isn't precompiled)

OK - I had the same problem. I didn't want to use "config.assets.compile = true" - I had to add all of my .css files to the list in config/environments/production.rb:

config.assets.precompile += %w( carts.css )

Then I had to create (and later delete) tmp/restart.txt

I consistently used the stylesheet_link_tag helper, so I found all the extra css files I needed to add with:

find . \( -type f -o -type l \) -exec grep stylesheet_link_tag {} /dev/null \;

Expected corresponding JSX closing tag for input Reactjs

All tags must have enclosing tags. In my case, the hr and input elements weren't closed properly.

Parent Error was: JSX element 'div' has no corresponding closing tag, due to code below:

<hr class="my-4">
<input
  type="password"
  id="inputPassword"
  class="form-control"
  placeholder="Password"
  required
 >

Fix:

<hr class="my-4"/>
<input
 type="password"
 id="inputPassword"
 class="form-control"
 placeholder="Password"
 required
/>

The parent elements will show errors due to child element errors. Therefore, start investigating from most inner elements up to the parent ones.

How to return a part of an array in Ruby?

You can use slice() for this:

>> foo = [1,2,3,4,5,6]
=> [1, 2, 3, 4, 5, 6]
>> bar = [10,20,30,40,50,60]
=> [10, 20, 30, 40, 50, 60]
>> half = foo.length / 2
=> 3
>> foobar = foo.slice(0, half) + bar.slice(half, foo.length)
=> [1, 2, 3, 40, 50, 60]

By the way, to the best of my knowledge, Python "lists" are just efficiently implemented dynamically growing arrays. Insertion at the beginning is in O(n), insertion at the end is amortized O(1), random access is O(1).

How do I add 1 day to an NSDate?

Since iOS 8 you can use NSCalendar.dateByAddingUnit

Example in Swift 1.x:

let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
    .dateByAddingUnit(
         .CalendarUnitDay, 
         value: 1, 
         toDate: today, 
         options: NSCalendarOptions(0)
    )

Swift 2.0:

let today = NSDate()
let tomorrow = NSCalendar.currentCalendar()
    .dateByAddingUnit(
        .Day, 
        value: 1, 
        toDate: today, 
        options: []
    )

Swift 3.0:

let today = Date()
let tomorrow = Calendar.current.date(byAdding: .day, value: 1, to: today)

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

JavaScript - Getting HTML form values

My 5 cents here, using form.elements which allows you to query each field by it's name, not only by iteration:

const form = document.querySelector('form[name="valform"]');
const ccValidation = form.elements['cctextbox'].value;
const ccType = form.elements['cardtype'].value;

How to linebreak an svg text within javascript?

I have adapted a bit the solution by @steco, switching the dependency from d3 to jquery and adding the height of the text element as parameter

function wrap(text, width, height) {
  text.each(function(idx,elem) {
    var text = $(elem);
    text.attr("dy",height);
        var words = text.text().split(/\s+/).reverse(),
        word,
        line = [],
        lineNumber = 0,
        lineHeight = 1.1, // ems
        y = text.attr("y"),
        dy = parseFloat( text.attr("dy") ),
        tspan = text.text(null).append("tspan").attr("x", 0).attr("y", y).attr("dy", dy + "em");
    while (word = words.pop()) {
      line.push(word);
      tspan.text(line.join(" "));
      if (elem.getComputedTextLength() > width) {
        line.pop();
        tspan.text(line.join(" "));
        line = [word];
        tspan = text.append("tspan").attr("x", 0).attr("y", y).attr("dy", ++lineNumber * lineHeight + dy + "em").text(word);
      }
    }
  });
}

How to disable CSS in Browser for testing purposes

All the suggested answers merely eliminate the css for that page load. Depending on your use-case, you may wish to not load the css at all:

Chrome Dev Tools > Network Tab > Right click on stylesheet in question > block request url

How to get the IP address of the docker host from inside a docker container

The only way is passing the host information as environment when you create a container

run --env <key>=<value>

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

There is an option in the Virtual Box itself. If you look in the Oracle VM Virtual Box Manager. Select the Virtual Box you want to start. Go to System, the second from above item in the right pane. In System go to the third tab called acceleration. In that tab the first check box is called something like: 'VT-x/AMD-V' (I have the Dutch version, so I don't know the exact string) UNCHECK And then start. That worked for me.

I also got this problem after an upgrade. And I did not have the problem before. But I fail to see the exact connection between the update and the check/unchecking of that option.

By the way, I have no idea where the hell that 'virtualization tab' should be in my 'BIOS'. Maybe I was looking in my PC's BIOS not the System page here which is the BIOS of the VM Machine maybe and that is what you meant Veer7? If it was, it was pretty unclear you meant this. Maybe it's because I have OVM in Dutch not English. But there was nothing called BIOS in the Oracle VM Virtual Box Manager I could find.

How can I build multiple submit buttons django form?

Eg:

if 'newsletter_sub' in request.POST:
    # do subscribe
elif 'newsletter_unsub' in request.POST:
    # do unsubscribe

How would I create a UIAlertView in Swift?

With the protocol extensions of Swift 2, you can make a protocol that provides a default implementation to your view controllers:

ShowsAlert.swift

import UIKit

protocol ShowsAlert {}

extension ShowsAlert where Self: UIViewController {
    func showAlert(title: String = "Error", message: String) {
        let alertController = UIAlertController(title: title, message: message, preferredStyle: .Alert)
        alertController.addAction(UIAlertAction(title: "Ok", style: .Default, handler: nil))
        presentViewController(alertController, animated: true, completion: nil)
    }
}

ViewController.swift

class ViewController: UIViewController, ShowsAlert {
    override func viewDidLoad() {
        super.viewDidLoad()
        showAlert(message: "Hey there, I am an error message!")
    }
}

How can I add a table of contents to a Jupyter / JupyterLab notebook?

Here is my approach, clunky as it is and available in github:

Put in the very first notebook cell, the import cell:

from IPythonTOC import IPythonTOC

toc = IPythonTOC()

Somewhere after the import cell, put in the genTOCEntry cell but don't run it yet:

''' if you called toc.genTOCMarkdownCell before running this cell, 
the title has been set in the class '''

print toc.genTOCEntry()

Below the genTOCEntry cell`, make a TOC cell as a markdown cell:

<a id='TOC'></a>

#TOC

As the notebook is developed, put this genTOCMarkdownCell before starting a new section:

with open('TOCMarkdownCell.txt', 'w') as outfile:

    outfile.write(toc.genTOCMarkdownCell('Introduction'))

!cat TOCMarkdownCell.txt

!rm TOCMarkdownCell.txt

Move the genTOCMarkdownCell down to the point in your notebook where you want to start a new section and make the argument to genTOCMarkdownCell the string title for your new section then run it. Add a markdown cell right after it and copy the output from genTOCMarkdownCell into the markdown cell that starts your new section. Then go to the genTOCEntry cell near the top of your notebook and run it. For example, if you make the argument to genTOCMarkdownCell as shown above and run it, you get this output to paste into the first markdown cell of your newly indexed section:

<a id='Introduction'></a>

###Introduction

Then when you go to the top of your notebook and run genTocEntry, you get the output:

[Introduction](#Introduction)

Copy this link string and paste it into the TOC markdown cell as follows:

<a id='TOC'></a>

#TOC

[Introduction](#Introduction)

After you edit the TOC cell to insert the link string and then you press shift-enter, the link to your new section will appear in your notebook Table of Contents as a web link and clicking it will position the browser to your new section.

One thing I often forget is that clicking a line in the TOC makes the browser jump to that cell but doesn't select it. Whatever cell was active when we clicked on the TOC link is still active, so a down or up arrow or shift-enter refers to still active cell, not the cell we got by clicking on the TOC link.

How do I remove all .pyc files from a project?

find . -name '*.pyc' -delete

Surely the simplest.

Write to rails console

puts or p is a good start to do that.

p "asd"       # => "asd"
puts "asd"    # => asd

here is more information about that: http://www.ruby-doc.org/core-1.9.3/ARGF.html

How can I call a function using a function pointer?

You can declare the function pointer as follows:

bool (funptr*)();

Which says we are declaring a function pointer to a function which does not take anything and return a bool.

Next assignment:

funptr = A;

To call the function using the function pointer:

funptr();

Android List View Drag and Drop sort

I recently stumbled upon this great Gist that gives a working implementation of a drag sort ListView, with no external dependencies needed.


Basically it consists on creating your custom Adapter extending ArrayAdapter as an inner class to the activity containing your ListView. On this adapter one then sets an onTouchListener to your List Items that will signal the start of the drag.

In that Gist they set the listener to a specific part of the layout of the List Item (the "handle" of the item), so one does not accidentally move it by pressing any part of it. Personally, I preferred to go with an onLongClickListener instead, but that is up to you to decide. Here an excerpt of that part:

public class MyArrayAdapter extends ArrayAdapter<String> {

    private ArrayList<String> mStrings = new ArrayList<String>();
    private LayoutInflater mInflater;
    private int mLayout;

    //constructor, clear, remove, add, insert...

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

        View view = convertView;
        //inflate, etc...

        final String string = mStrings.get(position);
        holder.title.setText(string);

        // Here the listener is set specifically to the handle of the layout
        holder.handle.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                if (motionEvent.getAction() == MotionEvent.ACTION_DOWN) {
                    startDrag(string);
                    return true;
                }
                return false;
            }
        });

        // change color on dragging item and other things...         

        return view;
    }
}

This also involves adding an onTouchListener to the ListView, which checks if an item is being dragged, handles the swapping and invalidation, and stops the drag state. An excerpt of that part:

mListView.setOnTouchListener(new View.OnTouchListener() {
     @Override
     public boolean onTouch(View view, MotionEvent event) {
        if (!mSortable) { return false; }
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN: {
                break;
            }
            case MotionEvent.ACTION_MOVE: {
                // get positions
                int position = mListView.pointToPosition((int) event.getX(), 
                    (int) event.getY());
                if (position < 0) {
                    break;
                }
                // check if it's time to swap
                if (position != mPosition) {
                    mPosition = position;
                    mAdapter.remove(mDragString);
                    mAdapter.insert(mDragString, mPosition);
                }
                return true;
            }
            case MotionEvent.ACTION_UP:
            case MotionEvent.ACTION_CANCEL:
            case MotionEvent.ACTION_OUTSIDE: {
                //stop drag state
                stopDrag();
                return true;
            }
        }
        return false;
    }
});

Finally, here is how the stopDrag and startDrag methods look like, which handle the enabling and disabling of the drag process:

public void startDrag(String string) {
    mPosition = -1;
    mSortable = true;
    mDragString = string;
    mAdapter.notifyDataSetChanged();
}

public void stopDrag() {
    mPosition = -1;
    mSortable = false;
    mDragString = null;
    mAdapter.notifyDataSetChanged();
}

Java Switch Statement - Is "or"/"and" possible?

The above are all excellent answers. I just wanted to add that when there are multiple characters to check against, an if-else might turn out better since you could instead write the following.

// switch on vowels, digits, punctuation, or consonants
char c; // assign some character to 'c'
if ("aeiouAEIOU".indexOf(c) != -1) {
  // handle vowel case
} else if ("!@#$%,.".indexOf(c) != -1) {
  // handle punctuation case
} else if ("0123456789".indexOf(c) != -1) {
  // handle digit case
} else {
  // handle consonant case, assuming other characters are not possible
}

Of course, if this gets any more complicated, I'd recommend a regex matcher.

How to create a date object from string in javascript

There are multiple methods of creating date as discussed above. I would not repeat same stuff. Here is small method to convert String to Date in Java Script if that is what you are looking for,

function compareDate(str1){
// str1 format should be dd/mm/yyyy. Separator can be anything e.g. / or -. It wont effect
var dt1   = parseInt(str1.substring(0,2));
var mon1  = parseInt(str1.substring(3,5));
var yr1   = parseInt(str1.substring(6,10));
var date1 = new Date(yr1, mon1-1, dt1);
return date1;
}

No notification sound when sending notification from firebase in android

Try this

{
    "to" : "DEVICE-TOKEN",

    "notification" : {
      "body"  : "NOTIFICATION BODY",
      "title" : "NOTIFICATION TITILE",
      "sound" : "default"
    }
  }

@note for custom notification sound:-> "sound" : "MyCustomeSound.wav"

Correct way to integrate jQuery plugins in AngularJS

Yes, you are correct. If you are using a jQuery plugin, do not put the code in the controller. Instead create a directive and put the code that you would normally have inside the link function of the directive.

There are a couple of points in the documentation that you could take a look at. You can find them here:
Common Pitfalls

Using controllers correctly

Ensure that when you are referencing the script in your view, you refer it last - after the angularjs library, controllers, services and filters are referenced.

EDIT: Rather than using $(element), you can make use of angular.element(element) when using AngularJS with jQuery

in iPhone App How to detect the screen resolution of the device

Use it in App Delegate: I am using storyboard

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{

if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {

    CGSize iOSDeviceScreenSize = [[UIScreen mainScreen] bounds].size;

    //----------------HERE WE SETUP FOR IPHONE 4/4s/iPod----------------------

    if(iOSDeviceScreenSize.height == 480){          

        UIStoryboard *iPhone35Storyboard = [UIStoryboard storyboardWithName:@"iPhone" bundle:nil];

        // Instantiate the initial view controller object from the storyboard
        UIViewController *initialViewController = [iPhone35Storyboard instantiateInitialViewController];

        // Instantiate a UIWindow object and initialize it with the screen size of the iOS device
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

        // Set the initial view controller to be the root view controller of the window object
        self.window.rootViewController  = initialViewController;

        // Set the window object to be the key window and show it
        [self.window makeKeyAndVisible];

        iphone=@"4";

        NSLog(@"iPhone 4: %f", iOSDeviceScreenSize.height);

    }

    //----------------HERE WE SETUP FOR IPHONE 5----------------------

    if(iOSDeviceScreenSize.height == 568){

        // Instantiate a new storyboard object using the storyboard file named Storyboard_iPhone4
        UIStoryboard *iPhone4Storyboard = [UIStoryboard storyboardWithName:@"iPhone5" bundle:nil];

        // Instantiate the initial view controller object from the storyboard
        UIViewController *initialViewController = [iPhone4Storyboard instantiateInitialViewController];

        // Instantiate a UIWindow object and initialize it with the screen size of the iOS device
        self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

        // Set the initial view controller to be the root view controller of the window object
        self.window.rootViewController  = initialViewController;

        // Set the window object to be the key window and show it
        [self.window makeKeyAndVisible];

         NSLog(@"iPhone 5: %f", iOSDeviceScreenSize.height);
        iphone=@"5";
    }

} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
    // NSLog(@"wqweqe");
    storyboard = [UIStoryboard storyboardWithName:@"iPad" bundle:nil];

}

 return YES;
 }

What is the equivalent of Java static methods in Kotlin?

Top-level / companion object for static properties

Top-level

When the properties are somewhat related to a class, define them as top-level properties just before the class declaration:

const val MAX_ATTEMPTS = 3
private const val DEFAULT_NAME = "Guest"
private const val MIN_AGE = 16

data class User(val id: String, val name: String = DEFAULT_NAME)

This is similar to the static properties in Java.

When the properties are completely independent of any class, you can define them as top-level in a separate file without the class.

companion object

When the properties are closely related to a class and will be used only in that class, define them inside a companion object:

data class User(val id: String, val name: String = DEFAULT_NAME) {
    companion object {
        const val DEFAULT_NAME = "Guest"
        const val MIN_AGE = 16
    }
}

Top-level / companion object for static methods

Top-level

Similar to the properties above, when the functions are somewhat related to a class, define them just above the class:

fun getAllUsers() { }

fun getProfileFor(userId: String) { }

data class User(val id: String, val name: String)

Usage:

val userList = getAllUsers()

companion object

When the functions are closely related to a class, define them inside a companion object:

data class User(val id: String, val name: String) {

    companion object {

        fun getAll() { }

        fun profileFor(userId: String) { }
    }
}

Usage:

val userProfile = User.profileFor("34")

This is similar to the static methods in Java.

The top-level functions are often more idiomatic to Kotlin. A better reason to define functions inside the companion object is when you are extending a companion object with an interface. An example of this is shown in the singleton section.


Nested class for static class

When the classes with related functionalities belong together, they can be grouped together by nesting:

class User(val id: String, val name: String) {
    class UserAccess : UserDao {
        override fun add(user: User) { }
        override fun remove(id: String) { }
    }
}

This is equivalent to the static nested classes in Java. The UserAccess class here implements an interface UserDao.

Usage:

fun main() {
    val john = User("34", "John")
    val userAccess = User.UserAccess()
    userAccess.add(john)
}

Singleton object for static INSTANCE

Top-level

When you just want a single object of a class, you no longer need to create a static INSTANCE inside a class like in Java. Simply use a top-level object declaration:

object UserAccess : UserDao {
    override fun add(user: User) { }
    override fun remove(id: String) { }
}

Notice also how easy it is to extend an interface or a class in a singleton.

The code above, under the hood, produces the following static INSTANCE singleton pattern in Java (simplified):

public final class UserAccess implements UserDao {
   public static final UserAccess INSTANCE;

   public void add(User user) { }

   public void remove(String id) { }

   private UserAccess() { }

   static { INSTANCE = new UserAccess();}
}

companion object

When the singleton is closely related to a class use companion object:

data class User(val id: String, val name: String) {
    companion object : UserDao {
        override fun add(user: User) { }
        override fun remove(id: String) { }
    }
}

This way you get more elegant naming: User.add(john). Also, you make the intent clear that this singleton is only used as a utility for the User class. You can also use the object without the companion keyword inside the class, if you want multiple singletons or groups of functions/properties.


companion object for static factory

Factory functions in Koltin are created using the companion object. Factory functions are useful when you want to provide multiple ways to create an object where the object construction process is complex or when multiple constructors are not expressive enough.

For example, the newInstance() factory function in the following snippet creates a user by generating the id automatically:

class User private constructor(val id: Long, val name: String) {
    companion object {
        private var currentId = 0L;
        fun newInstance(name: String) = User(currentId++, name)
    }
}

This is equivalent to the static factory methods in Java.

The constructor is kept private but the companion object has access to the constructor.

In the code above, consistency of the next id generation is guaranteed because a companion object is a singleton, only one object will keep track of the id, there won't be any duplicate ids.

Also notice that companion objects can have properties (currentId in this case) to represent state.

Usage:

val john = User.newInstance("John")

@JvmStatic for Java interoperability

The static concept of Java doesn't exist in Kotlin. A companion object is an instance of a real class called Companion. So, when you call the Kotlin code from Java, an object of the Companion class is first instantiated behind the scenes. You need to call the function using the Companion object in Java:

Profile userProfile = User.Companion.profileFor("34");

For the idiomatic Java naming and less verbosity, use @JvmStatic annotation on that function or property:

companion object {
    @JvmStatic
    fun profileFor(userId: String): Profile { }
}

The @JvmStatic annotation creates a separate pure static copy of the getProfileFor() function. Now you can use it from Java with regular syntax:

Profile userProfile = User.profileFor("34");

That's it! Hope the examples are useful for your projects.

How to convert an iterator to a stream?

Use Collections.list(iterator).stream()...

Converting string into datetime

If you want only date format then you can manually convert it by passing your individual fields like:

>>> import datetime
>>> date = datetime.date(int('2017'),int('12'),int('21'))
>>> date
datetime.date(2017, 12, 21)
>>> type(date)
<type 'datetime.date'>

You can pass your split string values to convert it into date type like:

selected_month_rec = '2017-09-01'
date_formate = datetime.date(int(selected_month_rec.split('-')[0]),int(selected_month_rec.split('-')[1]),int(selected_month_rec.split('-')[2]))

You will get the resulting value in date format.

HRESULT: 0x800A03EC on Worksheet.range

Looking at the various responses above, and drawing on my own recent experience (I got this error code doing something completely unrelated -- setting Application.Calculation) I conclude that the same error code is used to indicate multiple unrelated problems. So @Garreh you should probably be asking a new question (not that anyone will be able to help based on the error code alone). I've seen the same thing working with Word interop from C#, where the same HRESULT seems to be used for almost every kind of error. I've never found any satisfactory Microsoft documentation on what the codes might mean.