Programs & Examples On #Mozy

Mozy is an online backup service. It was created by Berkeley Data Systems, a company founded in 2005 and purchased by EMC in late 2007. Mozy currently offers home user, SOHO, and enterprise backup services.

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

Ternary operation in CoffeeScript

You may also write it in two statements if it mostly is true use:

a = 5
a = 10 if false

Or use a switch statement if you need more possibilities:

a = switch x
  when true then 5
  when false then 10

With a boolean it may be oversized but i find it very readable.

How to Select Min and Max date values in Linq Query

This should work for you

//Retrieve Minimum Date
var MinDate = (from d in dataRows select d.Date).Min();

//Retrieve Maximum Date
var MaxDate = (from d in dataRows select d.Date).Max(); 

(From here)

Pass object to javascript function

when you pass an object within curly braces as an argument to a function with one parameter , you're assigning this object to a variable which is the parameter in this case

Get all parameters from JSP page

HTML or Jsp Page         
<input type="text" name="1UserName">
<input type="text" name="2Password">
<Input type="text" name="3MobileNo">
<input type="text" name="4country">
and so on...
in java Code 

 SortedSet ss = new TreeSet();
 Enumeration<String> enm=request.getParameterNames();
while(enm.hasMoreElements())
{
    String pname = enm.nextElement();
    ss.add(pname);
}
Iterator i=ss.iterator();
while(i.hasNext())
{
    String param=(String)i.next();
    String value=request.getParameter(param);
}

`React/RCTBridgeModule.h` file not found

Latest releases of react-native libraries as explained in previous posts and here have breaking compatibility changes. If you do not plan to upgrade to react-native 0.40+ yet you can force install previous version of the library, for example with react-native-fs:

npm install --save -E [email protected]

How to move mouse cursor using C#?

First Add a Class called Win32.cs

public class Win32
{ 
    [DllImport("User32.Dll")]
    public static extern long SetCursorPos(int x, int y);

    [DllImport("User32.Dll")]
    public static extern bool ClientToScreen(IntPtr hWnd, ref POINT point);

    [StructLayout(LayoutKind.Sequential)]
    public struct POINT
    {
        public int x;
        public int y;

        public POINT(int X, int Y)
        {
            x = X;
            y = Y;
        }
    }
}

You can use it then like this:

Win32.POINT p = new Win32.POINT(xPos, yPos);

Win32.ClientToScreen(this.Handle, ref p);
Win32.SetCursorPos(p.x, p.y);

The character encoding of the HTML document was not declared

Add this as a first line in the HEAD section of your HTML template

<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<meta content="utf-8" http-equiv="encoding">

IE8 crashes when loading website - res://ieframe.dll/acr_error.htm

Check the header to make sure that the doctype is going to work with Internet Explorer without it having to 'guess' how to render it.

You can also force the render engine in IE 8/9 to use the earlier IE7 renderer. This also has the benefit of removing the 'compatibility view' icon in the address bar area.

Try putting this in your .htaccess:

Header set X-UA-Compatible IE=EmulateIE7  

Or, if you can write the headers:

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7">

@mawtex you will want to do this just for IE8 as your site works fine in 7 and 9, just not 8.

More details:

http://msdn.microsoft.com/en-us/library/cc288325(VS.85).aspx

How to create an empty matrix in R?

I'd be cautious as dismissing something as a bad idea because it is slow. If it is a part of the code that does not take much time to execute then the slowness is irrelevant. I just used the following code:

for (ic in 1:(dim(centroid)[2]))
{
cluster[[ic]]=matrix(,nrow=2,ncol=0)
}
# code to identify cluster=pindex[ip] to which to add the point
if(pdist[ip]>-1)
{
cluster[[pindex[ip]]]=cbind(cluster[[pindex[ip]]],points[,ip])
}

for a problem that ran in less than 1 second.

Open text file and program shortcut in a Windows batch file

I use

@echo off
Start notepad "filename.txt"
exit

to open the file.

Another example is

@echo off
start chrome "filename.html"
pause

Incorrect syntax near ''

I got this error because I pasted alias columns into a DECLARE statement.

DECLARE @userdata TABLE(
f.TABLE_CATALOG nvarchar(100),
f.TABLE_NAME nvarchar(100),
f.COLUMN_NAME nvarchar(100),
p.COLUMN_NAME nvarchar(100)
)
SELECT * FROM @userdata 

ERROR: Msg 102, Level 15, State 1, Line 2 Incorrect syntax near '.'.

DECLARE @userdata TABLE(
f_TABLE_CATALOG nvarchar(100),
f_TABLE_NAME nvarchar(100),
f_COLUMN_NAME nvarchar(100),
p_COLUMN_NAME nvarchar(100)
)
SELECT * FROM @userdata

NO ERROR

Generate a unique id

We can do something like this

string TransactionID = "BTRF"+DateTime.Now.Ticks.ToString().Substring(0, 10);

How to pass a value from one Activity to another in Android?

Sample Kotlin code as below:-

Page 1

val i = Intent(this, Page2::class.java)
            val getrec = list[position].promotion_id
            val bundle = Bundle()
            bundle.putString("stuff", getrec)
            i.putExtras(bundle)
            startActivity(i)

Page 2

        var bundle = getIntent().getExtras()
        var stuff = bundle.getString("stuff")

Saving changes after table edit in SQL Server Management Studio

Go into Tools -> Options -> Designers-> Uncheck "Prevent saving changes that require table re-creation". Voila.

That happens because sometimes it is necessary to drop and recreate a table in order to change something. This can take a while, since all data must be copied to a temp table and then re-inserted in the new table. Since SQL Server by default doesn't trust you, you need to say "OK, I know what I'm doing, now let me do my work."

Testing Spring's @RequestBody using Spring MockMVC

the following works for me,

  mockMvc.perform(
            MockMvcRequestBuilders.post("/api/test/url")
                    .contentType(MediaType.APPLICATION_JSON)
                    .content(asJsonString(createItemForm)))
            .andExpect(status().isCreated());

  public static String asJsonString(final Object obj) {
    try {
        return new ObjectMapper().writeValueAsString(obj);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

Delete duplicate records from a SQL table without a primary key

delete sub from (select ROW_NUMBER() OVer(Partition by empid order by empid)cnt from employee)sub where sub.cnt>1

Spring Data JPA find by embedded object property

The above - findByBookIdRegion() did not work for me. The following works with the latest release of String Data JPA:

Page<QueuedBook> findByBookId_Region(Region region, Pageable pageable);

How to create nonexistent subdirectories recursively using Bash?

While existing answers definitely solve the purpose, if your'e looking to replicate nested directory structure under two different subdirectories, then you can do this

mkdir -p {main,test}/{resources,scala/com/company}

It will create following directory structure under the directory from where it is invoked

+-- main
¦   +-- resources
¦   +-- scala
¦       +-- com
¦           +-- company
+-- test
    +-- resources
    +-- scala
        +-- com
            +-- company

The example was taken from this link for creating SBT directory structure

How to get Domain name from URL using jquery..?

You can use a trick, by creating a <a>-element, then setting the string to the href of that <a>-element and then you have a Location object you can get the hostname from.

You could either add a method to the String prototype:

String.prototype.toLocation = function() {
    var a = document.createElement('a');
    a.href = this;
    return a;
};

and use it like this:
"http://www.abc.com/search".toLocation().hostname

or make it a function:

function toLocation(url) {
    var a = document.createElement('a');
    a.href = url;
    return a;
};

and use it like this:
toLocation("http://www.abc.com/search").hostname

both of these will output: "www.abc.com"

If you also need the protocol, you can do something like this:

var url = "http://www.abc.com/search".toLocation();
url.protocol + "//" + url.hostname

which will output: "http://www.abc.com"

How to add button tint programmatically

You could use

button.setBackgroundTintList(ColorStateList.valueOf(resources.getColor(R.id.blue_100)));

But I would recommend you to use a support library drawable tinting which just got released yesterday:

Drawable drawable = ...;

// Wrap the drawable so that future tinting calls work
// on pre-v21 devices. Always use the returned drawable.
drawable = DrawableCompat.wrap(drawable);

// We can now set a tint
DrawableCompat.setTint(drawable, Color.RED);
// ...or a tint list
DrawableCompat.setTintList(drawable, myColorStateList);
// ...and a different tint mode
DrawableCompat.setTintMode(drawable, PorterDuff.Mode.SRC_OVER);

You can find more in this blog post (see section "Drawable tinting")

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

Set FormBorderStyle to 'FixedDialog'

FixedDialog

How to copy to clipboard in Vim?

Maybe someone will find it useful. I wanted to stay independent from X clipboard, and still be able to copy and paste some text between two running vims. This little code save the selected text in temp.txt file for copying. Put the code below into your .vimrc. Use CTRL-c CTRL-v to do the job.

vnoremap :w !cp /dev/null ~/temp.txt && cat > ~/temp.txt

noremap :r !cat ~/temp.txt

Import data.sql MySQL Docker Container

you can copy the export file for e.g dump.sql using docker cp into the container and then import the db. if you need full instructions, let me know and I will provide

List<String> to ArrayList<String> conversion issue

Arrays.asList does not return instance of java.util.ArrayListbut it returns instance of java.util.Arrays.ArrayList.

You will need to convert to ArrayList if you want to access ArrayList specific information

allWords.addAll(Arrays.asList(strTemp.toLowerCase().split("\\s+")));

Catch KeyError in Python

If you don't want to handle error just NoneType and use get() e.g.:

manager.connect.get("")

How to create a css rule for all elements except one class?

Wouldn't setting a css rule for all tables, and then a subsequent one for tables where class="dojoxGrid" work? Or am I missing something?

CGRectMake, CGPointMake, CGSizeMake, CGRectZero, CGPointZero is unavailable in Swift

You can use this with replacement of CGRectZero

CGRect.zero

Difference between a user and a schema in Oracle?

From Ask Tom

You should consider a schema to be the user account and collection of all objects therein as a schema for all intents and purposes.

SCOTT is a schema that includes the EMP, DEPT and BONUS tables with various grants, and other stuff.

SYS is a schema that includes tons of tables, views, grants, etc etc etc.

SYSTEM is a schema.....

Technically -- A schema is the set of metadata (data dictionary) used by the database, typically generated using DDL. A schema defines attributes of the database, such as tables, columns, and properties. A database schema is a description of the data in a database.

Curl error: Operation timed out

I got same problem lot of time. Check your request url, if you are requesting on local server like 127.1.1/api or 192.168...., try to change it, make sure you are hitting cloud.

Simplest way to detect a mobile device in PHP

You only need to include user_agent.php file which can be found from Mobile device detection in PHP page and use the following code.

<?php
//include file
include_once 'user_agent.php';

//create an instance of UserAgent class
$ua = new UserAgent();

//if site is accessed from mobile, then redirect to the mobile site.
if($ua->is_mobile()){
   header("Location:http://m.codexworld.com");
   exit;
}
?>

What is a practical use for a closure in JavaScript?

I like Mozilla's function factory example.

function makeAdder(x) {

    return function(y) {
        return x + y;
    };
}

var addFive = makeAdder(5);

console.assert(addFive(2) === 7);
console.assert(addFive(-5) === 0);

heroku - how to see all the logs

Logging has greatly improved in heroku!

$ heroku logs -n 500

Better!

$ heroku logs --tail

references: http://devcenter.heroku.com/articles/logging

UPDATED

These are no longer add-ons, but part of the default functionality :)

How to Set AllowOverride all

If you are using Linux you may edit the code in the directory of

/etc/httpd/conf/httpd.conf

now, here find the code line kinda like

# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
    AllowOverride None
#
# Controls who can get stuff from this server.
#
    Order allow,deny
    Allow from all

</Directory>

Change the AllowOveride None to AllowOveride All

Now now you can set any kind of rule in your .httacess file inside your directories if any other operating system just try to find the file of httpd.conf and edit it.

Remove carriage return from string

Since you're using VB.NET, you'll need the following code:

Dim newString As String = origString.Replace(vbCr, "").Replace(vbLf, "")

You could use escape characters (\r and \n) in C#, but these won't work in VB.NET. You have to use the equivalent constants (vbCr and vbLf) instead.

How can you export the Visual Studio Code extension list?

If you would like to transfer all the extensions from code to code-insiders or vice versa, here is what worked for me from Git Bash.

code --list-extensions | xargs -L 1 code-insiders --install-extension

This will install all the missing extensions and skip the installed ones. After that, you will need to close and reopen Visual Studio Code.

Similarly, you can transfer extensions from code-insiders to code with the following:

code-insiders --list-extensions | xargs -L 1 code --install-extension

How to break out of jQuery each Loop

According to the documentation return false; should do the job.

We can break the $.each() loop [..] by making the callback function return false.

Return false in the callback:

function callback(indexInArray, valueOfElement) {
  var booleanKeepGoing;

  this; // == valueOfElement (casted to Object)

  return booleanKeepGoing; // optional, unless false 
                           // and want to stop looping
}

BTW, continue works like this:

Returning non-false is the same as a continue statement in a for loop; it will skip immediately to the next iteration.

How can I copy a file from a remote server to using Putty in Windows?

One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.

Using SHA1 and RSA with java.security.Signature vs. MessageDigest and Cipher

A slightly more efficient version of the bytes2String method is

private static final char[] hex = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static String byteArray2Hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder(bytes.length * 2);
    for (final byte b : bytes) {
        sb.append(hex[(b & 0xF0) >> 4]);
        sb.append(hex[b & 0x0F]);
    }
    return sb.toString();
}

How to get the connection String from a database

If you created Connection Manager in your project then you can simply pull the connection string from there.

String connection = this.dts.connections["<connection_manager_name>"];

And use this connection in:

using (var conn = new SqlConnection(connection))

Please correct me if I am wrong.

how to convert string to numerical values in mongodb

Collation is what you need:

db.collectionName.find().sort({PartnerID: 1}).collation({locale: "en_US", numericOrdering: true})

How to remove a TFS Workspace Mapping?

I managed to remove the mapping using the /newowner command as suggested here:

How can I regain access to my Team Foundation Server Workspace?

The command opened an Edit Workspace windows where I removed the mapping. Afterwards I deleted the workspace I didn't need.

SQL Server replace, remove all after certain character

UPDATE MyTable
   SET MyText = SUBSTRING(MyText, 1, CHARINDEX(';', MyText) - 1)
 WHERE CHARINDEX(';', MyText) > 0 

Debugging with Android Studio stuck at "Waiting For Debugger" forever

I faced this problem in android studio 3.0. Just restarted device solved.

take(1) vs first()

Operators first() and take(1) aren't the same.

The first() operator takes an optional predicate function and emits an error notification when no value matched when the source completed.

For example this will emit an error:

import { EMPTY, range } from 'rxjs';
import { first, take } from 'rxjs/operators';

EMPTY.pipe(
  first(),
).subscribe(console.log, err => console.log('Error', err));

... as well as this:

range(1, 5).pipe(
  first(val => val > 6),
).subscribe(console.log, err => console.log('Error', err));

While this will match the first value emitted:

range(1, 5).pipe(
  first(),
).subscribe(console.log, err => console.log('Error', err));

On the other hand take(1) just takes the first value and completes. No further logic is involved.

range(1, 5).pipe(
  take(1),
).subscribe(console.log, err => console.log('Error', err));

Then with empty source Observable it won't emit any error:

EMPTY.pipe(
  take(1),
).subscribe(console.log, err => console.log('Error', err));

Jan 2019: Updated for RxJS 6

Android textview outline text

I have created a library based on Nouman Hanif's answer with some additions. For example, fixing a bug that caused an indirect infinite loop on View.invalidate() calls.

OTOH, the library also supports outlined text in EditText widgets, as it was my real goal and it needed a bit more work than TextView.

Here is the link to my library: https://github.com/biomorgoth/android-outline-textview

Thanks to Nouman Hanif for the initial idea on the solution!

How to display an image from a path in asp.net MVC 4 and Razor view?

 @foreach (var m in Model)
    {
      <img src="~/Images/@m.Url" style="overflow: hidden; position: relative; width:200px; height:200px;" />
    }

How to get next/previous record in MySQL?

In addition to cemkalyoncu's solution:

next record:

SELECT * FROM foo WHERE id > 4 ORDER BY id LIMIT 1;

previous record:

SELECT * FROM foo WHERE id < 4 ORDER BY id DESC LIMIT 1;

edit: Since this answer has been getting a few upvotes lately, I really want to stress the comment I made earlier about understanding that a primary key colum is not meant as a column to sort by, because MySQL does not guarantee that higher, auto incremented, values are necessarily added at a later time.

If you don't care about this, and simply need the record with a higher (or lower) id then this will suffice. Just don't use this as a means to determine whether a record is actually added later (or earlier). In stead, consider using a datetime column to sort by, for instance.

Get size of folder or file

java.io.File file = new java.io.File("myfile.txt");
file.length();

This returns the length of the file in bytes or 0 if the file does not exist. There is no built-in way to get the size of a folder, you are going to have to walk the directory tree recursively (using the listFiles() method of a file object that represents a directory) and accumulate the directory size for yourself:

public static long folderSize(File directory) {
    long length = 0;
    for (File file : directory.listFiles()) {
        if (file.isFile())
            length += file.length();
        else
            length += folderSize(file);
    }
    return length;
}

WARNING: This method is not sufficiently robust for production use. directory.listFiles() may return null and cause a NullPointerException. Also, it doesn't consider symlinks and possibly has other failure modes. Use this method.

CSS transition between left -> right and top -> bottom positions

For elements with dynamic width it's possible to use transform: translateX(-100%); to counter the horizontal percentage value. This leads to two possible solutions:

1. Option: moving the element in the entire viewport:

Transition from:

transform: translateX(0);

to

transform: translateX(calc(100vw - 100%));

_x000D_
_x000D_
#viewportPendulum {_x000D_
  position: fixed;_x000D_
  left: 0;_x000D_
  top: 0;_x000D_
  animation: 2s ease-in-out infinite alternate swingViewport;_x000D_
  /* just for styling purposes */_x000D_
  background: #c70039;_x000D_
  padding: 1rem;_x000D_
  color: #fff;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingViewport {_x000D_
  from {_x000D_
    transform: translateX(0);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateX(calc(100vw - 100%));_x000D_
  }_x000D_
}
_x000D_
<div id="viewportPendulum">Viewport</div>
_x000D_
_x000D_
_x000D_

2. Option: moving the element in the parent container:

Transition from:

transform: translateX(0);
left: 0;

to

left: 100%;
transform: translateX(-100%);

_x000D_
_x000D_
#parentPendulum {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  animation: 2s ease-in-out infinite alternate swingParent;_x000D_
  /* just for styling purposes */_x000D_
  background: #c70039;_x000D_
  padding: 1rem;_x000D_
  color: #fff;_x000D_
  font-family: sans-serif;_x000D_
}_x000D_
_x000D_
@keyframes swingParent {_x000D_
  from {_x000D_
    transform: translateX(0);_x000D_
    left: 0;_x000D_
  }_x000D_
  to {_x000D_
    left: 100%;_x000D_
    transform: translateX(-100%);_x000D_
  }_x000D_
}_x000D_
_x000D_
.wrapper {_x000D_
  padding: 2rem 0;_x000D_
  margin: 2rem 15%;_x000D_
  background: #eee;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div id="parentPendulum">Parent</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Demo on Codepen

Note: This approach can easily be extended to work for vertical positioning. Visit example here.

How to display a range input slider vertically

_x000D_
_x000D_
window.onload = function(){
var slider = document.getElementById("sss");
 var  result = document.getElementById("final");
slider.oninput = function(){
    result.innerHTML = slider.value ;
}
}
_x000D_
.slider{
    width: 100vw;
    height: 100vh;
   
    display: flex;
    justify-content: center;
    align-items: center;
}

.slider .container-slider{
    width: 600px;
    display: flex;
    justify-content: center;
    align-items: center;
    transform: rotate(90deg)
}

.slider .container-slider input[type="range"]{
    width: 60%;
    -webkit-appearance: none;
    background-color: blue;
    height: 7px;
    border-radius: 5px;;
    outline: none;
    margin: 0 20px
    
}

.slider .container-slider input[type="range"]::-webkit-slider-thumb{
    -webkit-appearance: none;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    background-color: red;
}



.slider .container-slider input[type="range"]::-webkit-slider-thumb:hover{

box-shadow: 0px 0px 10px rgba(255,255,255,.3),
            0px 0px 15px rgba(255,255,255,.4),
            0px 0px 20px rgba(255,255,255,.5),
            0px 0px 25px rgba(255,255,255,.6),
            0px 0px 30px rgba(255,255,255,.7)

}


.slider .container-slider .val {
    width: 60px;
    height: 40px;
    background-color: #ACB6E5;
    display: flex;
    justify-content: center;
    align-items: center;
    font-family: consolas;
    font-weight: 700;
    font-size: 20px;
    letter-spacing: 1.3px;
    transform: rotate(-90deg)
}

.slider .container-slider .val::before{
    content: "";
    position: absolute;
    width: 0;
    height: 0;
    display: block;
    border: 20px solid transparent;
    border-bottom-color: #ACB6E5;
    top: -30px;
}
_x000D_
<div class="slider">
  <div class="container-slider">
    <input type="range" min="0" max="100" step="1" value="" id="sss">
    <div class="val" id="final">0</div>
  </div>
</div>
_x000D_
_x000D_
_x000D_

Stacked bar chart

You will need to melt your dataframe to get it into the so-called long format:

require(reshape2)
sample.data.M <- melt(sample.data)

Now your field values are represented by their own rows and identified through the variable column. This can now be leveraged within the ggplot aesthetics:

require(ggplot2)
c <- ggplot(sample.data.M, aes(x = Rank, y = value, fill = variable))
c + geom_bar(stat = "identity")

Instead of stacking you may also be interested in showing multiple plots using facets:

c <- ggplot(sample.data.M, aes(x = Rank, y = value))
c + facet_wrap(~ variable) + geom_bar(stat = "identity")

iOS: present view controller programmatically

your code :

 AddTaskViewController *add = [[AddTaskViewController alloc] init];
 [self presentViewController:add animated:YES completion:nil];

this code can goes to the other controller , but you get a new viewController , not the controller of your storyboard, you can do like this :

AddTaskViewController *add = [self.storyboard instantiateViewControllerWithIdentifier:@"YourStoryboardID"];
[self presentViewController:add animated:YES completion:nil];

How do android screen coordinates work?

For Android API level 13 and you need to use this:

Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int maxX = size.x; 
int maxY = size.y;

Then (0,0) is top left corner and (maxX,maxY) is bottom right corner of the screen.

The 'getWidth()' for screen size is deprecated since API 13

Furthermore getwidth() and getHeight() are methods of android.view.View class in android.So when your java class extends View class there is no windowManager overheads.

          int maxX=getwidht();
          int maxY=getHeight();

as simple as that.

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

It's mainly a matter of choice most of the time. It's a matter of preference.

Note however that if you have numeric keys for example, that you can't do:

mydict = dict(1="foo", 2="bar")

You have to do:

mydict = {"1":"foo", "2":"bar"}

IE Driver download location Link for Selenium

You can download IE Driver (both 32 and 64-bit) from Selenium official site: http://docs.seleniumhq.org/download/

32 bit Windows IE

64 bit Windows IE

IE Driver is also available in the following site:

http://selenium-release.storage.googleapis.com/index.html

How to delete the last row of data of a pandas dataframe

Just use indexing

df.iloc[:-1,:]

That's why iloc exists. You can also use head or tail.

Refresh or force redraw the fragment

Use the following code for refreshing fragment again:

FragmentTransaction ftr = getFragmentManager().beginTransaction();                          
ftr.detach(EnterYourFragmentName.this).attach(EnterYourFragmentName.this).commit();

Zero an array in C code

Using memset:

int something[20];
memset(something, 0, 20 * sizeof(int));

How to output JavaScript with PHP

You need to escape the double quotes like this:

echo "<script type=\"text/javascript\">";
echo "document.write(\"Hello World!\")";
echo "</script>";

or use single quotes inside the double quotes instead, like this:

echo "<script type='text/javascript'>";
echo "document.write('Hello World!')";
echo "</script>";

or the other way around, like this:

echo '<script type="text/javascript">';
echo 'document.write("Hello World!")';
echo '</script>';

Also, checkout the PHP Manual for more info on Strings.

Also, why would you want to print JavaScript using PHP? I feel like there's something wrong with your design.

Telling gcc directly to link a library statically

You can add .a file in the linking command:

  gcc yourfiles /path/to/library/libLIBRARY.a

But this is not talking with gcc driver, but with ld linker as options like -Wl,anything are.

When you tell gcc or ld -Ldir -lLIBRARY, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose). To change order of library types checked you can use -Wl,-Bstatic and -Wl,-Bdynamic. Here is a man page of gnu LD: http://linux.die.net/man/1/ld

To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:

gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3

Assuming that default setting of ld is to use dynamic libraries (it is on Linux).

Using ResourceManager

in priciple it's the same idea as @Landeeyos. anyhow, expanding on that response: a bit late to the party but here are my two cents:

scenario:

I have a unique case of adding some (roughly 28 text files) predefined, template files with my WPF application. So, the idea is that everytime this app is to be installed, these template, text files will be readily available for usage. anyhow, what I did was that made a seperate library to hold the files by adding a resource.resx. Then I added all those files to this resource file (if you double click a .resx file, its designer gets opened in visual studio). I had set the Access Modifier to public for all. Also, each file was marked as an embedded resource via the Build Action of each text file (you can get that by looking at its properties). let's call this bibliothek1.dll i referenced this above library (bibliothek1.dll) in another library (call it bibliothek2.dll) and then consumed this second library in mf wpf app.

actual fun:

        // embedded resource file name <i>with out extension</i>(this is vital!) 

        string fileWithoutExt = Path.GetFileNameWithoutExtension(fileName);

        // is required in the next step

        // without specifying the culture
        string wildFile = IamAResourceFile.ResourceManager.GetString(fileWithoutExt);
        Console.Write(wildFile);

        // with culture
        string culturedFile = IamAResourceFile.ResourceManager.GetString(fileWithoutExt, CultureInfo.InvariantCulture);
        Console.Write(culturedFile);

sample: checkout 'testingresourcefilesusage' @ https://github.com/Natsikap/samples.git

I hope it helps someone, some day, somewhere!

check if "it's a number" function in Oracle

CREATE OR REPLACE FUNCTION is_number(N IN VARCHAR2) RETURN NUMBER IS
  BEGIN
    RETURN CASE regexp_like(N,'^[\+\-]?[0-9]*\.?[0-9]+$') WHEN TRUE THEN 1 ELSE 0 END;
END is_number;

Please note that it won't consider 45e4 as a number, But you can always change regex to accomplish the opposite.

How does createOrReplaceTempView work in Spark?

SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.

In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.

In order to create the view, developer need an utility called createOrReplaceTempView

Sorting an array of objects by property values

For sorting a array you must define a comparator function. This function always be different on your desired sorting pattern or order(i.e. ascending or descending).

Let create some functions that sort an array ascending or descending and that contains object or string or numeric values.

function sorterAscending(a,b) {
    return a-b;
}

function sorterDescending(a,b) {
    return b-a;
}

function sorterPriceAsc(a,b) {
    return parseInt(a['price']) - parseInt(b['price']);
}

function sorterPriceDes(a,b) {
    return parseInt(b['price']) - parseInt(b['price']);
}

Sort numbers (alphabetically and ascending):

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();

Sort numbers (alphabetically and descending):

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
fruits.reverse();

Sort numbers (numerically and ascending):

var points = [40,100,1,5,25,10];
points.sort(sorterAscending());

Sort numbers (numerically and descending):

var points = [40,100,1,5,25,10];
points.sort(sorterDescending());

As above use sorterPriceAsc and sorterPriceDes method with your array with desired key.

homes.sort(sorterPriceAsc()) or homes.sort(sorterPriceDes())

XXHDPI and XXXHDPI dimensions in dp for images and icons in android

it is different for different icons.(eg, diff sizes for action bar icons, laucnher icons, etc.) please follow this link icons handbook to learn more.

Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session

I just had the same problem .I solve it by adding this line:

@GeneratedValue(strategy=GenerationType.IDENTITY)

enter image description here

Navigation Controller Push View Controller

UINavigationController is not automatically presented in UIViewController.

This is what you should see in Interface Builder. Files owner has view outlet to Navigation controller and from navigation controller is outlet to actual view;

Interface Builder

How to set the maxAllowedContentLength to 500MB while running on IIS7?

The limit of requests in .Net can be configured from two properties together:

First

  • Web.Config/system.web/httpRuntime/maxRequestLength
  • Unit of measurement: kilobytes
  • Default value 4096 KB (4 MB)
  • Max. value 2147483647 KB (2 TB)

Second

  • Web.Config/system.webServer/security/requestFiltering/requestLimits/maxAllowedContentLength (in bytes)
  • Unit of measurement: bytes
  • Default value 30000000 bytes (28.6 MB)
  • Max. value 4294967295 bytes (4 GB)

References:

Example:

<location path="upl">
   <system.web>
     <!--The default size is 4096 kilobytes (4 MB). MaxValue is 2147483647 KB (2 TB)-->
     <!-- 100 MB in kilobytes -->
     <httpRuntime maxRequestLength="102400" />
   </system.web>
   <system.webServer>
     <security>
       <requestFiltering>          
         <!--The default size is 30000000 bytes (28.6 MB). MaxValue is 4294967295 bytes (4 GB)-->
         <!-- 100 MB in bytes -->
         <requestLimits maxAllowedContentLength="104857600" />
       </requestFiltering>
     </security>
   </system.webServer>
 </location>

How to get current date & time in MySQL?

The correct answer is SYSDATE().

INSERT INTO servers (
    server_name, online_status, exchange, disk_space,
    network_shares, date_time
)
VALUES (
    'm1', 'ONLINE', 'ONLINE', '100GB', 'ONLINE', SYSDATE()
);

We can change this behavior and make NOW() behave in the same way as SYSDATE() by setting sysdate_is_now command line argument to True.

Note that NOW() (which has CURRENT_TIMESTAMP() as an alias), differs from SYSDATE() in a subtle way:

SYSDATE() returns the time at which it executes. This differs from the behavior for NOW(), which returns a constant time that indicates the time at which the statement began to execute. (Within a stored function or trigger, NOW() returns the time at which the function or triggering statement began to execute.)

As indicated by Erandi, it is best to create your table with the DEFAULT clause so that the column gets populated automatically with the timestamp when you insert a new row:

date_time datetime NOT NULL DEFAULT SYSDATE()

If you want the current date in epoch format, then you can use UNIX_TIMESTAMP(). For example:

select now(3), sysdate(3), unix_timestamp();

would yield

+-------------------------+-------------------------+------------------+
| now(3)                  | sysdate(3)              | unix_timestamp() |
+-------------------------+-------------------------+------------------+
| 2018-11-27 01:40:08.160 | 2018-11-27 01:40:08.160 |       1543282808 |
+-------------------------+-------------------------+------------------+

Related:

Downgrade npm to an older version

Before doing that Download Node Js 8.11.3 from the URL: download

Open command prompt and run this:

npm install -g [email protected]

use this version this is the stable version which works along with cordova 7.1.0

for installing cordova use : • npm install -g [email protected]

• Run command

• Cordova platform remove android (if you have old android code or code is having some issue)

• Cordova platform add android : for building android app in cordova Running: Corodva run android

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

You should never use the unidirectional @OneToMany annotation because:

  1. It generates inefficient SQL statements
  2. It creates an extra table which increases the memory footprint of your DB indexes

Now, in your first example, both sides are owning the association, and this is bad.

While the @JoinColumn would let the @OneToMany side in charge of the association, it's definitely not the best choice. Therefore, always use the mappedBy attribute on the @OneToMany side.

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

    @OneToMany(fetch=FetchType.LAZY, cascade = CascadeType.ALL, mappedBy="user")
    public List<BPost> bPosts;
}

public class BPost extends Post {

    @ManyToOne(fetch=FetchType.LAZY)    
    public User user;
}

public class APost extends Post {

     @ManyToOne(fetch=FetchType.LAZY) 
     public User user;
}

Masking password input from the console : Java

Console console = System.console();
String username = console.readLine("Username: ");
char[] password = console.readPassword("Password: ");

php error: Class 'Imagick' not found

Debian 9

I just did the following and everything else needed got automatically installed as well.

sudo apt-get -y -f install php-imagick
sudo /etc/init.d/apache2 restart

Using PUT method in HTML form

XHTML 1.x forms only support GET and POST. GET and POST are the only allowed values for the "method" attribute.

Multiple simultaneous downloads using Wget?

A new (but yet not released) tool is Mget. It has already many options known from Wget and comes with a library that allows you to easily embed (recursive) downloading into your own application.

To answer your question:

mget --num-threads=4 [url]

UPDATE

Mget is now developed as Wget2 with many bugs fixed and more features (e.g. HTTP/2 support).

--num-threads is now --max-threads.

Performance of Arrays vs. Lists

Since List<> uses arrays internally, the basic performance should be the same. Two reasons, why the List might be slightly slower:

  • To look up a element in the list, a method of List is called, which does the look up in the underlying array. So you need an additional method call there. On the other hand the compiler might recognize this and optimize the "unnecessary" call away.
  • The compiler might do some special optimizations if it knows the size of the array, that it can't do for a list of unknown length. This might bring some performance improvement if you only have a few elements in your list.

To check if it makes any difference for you, it's probably best adjust the posted timing functions to a list of the size you're planning to use and see how the results for your special case are.

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

How to loop backwards in python?

All of these three solutions give the same results if the input is a string:

1.

def reverse(text):
    result = ""
    for i in range(len(text),0,-1):
        result += text[i-1]
    return (result)

2.

text[::-1]

3.

"".join(reversed(text))

Failure [INSTALL_FAILED_ALREADY_EXISTS] when I tried to update my application

This can also be caused if the application was built from different PCs. You can make it easier for your whole team if you copy a debug.keystore from someone's machine into a /cert folder at the top of your project and then add a signingConfigs section to your app/build.gradle:

  signingConfigs {
    debug {
      storeFile file("cert/debug.keystore")
    }
  }

Then tell your debug build how to sign the application:

  buildTypes {
    debug {
      // Other values 
      signingConfig signingConfigs.debug
    }
  }

Check this file into source control. This will allow for the seamless install/upgrade process across your entire development team and will make your project resilient against future machine upgrades too.

Is there an XSL "contains" directive?

Sure there is! For instance:

<xsl:if test="not(contains($hhref, '1234'))">
  <li>
    <a href="{$hhref}" title="{$pdate}">
      <xsl:value-of select="title"/>
    </a>
  </li>
</xsl:if>

The syntax is: contains(stringToSearchWithin, stringToSearchFor)

Cannot implicitly convert type 'int?' to 'int'.

Your method's return type is int and you're trying to return an int?.

How can I convert an HTML table to CSV?

Here's a ruby script that uses nokogiri -- http://nokogiri.rubyforge.org/nokogiri/

require 'nokogiri'

doc = Nokogiri::HTML(table_string)

doc.xpath('//table//tr').each do |row|
  row.xpath('td').each do |cell|
    print '"', cell.text.gsub("\n", ' ').gsub('"', '\"').gsub(/(\s){2,}/m, '\1'), "\", "
  end
  print "\n"
end

Worked for my basic test case.

What does it mean to write to stdout in C?

It depends.

When you commit to sending output to stdout, you're basically leaving it up to the user to decide where that output should go.

If you use printf(...) (or the equivalent fprintf(stdout, ...)), you're sending the output to stdout, but where that actually ends up can depend on how I invoke your program.

If I launch your program from my console like this, I'll see output on my console:

$ prog
Hello, World! # <-- output is here on my console

However, I might launch the program like this, producing no output on the console:

$ prog > hello.txt

but I would now have a file "hello.txt" with the text "Hello, World!" inside, thanks to the shell's redirection feature.

Who knows – I might even hook up some other device and the output could go there. The point is that when you decide to print to stdout (e.g. by using printf()), then you won't exactly know where it will go until you see how the process is launched or used.

How to make an AlertDialog in Flutter?

Or you can use RFlutter Alert library for that. It is easily customizable and easy-to-use. Its default style includes rounded corners and you can add buttons as much as you want.

Basic Alert:

Alert(context: context, title: "RFLUTTER", desc: "Flutter is awesome.").show();

Alert with Button:

Alert(
    context: context,
    type: AlertType.error,
    title: "RFLUTTER ALERT",
    desc: "Flutter is more awesome with RFlutter Alert.",
    buttons: [
    DialogButton(
        child: Text(
        "COOL",
        style: TextStyle(color: Colors.white, fontSize: 20),
        ),
        onPressed: () => Navigator.pop(context),
        width: 120,
    )
    ],
).show();

You can also define generic alert styles.

*I'm one of developer of RFlutter Alert.

Selenium webdriver click google search

Most of the answers on this page are outdated.
Here's an updated python version to search google and get all results href's:

import urllib.parse
import re
from selenium import webdriver
driver.get("https://google.com/")
q = driver.find_element_by_name('q')
q.send_keys("always look on the bright side of life monty python")
q.submit();
sleep(1)
links= driver.find_elements_by_xpath("//h3[@class='r']//a")
for link in links:
    url = urllib.parse.unquote(webElement.get_attribute("href")) # decode the url
    url = re.sub("^.*?(?:url\?q=)(.*?)&sa.*", r"\1", url, 0, re.IGNORECASE) # get the clean url

Please note that the element id/name/class (@class='r') ** will change depending on the user agent**.
The above code used PhantomJS default user agent.

user authentication libraries for node.js?

sweet-auth

A lightweight, zero-configuration user authentication module. It doesn't need a sperate database.

https://www.npmjs.com/package/sweet-auth

It's simple as:

app.get('/private-page', (req, res) => {

    if (req.user.isAuthorized) {
        // user is logged in! send the requested page
        // you can access req.user.email
    }
    else {
        // user not logged in. redirect to login page
    }
})

Java properties UTF-8 encoding in Eclipse

Properties props = new Properties();
URL resource = getClass().getClassLoader().getResource("data.properties");         
props.load(new InputStreamReader(resource.openStream(), "UTF8"));

Works like a charm

:-)

How to link to a named anchor in Multimarkdown?

Taken from the Multimarkdown Users Guide (thanks to @MultiMarkdown on Twitter for pointing it out)

[Some Text][]will link to a header named “Some Text”
e.g.

### Some Text ###

An optional label of your choosing to help disambiguate cases where multiple headers have the same title:

### Overview [MultiMarkdownOverview] ##

This allows you to use [MultiMarkdownOverview] to refer to this section specifically, and not another section named Overview. This works with atx- or settext-style headers.

If you have already defined an anchor using the same id that is used by a header, then the defined anchor takes precedence.

In addition to headers within the document, you can provide labels for images and tables which can then be used for cross-references as well.

How to use glyphicons in bootstrap 3.0

The icons (glyphicons) are now contained in a separate css file...

The markup has changed to:

<i class="glyphicon glyphicon-search"></i>

or

<span class="glyphicon glyphicon-search"></span>

Here is a helpful list of changes for Bootstrap 3: http://bootply.com/bootstrap-3-migration-guide

converting epoch time with milliseconds to datetime

Use datetime.datetime.fromtimestamp:

>>> import datetime
>>> s = 1236472051807 / 1000.0
>>> datetime.datetime.fromtimestamp(s).strftime('%Y-%m-%d %H:%M:%S.%f')
'2009-03-08 09:27:31.807000'

%f directive is only supported by datetime.datetime.strftime, not by time.strftime.

UPDATE Alternative using %, str.format:

>>> import time
>>> s, ms = divmod(1236472051807, 1000)  # (1236472051, 807)
>>> '%s.%03d' % (time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'
>>> '{}.{:03d}'.format(time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(s)), ms)
'2009-03-08 00:27:31.807'

How do you add a scroll bar to a div?

If you want to add a scroll bar using jquery the following will work. If your div had a id of 'mydiv' you could us the following jquery id selector with css property:

jQuery('#mydiv').css("overflow-y", "scroll");

Python: Get HTTP headers from urllib2.urlopen call?

urllib2.urlopen does an HTTP GET (or POST if you supply a data argument), not an HTTP HEAD (if it did the latter, you couldn't do readlines or other accesses to the page body, of course).

How to change root logging level programmatically for logback

Here's a controller

@RestController
@RequestMapping("/loggers")
public class LoggerConfigController {

private final static org.slf4j.Logger LOGGER = LoggerFactory.getLogger(PetController.class);

@GetMapping()
public List<LoggerDto> getAllLoggers() throws CoreException {
    
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    
    List<Logger> loggers = loggerContext.getLoggerList();
    
    List<LoggerDto> loggerDtos = new ArrayList<>();
    
    for (Logger logger : loggers) {
        
        if (Objects.isNull(logger.getLevel())) {
            continue;
        }
        
        LoggerDto dto = new LoggerDto(logger.getName(), logger.getLevel().levelStr);
        loggerDtos.add(dto);
    }
    
    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("All loggers retrieved. Total of {} loggers found", loggerDtos.size());
    }
    
    return loggerDtos;
}

@PutMapping
public boolean updateLoggerLevel(
        @RequestParam String name, 
        @RequestParam String level
)throws CoreException {
    
    LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
    
    Logger logger = loggerContext.getLogger(name);
    
    if (Objects.nonNull(logger) && StringUtils.isNotBlank(level)) {
        
        switch (level) {
            case "INFO":
                logger.setLevel(Level.INFO);
                LOGGER.info("Logger [{}] updated to [{}]", name, level);
                break;
                
            case "DEBUG":
                logger.setLevel(Level.DEBUG);
                LOGGER.info("Logger [{}] updated to [{}]", name, level);
                break;
                
            case "ALL":
                logger.setLevel(Level.ALL);
                LOGGER.info("Logger [{}] updated to [{}]", name, level);
                break;
                
            case "OFF":
            default: 
                logger.setLevel(Level.OFF);
                LOGGER.info("Logger [{}] updated to [{}]", name, level);
        }
    }
    
    return true;
}

}

How to insert a value that contains an apostrophe (single quote)?

Single quotes are escaped by doubling them up,

The following SQL illustrates this functionality.

declare @person TABLE (
    [First] nvarchar(200),
    [Last] nvarchar(200)
)

insert into @person 
    (First, Last)
values
    ('Joe', 'O''Brien')

select * from @person

Results

First   | Last
===================
Joe     | O'Brien

Can’t delete docker image with dependent child images

Here's a script to remove an image and all the images that depend on it.

#!/bin/bash

if [[ $# -lt 1 ]]; then
    echo must supply image to remove;
    exit 1;
fi;

get_image_children ()
{
    ret=()
    for i in $(docker image ls -a --no-trunc -q); do
        #>&2 echo processing image "$i";
        #>&2 echo parent is $(docker image inspect --format '{{.Parent}}' "$i")
        if [[ "$(docker image inspect --format '{{.Parent}}' "$i")" == "$1" ]]; then
            ret+=("$i");
        fi;
    done;
    echo "${ret[@]}";
}

realid=$(docker image inspect --format '{{.Id}}' "$1")
if [[ -z "$realid" ]]; then
    echo "$1 is not a valid image.";
    exit 2;
fi;
images_to_remove=("$realid");
images_to_process=("$realid");
while [[ "${#images_to_process[@]}" -gt 0 ]]; do
    children_to_process=();
    for i in "${!images_to_process[@]}"; do
        children=$(get_image_children "${images_to_process[$i]}");
        if [[ ! -z "$children" ]]; then
            # allow word splitting on the children.
            children_to_process+=($children);
        fi;
    done;
    if [[ "${#children_to_process[@]}" -gt 0 ]]; then
        images_to_process=("${children_to_process[@]}");
        images_to_remove+=("${children_to_process[@]}");
    else
        #no images have any children. We're done creating the graph.
        break;
    fi;
done;
echo images_to_remove = "$(printf %s\n "${images_to_remove[@]}")";
indices=(${!images_to_remove[@]});
for ((i="${#indices[@]}" - 1; i >= 0; --i)) ; do
    image_to_remove="${images_to_remove[indices[i]]}"
    if [[ "${image_to_remove:0:7}" == "sha256:" ]]; then
        image_to_remove="${image_to_remove:7}";
    fi
    echo removing image "$image_to_remove";
    docker rmi "$image_to_remove";
done

Trigger change event <select> using jquery

If you want to do some checks then use this way

 <select size="1" name="links" onchange="functionToTriggerClick(this.value)">
    <option value="">Select a Search Engine</option>        
    <option value="http://www.google.com">Google</option>
    <option value="http://www.yahoo.com">Yahoo</option>
</select>

<script>

   function functionToTriggerClick(link) {

     if(link != ''){
        window.location.href=link;
        }
    }  

</script>

Calculate RSA key fingerprint

On Fedora I do locate ~/.ssh which tells me keys are at

/root/.ssh
/root/.ssh/authorized_keys

Generating a PDF file from React Components

React-PDF is a great resource for this.

It is a bit time consuming converting your markup and CSS to React-PDF's format, but it is easy to understand. Exporting a PDF and from it is fairly straightforward.

To allow a user to download a PDF generated by react-PDF, use their on the fly rendering, which provides a customizable download link. When clicked, the site renders and downloads the PDF for the user.

Here's their REPL which will familiarize you with the markup and styling required. They have a download link for the PDF too, but they don't show the code for that here.

SASS - use variables across multiple files

Create an index.scss and there you can import all file structure you have. I will paste you my index from an enterprise project, maybe it will help other how to structure files in css:

@import 'base/_reset';

@import 'helpers/_variables';
@import 'helpers/_mixins';
@import 'helpers/_functions';
@import 'helpers/_helpers';
@import 'helpers/_placeholders';

@import 'base/_typography';

@import 'pages/_versions';
@import 'pages/_recording';
@import 'pages/_lists';
@import 'pages/_global';

@import 'forms/_buttons';
@import 'forms/_inputs';
@import 'forms/_validators';
@import 'forms/_fieldsets';

@import 'sections/_header';
@import 'sections/_navigation';
@import 'sections/_sidebar-a';
@import 'sections/_sidebar-b';
@import 'sections/_footer';

@import 'vendors/_ui-grid';

@import 'components/_modals';
@import 'components/_tooltip';
@import 'components/_tables';
@import 'components/_datepickers';

And you can watch them with gulp/grunt/webpack etc, like:

gulpfile.js

// SASS Task

var gulp = require('gulp');
var sass = require('gulp-sass');
//var concat = require('gulp-concat');
var uglifycss = require('gulp-uglifycss');
var sourcemaps = require('gulp-sourcemaps');

gulp.task('styles', function(){
    return gulp
            .src('sass/**/*.scss')
            .pipe(sourcemaps.init())
            .pipe(sass().on('error', sass.logError))
            .pipe(concat('styles.css'))
            .pipe(uglifycss({
                "maxLineLen": 80,
                "uglyComments": true
            }))
            .pipe(sourcemaps.write('.'))
            .pipe(gulp.dest('./build/css/'));
});

gulp.task('watch', function () {
    gulp.watch('sass/**/*.scss', ['styles']);
});

gulp.task('default', ['watch']);

How do you increase the max number of concurrent connections in Apache?

Here's a detailed explanation about the calculation of MaxClients and MaxRequestsPerChild

http://web.archive.org/web/20160415001028/http://www.genericarticles.com/mediawiki/index.php?title=How_to_optimize_apache_web_server_for_maximum_concurrent_connections_or_increase_max_clients_in_apache

ServerLimit 16
StartServers 2
MaxClients 200
MinSpareThreads 25
MaxSpareThreads 75
ThreadsPerChild 25

First of all, whenever an apache is started, it will start 2 child processes which is determined by StartServers parameter. Then each process will start 25 threads determined by ThreadsPerChild parameter so this means 2 process can service only 50 concurrent connections/clients i.e. 25x2=50. Now if more concurrent users comes, then another child process will start, that can service another 25 users. But how many child processes can be started is controlled by ServerLimit parameter, this means that in the configuration above, I can have 16 child processes in total, with each child process can handle 25 thread, in total handling 16x25=400 concurrent users. But if number defined in MaxClients is less which is 200 here, then this means that after 8 child processes, no extra process will start since we have defined an upper cap of MaxClients. This also means that if I set MaxClients to 1000, after 16 child processes and 400 connections, no extra process will start and we cannot service more than 400 concurrent clients even if we have increase the MaxClient parameter. In this case, we need to also increase ServerLimit to 1000/25 i.e. MaxClients/ThreadsPerChild=40 So this is the optmized configuration to server 1000 clients

<IfModule mpm_worker_module>
    ServerLimit          40
    StartServers          2
    MaxClients          1000
    MinSpareThreads      25
    MaxSpareThreads      75 
    ThreadsPerChild      25
    MaxRequestsPerChild   0
</IfModule>

TypeError: unhashable type: 'list' when using built-in set function

Sets require their items to be hashable. Out of types predefined by Python only the immutable ones, such as strings, numbers, and tuples, are hashable. Mutable types, such as lists and dicts, are not hashable because a change of their contents would change the hash and break the lookup code.

Since you're sorting the list anyway, just place the duplicate removal after the list is already sorted. This is easy to implement, doesn't increase algorithmic complexity of the operation, and doesn't require changing sublists to tuples:

def uniq(lst):
    last = object()
    for item in lst:
        if item == last:
            continue
        yield item
        last = item

def sort_and_deduplicate(l):
    return list(uniq(sorted(l, reverse=True)))

ORA-00972 identifier is too long alias column name

If you have recently upgraded springboot to 1.4.3, you might need to make changes to yml file:

yml in 1.3 :

jpa: 
  hibernate: 
    namingStrategy: org.hibernate.cfg.EJB3NamingStrategy

yml in 1.4.3 :

jpa: 
  hibernate: 
    naming: physical-strategy: org.hibernate.boot.model.naming.PhysicalNamingStrategyStandardImpl

Android background music service

I have found two great resources to share, if anyone else come across this thread via Google, this may help them ( 2018 ). One is this video tutorial in which you'll see practically how service works, this is good for starters.

Link :- https://www.youtube.com/watch?v=p2ffzsCqrs8

Other is this website which will really help you with background audio player.

Link :- https://www.dev2qa.com/android-play-audio-file-in-background-service-example/

Good Luck :)

C# Iterate through Class properties

// the index of each item in fieldNames must correspond to 
// the correct index in resultItems
var fieldnames = new []{"itemtype", "etc etc "};

for (int e = 0; e < fieldNames.Length - 1; e++)
{
    newRecord
       .GetType()
       .GetProperty(fieldNames[e])
       .SetValue(newRecord, resultItems[e]);
}

Javascript Equivalent to PHP Explode()

console.log(('0000000020C90037:TEMP:data').split(":").slice(1).join(':'))

outputs: TEMP:data

  • .split() will disassemble a string into parts
  • .join() reassembles the array back to a string
  • when you want the array without it's first item, use .slice(1)

Responsive iframe using Bootstrap

The best solution that worked great for me.

You have to: Copy this code to your main CSS file,

.responsive-video {
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 60px; overflow: hidden;
}

.responsive-video iframe,
.responsive-video object,
.responsive-video embed {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

and then put your embeded video to

<div class="responsive-video">
    <iframe ></iframe>
</div>

That’s it! Now you can use responsive videos on your site.

C++: variable 'std::ifstream ifs' has initializer but incomplete type

This seems to be answered - #include <fstream>.

The message means :-

incomplete type - the class has not been defined with a full class. The compiler has seen statements such as class ifstream; which allow it to understand that a class exists, but does not know how much memory the class takes up.

The forward declaration allows the compiler to make more sense of :-

void BindInput( ifstream & inputChannel ); 

It understands the class exists, and can send pointers and references through code without being able to create the class, see any data within the class, or call any methods of the class.

The has initializer seems a bit extraneous, but is saying that the incomplete object is being created.

How to convert php array to utf8?

You can send the array to this function:

function utf8_converter($array){
    array_walk_recursive($array, function(&$item, $key){
        if(!mb_detect_encoding($item, 'utf-8', true)){
            $item = utf8_encode($item);
        }
    }); 
    return $array;
}

It works for me.

jQuery CSS Opacity

Try with this :

jQuery('#main').css({ opacity: 0.6 });

Black transparent overlay on image hover with only CSS?

You were close. This will work:

.image { position: relative; border: 1px solid black; width: 200px; height: 200px; }
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; right:0; bottom:0; display: none; background-color: rgba(0,0,0,0.5); }
.image:hover .overlay { display: block; }

You needed to put the :hover on image, and make the .overlay cover the whole image by adding right:0; and bottom:0.

jsfiddle: http://jsfiddle.net/Zf5am/569/

In Angular, What is 'pathmatch: full' and what effect does it have?

While technically correct, the other answers would benefit from an explanation of Angular's URL-to-route matching. I don't think you can fully (pardon the pun) understand what pathMatch: full does if you don't know how the router works in the first place.


Let's first define a few basic things. We'll use this URL as an example: /users/james/articles?from=134#section.

  1. It may be obvious but let's first point out that query parameters (?from=134) and fragments (#section) do not play any role in path matching. Only the base url (/users/james/articles) matters.

  2. Angular splits URLs into segments. The segments of /users/james/articles are, of course, users, james and articles.

  3. The router configuration is a tree structure with a single root node. Each Route object is a node, which may have children nodes, which may in turn have other children or be leaf nodes.

The goal of the router is to find a router configuration branch, starting at the root node, which would match exactly all (!!!) segments of the URL. This is crucial! If Angular does not find a route configuration branch which could match the whole URL - no more and no less - it will not render anything.

E.g. if your target URL is /a/b/c but the router is only able to match either /a/b or /a/b/c/d, then there is no match and the application will not render anything.

Finally, routes with redirectTo behave slightly differently than regular routes, and it seems to me that they would be the only place where anyone would really ever want to use pathMatch: full. But we will get to this later.

Default (prefix) path matching

The reasoning behind the name prefix is that such a route configuration will check if the configured path is a prefix of the remaining URL segments. However, the router is only able to match full segments, which makes this naming slightly confusing.

Anyway, let's say this is our root-level router configuration:

const routes: Routes = [
  {
    path: 'products',
    children: [
      {
        path: ':productID',
        component: ProductComponent,
      },
    ],
  },
  {
    path: ':other',
    children: [
      {
        path: 'tricks',
        component: TricksComponent,
      },
    ],
  },
  {
    path: 'user',
    component: UsersonComponent,
  },
  {
    path: 'users',
    children: [
      {
        path: 'permissions',
        component: UsersPermissionsComponent,
      },
      {
        path: ':userID',
        children: [
          {
            path: 'comments',
            component: UserCommentsComponent,
          },
          {
            path: 'articles',
            component: UserArticlesComponent,
          },
        ],
      },
    ],
  },
];

Note that every single Route object here uses the default matching strategy, which is prefix. This strategy means that the router iterates over the whole configuration tree and tries to match it against the target URL segment by segment until the URL is fully matched. Here's how it would be done for this example:

  1. Iterate over the root array looking for a an exact match for the first URL segment - users.
  2. 'products' !== 'users', so skip that branch. Note that we are using an equality check rather than a .startsWith() or .includes() - only full segment matches count!
  3. :other matches any value, so it's a match. However, the target URL is not yet fully matched (we still need to match james and articles), thus the router looks for children.
  • The only child of :other is tricks, which is !== 'james', hence not a match.
  1. Angular then retraces back to the root array and continues from there.
  2. 'user' !== 'users, skip branch.
  3. 'users' === 'users - the segment matches. However, this is not a full match yet, thus we need to look for children (same as in step 3).
  • 'permissions' !== 'james', skip it.
  • :userID matches anything, thus we have a match for the james segment. However this is still not a full match, thus we need to look for a child which would match articles.
    1. We can see that :userID has a child route articles, which gives us a full match! Thus the application renders UserArticlesComponent.

Full URL (full) matching

Example 1

Imagine now that the users route configuration object looked like this:

{
  path: 'users',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

Note the usage of pathMatch: full. If this were the case, steps 1-5 would be the same, however step 6 would be different:

  1. 'users' !== 'users/james/articles - the segment does not match because the path configuration users with pathMatch: full does not match the full URL, which is users/james/articles.
  2. Since there is no match, we are skipping this branch.
  3. At this point we reached the end of the router configuration without having found a match. The application renders nothing.

Example 2

What if we had this instead:

{
  path: 'users/:userID',
  component: UsersComponent,
  pathMatch: 'full',
  children: [
    {
      path: 'comments',
      component: UserCommentsComponent,
    },
    {
      path: 'articles',
      component: UserArticlesComponent,
    },
  ],
}

users/:userID with pathMatch: full matches only users/james thus it's a no-match once again, and the application renders nothing.

Example 3

Let's consider this:

{
  path: 'users',
  children: [
    {
      path: 'permissions',
      component: UsersPermissionsComponent,
    },
    {
      path: ':userID',
      component: UserComponent,
      pathMatch: 'full',
      children: [
        {
          path: 'comments',
          component: UserCommentsComponent,
        },
        {
          path: 'articles',
          component: UserArticlesComponent,
        },
      ],
    },
  ],
}

In this case:

  1. 'users' === 'users - the segment matches, but james/articles still remains unmatched. Let's look for children.
  • 'permissions' !== 'james' - skip.
  • :userID' can only match a single segment, which would be james. However, it's a pathMatch: full route, and it must match james/articles (the whole remaining URL). It's not able to do that and thus it's not a match (so we skip this branch)!
  1. Again, we failed to find any match for the URL and the application renders nothing.

As you may have noticed, a pathMatch: full configuration is basically saying this:

Ignore my children and only match me. If I am not able to match all of the remaining URL segments myself, then move on.

Redirects

Any Route which has defined a redirectTo will be matched against the target URL according to the same principles. The only difference here is that the redirect is applied as soon as a segment matches. This means that if a redirecting route is using the default prefix strategy, a partial match is enough to cause a redirect. Here's a good example:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];

For our initial URL (/users/james/articles), here's what would happen:

  1. 'not-found' !== 'users' - skip it.
  2. 'users' === 'users' - we have a match.
  3. This match has a redirectTo: 'not-found', which is applied immediately.
  4. The target URL changes to not-found.
  5. The router begins matching again and finds a match for not-found right away. The application renders NotFoundComponent.

Now consider what would happen if the users route also had pathMatch: full:

const routes: Routes = [
  {
    path: 'not-found',
    component: NotFoundComponent,
  },
  {
    path: 'users',
    pathMatch: 'full',
    redirectTo: 'not-found',
  },
  {
    path: 'users/:userID',
    children: [
      {
        path: 'comments',
        component: UserCommentsComponent,
      },
      {
        path: 'articles',
        component: UserArticlesComponent,
      },
    ],
  },
];
  1. 'not-found' !== 'users' - skip it.
  2. users would match the first segment of the URL, but the route configuration requires a full match, thus skip it.
  3. 'users/:userID' matches users/james. articles is still not matched but this route has children.
  • We find a match for articles in the children. The whole URL is now matched and the application renders UserArticlesComponent.

Empty path (path: '')

The empty path is a bit of a special case because it can match any segment without "consuming" it (so it's children would have to match that segment again). Consider this example:

const routes: Routes = [
  {
    path: '',
    children: [
      {
        path: 'users',
        component: BadUsersComponent,
      }
    ]
  },
  {
    path: 'users',
    component: GoodUsersComponent,
  },
];

Let's say we are trying to access /users:

  • path: '' will always match, thus the route matches. However, the whole URL has not been matched - we still need to match users!
  • We can see that there is a child users, which matches the remaining (and only!) segment and we have a full match. The application renders BadUsersComponent.

Now back to the original question

The OP used this router configuration:

const routes: Routes = [
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
  {
    path: '',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
  {
    path: '**',
    redirectTo: 'welcome',
    pathMatch: 'full',
  },
];

If we are navigating to the root URL (/), here's how the router would resolve that:

  1. welcome does not match an empty segment, so skip it.
  2. path: '' matches the empty segment. It has a pathMatch: 'full', which is also satisfied as we have matched the whole URL (it had a single empty segment).
  3. A redirect to welcome happens and the application renders WelcomeComponent.

What if there was no pathMatch: 'full'?

Actually, one would expect the whole thing to behave exactly the same. However, Angular explicitly prevents such a configuration ({ path: '', redirectTo: 'welcome' }) because if you put this Route above welcome, it would theoretically create an endless loop of redirects. So Angular just throws an error, which is why the application would not work at all! (https://angular.io/api/router/Route#pathMatch)

Actually, this does not make too much sense to me because Angular also has implemented a protection against such endless redirects - it only runs a single redirect per routing level! This would stop all further redirects (as you'll see in the example below).

What about path: '**'?

path: '**' will match absolutely anything (af/frewf/321532152/fsa is a match) with or without a pathMatch: 'full'.

Also, since it matches everything, the root path is also included, which makes { path: '', redirectTo: 'welcome' } completely redundant in this setup.

Funnily enough, it is perfectly fine to have this configuration:

const routes: Routes = [
  {
    path: '**',
    redirectTo: 'welcome'
  },
  {
    path: 'welcome',
    component: WelcomeComponent,
  },
];

If we navigate to /welcome, path: '**' will be a match and a redirect to welcome will happen. Theoretically this should kick off an endless loop of redirects but Angular stops that immediately (because of the protection I mentioned earlier) and the whole thing works just fine.

Getting java.lang.ClassNotFoundException: org.apache.commons.logging.LogFactory exception

I have already included common-logging1.1.1.jar and ...

Are you sure you spelled the name of the JAR file exactly right? I think it should probably be commons-logging-1.1.1.jar (note the extra - in the name). Also check if the directory name is correct.

NoClassDefFoundError always means that a class cannot be found, so most likely your class path is not correct.

Convert utf8-characters to iso-88591 and back in PHP

First of all, don't use different encodings. It leads to a mess, and UTF-8 is definitely the one you should be using everywhere.

Chances are your input is not ISO-8859-1, but something else (ISO-8859-15, Windows-1252). To convert from those, use iconv or mb_convert_encoding.

Nevertheless, utf8_encode and utf8_decode should work for ISO-8859-1. It would be nice if you could post a link to a file or a uuencoded or base64 example string for which the conversion fails or yields unexpected results.

Simplest way to do grouped barplot

Not a barplot solution but using lattice and barchart:

library(lattice)
barchart(Species~Reason,data=Reasonstats,groups=Catergory, 
         scales=list(x=list(rot=90,cex=0.8)))

enter image description here

Angular 2 http post params and body

Seems like you use Angular 4.3 version, I also faced with same problem. Use Angular 4.0.1 and post with code by @trichetricheand and it will work. I am also not sure how to solve it on Angular 4.3 :S

Modify property value of the objects in list using Java 8 streams

You can do it using streams map function like below, get result in new stream for further processing.

Stream<Fruit> newFruits = fruits.stream().map(fruit -> {fruit.name+="s"; return fruit;});
        newFruits.forEach(fruit->{
            System.out.println(fruit.name);
        });

How do I manually configure a DataSource in Java?

Basically in JDBC most of these properties are not configurable in the API like that, rather they depend on implementation. The way JDBC handles this is by allowing the connection URL to be different per vendor.

So what you do is register the driver so that the JDBC system can know what to do with the URL:

 DriverManager.registerDriver((Driver) Class.forName("com.mysql.jdbc.Driver").newInstance());

Then you form the URL:

 String url = "jdbc:mysql://[host][,failoverhost...][:port]/[database][?propertyName1][=propertyValue1][&propertyName2][=propertyValue2]"

And finally, use it to get a connection:

 Connection c = DriverManager.getConnection(url);

In more sophisticated JDBC, you get involved with connection pools and the like, and application servers often have their own way of registering drivers in JNDI and you look up a DataSource from there, and call getConnection on it.

In terms of what properties MySQL supports, see here.

EDIT: One more thought, technically just having a line of code which does Class.forName("com.mysql.jdbc.Driver") should be enough, as the class should have its own static initializer which registers a version, but sometimes a JDBC driver doesn't, so if you aren't sure, there is little harm in registering a second one, it just creates a duplicate object in memeory.

Why doesn't Mockito mock static methods?

I seriously do think that it is code smell if you need to mock static methods, too.

  • Static methods to access common functionality? -> Use a singleton instance and inject that
  • Third party code? -> Wrap it into your own interface/delegate (and if necessary make it a singleton, too)

The only time this seems overkill to me, is libs like Guava, but you shouldn't need to mock this kind anyway cause it's part of the logic... (stuff like Iterables.transform(..))
That way your own code stays clean, you can mock out all your dependencies in a clean way, and you have an anti corruption layer against external dependencies. I've seen PowerMock in practice and all the classes we needed it for were poorly designed. Also the integration of PowerMock at times caused serious problems
(e.g. https://code.google.com/p/powermock/issues/detail?id=355)

PS: Same holds for private methods, too. I don't think tests should know about the details of private methods. If a class is so complex that it tempts to mock out private methods, it's probably a sign to split up that class...

How can I determine if a variable is 'undefined' or 'null'?

The foo == null check should do the trick and resolve the "undefined OR null" case in the shortest manner. (Not considering "foo is not declared" case.) But people who are used to have 3 equals (as the best practice) might not accept it. Just look at eqeqeq or triple-equals rules in eslint and tslint...

The explicit approach, when we are checking if a variable is undefined or null separately, should be applied in this case, and my contribution to the topic (27 non-negative answers for now!) is to use void 0 as both short and safe way to perform check for undefined.

Using foo === undefined is not safe because undefined is not a reserved word and can be shadowed (MDN). Using typeof === 'undefined' check is safe, but if we are not going to care about foo-is-undeclared case the following approach can be used:

if (foo === void 0 || foo === null) { ... }

PHP parse/syntax errors; and how to solve them

I think this topic is totally overdiscussed/overcomplicated. Using an IDE is THE way to go to completely avoid any syntax errors. I would even say that working without an IDE is kind of unprofessional. Why? Because modern IDEs check your syntax after every character you type. When you code and your entire line turns red, and a big warning notice shows you the exact type and the exact position of the syntax error, then there's absolutely no need to search for another solution.

Using a syntax-checking IDE means:

You'll (effectively) never run into syntax errors again, simply because you see them right as you type. Seriously.

Excellent IDEs with syntax check (all of them are available for Linux, Windows and Mac):

  1. NetBeans [free]
  2. PHPStorm [$199 USD]
  3. Eclipse with PHP Plugin [free]
  4. Sublime [$80 USD] (mainly a text editor, but expandable with plugins, like PHP Syntax Parser)

Failed to load ApplicationContext from Unit Test: FileNotFound

Try with the relative path using *

  @ContextConfiguration(locations = {
"classpath*:spring/applicationContext.xml",
"classpath*:spring/applicationContext-jpa.xml",
"classpath*:spring/applicationContext-security.xml" })

If not look if your xml are really on resources/spring/.

Finally try just on without location

 @ContextConfiguration({"classpath*:spring/applicationContext.xml"})

The other error that you´re showing is because you have this tag duplicated on applicationContext.xml and applicationContext-security.xml

 Duplicate <global-method-security>

Python, compute list difference

If the order does not matter, you can simply calculate the set difference:

>>> set([1,2,3,4]) - set([2,5])
set([1, 4, 3])
>>> set([2,5]) - set([1,2,3,4])
set([5])

Anchor links in Angularjs?

Works for me:

 <a onclick='return false;' href="" class="collapsed" role="button" data-toggle="collapse" data-parent="#accordion" ng-href="#profile#collapse{{$index}}"> blalba </a>

What is Ruby's double-colon `::`?

:: Lets you access a constant, module, or class defined inside another class or module. It is used to provide namespaces so that method and class names don't conflict with other classes by different authors.

When you see ActiveRecord::Base in Rails it means that Rails has something like

module ActiveRecord
  class Base
  end
end

i.e. a class called Base inside a module ActiveRecord which is then referenced as ActiveRecord::Base (you can find this in the Rails source in activerecord-n.n.n/lib/active_record/base.rb)

A common use of :: is to access constants defined in modules e.g.

module Math
  PI = 3.141 # ...
end

puts Math::PI

The :: operator does not allow you to bypass visibility of methods marked private or protected.

How to edit the size of the submit button on a form?

Using CSS you can set a style for that specific button using the id (#) selector:

#search {
    width: 20em;  height: 2em;
}

or if you want all submit buttons to be a particular size:

input[type=submit] {
    width: 20em;  height: 2em;
}

or if you want certain classes of button to be a particular style you can use CSS classes:

<input type="submit" id="search" value="Search" class="search" />

and

input.search {
    width: 20em;  height: 2em;
}

I use ems as the measurement unit because they tend to scale better.

Create component to specific module with Angular-CLI

First run ng g module newModule . Then run ng g component newModule/newModule --flat

Alternative to google finance api

Updating answer a bit

1. Try Twelve Data API

For beginners try to run the following query with a JSON response:

https://api.twelvedata.com/time_series?symbol=AAPL&interval=1min&apikey=demo&source=docs

NO more real time Alpha Vantage API

For beginners you can try to get a JSON output from query such as

https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=MSFT&apikey=demo

DON'T Try Yahoo Finance API (it is DEPRECATED or UNAVAILABLE NOW).

For beginners, you can generate a CSV with a simple API call:

http://finance.yahoo.com/d/quotes.csv?s=AAPL+GOOG+MSFT&f=sb2b3jk

(This will generate and save a CSV for AAPL, GOOG, and MSFT)

Note that you must append the format to the query string (f=..). For an overview of all of the formats see this page.

For more examples, visit this page.

For XML and JSON-based data, you can do the following:

Don't use YQL (Yahoo Query Language)

For example:

http://developer.yahoo.com/yql/console/?q=select%20*%20from%20yahoo.finance
.quotes%20where%20symbol%20in%20(%22YHOO%22%2C%22AAPL%22%2C%22GOOG%22%2C%22
MSFT%22)%0A%09%09&env=http%3A%2F%2Fdatatables.org%2Falltables.env

2. Use the webservice

For example, to get all stock quotes in XML:

http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote

To get all stock quotes in JSON, just add format=JSON to the end of the URL:

http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json

Alternatives:

  1. Currency API

    • 165+ real time currency rates, including few cryptos. Docs here.
  2. Financial Content API

  3. IEX

  4. Open Exchange Rates

  5. Polygon

  6. XE API

  7. Xignite API

  8. currencylayer API

  9. Other APIs - discussed at programmableWeb

Java: How To Call Non Static Method From Main Method?

Please find answer:

public class Customer {

    public static void main(String[] args) {
        Customer customer=new Customer();
        customer.business();
    }

    public void business(){
        System.out.println("Hi Harry");
    }
}

Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document'

You are allowed to use IDs that start with a digit in your HTML5 documents:

The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.

There are no other restrictions on what form an ID can take; in particular, IDs can consist of just digits, start with a digit, start with an underscore, consist of just punctuation, etc.

But querySelector method uses CSS3 selectors for querying the DOM and CSS3 doesn't support ID selectors that start with a digit:

In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9] and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_); they cannot start with a digit, two hyphens, or a hyphen followed by a digit.

Use a value like b22 for the ID attribute and your code will work.

Since you want to select an element by ID you can also use .getElementById method:

document.getElementById('22')

swift UITableView set rowHeight

yourTableView.rowHeight = UITableViewAutomaticDimension

Try this.

JBoss debugging in Eclipse

You need to define a Remote Java Application in the Eclipse debug configurations:

Open the debug configurations (select project, then open from menu run/debug configurations) Select Remote Java Application in the left tree and press "New" button On the right panel select your web app project and enter 8787 in the port field. Here is a link to a detailed description of this process.

When you start the remote debug configuration Eclipse will attach to the JBoss process. If successful the debug view will show the JBoss threads. There is also a disconnect icon in the toolbar/menu to stop remote debugging.

When to use extern in C++

It is useful when you share a variable between a few modules. You define it in one module, and use extern in the others.

For example:

in file1.cpp:

int global_int = 1;

in file2.cpp:

extern int global_int;
//in some function
cout << "global_int = " << global_int;

What to do about Eclipse's "No repository found containing: ..." error messages?

I am using lubuntu( like ubuntu) and I found that when I install ccs, I used sudo cmd, so some file can't be changed by another user, that's why the problem comes up. So in the place I installed ccs, I run the cmd

sudo chown -R username:groupname * 

with username and groupname are the same as my computer account.

How can I return an empty IEnumerable?

I think the simplest way would be

 return new Friend[0];

The requirements of the return are merely that the method return an object which implements IEnumerable<Friend>. The fact that under different circumstances you return two different kinds of objects is irrelevant, as long as both implement IEnumerable.

Handlebars.js Else If

Handlebars supports {{else if}} blocks as of 3.0.0.

Handlebars v3.0.0 or greater:

{{#if FriendStatus.IsFriend}}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{else if FriendStatus.FriendRequested}}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
{{else}}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
{{/if}}

Prior to Handlebars v3.0.0, however, you will have to either define a helper that handles the branching logic or nest if statements manually:

{{#if FriendStatus.IsFriend}}
  <div class="ui-state-default ui-corner-all" title=".ui-icon-mail-closed"><span class="ui-icon ui-icon-mail-closed"></span></div>
{{else}}
  {{#if FriendStatus.FriendRequested}}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-check"><span class="ui-icon ui-icon-check"></span></div>
  {{else}}
    <div class="ui-state-default ui-corner-all" title=".ui-icon-plusthick"><span class="ui-icon ui-icon-plusthick"></span></div>
  {{/if}}
{{/if}}

How do I set vertical space between list items?

Old question but I think it lacked an answer. I would use an adjacent siblings selector. This way we only write "one" line of CSS and take into consideration the space at the end or beginning, which most of the answers lacks.

li + li {
  margin-top: 10px;
}

How do I add a newline using printf?

Try this:

printf '\n%s\n' 'I want this on a new line!'

That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
      38    142.15  advanced widget

How do I detect if a user is already logged in Firebase?

One another way is to use the same thing what firebase uses.

For example when user logs in, firebase stores below details in local storage. When user comes back to the page, firebase uses the same method to identify if user should be logged in automatically.

enter image description here

ATTN: As this is neither listed or recommended by firebase. You can call this method un-official way of doing this. Which means later if firebase changes their inner working, this method may not work. Or in short. Use at your own risk! :)

How to increase apache timeout directive in .htaccess?

if you have long processing server side code, I don't think it does fall into 404 as you said ("it goes to a webpage is not found error page")

Browser should report request timeout error.

You may do 2 things:

Based on CGI/Server side engine increase timeout there

PHP : http://www.php.net/manual/en/info.configuration.php#ini.max-execution-time - default is 30 seconds

In php.ini:

max_execution_time 60

Increase apache timeout - default is 300 (in version 2.4 it is 60).

In your httpd.conf (in server config or vhost config)

TimeOut 600

Note that first setting allows your PHP script to run longer, it will not interferre with network timeout.

Second setting modify maximum amount of time the server will wait for certain events before failing a request

Sorry, I'm not sure if you are using PHP as server side processing, but if you provide more info I will be more accurate.

How do I go about adding an image into a java project with eclipse?

If you still have problems with Eclipse finding your files, you might try the following:

  1. Verify that the file exists according to the current execution environment by using the java.io.File class to get a canonical path format and verify that (a) the file exists and (b) what the canonical path is.
  2. Verify the default working directory by printing the following in your main:

        System.out.println("Working dir:  " + System.getProperty("user.dir"));
    

For (1) above, I put the following debugging code around the specific file I was trying to access:

            File imageFile = new File(source);
            System.out.println("Canonical path of target image: " + imageFile.getCanonicalPath());
            if (!imageFile.exists()) {
                System.out.println("file " + imageFile + " does not exist");
            }
            image = ImageIO.read(imageFile);                

For whatever reason, I ended up ignoring most of the other posts telling me to put the image files in "src" or some other variant, as I verified that the system was looking at the root of the Eclipse project directory hierarchy (e.g., $HOME/workspace/myProject).

Having the images in src/ (which is automatically copied to bin/) didn't do the trick on Eclipse Luna.

Printing out a linked list using toString

A very simple solution is to override the toString() method in the Node. Then, you can call print by passing LinkedList's head. You don't need to implement any kind of loop.

Code:

public class LinkedListNode {
    ...

    //New
    @Override
    public String toString() {
        return String.format("Node(%d, next = %s)", data, next);
    }
} 


public class LinkedList {

    public static void main(String[] args) {

        LinkedList l = new LinkedList();
        l.insertFront(0);
        l.insertFront(1);
        l.insertFront(2);
        l.insertFront(3);

        //New
        System.out.println(l.head);
    }
}

Error in Eclipse: "The project cannot be built until build path errors are resolved"

  1. Right click your Project > Properties > Java Build Path > Libraries

  2. Remove the file with red "X" (something like JRE...)

  3. Add Library

That's how I solved my problem.

Conda activate not working?

As of conda 4.4, the command

conda activate <envname>

is the same on all platforms. The procedure to add conda to the PATH environment variable for non-Windows platforms (on Windows you should use the Anaconda Prompt), as well as the change in environment activation procedure, is detailed in the release notes for conda 4.4.0.


For conda versions older than 4.4, command is either

source activate <envname>

on Linux and macOS or

activate <envname>

on Windows. You need to remove the conda.

How to clone object in C++ ? Or Is there another solution?

If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.

If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.

Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.

SQL Bulk Insert with FIRSTROW parameter skips the following line

I don't think you can skip rows in a different format with BULK INSERT/BCP.

When I run this:

TRUNCATE TABLE so1029384

BULK INSERT so1029384
FROM 'C:\Data\test\so1029384.txt'
WITH
(
--FIRSTROW = 2,
FIELDTERMINATOR= '|',
ROWTERMINATOR = '\n'
)

SELECT * FROM so1029384

I get:

col1                                               col2                                               col3
-------------------------------------------------- -------------------------------------------------- --------------------------------------------------
***A NICE HEADER HERE***
0000001234               SSNV                                               00013893-03JUN09
0000005678                                         ABCD                                               00013893-03JUN09
0000009112                                         0000                                               00013893-03JUN09
0000009112                                         0000                                               00013893-03JUN09

It looks like it requires the '|' even in the header data, because it reads up to that into the first column - swallowing up a newline into the first column. Obviously if you include a field terminator parameter, it expects that every row MUST have one.

You could strip the row with a pre-processing step. Another possibility is to select only complete rows, then process them (exluding the header). Or use a tool which can handle this, like SSIS.

What is the best (and safest) way to merge a Git branch into master?

Old thread, but I haven't found my way of doing it. It might be valuable for someone who works with rebase and wants to merge all the commits from a (feature) branch on top of master. If there is a conflict on the way, you can resolve them for every commit. You keep full control during the process and can abort any time.

Get Master and Branch up-to-date:

git checkout master
git pull --rebase origin master
git checkout <branch_name>
git pull --rebase origin <branch_name>

Merge Branch on top of Master:

git checkout <branch_name>
git rebase master

Optional: If you run into Conflicts during the Rebase:

First, resolve conflict in file. Then:

git add .
git rebase --continue

Push your rebased Branch:

git push origin <branch_name>

Now you've got two options:

  • A) Create a PR (e.g. on GitHub) and merge it there via the UI
  • B) Go back on the command line and merge the branch into master
git checkout master
git merge --no-ff <branch_name>
git push origin master

Done.

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

AFNetworking Post Request

NSURL *URL = [NSURL URLWithString:@"url"];


AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"prefix":@"param",@"prefix":@"param",@"prefix":@"param"};
[manager POST:URL.absoluteString parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    self.arrayFromPost = [responseObject objectForKey:@"data"];
    // values in foreach loop


    NSLog(@"POst send: %@",_arrayFromPost);
} failure:^(NSURLSessionTask *operation, NSError *error) {


    NSLog(@"Error: %@", error);
}];

Does delete on a pointer to a subclass call the base class destructor?

You should delete A yourself in the destructor of B.

Forwarding port 80 to 8080 using NGINX

This is how you can achieve this.

upstream {
    nodeapp 127.0.0.1:8080;
}

server {
    listen 80;

    # The host name to respond to
    server_name cdn.domain.com;

    location /(.*) {
        proxy_pass http://nodeapp/$1$is_args$args;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header X-Forwarded-For $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Real-Port $server_port;
        proxy_set_header X-Real-Scheme $scheme;
    }
}

You can also use this configuration to load balance amongst multiple Node processes like so:

upstream {
    nodeapp 127.0.0.1:8081;
    nodeapp 127.0.0.1:8082;
    nodeapp 127.0.0.1:8083;
}

Where you are running your node server on ports 8081, 8082 and 8083 in separate processes. Nginx will easily load balance your traffic amongst these server processes.

how to make a new line in a jupyter markdown cell

The double space generally works well. However, sometimes the lacking newline in the PDF still occurs to me when using four pound sign sub titles #### in Jupyter Notebook, as the next paragraph is put into the subtitle as a single paragraph. No amount of double spaces and returns fixed this, until I created a notebook copy 'v. PDF' and started using a single backslash '\' which also indents the next paragraph nicely:

#### 1.1 My Subtitle  \

1.1 My Subtitle
    Next paragraph text.

An alternative to this, is to upgrade the level of your four # titles to three # titles, etc. up the title chain, which will remove the next paragraph indent and format the indent of the title itself (#### My Subtitle ---> ### My Subtitle).

### My Subtitle


1.1 My Subtitle

Next paragraph text.

Binding a generic list to a repeater - ASP.NET

You may want to create a subRepeater.

<asp:Repeater ID="SubRepeater" runat="server" DataSource='<%# Eval("Fields") %>'>
  <ItemTemplate>
    <span><%# Eval("Name") %></span>
  </ItemTemplate>
</asp:Repeater>

You can also cast your fields

<%# ((ArrayFields)Container.DataItem).Fields[0].Name %>

Finally you could do a little CSV Function and write out your fields with a function

<%# GetAsCsv(((ArrayFields)Container.DataItem).Fields) %>

public string GetAsCsv(IEnumerable<Fields> fields)
{
  var builder = new StringBuilder();
  foreach(var f in fields)
  {
    builder.Append(f);
    builder.Append(",");
  }
  builder.Remove(builder.Length - 1);
  return builder.ToString();
}

How to add a reference programmatically

Here is how to get the Guid's programmatically! You can then use these guids/filepaths with an above answer to add the reference!

Reference: http://www.vbaexpress.com/kb/getarticle.php?kb_id=278

Sub ListReferencePaths()
'Lists path and GUID (Globally Unique Identifier) for each referenced library.
'Select a reference in Tools > References, then run this code to get GUID etc.
    Dim rw As Long, ref
    With ThisWorkbook.Sheets(1)
        .Cells.Clear
        rw = 1
        .Range("A" & rw & ":D" & rw) = Array("Reference","Version","GUID","Path")
        For Each ref In ThisWorkbook.VBProject.References
            rw = rw + 1
            .Range("A" & rw & ":D" & rw) = Array(ref.Description, _
                   "v." & ref.Major & "." & ref.Minor, ref.GUID, ref.FullPath)
        Next ref
        .Range("A:D").Columns.AutoFit
    End With
End Sub

Here is the same code but printing to the terminal if you don't want to dedicate a worksheet to the output.

Sub ListReferencePaths() 
 'Macro purpose:  To determine full path and Globally Unique Identifier (GUID)
 'to each referenced library.  Select the reference in the Tools\References
 'window, then run this code to get the information on the reference's library

On Error Resume Next 
Dim i As Long 

Debug.Print "Reference name" & " | " & "Full path to reference" & " | " & "Reference GUID" 

For i = 1 To ThisWorkbook.VBProject.References.Count 
  With ThisWorkbook.VBProject.References(i) 
    Debug.Print .Name & " | " & .FullPath  & " | " & .GUID 
  End With 
Next i 
On Error GoTo 0 
End Sub 

Reference list item by index within Django template?

@jennifer06262016, you can definitely add another filter to return the objects inside a django Queryset.

@register.filter 
def get_item(Queryset):
    return Queryset.your_item_key

In that case, you would type something like this {{ Queryset|index:x|get_item }} into your template to access some dictionary object. It works for me.

script to map network drive

Does this not work (assuming "ROUTERNAME" is the user name the router expects)?

net use Z: "\\10.0.1.1\DRIVENAME" /user:"ROUTERNAME" "PW"

Alternatively, you can use use a small VBScript:

Option Explicit
Dim u, p, s, l
Dim Network: Set Network= CreateObject("WScript.Network")

l = "Z:"
s = "\\10.0.1.1\DRIVENAME"

u = "ROUTERNAME"
p = "PW"

Network.MapNetworkDrive l, s, False, u, p

Find files with size in Unix

find . -size +10000k -exec ls -sd {} +

If your version of find won't accept the + notation (which acts rather like xargs does), then you might use (GNU find and xargs, so find probably supports + anyway):

find . -size +10000k -print0 | xargs -0 ls -sd

or you might replace the + with \; (and live with the relative inefficiency of this), or you might live with problems caused by spaces in names and use the portable:

find . -size +10000k -print | xargs ls -sd

The -d on the ls commands ensures that if a directory is ever found (unlikely, but...), then the directory information will be printed, not the files in the directory. And, if you're looking for files more than 1 MB (as a now-deleted comment suggested), you need to adjust the +10000k to 1000k or maybe +1024k, or +2048 (for 512-byte blocks, the default unit for -size). This will list the size and then the file name. You could avoid the need for -d by adding -type f to the find command, of course.

Waiting until two async blocks are executed before starting another block

I know you asked about GCD, but if you wanted, NSOperationQueue also handles this sort of stuff really gracefully, e.g.:

NSOperationQueue *queue = [[NSOperationQueue alloc] init];

NSOperation *completionOperation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"Starting 3");
}];

NSOperation *operation;

operation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"Starting 1");
    sleep(7);
    NSLog(@"Finishing 1");
}];

[completionOperation addDependency:operation];
[queue addOperation:operation];

operation = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"Starting 2");
    sleep(5);
    NSLog(@"Finishing 2");
}];

[completionOperation addDependency:operation];
[queue addOperation:operation];

[queue addOperation:completionOperation];

Finding the second highest number in array

Its very easy to get the 2nd highest element in an array. I've shows below for all your reference. Hope this will be helpful.

import java.util.Arrays;

public class Testdemo {
    public static void main(String[] args) {
    int[] numbers = {1, 5, 4, 2, 8, 1, 1, 6, 7, 8, 9};
    Arrays.sort(numbers);
    System.out.println("The second Higest Element :" + numbers[numbers.length-2]);
    }
}

Ans - The second Higest Element :8

Nullable types: better way to check for null or zero in c#

class Item{  
 bool IsNullOrZero{ get{return ((this.Rate ?? 0) == 0);}}
}

How to backup a local Git repository?

You can backup the git repo with git-copy . git-copy saved new project as a bare repo, it means minimum storage cost.

git copy /path/to/project /backup/project.backup

Then you can restore your project with git clone

git clone /backup/project.backup project

Using Panel or PlaceHolder

PlaceHolder control

Use the PlaceHolder control as a container to store server controls that are dynamically added to the Web page. The PlaceHolder control does not produce any visible output and is used only as a container for other controls on the Web page. You can use the Control.Controls collection to add, insert, or remove a control in the PlaceHolder control.

Panel control

The Panel control is a container for other controls. It is especially useful when you want to generate controls programmatically, hide/show a group of controls, or localize a group of controls.

The Direction property is useful for localizing a Panel control's content to display text for languages that are written from right to left, such as Arabic or Hebrew.

The Panel control provides several properties that allow you to customize the behavior and display of its contents. Use the BackImageUrl property to display a custom image for the Panel control. Use the ScrollBars property to specify scroll bars for the control.

Small differences when rendering HTML: a PlaceHolder control will render nothing, but Panel control will render as a <div>.

More information at ASP.NET Forums

In Jenkins, how to checkout a project into a specific directory (using GIT)

Find repoName from the url, and then checkout to the specified directory.

String url = 'https://github.com/foo/bar.git';
String[] res = url.split('/');
String repoName = res[res.length-1];
if (repoName.endsWith('.git')) repoName=repoName.substring(0, repoName.length()-4);

checkout([
  $class: 'GitSCM', 
  branches: [[name: 'refs/heads/'+env.BRANCH_NAME]],
  doGenerateSubmoduleConfigurations: false,
  extensions: [
    [$class: 'RelativeTargetDirectory', relativeTargetDir: repoName],
    [$class: 'GitLFSPull'],
    [$class: 'CheckoutOption', timeout: 20],
    [$class: 'CloneOption',
        depth: 3,
        noTags: false,
        reference: '/other/optional/local/reference/clone',
        shallow: true,
        timeout: 120],
    [$class: 'SubmoduleOption', depth: 5, disableSubmodules: false, parentCredentials: true, recursiveSubmodules: true, reference: '', shallow: true, trackingSubmodules: true]
  ],
  submoduleCfg: [],
  userRemoteConfigs: [
    [credentialsId: 'foobar',
    url: url]
  ]
])

how do I give a div a responsive height

For the height of a div to be responsive, it must be inside a parent element with a defined height to derive it's relative height from.

If you set the height of the container holding the image and text box on the right, you can subsequently set the heights of its two children to be something like 75% and 25%.

However, this will get a bit tricky when the site layout gets narrower and things will get wonky. Try setting the padding on .contentBg to something like 5.5%.

My suggestion is to use Media Queries to tweak the padding at different screen sizes, then bump everything into a single column when appropriate.

sql how to cast a select query

You just CAST() this way

SELECT cast(yourNumber as varchar(10))
FROM yourTable

Then if you want to JOIN based on it, you can use:

SELECT *
FROM yourTable t1
INNER JOIN yourOtherTable t2
    on cast(t1.yourNumber as varchar(10)) = t2.yourString

Java Spring Boot: How to map my app root (“/”) to index.html?

If you use the latest spring-boot 2.1.6.RELEASE with a simple @RestController annotation then you do not need to do anything, just add your index.html file under the resources/static folder:

project
  +-- src
      +-- main
          +-- resources
              +-- static
                  +-- index.html

Then hit the URL http://localhost:8080. Hope that it will help everyone.

How do I auto size columns through the Excel interop objects?

This method opens already created excel file, Autofit all columns of all sheets based on 3rd Row. As you can see Range is selected From "A3 to K3" in excel.

 public static void AutoFitExcelSheets()
    {
        Microsoft.Office.Interop.Excel.Application _excel = null;
        Microsoft.Office.Interop.Excel.Workbook excelWorkbook = null;
        try
        {
            string ExcelPath = ApplicationData.PATH_EXCEL_FILE;
            _excel = new Microsoft.Office.Interop.Excel.Application();
            _excel.Visible = false;
            object readOnly = false;
            object isVisible = true;
            object missing = System.Reflection.Missing.Value;

            excelWorkbook = _excel.Workbooks.Open(ExcelPath,
                   0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "",
                   true, false, 0, true, false, false);
            Microsoft.Office.Interop.Excel.Sheets excelSheets = excelWorkbook.Worksheets;
            foreach (Microsoft.Office.Interop.Excel.Worksheet currentSheet in excelSheets)
            {
                string Name = currentSheet.Name;
                Microsoft.Office.Interop.Excel.Worksheet excelWorksheet = (Microsoft.Office.Interop.Excel.Worksheet)excelSheets.get_Item(Name);
                Microsoft.Office.Interop.Excel.Range excelCells =
(Microsoft.Office.Interop.Excel.Range)excelWorksheet.get_Range("A3", "K3");
                excelCells.Columns.AutoFit();
            }
        }
        catch (Exception ex)
        {
            ProjectLog.AddError("EXCEL ERROR: Can not AutoFit: " + ex.Message);
        }
        finally
        {
            excelWorkbook.Close(true, Type.Missing, Type.Missing);
            GC.Collect();
            GC.WaitForPendingFinalizers();
            releaseObject(excelWorkbook);
            releaseObject(_excel);
        }
    }

How to add image in a TextView text?

This might Help You

  SpannableStringBuilder ssBuilder;

        ssBuilder = new SpannableStringBuilder(" ");
        // working code ImageSpan image = new ImageSpan(textView.getContext(), R.drawable.image);
        Drawable image = ContextCompat.getDrawable(textView.getContext(), R.drawable.image);
        float scale = textView.getContext().getResources().getDisplayMetrics().density;
        int width = (int) (12 * scale + 0.5f);
        int height = (int) (18 * scale + 0.5f);
        image.setBounds(0, 0, width, height);
        ImageSpan imageSpan = new ImageSpan(image, ImageSpan.ALIGN_BASELINE);
        ssBuilder.setSpan(
                imageSpan, // Span to add
                0, // Start of the span (inclusive)
                1, // End of the span (exclusive)
                Spanned.SPAN_INCLUSIVE_EXCLUSIVE);// Do not extend the span when text add later

        ssBuilder.append(" " + text);
        ssBuilder = new SpannableStringBuilder(text);
        textView.setText(ssBuilder);

What is a deadlock?

Deadlock is a situation occurs when there is less number of available resources as it is requested by the different process. It means that when the number of available resources become less than it is requested by the user then at that time the process goes in waiting condition .Some times waiting increases more and there is not any chance to check out the problem of lackness of resources then this situation is known as deadlock . Actually, deadlock is a major problem for us and it occurs only in multitasking operating system .deadlock can not occur in single tasking operating system because all the resources are present only for that task which is currently running......

How to quickly edit values in table in SQL Server Management Studio?

In Mgmt Studio, when you are editing the top 200, you can view the SQL pane - either by right clicking in the grid and choosing Pane->SQL or by the button in the upper left. This will allow you to write a custom query to drill down to the row(s) you want to edit.

But ultimately mgmt studio isn't a data entry/update tool which is why this is a little cumbersome.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

Was facing the same issue multiple times and I have 2 solutions:

Solution 1: Add surefire plugin reference to pom.xml. Watch that you have all nodes! In my IDEs auto import version was missing!!!

<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>3.0.0-M3</version>
    </plugin>
</plugins>

Solution 2: My IDE added wrong import to the start of the file.

IDE added

import org.junit.Test;

I had to replace it with

import org.junit.jupiter.api.Test;

JQuery Find #ID, RemoveClass and AddClass

jQuery('#testID2').find('.test2').replaceWith('.test3');

Semantically, you are selecting the element with the ID testID2, then you are looking for any descendent elements with the class test2 (does not exist) and then you are replacing that element with another element (elements anywhere in the page with the class test3) that also do not exist.

You need to do this:

jQuery('#testID2').addClass('test3').removeClass('test2');

This selects the element with the ID testID2, then adds the class test3 to it. Last, it removes the class test2 from that element.

AttributeError: can't set attribute in python

namedtuples are immutable, just like standard tuples. You have two choices:

  1. Use a different data structure, e.g. a class (or just a dictionary); or
  2. Instead of updating the structure, replace it.

The former would look like:

class N(object):

    def __init__(self, ind, set, v):
        self.ind = ind
        self.set = set
        self.v = v

And the latter:

item = items[node.ind]
items[node.ind] = N(item.ind, item.set, node.v)

Edit: if you want the latter, Ignacio's answer does the same thing more neatly using baked-in functionality.

AppStore - App status is ready for sale, but not in app store

I had "ready for sale" status for 1 week and app still wasn't visible in store. I "changed" the pricing (from free to free starting today) like KlimczakM suggested in one of comments above. Also, I changed promotional text and saved changes. After less than half of hour app was in the store.

Sql Server string to date conversion

In SQL Server Denali, you will be able to do something that approaches what you're looking for. But you still can't just pass any arbitrarily defined wacky date string and expect SQL Server to accommodate. Here is one example using something you posted in your own answer. The FORMAT() function and can also accept locales as an optional argument - it is based on .Net's format, so most if not all of the token formats you'd expect to see will be there.

DECLARE @d DATETIME = '2008-10-13 18:45:19';

-- returns Oct-13/2008 18:45:19:
SELECT FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss');

-- returns NULL if the conversion fails:
SELECT TRY_PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);

-- returns an error if the conversion fails:
SELECT PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);

I strongly encourage you to take more control and sanitize your date inputs. The days of letting people type dates using whatever format they want into a freetext form field should be way behind us by now. If someone enters 8/9/2011 is that August 9th or September 8th? If you make them pick a date on a calendar control, then the app can control the format. No matter how much you try to predict your users' behavior, they'll always figure out a dumber way to enter a date that you didn't plan for.

Until Denali, though, I think that @Ovidiu has the best advice so far... this can be made fairly trivial by implementing your own CLR function. Then you can write a case/switch for as many wacky non-standard formats as you want.


UPDATE for @dhergert:

SELECT TRY_PARSE('10/15/2008 10:06:32 PM' AS DATETIME USING 'en-us');
SELECT TRY_PARSE('15/10/2008 10:06:32 PM' AS DATETIME USING 'en-gb');

Results:

2008-10-15 22:06:32.000
2008-10-15 22:06:32.000

You still need to have that other crucial piece of information first. You can't use native T-SQL to determine whether 6/9/2012 is June 9th or September 6th.

How To Convert A Number To an ASCII Character?

C# represents a character in UTF-16 coding rather than ASCII. Therefore converting a integer to character do not make any difference for A-Z and a-z. But I was working with ASCII Codes besides alphabets and number which did not work for me as system uses UTF-16 code. Therefore I browsed UTF-16 code for all UTF-16 character. Here is the module :

void utfchars()
{
 int i, a, b, x;
 ConsoleKeyInfo z;
  do
  {
   a = 0; b = 0; Console.Clear();
    for (i = 1; i <= 10000; i++)
    {
     if (b == 20)
     {
      b = 0;
      a = a + 1;
     }
    Console.SetCursorPosition((a * 15) + 1, b + 1);
    Console.Write("{0} == {1}", i, (char)i);
   b = b+1;
   if (i % 100 == 0)
  {
 Console.Write("\n\t\t\tPress any key to continue {0}", b);
 a = 0; b = 0;
 Console.ReadKey(true); Console.Clear();
 }
}
Console.Write("\n\n\n\n\n\n\n\t\t\tPress any key to Repeat and E to exit");
z = Console.ReadKey();
if (z.KeyChar == 'e' || z.KeyChar == 'E') Environment.Exit(0);
} while (1 == 1);
}

CSS-moving text from left to right

You could simply use CSS animated text generator. There are pre-created templates already

Using Java generics for JPA findAll() query with WHERE clause

I found this page very useful

https://code.google.com/p/spring-finance-manager/source/browse/trunk/src/main/java/net/stsmedia/financemanager/dao/GenericDAOWithJPA.java?r=2

public abstract class GenericDAOWithJPA<T, ID extends Serializable> {

    private Class<T> persistentClass;

    //This you might want to get injected by the container
    protected EntityManager entityManager;

    @SuppressWarnings("unchecked")
    public GenericDAOWithJPA() {
            this.persistentClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public List<T> findAll() {
            return entityManager.createQuery("Select t from " + persistentClass.getSimpleName() + " t").getResultList();
    }
}

JSON to PHP Array using file_get_contents

The JSON sample you provided is not valid. Check it online with this JSON Validator http://jsonlint.com/. You need to remove the extra comma on line 59.

One you have valid json you can use this code to convert it to an array.

json_decode($json, true);

Array
(
    [bpath] => http://www.sampledomain.com/
    [clist] => Array
        (
            [0] => Array
                (
                    [cid] => 11
                    [display_type] => grid
                    [ctitle] => abc
                    [acount] => 71
                    [alist] => Array
                        (
                            [0] => Array
                                (
                                    [aid] => 6865
                                    [adate] => 2 Hours ago
                                    [atitle] => test
                                    [adesc] => test desc
                                    [aimg] => 
                                    [aurl] => ?nid=6865
                                    [weburl] => news.php?nid=6865
                                    [cmtcount] => 0
                                )

                            [1] => Array
                                (
                                    [aid] => 6857
                                    [adate] => 20 Hours ago
                                    [atitle] => test1
                                    [adesc] => test desc1
                                    [aimg] => 
                                    [aurl] => ?nid=6857
                                    [weburl] => news.php?nid=6857
                                    [cmtcount] => 0
                                )

                        )

                )

            [1] => Array
                (
                    [cid] => 1
                    [display_type] => grid
                    [ctitle] => test1
                    [acount] => 2354
                    [alist] => Array
                        (
                            [0] => Array
                                (
                                    [aid] => 6851
                                    [adate] => 1 Days ago
                                    [atitle] => test123
                                    [adesc] => test123 desc
                                    [aimg] => 
                                    [aurl] => ?nid=6851
                                    [weburl] => news.php?nid=6851
                                    [cmtcount] => 7
                                )

                            [1] => Array
                                (
                                    [aid] => 6847
                                    [adate] => 2 Days ago
                                    [atitle] => test12345
                                    [adesc] => test12345 desc
                                    [aimg] => 
                                    [aurl] => ?nid=6847
                                    [weburl] => news.php?nid=6847
                                    [cmtcount] => 7
                                )

                        )

                )

        )

)

jQuery UI Dialog - missing close icon

I know this question is old but I just had this issue with jquery-ui v1.12.0.

Short Answer Make sure you have a folder called Images in the same place you have jquery-ui.min.css. The images folder must contains the images found with a fresh download of the jquery-ui

Long answer

My issue is that I am using gulp to merge all of my css files into a single file. When I do that, I am changing the location of the jquery-ui.min.css. The css code for the dialog expects a folder called Images in the same directory and inside this folder it expects default icons. since gulp was not copying the images into the new destination it was not showing the x icon.

Execute command without keeping it in history

You can start your session with

export HISTFILE=/dev/null ;history -d $(history 1)

then proceed with your sneaky doings. Setting the histfile to /dev/null will be logged to the history file, yet this entry will be readily deleted and no traces (at least in the history file) will be shown.

Also, this is non-permanent.

The difference between sys.stdout.write and print?

Are there situations in which sys.stdout.write() is preferable to print?

I have found that stdout works better than print in a multithreading situation. I use a queue (FIFO) to store the lines to print and I hold all threads before the print line until my print queue is empty. Even so, using print I sometimes lose the final \n on the debug I/O (using the Wing Pro IDE).

When I use std.out with \n in the string, the debug I/O formats correctly and the \n's are accurately displayed.

Fail to create Android virtual Device, "No system image installed for this Target"

If you use Android Studio .Open the SDK-Manager, checked "Show Package Details" you will find out "Android Wear ARM EABI v7a System Image" download it , success !

Sort a List of Object in VB.NET

If you need a custom string sort, you can create a function that returns a number based on the order you specify.

For example, I had pictures that I wanted to sort based on being front side or clasp. So I did the following:

Private Function sortpictures(s As String) As Integer
    If Regex.IsMatch(s, "FRONT") Then
        Return 0
    ElseIf Regex.IsMatch(s, "SIDE") Then
        Return 1
    ElseIf Regex.IsMatch(s, "CLASP") Then
        Return 2
    Else
        Return 3
    End If
End Function

Then I call the sort function like this:

list.Sort(Function(elA As String, elB As String)
                  Return sortpictures(elA).CompareTo(sortpictures(elB))
              End Function)

How to get the name of a class without the package?

If using a StackTraceElement, use:

String fullClassName = stackTraceElement.getClassName();
String simpleClassName = fullClassName.substring(fullClassName.lastIndexOf('.') + 1);

System.out.println(simpleClassName);

Uncaught TypeError: Cannot read property 'length' of undefined

You are accessing an object that is not defined.

The solution is check for null or undefined (to see whether the object exists) and only then iterate.

Cannot open backup device. Operating System error 5

I had a similar issue. I added write permissions to the .bak file itself, and my folder that I was writing the backup to for the NETWORK SERVICE user. To add permissions just right-click what file/directory you want to alter, select the security tab, and add the appropriate users/permissions there.

sql: check if entry in table A exists in table B

Or if "NOT EXISTS" are not implemented

SELECT *
FROM   B
WHERE (SELECT count(*)  FROM   A WHERE  A.ID = B.ID) < 1

How to run composer from anywhere?

You can do a global installation (archived guide):

Since Composer works with the current working directory it is possible to install it in a system-wide way.

  1. Change into a directory in your path like cd /usr/local/bin
  2. Get Composer curl -sS https://getcomposer.org/installer | php
  3. Make the phar executable chmod a+x composer.phar
  4. Change into a project directory cd /path/to/my/project
  5. Use Composer as you normally would composer.phar install
  6. Optionally you can rename the composer.phar to composer to make it easier

Update: Sometimes you can't or don't want to download at /usr/local/bin (some have experienced user permissions issues or restricted access), in this case, you can try this

  1. Open terminal
  2. curl -sS http://getcomposer.org/installer | php -- --filename=composer
  3. chmod a+x composer
  4. sudo mv composer /usr/local/bin/composer

Update 2: For Windows 10 and PHP 7 I recommend this tutorial (archived). Personally, I installed Visual C++ Redistributable for Visual Studio 2017 x64 before PHP 7.3 VC15 x64 Non Thread Safe version (check which versions of both in the PHP for Windows page, side menu). Read carefully and maybe the enable-extensions section could differ (extension=curl instead of extension=php_curl.dll). Works like a charm, good luck!

You don't have write permissions for the /var/lib/gems/2.3.0 directory

If you want to use the distribution Ruby instead of rb-env/rvm, you can set up a GEM_HOME for your current user. Start by creating a directory to store the Ruby gems for your user:

$ mkdir ~/.ruby

Then update your shell to use that directory for GEM_HOME and to update your PATH variable to include the Ruby gem bin directory.

$ echo 'export GEM_HOME=~/.ruby/' >> ~/.bashrc
$ echo 'export PATH="$PATH:~/.ruby/bin"' >> ~/.bashrc
$ source ~/.bashrc

(That last line will reload the environment variables in your current shell.)

Now you should be able to install Ruby gems under your user using the gem command. I was able to get this working with Ruby 2.5.1 under Ubuntu 18.04. If you are using a shell that is not Bash, then you will need to edit the startup script for that shell instead of bashrc.

How to escape special characters of a string with single backslashes

We could use built-in function repr() or string interpolation fr'{}' escape all backwardslashs \ in Python 3.7.*

repr('my_string') or fr'{my_string}'

Check the Link: https://docs.python.org/3/library/functions.html#repr

How to run a Command Prompt command with Visual Basic code?

You need to use CreateProcess [ http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx ]

For ex:

LPTSTR szCmdline[] = _tcsdup(TEXT("\"C:\Program Files\MyApp\" -L -S")); CreateProcess(NULL, szCmdline, /.../);

Hover and Active only when not disabled

In sass (scss):

 button {
  color: white;
  cursor: pointer;
  border-radius: 4px;

  &:disabled{
    opacity: 0.4;

    &:hover{
      opacity: 0.4;  //this is what you want
    }
  }

  &:hover{
    opacity: 0.9;
  }
}

How to convert a String to Bytearray

The best solution I've come up with at on the spot (though most likely crude) would be:

String.prototype.getBytes = function() {
    var bytes = [];
    for (var i = 0; i < this.length; i++) {
        var charCode = this.charCodeAt(i);
        var cLen = Math.ceil(Math.log(charCode)/Math.log(256));
        for (var j = 0; j < cLen; j++) {
            bytes.push((charCode << (j*8)) & 0xFF);
        }
    }
    return bytes;
}

Though I notice this question has been here for over a year.

get one item from an array of name,value JSON

I know this question is old, but no one has mentioned a native solution yet. If you're not trying to support archaic browsers (which you shouldn't be at this point), you can use array.filter:

_x000D_
_x000D_
var arr = [];_x000D_
arr.push({name:"k1", value:"abc"});_x000D_
arr.push({name:"k2", value:"hi"});_x000D_
arr.push({name:"k3", value:"oa"});_x000D_
_x000D_
var found = arr.filter(function(item) { return item.name === 'k1'; });_x000D_
_x000D_
console.log('found', found[0]);
_x000D_
Check the console.
_x000D_
_x000D_
_x000D_

You can see a list of supported browsers here.

In the future with ES6, you'll be able to use array.find.

What is the easiest way to remove the first character from a string?

Similar to Pablo's answer above, but a shade cleaner :

str[1..-1]

Will return the array from 1 to the last character.

'Hello World'[1..-1]
 => "ello World"