Programs & Examples On #Webforms view engine

Git push/clone to new server

remote server> cd /home/ec2-user
remote server> git init --bare --shared  test
add ssh pub key to remote server
local> git remote add aws ssh://ec2-user@<hostorip>:/home/ec2-user/dev/test
local> git push aws master

How do I make an HTML button not reload the page

Use either the <button> element or use an <input type="button"/>.

Run function in script from command line (Node JS)

Sometimes you want to run a function via CLI, sometimes you want to require it from another module. Here's how to do both.

// file to run
const runMe = () => {}
if (require.main === module) {
  runMe()
} 
module.exports = runMe

How do I reset a sequence in Oracle?

In my project, once it happened that someone manually entered the records without using sequence, hence I have to reset sequence value manually, for which I wrote below sql code snippet:

declare
max_db_value number(10,0);
cur_seq_value number(10,0);
counter number(10,0);
difference number(10,0);
dummy_number number(10);

begin

-- enter table name here
select max(id) into max_db_value from persons;
-- enter sequence name here
select last_number into cur_seq_value from user_sequences where  sequence_name = 'SEQ_PERSONS';

difference  := max_db_value - cur_seq_value;

 for counter in 1..difference
 loop
    -- change sequence name here as well
    select SEQ_PERSONS.nextval into dummy_number from dual;
 end loop;
end;

Please note, the above code will work if the sequence is lagging.

How to pass extra variables in URL with WordPress

Since this is a frequently visited post i thought to post my solution in case it helps anyone. In WordPress along with using query vars you can change permalinks too like this

www.example.com?c=123 to www.example.com/c/123

For this you have to add these lines of code in functions.php or your plugin base file.

From shankhan's anwer

add_filter( 'query_vars', 'addnew_query_vars', 10, 1 );
function addnew_query_vars($vars)
{   
    $vars[] = 'c'; // c is the name of variable you want to add       
    return $vars;
}

And additionally this snipped to add custom rewriting rules.

function custom_rewrite_basic() 
{
    add_rewrite_rule('^c/([0-9]+)/?', '?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');

For the case where you need to add rewrite rules for a specifc page you can use that page slug to write a rewrite rule for that specific page. Like in the question OP has asked about

www.example.com/news?c=123 to www.example.com/news/123

We can change it to the desired behaviour by adding a little modification to our previous function.

function custom_rewrite_basic() 
{
    add_rewrite_rule('^news/([0-9]+)/?', 'news?c=$1', 'top');
}
add_action('init', 'custom_rewrite_basic');

Hoping that it becomes useful for someone.

Error message "Strict standards: Only variables should be passed by reference"

$instance->find() returns a reference to a variable.

You get the report when you are trying to use this reference as an argument to a function, without storing it in a variable first.

This helps preventing memory leaks and will probably become an error in the next PHP versions.

Your second code block would throw an error if it wrote like (note the & in the function signature):

function &get_arr(){
    return array(1, 2);
}
$el = array_shift(get_arr());

So a quick (and not so nice) fix would be:

$el = array_shift($tmp = $instance->find(..));

Basically, you do an assignment to a temporary variable first and send the variable as an argument.

Get Enum from Description attribute

The solution works good except if you have a Web Service.

You would need to do the Following as the Description Attribute is not serializable.

[DataContract]
public enum ControlSelectionType
{
    [EnumMember(Value = "Not Applicable")]
    NotApplicable = 1,
    [EnumMember(Value = "Single Select Radio Buttons")]
    SingleSelectRadioButtons = 2,
    [EnumMember(Value = "Completely Different Display Text")]
    SingleSelectDropDownList = 3,
}

public static string GetDescriptionFromEnumValue(Enum value)
{
        EnumMemberAttribute attribute = value.GetType()
            .GetField(value.ToString())
            .GetCustomAttributes(typeof(EnumMemberAttribute), false)
            .SingleOrDefault() as EnumMemberAttribute;
        return attribute == null ? value.ToString() : attribute.Value;
}

ReactJS - Get Height of an element

Following is an up to date ES6 example using a ref.

Remember that we have to use a React class component since we need to access the Lifecycle method componentDidMount() because we can only determine the height of an element after it is rendered in the DOM.

import React, {Component} from 'react'
import {render} from 'react-dom'

class DivSize extends Component {

  constructor(props) {
    super(props)

    this.state = {
      height: 0
    }
  }

  componentDidMount() {
    const height = this.divElement.clientHeight;
    this.setState({ height });
  }

  render() {
    return (
      <div 
        className="test"
        ref={ (divElement) => { this.divElement = divElement } }
      >
        Size: <b>{this.state.height}px</b> but it should be 18px after the render
      </div>
    )
  }
}

render(<DivSize />, document.querySelector('#container'))

You can find the running example here: https://codepen.io/bassgang/pen/povzjKw

How can I set a custom date time format in Oracle SQL Developer?

With Oracle SQL Developer 3.2.20.09, i managed to set the custom format for the type DATE this way :

In : Tools > Preferences > Database > NLS

Or : Outils > Préférences > Base de donées > NLS

YYYY-MM-DD HH24:MI:SS

Settings Menu screenshot

Note that the following format does not worked for me :

DD-MON-RR HH24:MI:SS

As a result, it keeps the default format, without any error.

How do I remove lines between ListViews on Android?

Set divider to null:

JAVA

  listview_id.setDivider(null);

XML

<ListView 
  android:id="@+id/listview"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:divider="@null"
  />

When is "java.io.IOException:Connection reset by peer" thrown?

There are lot of factors , first see whether server returns the result, then check between server and client.

rectify them from server side first,then check the writing condition between server and client !

server side rectify the time outs between the datalayer and server from client side rectify the time out and number of available connections !

How do I determine whether an array contains a particular value in Java?

Concise update for Java SE 9

Reference arrays are bad. For this case we are after a set. Since Java SE 9 we have Set.of.

private static final Set<String> VALUES = Set.of(
    "AB","BC","CD","AE"
);

"Given String s, is there a good way of testing whether VALUES contains s?"

VALUES.contains(s)

O(1).

The right type, immutable, O(1) and concise. Beautiful.*

Original answer details

Just to clear the code up to start with. We have (corrected):

public static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

This is a mutable static which FindBugs will tell you is very naughty. Do not modify statics and do not allow other code to do so also. At an absolute minimum, the field should be private:

private static final String[] VALUES = new String[] {"AB","BC","CD","AE"};

(Note, you can actually drop the new String[]; bit.)

Reference arrays are still bad and we want a set:

private static final Set<String> VALUES = new HashSet<String>(Arrays.asList(
     new String[] {"AB","BC","CD","AE"}
));

(Paranoid people, such as myself, may feel more at ease if this was wrapped in Collections.unmodifiableSet - it could then even be made public.)

(*To be a little more on brand, the collections API is predictably still missing immutable collection types and the syntax is still far too verbose, for my tastes.)

What is the difference between new/delete and malloc/free?

new calls the ctor of the object, delete call the dtor.

malloc & free just allocate and release raw memory.

How to unzip gz file using Python

import gzip
import shutil
with gzip.open('file.txt.gz', 'rb') as f_in:
    with open('file.txt', 'wb') as f_out:
        shutil.copyfileobj(f_in, f_out)

How to kill an application with all its activities?

Using onBackPressed() method:

@Override
public void onBackPressed() {    
    android.os.Process.killProcess(android.os.Process.myPid());
}

or use the finish() method, I have something like

//Password Error, I call function
    Quit();             


    protected void Quit() {
        super.finish();
    }

With super.finish() you close the super class's activity.

Windows 7: unable to register DLL - Error Code:0X80004005

Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.

C:\Windows\SysWOW64>regsvr32 "c:\dll.name" 

Java error - "invalid method declaration; return type required"

You forgot to declare double as a return type

public double diameter()
{
    double d = radius * 2;
    return d;
}

What is the bit size of long on 64-bit Windows?

If you need to use integers of certain length, you probably should use some platform independent headers to help you. Boost is a good place to look at.

How to create query parameters in Javascript?

We've just released arg.js, a project aimed at solving this problem once and for all. It's traditionally been so difficult but now you can do:

var querystring = Arg.url({name: "Mat", state: "CO"});

And reading works:

var name = Arg("name");

or getting the whole lot:

var params = Arg.all();

and if you care about the difference between ?query=true and #hash=true then you can use the Arg.query() and Arg.hash() methods.

Convert JS object to JSON string

All current browsers have native JSON support built in. So as long as you're not dealing with prehistoric browsers like IE6/7 you can do it just as easily as that:

_x000D_
_x000D_
var j = {_x000D_
  "name": "binchen"_x000D_
};_x000D_
console.log(JSON.stringify(j));
_x000D_
_x000D_
_x000D_

Finding longest string in array

Maybe not the fastest, but certainly pretty readable:

function findLongestWord(array) {
  var longestWord = "";

  array.forEach(function(word) {
    if(word.length > longestWord.length) {
      longestWord = word;
    }
  });

  return longestWord;
}

var word = findLongestWord(["The","quick","brown", "fox", "jumped", "over", "the", "lazy", "dog"]);
console.log(word); // result is "jumped"

The array function forEach has been supported since IE9+.

How do you create nested dict in Python?

UPDATE: For an arbitrary length of a nested dictionary, go to this answer.

Use the defaultdict function from the collections.

High performance: "if key not in dict" is very expensive when the data set is large.

Low maintenance: make the code more readable and can be easily extended.

from collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val

How to open a new file in vim in a new window

I'm using the following, though it's hardcoded for gnome-terminal. It also changes the CWD and buffer for vim to be the same as your current buffer and it's directory.

:silent execute '!gnome-terminal -- zsh -i -c "cd ' shellescape(expand("%:h")) '; vim' shellescape(expand("%:p")) '; zsh -i"' <cr>

jQuery duplicate DIV into another DIV

Put this on an event

$(function(){
    $('.package').click(function(){
       var content = $('.container').html();
       $(this).html(content);
    });
});

Clear text input on click with AngularJS

If you want to clean up the whole form, you can use such approach. This is your model into controller:

    $scope.registrationForm = {
    'firstName'     : '',
    'lastName'      : ''
};

Your HTML:

<form class="form-horizontal" name="registrForm" role="form">
   <input type="text" class="form-control"
                       name="firstName"
                       id="firstName"
                       ng-model="registrationForm.firstName"
                       placeholder="First name"
                       required> First name
   <input type="text" class="form-control"
                       name="lastName"
                       id="lastName"
                       ng-model="registrationForm.lastName"
                       placeholder="Last name"
                       required> Last name
</form>

Then, you should clone/save your clear state by:

$scope.originForm = angular.copy($scope.registrationForm);

Your reset function will be:

$scope.resetForm = function(){
    $scope.registrationForm = angular.copy($scope.originForm); // Assign clear state to modified form 
    $scope.registrForm.$setPristine(); // this line will update status of your form, but will not clean your data, where `registrForm` - name of form.
};

In such way you are able to clean up the whole your form

Foreign key referencing a 2 columns primary key in SQL Server

The key is "the order of the column should be the same"

Example:

create Table A (
    A_ID char(3) primary key,
    A_name char(10) primary key,
    A_desc desc char(50)
)

create Table B (
    B_ID char(3) primary key,
    B_A_ID char(3),
    B_A_Name char(10),
    constraint [Fk_B_01] foreign key (B_A_ID,B_A_Name) references A(A_ID,A_Name)
)

the column order on table A should be --> A_ID then A_Name; defining the foreign key should follow the same order as well.

Regex to get NUMBER only from String

\d+

\d represents any digit, + for one or more. If you want to catch negative numbers as well you can use -?\d+.

Note that as a string, it should be represented in C# as "\\d+", or @"\d+"

R solve:system is exactly singular

Lapack is a Linear Algebra package which is used by R (actually it's used everywhere) underneath solve(), dgesv spits this kind of error when the matrix you passed as a parameter is singular.

As an addendum: dgesv performs LU decomposition, which, when using your matrix, forces a division by 0, since this is ill-defined, it throws this error. This only happens when matrix is singular or when it's singular on your machine (due to approximation you can have a really small number be considered 0)

I'd suggest you check its determinant if the matrix you're using contains mostly integers and is not big. If it's big, then take a look at this link.

Replace String in all files in Eclipse

  • "Search"->"File"
  • Enter text, file pattern and projects
  • "Replace"
  • Enter new text

Voilà...

What is Vim recording and how can it be disabled?

It means you're in "record macro" mode. This mode is entered by typing q followed by a register name, and can be exited by typing q again.

Enable/Disable a dropdownbox in jquery

$("#chkdwn2").change(function() { 
    if (this.checked) $("#dropdown").prop("disabled",'disabled');
}) 

Class name does not name a type in C++

NOTE: Because people searching with the same keyword will land on this page, I am adding this answer which is not the cause for this compiler error in the above mentioned case.

I was facing this error when I had an enum declared in some file which had one of the elements having the same symbol as my class name.

e.g. if I declare an enum = {A, B, C} in some file which is included in another file where I declare an object of class A.

This was throwing the same compiler error message mentioning that Class A does not name a type. There was no circular dependency in my case.

So, be careful while naming classes and declaring enums (which might be visible, imported and used externally in other files) in C++.

How to concat a string to xsl:value-of select="...?

The easiest way to concat a static text string to a selected value is to use element.

<a>
  <xsl:attribute name="href"> 
    <xsl:value-of select="/*/properties/property[@name='report']/@value" />
    <xsl:text>staticIconExample.png</xsl:text>
  </xsl:attribute>
</a>

What is the difference between i = i + 1 and i += 1 in a 'for' loop?

A key issue here is that this loop iterates over the rows (1st dimension) of B:

In [258]: B
Out[258]: 
array([[ 0,  1,  2],
       [ 3,  4,  5],
       [ 6,  7,  8],
       [ 9, 10, 11]])
In [259]: for b in B:
     ...:     print(b,'=>',end='')
     ...:     b += 1
     ...:     print(b)
     ...:     
[0 1 2] =>[1 2 3]
[3 4 5] =>[4 5 6]
[6 7 8] =>[7 8 9]
[ 9 10 11] =>[10 11 12]

Thus the += is acting on a mutable object, an array.

This is implied in the other answers, but easily missed if your focus is on the a = a+1 reassignment.

I could also make an in-place change to b with [:] indexing, or even something fancier, b[1:]=0:

In [260]: for b in B:
     ...:     print(b,'=>',end='')
     ...:     b[:] = b * 2

[1 2 3] =>[2 4 6]
[4 5 6] =>[ 8 10 12]
[7 8 9] =>[14 16 18]
[10 11 12] =>[20 22 24]

Of course with a 2d array like B we usually don't need to iterate on the rows. Many operations that work on a single of B also work on the whole thing. B += 1, B[1:] = 0, etc.

How to rename array keys in PHP?

You could use array_map() to do it.

$tags = array_map(function($tag) {
    return array(
        'name' => $tag['name'],
        'value' => $tag['url']
    );
}, $tags);

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

Are arrays passed by value or passed by reference in Java?

Everything in Java is passed by value .

In the case of the array the reference is copied into a new reference, but remember that everything in Java is passed by value .

Take a look at this interesting article for further information ...

React hooks useState Array

Try to keep your state minimal. There is no need to store

   const initialValue = [
    { id: 0,value: " --- Select a State ---" }];

as state. Separate the permanent from the changing

const ALL_STATE_VALS = [
    { id: 0,value: " --- Select a State ---" }
    { id: 1, value: "Alabama" },
    { id: 2, value: "Georgia" },
    { id: 3, value: "Tennessee" }
];

Then you can store just the id as your state:

const StateSelector = () =>{
  const [selectedStateOption, setselectedStateOption] = useState(0);

  return (
    <div>
      <label>Select a State:</label>
      <select>
        {ALL_STATE_VALS.map((option, index) => (
          <option key={option.id} selected={index===selectedStateOption}>{option.value}</option>
        ))}
      </select>
    </div>);
   )
}

How to do if-else in Thymeleaf?

<div style="width:100%">
<span th:each="i : ${#numbers.sequence(1, 3)}">
<span th:if="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-success custom-width" th:text="${i}"></a
</span>
<span th:unless="${i == curpage}">
<a href="/listEmployee/${i}" class="btn btn-danger custom-width" th:text="${i}"></a> 
</span>
</span>
</div>

enter image description here

how to list all sub directories in a directory

To just get the simple list of folders without full path, you can use:

Directory.GetDirectories(parentDirectory).Select(d => Path.GetRelativePath(parentDirectory, d)

How to make MySQL handle UTF-8 properly

SET NAMES UTF8

This is does the trick

Check if something is (not) in a list in Python

The bug is probably somewhere else in your code, because it should work fine:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

Or with tuples:

>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True

What does the ??!??! operator do in C?

??! is a trigraph that translates to |. So it says:

!ErrorHasOccured() || HandleError();

which, due to short circuiting, is equivalent to:

if (ErrorHasOccured())
    HandleError();

Guru of the Week (deals with C++ but relevant here), where I picked this up.

Possible origin of trigraphs or as @DwB points out in the comments it's more likely due to EBCDIC being difficult (again). This discussion on the IBM developerworks board seems to support that theory.

From ISO/IEC 9899:1999 §5.2.1.1, footnote 12 (h/t @Random832):

The trigraph sequences enable the input of characters that are not defined in the Invariant Code Set as described in ISO/IEC 646, which is a subset of the seven-bit US ASCII code set.

How to find difference between two columns data?

Yes, you can select the data, calculate the difference, and insert all values in the other table:

insert into #temp2 (Difference)
select previous - Present
from #TEMP1

How can I insert binary file data into a binary SQL field using a simple insert statement?

I believe this would be somewhere close.

INSERT INTO Files
(FileId, FileData)
SELECT 1, * FROM OPENROWSET(BULK N'C:\Image.jpg', SINGLE_BLOB) rs

Something to note, the above runs in SQL Server 2005 and SQL Server 2008 with the data type as varbinary(max). It was not tested with image as data type.

C# Get a control's position on a form

You can use the controls PointToScreen method to get the absolute position with respect to the screen.

You can do the Forms PointToScreen method, and with basic math, get the control's position.

How do I count unique values inside a list

ipta = raw_input("Word: ") ## asks for input
words = [] ## creates list

while ipta: ## while loop to ask for input and append in list
  words.append(ipta)
  ipta = raw_input("Word: ")
  words.append(ipta)
#Create a set, sets do not have repeats
unique_words = set(words)

print "There are " +  str(len(unique_words)) + " unique words!"

How to set maximum fullscreen in vmware?

Change the resolution of your operating system running in VMware and hope it will stretch the screen when chosen the correct values

How to Execute SQL Script File in Java?

The Apache iBatis solution worked like a charm.

The script example I used was exactly the script I was running from MySql workbench.

There is an article with examples here: https://www.tutorialspoint.com/how-to-run-sql-script-using-jdbc#:~:text=You%20can%20execute%20.,to%20pass%20a%20connection%20object.&text=Register%20the%20MySQL%20JDBC%20Driver,method%20of%20the%20DriverManager%20class.

This is what I did:

pom.xml dependency

<!-- IBATIS SQL Script runner from Apache (https://mvnrepository.com/artifact/org.apache.ibatis/ibatis-core) -->
<dependency>
    <groupId>org.apache.ibatis</groupId>
    <artifactId>ibatis-core</artifactId>
    <version>3.0</version>
</dependency>

Code to execute script:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.sql.Connection;   
import org.apache.ibatis.jdbc.ScriptRunner;   
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class SqlScriptExecutor {

    public static void executeSqlScript(File file, Connection conn) throws Exception {
        Reader reader = new BufferedReader(new FileReader(file));
        log.info("Running script from file: " + file.getCanonicalPath());
        ScriptRunner sr = new ScriptRunner(conn);
        sr.setAutoCommit(true);
        sr.setStopOnError(true);
        sr.runScript(reader);
        log.info("Done.");
    }
    
}

Using custom fonts using CSS?

If you dont find any fonts that you like from Google.com/webfonts or fontsquirrel.com you can always make your own web font with a font you made.

here's a nice tutorial: Make your own font face web font kit

Although im not sure about preventing someone from downloading your font.

Hope this helps,

Pandas: Appending a row to a dataframe and specify its index label

The name of the Series becomes the index of the row in the DataFrame:

In [99]: df = pd.DataFrame(np.random.randn(8, 4), columns=['A','B','C','D'])

In [100]: s = df.xs(3)

In [101]: s.name = 10

In [102]: df.append(s)
Out[102]: 
           A         B         C         D
0  -2.083321 -0.153749  0.174436  1.081056
1  -1.026692  1.495850 -0.025245 -0.171046
2   0.072272  1.218376  1.433281  0.747815
3  -0.940552  0.853073 -0.134842 -0.277135
4   0.478302 -0.599752 -0.080577  0.468618
5   2.609004 -1.679299 -1.593016  1.172298
6  -0.201605  0.406925  1.983177  0.012030
7   1.158530 -2.240124  0.851323 -0.240378
10 -0.940552  0.853073 -0.134842 -0.277135

Check if multiple strings exist in another string

flog = open('test.txt', 'r')
flogLines = flog.readlines()
strlist = ['SUCCESS', 'Done','SUCCESSFUL']
res = False
for line in flogLines:
     for fstr in strlist:
         if line.find(fstr) != -1:
            print('found') 
            res = True


if res:
    print('res true')
else: 
    print('res false')

output example image

TypeError: 'list' object cannot be interpreted as an integer

since it's a list it cannot be taken directly into range function as the singular integer value of the list is missing.

use this

for i in range(len(myList)):

with this, we get the singular integer value which can be used easily

Tomcat view catalina.out log file

If you type in the command line

catalina

you will see some message about it, look for this:

CATALINA_BASE: /usr/local/Cellar/tomcat/9.0.27/libexec

cd /usr/local/Cellar/tomcat/9.0.27/libexec/logs
tail -f catalina.out

You will then see the live logs.

NOTE: My Tomcat installation was done via Homebrew

How to change context root of a dynamic web project in Eclipse?

If the project is maven, change the "finalName" in pom.xml and Update Project as Maven.This worked for me.

How to get file extension from string in C++

_splitpath, _wsplitpath, _splitpath_s, _wsplitpath_w

This is Windows (Platform SDK) only

How to preview git-pull without doing fetch?

What about cloning the repo elsewhere, and doing git log on both the real checkout and the fresh clone to see if you got the same thing.

How to format a Date in MM/dd/yyyy HH:mm:ss format in JavaScript?

var d = new Date();

var curr_date = d.getDate();

var curr_month = d.getMonth();

var curr_year = d.getFullYear();

document.write(curr_date + "-" + curr_month + "-" + curr_year);

using this you can format date.

you can change the appearance in the way you want then

for more info you can visit here

Why use the params keyword?

It allows you to add as many base type parameters in your call as you like.

addTwoEach(10, 2, 4, 6)

whereas with the second form you have to use an array as parameter

addTwoEach(new int[] {10,2,4,6})

How to Install Font Awesome in Laravel Mix

the path you are using is not correct you could just open the node_module and find the path of font-awesome. use could use js or svg font but i prefer the css style.

at first use this command to install font-awesome-free npm install --save-dev @fortawesome/fontawesome-free

after that you can do this

@import "~@fortawesome/fontawesome-free/scss/fontawesome";
@import "~@fortawesome/fontawesome-free/scss/regular";
@import "~@fortawesome/fontawesome-free/scss/solid";
@import "~@fortawesome/fontawesome-free/scss/brands";

and I copy the font path like below this is optional

.copy('node_modules/@fortawesome/fontawesome-free/webfonts', 'public/fonts');

and finally just run the script npm run dev or npm run watch in laravel

How to parse this string in Java?

public class Test {
    public static void main(String args[]) {
    String s = "pre/fix/dir1/dir2/dir3/dir4/..";
    String prefix = "pre/fix";
    String[] tokens = s.substring(prefix.length()).split("/");
    for (int i=0; i<tokens.length; i++) {
        System.out.println(tokens[i]);
    }
    }

}

Apache Maven install "'mvn' not recognized as an internal or external command" after setting OS environmental variables?

Heres what i did wrong:

1) make sure its NOT in a [C:\Program Files (x86)] it should be in [C:\Program Files] i am not 100% if that could break it but you never know.

2) There were 3 things i needed to do in my Environment Variables to get it to work

  1. Create a user var like this [ M2 = %M2_HOME% ]
  2. Create a user var like this [M2_HOME = C:\Program Files\Apache Software Foundation\apache-maven-3.2.2]
  3. Edit the PATH to [What ever is already in here +];%M2%

Multiple submit buttons in the same form calling different Servlets

    function gotofirst(){
        window.location = "firstServelet.java";
}
    function gotosecond(){
        window.location = "secondServelet.java";
}
<form action="FirstServlet" method="Post">
    Last Name: <input type="text" name="lastName" size="20">
    <br><br>
    <input type="submit" onclick="gotofirst()" value="FirstServlet">
    <input type="submit" onclick="gotosecond()" value="SecondServlet">
</form>

MAVEN_HOME, MVN_HOME or M2_HOME

Here is my Maven setup. You can use it as an example. You don't need anything else in order to use Maven.

M2_HOME is used for both Maven 2 and 3

export M2_HOME=/Users/xxx/sdk/apache-maven-3.0.5
export M2=$M2_HOME/bin
export MAVEN_OPTS="-Xmx1048m -Xms256m -XX:MaxPermSize=312M"
export PATH=$M2:$PATH

MySQL equivalent of DECODE function in Oracle

Try this:

Select Name, ELT(Age-12,'Thirteen','Fourteen','Fifteen','Sixteen',
   'Seventeen','Eighteen','Nineteen','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult',
   'Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult','Adult') AS AgeBracket FROM Person

Write to CSV file and export it?

A comment about Will's answer, you might want to replace HttpContext.Current.Response.End(); with HttpContext.Current.ApplicationInstance.CompleteRequest(); The reason is that Response.End() throws a System.Threading.ThreadAbortException. It aborts a thread. If you have an exception logger, it will be littered with ThreadAbortExceptions, which in this case is expected behavior.

Intuitively, sending a CSV file to the browser should not raise an exception.

See here for more Is Response.End() considered harmful?

How to find all duplicate from a List<string>?

and without the LINQ:

string[] ss = {"1","1","1"};

var myList = new List<string>();
var duplicates = new List<string>();

foreach (var s in ss)
{
   if (!myList.Contains(s))
      myList.Add(s);
   else
      duplicates.Add(s);
}

// show list without duplicates 
foreach (var s in myList)
   Console.WriteLine(s);

// show duplicates list
foreach (var s in duplicates)
   Console.WriteLine(s);

passing several arguments to FUN of lapply (and others *apply)

You can do it in the following way:

 myfxn <- function(var1,var2,var3){
      var1*var2*var3

    }

    lapply(1:3,myfxn,var2=2,var3=100)

and you will get the answer:

[[1]] [1] 200

[[2]] [1] 400

[[3]] [1] 600

Converting A String To Hexadecimal In Java

First convert it into bytes using getBytes() function and then convert it into hex usign this :

private static String hex(byte[] bytes) {
    StringBuilder sb = new StringBuilder();
    for (int i=0; i<bytes.length; i++) {
        sb.append(String.format("%02X ",bytes[i]));
    }
    return sb.toString();
}

how to make negative numbers into positive

a *= (-1);

problem solved. If there is a smaller solution for a problem, then why you guys going for a complex solution. Please direct people to use the base logic also because then only the people can train their programming logic.

Setting action for back button in navigation controller

Unlike Amagrammer said, it's possible. You have to subclass your navigationController. I explained everything here (including example code).

How do I check if a Key is pressed on C++

As mentioned by others there's no cross platform way to do this, but on Windows you can do it like this:

The Code below checks if the key 'A' is down.

if(GetKeyState('A') & 0x8000/*Check if high-order bit is set (1 << 15)*/)
{
    // Do stuff
}

In case of shift or similar you will need to pass one of these: https://msdn.microsoft.com/de-de/library/windows/desktop/dd375731(v=vs.85).aspx

if(GetKeyState(VK_SHIFT) & 0x8000)
{
    // Shift down
}

The low-order bit indicates if key is toggled.

SHORT keyState = GetKeyState(VK_CAPITAL/*(caps lock)*/);
bool isToggled = keyState & 1;
bool isDown = keyState & 0x8000;

Oh and also don't forget to

#include <Windows.h>

How can I use MS Visual Studio for Android Development?

You can use Visual Studio 2015 to building cross-platform apps for Android, iOS, and Windows.

IDE: https://www.visualstudio.com/en-US/explore/cordova-vs

Hope this will help!

Import one schema into another new schema - Oracle

After you correct the possible dmp file problem, this is a way to ensure that the schema is remapped and imported appropriately. This will also ensure that the tablespace will change also, if needed:

impdp system/<password> SCHEMAS=user1 remap_schema=user1:user2 \
            remap_tablespace=user1:user2 directory=EXPORTDIR \
            dumpfile=user1.dmp logfile=E:\Data\user1.log

EXPORTDIR must be defined in oracle as a directory as the system user

create or replace directory EXPORTDIR as 'E:\Data';
grant read, write on directory EXPORTDIR to user2;

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

ngAttr directive can totally be of help here, as introduced in the official documentation

https://docs.angularjs.org/guide/interpolation#-ngattr-for-binding-to-arbitrary-attributes

For instance, to set the id attribute value of a div element, so that it contains an index, a view fragment might contain

<div ng-attr-id="{{ 'object-' + myScopeObject.index }}"></div>

which would get interpolated to

<div id="object-1"></div>

Solving Quadratic Equation

<code>
import cmath
import math
print(" we are going to programming second grade equation in python")
print(" a^2 x + b x + c =0")

num1 = int(input(" enter A please : "))
num2 = int(input(" enter B please : "))
num3 = int(input(" enter c please : "))
v = num2*num2 - 4 *num1 * num3
print(v)
if v < 0 :
    print("wrong values")
else:
    print("root of delta =", v)
    k= math.sqrt(v)

def two_sol(x,y) :
    x_f= (-y + v)/(4*x)
    x_s =(-y - v)/(4*x)
    return x_f , x_s

def one_sol(x):
    x_f = (-y + v) / (4 * x)

if v >0 :
    print("we have two solution :" ,two_sol(num1,num2)) 
elif v == 0:
    print( "we have one solution :" , one_sol(y)) 
else:
    print(" there is no solution !!")
</code>

Why is php not running?

When installing Apache and PHP under Ubuntu 14.04, I needed to specifically enable php configs by issuing a2enmod php5-cgi

push multiple elements to array

You can use Array.concat:

var result = a.concat(b);

How to override the [] operator in Python?

You are looking for the __getitem__ method. See http://docs.python.org/reference/datamodel.html, section 3.4.6

Determine if a String is an Integer in Java

As an alternative approach to trying to parse the string and catching NumberFormatException, you could use a regex; e.g.

if (Pattern.compile("-?[0-9]+").matches(str)) {
    // its an integer
}

This is likely to be faster, especially if you precompile and reuse the regex.

However, the problem with this approach is that Integer.parseInt(str) will also fail if str represents a number that is outside range of legal int values. While it is possible to craft a regex that only matches integers in the range Integer.MIN_INT to Integer.MAX_INT, it is not a pretty sight. (And I am not going to try it ...)

On the other hand ... it may be acceptable to treat "not an integer" and "integer too large" separately for validation purposes.

How to always show scrollbar

android:scrollbarFadeDuration="0" sometimes does not work after I exit from the apps and start again. So I add gallery.setScrollbarFadingEnabled(false); to the activity and it works!

How to get id from URL in codeigniter?

Check the below code hope that you get your parameter

echo $this->uri->segment('3');

What is the difference between JOIN and JOIN FETCH when using JPA and Hibernate

In this two queries, you are using JOIN to query all employees that have at least one department associated.

But, the difference is: in the first query you are returning only the Employes for the Hibernate. In the second query, you are returning the Employes and all Departments associated.

So, if you use the second query, you will not need to do a new query to hit the database again to see the Departments of each Employee.

You can use the second query when you are sure that you will need the Department of each Employee. If you not need the Department, use the first query.

I recomend read this link if you need to apply some WHERE condition (what you probably will need): How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

Update

If you don't use fetch and the Departments continue to be returned, is because your mapping between Employee and Department (a @OneToMany) are setted with FetchType.EAGER. In this case, any HQL (with fetch or not) query with FROM Employee will bring all Departments. Remember that all mapping *ToOne (@ManyToOne and @OneToOne) are EAGER by default.

Eclipse java debugging: source not found

When running in debug mode, click Edit Source Lookup after suspended from thread. At this point, we should be able to add the necessary project/jar which contains your source code. After I added my current project in this way, and it solved my problem. Thanks

Oracle pl-sql escape character (for a " ' ")

you can use ESCAPE like given example below

The '_' wild card character is used to match exactly one character, while '%' is used to match zero or more occurrences of any characters. These characters can be escaped in SQL.

SELECT name FROM emp WHERE id LIKE '%/_%' ESCAPE '/';

The same works inside PL/SQL:

 if( id like '%/_%' ESCAPE '/' )

This applies only to like patterns, for example in an insert there is no need to escape _ or %, they are used as plain characters anyhow. In arbitrary strings only ' needs to be escaped by ''.

MySQL high CPU usage

First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.

Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.

Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.

Some other things you can check would be to run the following query while the CPU load is high:

SHOW PROCESSLIST;

This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).

You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.

You'll also probably want to give the following a read over as they contain some good information.

It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.

How to start a background process in Python?

While jkp's solution works, the newer way of doing things (and the way the documentation recommends) is to use the subprocess module. For simple commands its equivalent, but it offers more options if you want to do something complicated.

Example for your case:

import subprocess
subprocess.Popen(["rm","-r","some.file"])

This will run rm -r some.file in the background. Note that calling .communicate() on the object returned from Popen will block until it completes, so don't do that if you want it to run in the background:

import subprocess
ls_output=subprocess.Popen(["sleep", "30"])
ls_output.communicate()  # Will block for 30 seconds

See the documentation here.

Also, a point of clarification: "Background" as you use it here is purely a shell concept; technically, what you mean is that you want to spawn a process without blocking while you wait for it to complete. However, I've used "background" here to refer to shell-background-like behavior.

How do I compile with -Xlint:unchecked?

A cleaner way to specify the Gradle compiler arguments follow:

compileJava.options.compilerArgs = ['-Xlint:unchecked','-Xlint:deprecation']

How to use the ConfigurationManager.AppSettings

you should use []

var x = ConfigurationManager.AppSettings["APIKey"];

Visual Studio 2015 or 2017 does not discover unit tests

I believe you already found the issue, but in my case helped to simply install the Microsoft.NET.Test.Sdk. Make sure you add it to your test project. I've spent few days trying to solve the problem and it's as simple as that.

Microsoft.Net.Test.Sdk should be installed no matter what testing framework you are using.

https://i.imgur.com/Ol6AoOm.png

iOS Launching Settings -> Restrictions URL Scheme

Here is something else I found:

  1. After I have the "prefs" URL Scheme defined, "prefs:root=Safari&path=ContentBlockers" is working on Simulator (iOS 9.1 English), but not working on Simulator (Simplified Chinese). It just jump to Safari, but not Content Blockers. If your app is international, be careful.
    Update: Don't know why, now I can't jump into ContentBlockers anymore, the same code, the same version, doesn't work now. :(

  2. On real devcies (mine is iPhone 6S & iPad mini 2), "Safari" should be "SAFARI", "Safari" not working on real device, "SAFARI" now working on simulator:

    #if arch(i386) || arch(x86_64)
        // Simulator
        let url = NSURL(string: "prefs:root=Safari")!
    #else
        // Device
        let url = NSURL(string: "prefs:root=SAFARI")!
    #endif
    
    if UIApplication.sharedApplication().canOpenURL(url) {
        UIApplication.sharedApplication().openURL(url)
    }
    
  3. So far, did not find any differences between iPhone and iPad.

C# Enum - How to Compare Value

You can use Enum.Parse like, if it is string

AccountType account = (AccountType)Enum.Parse(typeof(AccountType), "Retailer")

Can RDP clients launch remote applications and not desktops

This is called "seamless" mode. rdesktop, the RDP client for Unix, is capable of this. From the manpage:

   -A     Enable SeamlessRDP. In this mode, rdesktop creates a X11 window for each window on the server
          side.  This  mode  requires  the  SeamlessRDP  server side component, which is available from
          http://www.cendio.com/seamlessrdp/.  When using this option, you  should  specify  a  startup
          shell which launches the desired application through SeamlessRDP.

See mentioned Cendio website for more information.

Switch statement fallthrough in C#?

After each case statement require break or goto statement even if it is a default case.

how concatenate two variables in batch script?

Enabling delayed variable expansion solves you problem, the script produces "hi":

setlocal EnableDelayedExpansion

set var1=A
set var2=B

set AB=hi

set newvar=!%var1%%var2%!

echo %newvar%

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

Use:

((Long) userService.getAttendanceList(currentUser)).intValue();

instead.

The .intValue() method is defined in class Number, which Long extends.

How to access PHP variables in JavaScript or jQuery rather than <?php echo $variable ?>

Basically, yes. You write alert('<?php echo($phpvariable); ?>');

There are sure other ways to interoperate, but none of which i can think of being as simple (or better) as the above.

No provider for HttpClient

adding HttpClientModule in app.module.ts file in import section fixed my issue.

Understanding implicit in Scala

A very basic example of Implicits in scala.

Implicit parameters:

val value = 10
implicit val multiplier = 3
def multiply(implicit by: Int) = value * by
val result = multiply // implicit parameter wiil be passed here
println(result) // It will print 30 as a result

Note: Here multiplier will be implicitly passed into the function multiply. Missing parameters to the function call are looked up by type in the current scope meaning that code will not compile if there is no implicit variable of type Int in the scope.

Implicit conversions:

implicit def convert(a: Double): Int = a.toInt
val res = multiply(2.0) // Type conversions with implicit functions
println(res)  // It will print 20 as a result

Note: When we call multiply function passing a double value, the compiler will try to find the conversion implicit function in the current scope, which converts Int to Double (As function multiply accept Int parameter). If there is no implicit convert function then the compiler will not compile the code.

PHP Get Highest Value from Array

If you just want the largest value in the array use the max function. This will return the largest value, although not the corresponding key. It does not change the original array.

If you care about the the key you could then do

$key = array_search(max($array), $array)

(Edited to include @binaryLV's suggestion)

Convert NaN to 0 in javascript

Rather than kludging it so you can continue, why not back up and wonder why you're running into a NaN in the first place?

If any of the numeric inputs to an operation is NaN, the output will also be NaN. That's the way the current IEEE Floating Point standard works (it's not just Javascript). That behavior is for a good reason: the underlying intention is to keep you from using a bogus result without realizing it's bogus.

The way NaN works is if something goes wrong way down in some sub-sub-sub-operation (producing a NaN at that lower level), the final result will also be NaN, which you'll immediately recognize as an error even if your error handling logic (throw/catch maybe?) isn't yet complete.

NaN as the result of an arithmetic calculation always indicates something has gone awry in the details of the arithmetic. It's a way for the computer to say "debugging needed here". Rather than finding some way to continue anyway with some number that's hardly ever right (is 0 really what you want?), why not find the problem and fix it.

A common problem in Javascript is that both parseInt(...) and parseFloat(...) will return NaN if given a nonsensical argument (null, '', etc). Fix the issue at the lowest level possible rather than at a higher level. Then the result of the overall calculation has a good chance of making sense, and you're not substituting some magic number (0 or 1 or whatever) for the result of the entire calculation. (The trick of (parseInt(foo.value) || 0) works only for sums, not products - for products you want the default value to be 1 rather than 0, but not if the specified value really is 0.)

Perhaps for ease of coding you want a function to retrieve a value from the user, clean it up, and provide a default value if necessary, like this:

function getFoobarFromUser(elementid) {
        var foobar = parseFloat(document.getElementById(elementid).innerHTML)
        if (isNaN(foobar)) foobar = 3.21;       // default value
        return(foobar.toFixed(2));
}

How do you know a variable type in java?

If you want the name, use Martin's method. If you want to know whether it's an instance of a certain class:

boolean b = a instanceof String

Groovy String to Date

Below is the way we are going within our developing application.

import java.text.SimpleDateFormat

String newDateAdded = "2018-11-11T09:30:31"
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss")
Date dateAdded = dateFormat.parse(newDateAdded)

println(dateAdded)

The output looks like

Sun Nov 11 09:30:31 GMT 2018

In your example, we could adjust a bit to meet your need. If I were you, I will do:

String datePattern = "d/M/yyyy H:m:s"
String theDate = "28/09/2010 16:02:43"
SimpleDateFormat df = new SimpleDateFormat(datePattern)
println df.parse(theDate)

I hope this would help you much.

Remove stubborn underline from link

Here is an example for the asp.net webforms LinkButton control:

 <asp:LinkButton ID="lbmmr1" runat="server" ForeColor="Blue" />

Code behind:

 lbmmr1.Attributes.Add("style", "text-decoration: none;")

Image overlay on responsive sized images bootstrap

If i understand your question you want to have the overlay just over the image and not cover everything?

I'd set the parent DIV (i renamed in content in the jsfiddle) position to relative, as the overlay should be positioned relative to this div not the window.

.content
{
  position: relative;
}

I did some pocking around and updated your fiddle to just have the overlay sized to the img which (I think) is what you want, let me know anyway :) http://jsfiddle.net/b9Vyw/

Iterate two Lists or Arrays with one ForEach statement in C#

This is known as a Zip operation and will be supported in .NET 4.

With that, you would be able to write something like:

var numbers = new [] { 1, 2, 3, 4 };
var words = new [] { "one", "two", "three", "four" };

var numbersAndWords = numbers.Zip(words, (n, w) => new { Number = n, Word = w });
foreach(var nw in numbersAndWords)
{
    Console.WriteLine(nw.Number + nw.Word);
}

As an alternative to the anonymous type with the named fields, you can also save on braces by using a Tuple and its static Tuple.Create helper:

foreach (var nw in numbers.Zip(words, Tuple.Create)) 
{
    Console.WriteLine(nw.Item1 + nw.Item2);
}

Redeploy alternatives to JRebel

DCEVM supports enhanced class redefinitions and is available for current JDK7 and JDK8.

https://github.com/dcevm/dcevm/releases

HotswapAgent is an free JRebel alternative and supports DCEVM in various Frameworks.

http://hotswapagent.org/

Warning: Permanently added the RSA host key for IP address

If you are accessing your repositories over the SSH protocol, you will receive a warning message each time your client connects to a new IP address for github.com. As long as the IP address from the warning is in the range of IP addresses , you shouldn't be concerned. Specifically, the new addresses that are being added this time are in the range from 192.30.252.0 to 192.30.255.255. The warning message looks like this:

Warning: Permanently added the RSA host key for IP address '$IP' to the list of 

https://github.com/blog/1606-ip-address-changes

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

According to MSDN maxAllowedContentLength has type uint, its maximum value is 4,294,967,295 bytes = 3,99 gb

So it should work fine.

See also Request Limits article. Does IIS return one of these errors when the appropriate section is not configured at all?

See also: Maximum request length exceeded

Elegant solution for line-breaks (PHP)

Not very "elegant" and kinda a waste, but if you really care what the code looks like you could make your own fancy flag and then do a str_replace.

Example:<br />
$myoutput =  "After this sentence there is a line break.<b>.|..</b> Here is a new line.";<br />
$myoutput =  str_replace(".|..","&lt;br />",$myoutput);<br />

or

how about:<br />
$myoutput =  "After this sentence there is a line break.<b>E(*)3</b> Here is a new line.";<br />
$myoutput =  str_replace("E(*)3","&lt;br />",$myoutput);<br />

I call the first method "middle finger style" and the second "goatse style".

TensorFlow: "Attempting to use uninitialized value" in variable initialization

Normally there are two ways of initializing variables, 1) using the sess.run(tf.global_variables_initializer()) as the previous answers noted; 2) the load the graph from checkpoint.

You can do like this:

sess = tf.Session(config=config)
saver = tf.train.Saver(max_to_keep=3)
try:
    saver.restore(sess, tf.train.latest_checkpoint(FLAGS.model_dir))
    # start from the latest checkpoint, the sess will be initialized 
    # by the variables in the latest checkpoint
except ValueError:
    # train from scratch
    init = tf.global_variables_initializer()
    sess.run(init)

And the third method is to use the tf.train.Supervisor. The session will be

Create a session on 'master', recovering or initializing the model as needed, or wait for a session to be ready.

sv = tf.train.Supervisor([parameters])
sess = sv.prepare_or_wait_for_session()

cURL equivalent in Node.js?

The above examples work but don't go so far as to really deal with a real world example (i.e. when you process data coming in multiple chunks. One thing you need to make sure of is that you have an 'on chunk' handler that push's the data into an array (fastest way to do this in JS) and an 'on end' handler that joins them all together so you can return it.

This is especially necessary when you're working with big requests (5000+ lines) and the server sends a bunch of data at you.

Here's an example in one of my programs (coffeescript): https://gist.github.com/1105888

What is the right way to debug in iPython notebook?

After you get an error, in the next cell just run %debug and that's it.

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

Since iOS 11, you can use the native framework called PDFKit for displaying and manipulating PDFs.

After importing PDFKit, you should initialize a PDFView with a local or a remote URL and display it in your view.

if let url = Bundle.main.url(forResource: "example", withExtension: "pdf") {
    let pdfView = PDFView(frame: view.frame)
    pdfView.document = PDFDocument(url: url)
    view.addSubview(pdfView)
}

Read more about PDFKit in the Apple Developer documentation.

How can I strip first X characters from string using sed?

pipe it through awk '{print substr($0,42)}' where 42 is one more than the number of characters to drop. For example:

$ echo abcde| awk '{print substr($0,2)}'
bcde
$

Add my custom http header to Spring RestTemplate request / extend RestTemplate

If the goal is to have a reusable RestTemplate which is in general useful for attaching the same header to a series of similar request a org.springframework.boot.web.client.RestTemplateCustomizer parameter can be used with a RestTemplateBuilder:

 String accessToken= "<the oauth 2 token>";
 RestTemplate restTemplate = new RestTemplateBuilder(rt-> rt.getInterceptors().add((request, body, execution) -> {
        request.getHeaders().add("Authorization", "Bearer "+accessToken);
        return execution.execute(request, body);
    })).build();

Is there a max array length limit in C++?

As has already been pointed out, array size is limited by your hardware and your OS (man ulimit). Your software though, may only be limited by your creativity. For example, can you store your "array" on disk? Do you really need long long ints? Do you really need a dense array? Do you even need an array at all?

One simple solution would be to use 64 bit Linux. Even if you do not physically have enough ram for your array, the OS will allow you to allocate memory as if you do since the virtual memory available to your process is likely much larger than the physical memory. If you really need to access everything in the array, this amounts to storing it on disk. Depending on your access patterns, there may be more efficient ways of doing this (ie: using mmap(), or simply storing the data sequentially in a file (in which case 32 bit Linux would suffice)).

How do I write a compareTo method which compares objects?

A String is an object in Java.

you could compare like so,

if(this.lastName.compareTo(s.getLastName() == 0)//last names are the same

Use sed to replace all backslashes with forward slashes

Just use:

sed 's.\\./.g'

There's no reason to use / as the separator in sed. But if you really wanted to:

sed 's/\\/\//g'

javascript cell number validation

Mobile number Validation using Java Script, This link will provide demo and more information.

_x000D_
_x000D_
function isNumber(evt) {_x000D_
  evt = (evt) ? evt : window.event;_x000D_
  var charCode = (evt.which) ? evt.which : evt.keyCode;_x000D_
  if (charCode > 31 && (charCode < 48 || charCode > 57)) {_x000D_
    alert("Please enter only Numbers.");_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
  return true;_x000D_
}_x000D_
_x000D_
function ValidateNo() {_x000D_
  var phoneNo = document.getElementById('txtPhoneNo');_x000D_
_x000D_
  if (phoneNo.value == "" || phoneNo.value == null) {_x000D_
    alert("Please enter your Mobile No.");_x000D_
    return false;_x000D_
  }_x000D_
  if (phoneNo.value.length < 10 || phoneNo.value.length > 10) {_x000D_
    alert("Mobile No. is not valid, Please Enter 10 Digit Mobile No.");_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
  alert("Success ");_x000D_
  return true;_x000D_
}
_x000D_
<input id="txtPhoneNo" type="text" onkeypress="return isNumber(event)" />_x000D_
<input type="button" value="Submit" onclick="ValidateNo();">
_x000D_
_x000D_
_x000D_

How to log in to phpMyAdmin with WAMP, what is the username and password?

http://localhost/phpmyadmin

Username: root

Password:

(No password set)

Android: how to parse URL String with spaces to URI object?

To handle spaces, @, and other unsafe characters in arbitrary locations in the url path, Use Uri.Builder in combination with a local instance of URL as I have described here:

private Uri.Builder builder;
public Uri getUriFromUrl(String thisUrl) {
    URL url = new URL(thisUrl);
    builder =  new Uri.Builder()
                            .scheme(url.getProtocol())
                            .authority(url.getAuthority())
                            .appendPath(url.getPath());
    return builder.build();
}

How can I generate a list of consecutive numbers?

In Python 3, you can use the builtin range function like this

>>> list(range(9))
[0, 1, 2, 3, 4, 5, 6, 7, 8]

Note 1: Python 3.x's range function, returns a range object. If you want a list you need to explicitly convert that to a list, with the list function like I have shown in the answer.

Note 2: We pass number 9 to range function because, range function will generate numbers till the given number but not including the number. So, we give the actual number + 1.

Note 3: There is a small difference in functionality of range in Python 2 and 3. You can read more about that in this answer.

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

Hi Could you try this line cmd its work for me

python -m pip install --user --upgrade pip

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

Dictionary<int,string> comboSource = new Dictionary<int,string>();
comboSource.Add(1, "Sunday");
comboSource.Add(2, "Monday");

Aftr adding values to Dictionary, use this as combobox datasource:

comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

Where should I put the CSS and Javascript code in an HTML webpage?

And if you have more than one .css or .js file to call, just include them one after another, or:

<head>

<link href="css/grid.css" rel="stylesheet" />

<link href="css/style.css" rel="stylesheet" />

<script src="js/jquery-1.4.4.min.js"></script>

<script src="js/jquery.animate-colors-min.js"></script>

</head>

Where does Android app package gets installed on phone

An application when installed on a device or on an emulator will install at:

/data/data/APP_PACKAGE_NAME

The APK itself is placed in the /data/app/ folder.

These paths, however, are in the System Partition and to access them, you will need to have root. This is for a device. On the emulator, you can see it in your logcat (DDMS) in the File Explorer tab

By the way, it only shows the package name that is defined in your Manifest.XML under the package="APP_PACKAGE_NAME" attribute. Any other packages you may have created in your project in Eclipse do not show up here.

What is the difference between <section> and <div>?

Take caution not to overuse the section tag as a replacement for a div element. A section tag should define a significant region within the context of the body. Semantically, HTML5 encourages us to define our document as follows:

_x000D_
_x000D_
<html>_x000D_
<head></head>_x000D_
<body>_x000D_
    <header></header>_x000D_
    <section>_x000D_
        <h1></h1>_x000D_
        <div>_x000D_
            <span></span>_x000D_
        </div>_x000D_
        <div></div>_x000D_
    </section>_x000D_
    <footer></footer>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

This strategy allows web robots and automated screen readers to better understand the flow of your content. This markup clearly defines where your major page content is contained. Of course, headers and footers are often common across hundreds if not thousands of pages within a website. The section tag should be limited to explain where the unique content is contained. Within the section tag, we should then continue to markup and control the content with HTML tags which are lower in the hierarchy, like h1, div, span, etc.

In most simple pages, there should only be a single section tag, not multiple ones. Please also consider also that there are other interesting HTML5 tags which are similar to section. Consider using article, summary, aside and others within your document flow. As you can see, these tags further enhance our ability to define the major regions of the HTML document.

Exception : mockito wanted but not invoked, Actually there were zero interactions with this mock

@jk1 answer is perfect, since @igor Ganapolsky asked, why can't we use Mockito.mock here? i post this answer.

For that we have provide one setter method for myobj and set the myobj value with mocked object.

class MyClass {
    MyInterface myObj;

    public void abc() {
        myObj.myMethodToBeVerified (new String("a"), new String("b"));
    }

    public void setMyObj(MyInterface obj)
    {
        this.myObj=obj;
    }
}

In our Test class, we have to write below code

class MyClassTest {

MyClass myClass = new MyClass();

    @Mock
    MyInterface myInterface;

    @test
    testAbc() {
        myclass.setMyObj(myInterface); //it is good to have in @before method
        myClass.abc();
        verify(myInterface).myMethodToBeVerified(new String("a"), new String("b"));
     }
}

ASP.NET Core 1.0 on IIS error 502.5

For me it was that the connectionString in Startup.cs was null in:

services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

and it was null because the application was not looking into appsettings.json for the connection string.

Had to change Program.cs to:

public static void Main(string[] args)
{
    BuildWebHost(args).Run();
}

public static IWebHost BuildWebHost(string[] args) =>
     WebHost.CreateDefaultBuilder(args)
     .ConfigureAppConfiguration((context, builder) => builder.SetBasePath(context.HostingEnvironment.ContentRootPath)
     .AddJsonFile("appsettings.json").Build())
     .UseStartup<Startup>().Build();

How do I clone into a non-empty directory?

I have used this a few moments ago, requires the least potentially destructive commands:

cd existing-dir
git clone --bare repo-to-clone .git
git config --unset core.bare
git remote rm origin
git remote add origin repo-to-clone
git reset

And voilá!

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

ssh -v -L 8783:localhost:8783 [email protected]
...
channel 3: open failed: connect failed: Connection refused

When you connect to port 8783 on your local system, that connection is tunneled through your ssh link to the ssh server on server.com. From there, the ssh server makes TCP connection to localhost port 8783 and relays data between the tunneled connection and the connection to target of the tunnel.

The "connection refused" error is coming from the ssh server on server.com when it tries to make the TCP connection to the target of the tunnel. "Connection refused" means that a connection attempt was rejected. The simplest explanation for the rejection is that, on server.com, there's nothing listening for connections on localhost port 8783. In other words, the server software that you were trying to tunnel to isn't running, or else it is running but it's not listening on that port.

How do I reset the setInterval timer?

If by "restart", you mean to start a new 4 second interval at this moment, then you must stop and restart the timer.

function myFn() {console.log('idle');}

var myTimer = setInterval(myFn, 4000);

// Then, later at some future time, 
// to restart a new 4 second interval starting at this exact moment in time
clearInterval(myTimer);
myTimer = setInterval(myFn, 4000);

You could also use a little timer object that offers a reset feature:

function Timer(fn, t) {
    var timerObj = setInterval(fn, t);

    this.stop = function() {
        if (timerObj) {
            clearInterval(timerObj);
            timerObj = null;
        }
        return this;
    }

    // start timer using current settings (if it's not already running)
    this.start = function() {
        if (!timerObj) {
            this.stop();
            timerObj = setInterval(fn, t);
        }
        return this;
    }

    // start with new or original interval, stop current interval
    this.reset = function(newT = t) {
        t = newT;
        return this.stop().start();
    }
}

Usage:

var timer = new Timer(function() {
    // your function here
}, 5000);


// switch interval to 10 seconds
timer.reset(10000);

// stop the timer
timer.stop();

// start the timer
timer.start();

Working demo: https://jsfiddle.net/jfriend00/t17vz506/

How to compare only date components from DateTime in EF?

To do it in LINQ to Entities, you have to use supported methods:

var year = someDate.Year;
var month = ...
var q = from r in Context.Records
        where Microsoft.VisualBasic.DateAndTime.Year(r.SomeDate) == year 
              && // month and day

Ugly, but it works, and it's done on the DB server.

OSX El Capitan: sudo pip install OSError: [Errno: 1] Operation not permitted

I had the same issues. As others have mentioned, don't run pip install with sudo. Run

brew doctor 

and fix the warnings and you should be able to proceed with your pip install.

Conditionally hide CommandField or ButtonField in Gridview

Convert the CommandField to a TemplateField and set the visible property of the button based on the value of the field (true/false)

<asp:Button ID="btnSelect" 
runat="server" Text="Select" 
Visible='<%# DataBinder.Eval(Container.DataItem,"IsLeaf") %>'/>

Disable cross domain web security in Firefox

Almost everywhere you look, people refer to the about:config and the security.fileuri.strict_origin_policy. Sometimes also the network.http.refere.XOriginPolicy.

For me, none of these seem to have any effect.

This comment implies there is no built-in way in Firefox to do this (as of 2/8/14).

How to get the path of the batch script in Windows?

%cd% will give you the path of the directory from where the script is running.

Just run:

echo %cd%

How would I find the second largest salary from the employee table?

select max(Salary) from Employee 
where Salary
  not in (Select top4 salary from Employee);

because answer is as follows

max(5,6,7,8)

so 5th highest record will be displayed, first four will not be considered

HTML5: Slider with two inputs possible?

Coming late, but noUiSlider avoids having a jQuery-ui dependency, which the accepted answer does not. Its only "caveat" is IE support is for IE9 and newer, if legacy IE is a deal breaker for you.

It's also free, open source and can be used in commercial projects without restrictions.

Installation: Download noUiSlider, extract the CSS and JS file somewhere in your site file system, and then link to the CSS from head and to JS from body:

<!-- In <head> -->
<link href="nouislider.min.css" rel="stylesheet">

<!-- In <body> -->
<script src="nouislider.min.js"></script>

Example usage: Creates a slider which goes from 0 to 100, and starts set to 20-80.

HTML:

<div id="slider">
</div>

JS:

var slider = document.getElementById('slider');

noUiSlider.create(slider, {
    start: [20, 80],
    connect: true,
    range: {
        'min': 0,
        'max': 100
    }
});

How to call two methods on button's onclick method in HTML or JavaScript?

Hi,

You can also do as like below... In this way, your both functions should call and if both functions return true then it will return true else return false.

<input type="button" 
     onclick="var valFunc1 = func1(); var valFunc2 = func2(); if(valFunc1 == true && valFunc2 ==true) {return true;} else{return false;}" 
     value="Call2Functions" />

Thank you, Vishal Patel

JavaScript get window X/Y position for scroll

Maybe more simple;

var top  = window.pageYOffset || document.documentElement.scrollTop,
    left = window.pageXOffset || document.documentElement.scrollLeft;

Credits: so.dom.js#L492

What is the purpose of class methods?

What just hit me, coming from Ruby, is that a so-called class method and a so-called instance method is just a function with semantic meaning applied to its first parameter, which is silently passed when the function is called as a method of an object (i.e. obj.meth()).

Normally that object must be an instance but the @classmethod method decorator changes the rules to pass a class. You can call a class method on an instance (it's just a function) - the first argument will be its class.

Because it's just a function, it can only be declared once in any given scope (i.e. class definition). If follows therefore, as a surprise to a Rubyist, that you can't have a class method and an instance method with the same name.

Consider this:

class Foo():
  def foo(x):
    print(x)

You can call foo on an instance

Foo().foo()
<__main__.Foo instance at 0x7f4dd3e3bc20>

But not on a class:

Foo.foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method foo() must be called with Foo instance as first argument (got nothing instead)

Now add @classmethod:

class Foo():
  @classmethod
  def foo(x):
    print(x)

Calling on an instance now passes its class:

Foo().foo()
__main__.Foo

as does calling on a class:

Foo.foo()
__main__.Foo

It's only convention that dictates that we use self for that first argument on an instance method and cls on a class method. I used neither here to illustrate that it's just an argument. In Ruby, self is a keyword.

Contrast with Ruby:

class Foo
  def foo()
    puts "instance method #{self}"
  end
  def self.foo()
    puts "class method #{self}"
  end
end

Foo.foo()
class method Foo

Foo.new.foo()
instance method #<Foo:0x000000020fe018>

The Python class method is just a decorated function and you can use the same techniques to create your own decorators. A decorated method wraps the real method (in the case of @classmethod it passes the additional class argument). The underlying method is still there, hidden but still accessible.


footnote: I wrote this after a name clash between a class and instance method piqued my curiosity. I am far from a Python expert and would like comments if any of this is wrong.

Can't start Tomcat as Windows Service

I had the similar issue, But installing tomcat 32bit and jdk 32 bit worked, This happens mostly because of mismatch Bit.

..The underlying connection was closed: An unexpected error occurred on a receive

Before Execute query I put the statement as below and it resolved my error. Just FYI in case it will help someone.

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072; ctx.ExecuteQuery();

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

In your web.config make sure these keys exist:

<configuration>
    <system.webServer>
        <validation validateIntegratedModeConfiguration="false"/>
    </system.webServer>
</configuration>

As well as check the Asp.Net Impresonation = Disable In IIS Site Authetication

Location of WSDL.exe

It is included with .NET (not sure if only in the SDK).

Pycharm and sys.argv arguments

Add the following to the top of your Python file.

import sys

sys.argv = [
    __file__,
    'arg1',
    'arg2'
]

Now, you can simply right click on the Python script.

Maintaining Session through Angular.js

Because the answer is no longer valid with a more stable version of angular, I am posting a newer solution.

PHP Page: session.php

if (!isset($_SESSION))
{    
    session_start();
}    

$_SESSION['variable'] = "hello world";

$sessions = array();

$sessions['variable'] = $_SESSION['variable'];

header('Content-Type: application/json');
echo json_encode($sessions);

Send back only the session variables you want in Angular not all of them don't want to expose more than what is needed.

JS All Together

var app = angular.module('StarterApp', []);
app.controller("AppCtrl", ['$rootScope', 'Session', function($rootScope, Session) {      
    Session.then(function(response){
        $rootScope.session = response;
    });
}]);

 app.factory('Session', function($http) {    
    return $http.get('/session.php').then(function(result) {       
        return result.data; 
    });
}); 
  • Do a simple get to get sessions using a factory.
  • If you want to make it post to make the page not visible when you just go to it in the browser you can, I'm just simplifying it
  • Add the factory to the controller
  • I use rootScope because it is a session variable that I use throughout all my code.

HTML

Inside your html you can reference your session

<html ng-app="StarterApp">

<body ng-controller="AppCtrl">
{{ session.variable }}
</body>

nginx error connect to php5-fpm.sock failed (13: Permission denied)

After upgrading from Ubuntu 14.04 lts to Ubuntu 16.04 lts I found a yet another reason for this error that I haven't seen before.

During the upgrading process I had somehow lost my php5-fpm executable altogether. All the config files were intact and it took me a while to realize that service php5-fpm start didn't really start a process, as it did not show any errors.

My moment of awakening was when I noticed that there were no socket file in /var/run/php5-fpm.sock, as there should be, nor did netstat -an show processes listening on the port that I tried as an alternative while trying to solve this problem. Since the file /usr/sbin/php5-fpm was also non-existing, I was finally on the right track.

In order to solve this problem I upgraded php from version 5.5 to 7.0. apt-get install php-fpm did the trick as a side effect. After that and installing other necessary packages everything was back to normal.


This upgrading solution may have problems of its own, however. Since php has evolved quite a bit, it's possible that the software will break in unimaginable ways. So, even though I did go down that path, you may want to keep the version you're fond of just for a while longer.

Luckily, there seems to be a neat way for that, as described on The Customize Windows site:

add-apt-repository ppa:ondrej/php
apt-get purge php5-common
apt-get update
apt-get install php5.6

Neater solution as it might be, I didn't try that. I expect the next couple of days will tell me whether I should have.

How to get a value from the last inserted row?

Use that simple code:

// Do your insert code

myDataBase.execSQL("INSERT INTO TABLE_NAME (FIELD_NAME1,FIELD_NAME2,...)VALUES (VALUE1,VALUE2,...)");

// Use the sqlite function "last_insert_rowid"

Cursor last_id_inserted = yourBD.rawQuery("SELECT last_insert_rowid()", null);

// Retrieve data from cursor.

last_id_inserted.moveToFirst(); // Don't forget that!

ultimo_id = last_id_inserted.getLong(0);  // For Java, the result is returned on Long type  (64)

Should have subtitle controller already set Mediaplayer error Android

To remove message on logcat, i add a subtitle to track. On windows, right click on track -> Property -> Details -> insert a text on subtitle. Done :)

How to load image (and other assets) in Angular an project?

Angular-cli includes the assets folder in the build options by default. I got this issue when the name of my images had spaces or dashes. For example :

  • 'my-image-name.png' should be 'myImageName.png'
  • 'my image name.png' should be 'myImageName.png'

If you put the image in the assets/img folder, then this line of code should work in your templates :

<img alt="My image name" src="./assets/img/myImageName.png">

If the issue persist just check if your Angular-cli config file and be sure that your assets folder is added in the build options.

Pass arguments to Constructor in VBA

Using the trick

Attribute VB_PredeclaredId = True

I found another more compact way:

Option Explicit
Option Base 0
Option Compare Binary

Private v_cBox As ComboBox

'
' Class creaor
Public Function New_(ByRef cBox As ComboBox) As ComboBoxExt_c
  If Me Is ComboBoxExt_c Then
    Set New_ = New ComboBoxExt_c
    Call New_.New_(cBox)
  Else
    Set v_cBox = cBox
  End If
End Function

As you can see the New_ constructor is called to both create and set the private members of the class (like init) only problem is, if called on the non-static instance it will re-initialize the private member. but that can be avoided by setting a flag.

Running Java Program from Command Line Linux

What is the package name of your class? If there is no package name, then most likely the solution is:

java -cp FileManagement Main

How to write a foreach in SQL Server?

The following line is wrong in your version:

WHILE (@i <= (SELECT MAX(idx) FROM @Practitioner))

(Missing the @)

Might be an idea to change your naming convention so that the tables are more different.

Two HTML tables side by side, centered on the page

If it was me - I would do with the table something like this:

_x000D_
_x000D_
<style type="text/css" media="screen">_x000D_
  table {_x000D_
    border: 1px solid black;_x000D_
    float: left;_x000D_
    width: 148px;_x000D_
  }_x000D_
  _x000D_
  #table_container {_x000D_
    width: 300px;_x000D_
    margin: 0 auto;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
<div id="table_container">_x000D_
  <table>_x000D_
    <tr>_x000D_
      <th>a</th>_x000D_
      <th>b</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>9</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>16</td>_x000D_
      <td>25</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
  <table>_x000D_
    <tr>_x000D_
      <th>a</th>_x000D_
      <th>b</th>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>1</td>_x000D_
      <td>2</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>4</td>_x000D_
      <td>9</td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <td>16</td>_x000D_
      <td>25</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get a Docker container's IP address from the host

Just another classic solution:

docker ps -aq | xargs docker inspect -f '{{.Name}} - {{.NetworkSettings.IPAddress }}'

Call removeView() on the child's parent first

Ok, call me paranoid but I suggest:

  final android.view.ViewParent parent = view.getParent ();

  if (parent instanceof android.view.ViewManager)
  {
     final android.view.ViewManager viewManager = (android.view.ViewManager) parent;

     viewManager.removeView (view);
  } // if

casting without instanceof just seems wrong. And (thanks IntelliJ IDEA for telling me) removeView is part of the ViewManager interface. And one should not cast to a concrete class when a perfectly suitable interface is available.

How to search for an element in an stl list?

No, find() method is not a member of std::list. Instead, use std::find from <algorithm>

    std :: list < int > l;
    std :: list < int > :: iterator pos;

    l.push_back(1);
    l.push_back(2);
    l.push_back(3);
    l.push_back(4);
    l.push_back(5);
    l.push_back(6);

    int elem = 3;   
    pos = find(l.begin() , l.end() , elem);
    if(pos != l.end() )
        std :: cout << "Element is present. "<<std :: endl;
    else
        std :: cout << "Element is not present. "<<std :: endl;

File.separator vs FileSystem.getSeparator() vs System.getProperty("file.separator")?

If your code doesn't cross filesystem boundaries, i.e. you're just working with one filesystem, then use java.io.File.separator.

This will, as explained, get you the default separator for your FS. As Bringer128 explained, System.getProperty("file.separator") can be overriden via command line options and isn't as type safe as java.io.File.separator.

The last one, java.nio.file.FileSystems.getDefault().getSeparator(); was introduced in Java 7, so you might as well ignore it for now if you want your code to be portable across older Java versions.

So, every one of these options is almost the same as others, but not quite. Choose one that suits your needs.

Generate table relationship diagram from existing schema (SQL Server)

For SQL statements you can try reverse snowflakes. You can join at sourceforge or the demo site at http://snowflakejoins.com/.

How to pass model attributes from one Spring MVC controller to another controller?

If you want just pass all attributes to redirect...

public String yourMethod( ...., HttpServletRequest request, RedirectAttributes redirectAttributes) {
    if(shouldIRedirect()) {
        redirectAttributes.addAllAttributes(request.getParameterMap());
        return "redirect:/newPage.html";
    }
}

Using 'starts with' selector on individual class names

Try this:

$("div[class]").filter(function() {
    var classNames = this.className.split(/\s+/);
    for (var i=0; i<classNames.length; ++i) {
        if (classNames[i].substr(0, 6) === "apple-") {
            return true;
        }
    }
    return false;
})

Plot Normal distribution with Matplotlib

Assuming you're getting norm from scipy.stats, you probably just need to sort your list:

import numpy as np
import scipy.stats as stats
import matplotlib.pyplot as plt

h = [186, 176, 158, 180, 186, 168, 168, 164, 178, 170, 189, 195, 172,
     187, 180, 186, 185, 168, 179, 178, 183, 179, 170, 175, 186, 159,
     161, 178, 175, 185, 175, 162, 173, 172, 177, 175, 172, 177, 180]
h.sort()
hmean = np.mean(h)
hstd = np.std(h)
pdf = stats.norm.pdf(h, hmean, hstd)
plt.plot(h, pdf) # including h here is crucial

And so I get: enter image description here

Get the latest record from mongodb collection

This is a rehash of the previous answer but it's more likely to work on different mongodb versions.

db.collection.find().limit(1).sort({$natural:-1})

Update multiple columns in SQL

The Update table1 set (a,b,c) = (select x,y,x) syntax is an example of the use of row-value constructors, Oracle supports this, MSSQL does not. (Connect item)

Android - How to get application name? (Not package name)

Have you tried using the PackageManager#getActivityInfo() method? There will be a field that should contain the name of the application.

See the answer to a very similar question here.

Angular2 router (@angular/router), how to set default route?

according to documentation you should just

{ path: '**', component: DefaultLayoutComponent }

on your app-routing.module.ts source: https://angular.io/guide/router

How to create Android Facebook Key Hash?

For Windows:

  1. open command prompt and paste below command

keytool -exportcert -alias androiddebugkey -keystore %HOMEPATH%.android\debug.keystore | openssl sha1 -binary | openssl base64

  1. Enter password : android --> Hit Enter

  2. Copy Generated Hash Key --> Login Facebook with your developer account

  3. Go to your Facebook App --> Settings--> Paste Hash key in "key hashes" option -->save changes.

  4. Now Test your android app with Facebook Log-in/Share etc.

How to run jenkins as a different user

On Mac OS X, the way I enabled Jenkins to pull from my (private) Github repo is:

First, ensure that your user owns the Jenkins directory

sudo chown -R me:me /Users/Shared/Jenkins

Then edit the LaunchDaemon plist for Jenkins (at /Library/LaunchDaemons/org.jenkins-ci.plist) so that your user is the GroupName and the UserName:

    <key>GroupName</key>
    <string>me</string>
...
    <key>UserName</key>
    <string>me</string>

Then reload Jenkins:

sudo launchctl unload -w /Library/LaunchDaemons/org.jenkins-ci.plist
sudo launchctl load -w /Library/LaunchDaemons/org.jenkins-ci.plist

Then Jenkins, since it's running as you, has access to your ~/.ssh directory which has your keys.

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Use codecs if possible,

with codecs.open('file_path', 'a+', 'utf-8') as fp:
    fp.write(json.dumps(res, ensure_ascii=False))

Angular.js directive dynamic templateURL

Thanks to @pgregory, I could resolve my problem using this directive for inline editing

.directive("superEdit", function($compile){
    return{
        link: function(scope, element, attrs){
            var colName = attrs["superEdit"];
            alert(colName);

            scope.getContentUrl = function() {
                if (colName == 'Something') {
                    return 'app/correction/templates/lov-edit.html';
                }else {
                    return 'app/correction/templates/simple-edit.html';
                }
            }

            var template = '<div ng-include="getContentUrl()"></div>';

            var linkFn = $compile(template);
            var content = linkFn(scope);
            element.append(content);
        }
    }
})

ReadFile in Base64 Nodejs

var fs = require('fs');

function base64Encode(file) {
    var body = fs.readFileSync(file);
    return body.toString('base64');
}


var base64String = base64Encode('test.jpg');
console.log(base64String);

Initial size for the ArrayList

Right now there are no elements in your list so you cannot add to index 5 of the list when it does not exist. You are confusing the capacity of the list with its current size.

Just call:

arr.add(10)

to add the Integer to your ArrayList

SSIS expression: convert date to string

Something simpler than what @Milen proposed but it gives YYYY-MM-DD instead of the DD-MM-YYYY you wanted :

SUBSTRING((DT_STR,30, 1252) GETDATE(), 1, 10)

Expression builder screen:

enter image description here

SASS - use variables across multiple files

You can do it like this:

I have a folder named utilities and inside that I have a file named _variables.scss

in that file i declare variables like so:

$black: #000;
$white: #fff;

then I have the style.scss file in which i import all of my other scss files like this:

// Utilities
@import "utilities/variables";

// Base Rules
@import "base/normalize";
@import "base/global";

then, within any of the files I have imported, I should be able to access the variables I have declared.

Just make sure you import the variable file before any of the others you would like to use it in.

Get rid of "The value for annotation attribute must be a constant expression" message

The value for an annotation must be a compile time constant, so there is no simple way of doing what you are trying to do.

See also here: How to supply value to an annotation from a Constant java

It is possible to use some compile time tools (ant, maven?) to config it if the value is known before you try to run the program.

Fitting a density curve to a histogram in R

Dirk has explained how to plot the density function over the histogram. But sometimes you might want to go with the stronger assumption of a skewed normal distribution and plot that instead of density. You can estimate the parameters of the distribution and plot it using the sn package:

> sn.mle(y=c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4)))
$call
sn.mle(y = c(rep(65, times = 5), rep(25, times = 5), rep(35, 
    times = 10), rep(45, times = 4)))

$cp
    mean     s.d. skewness 
41.46228 12.47892  0.99527 

Skew-normal distributed data plot

This probably works better on data that is more skew-normal:

Another skew-normal plot

Fast and simple String encrypt/decrypt in JAVA

If you are using Android then you can use android.util.Base64 class.

Encode:

passwd = Base64.encodeToString( passwd.getBytes(), Base64.DEFAULT );

Decode:

passwd = new String( Base64.decode( passwd, Base64.DEFAULT ) );

A simple and fast single line solution.

What does Ruby have that Python doesn't, and vice versa?

What Ruby has over Python are its scripting language capabilities. Scripting language in this context meaning to be used for "glue code" in shell scripts and general text manipulation.

These are mostly shared with Perl. First-class built-in regular expressions, $-Variables, useful command line options like Perl (-a, -e) etc.

Together with its terse yet epxressive syntax it is perfect for these kind of tasks.

Python to me is more of a dynamically typed business language that is very easy to learn and has a neat syntax. Not as "cool" as Ruby but neat. What Python has over Ruby to me is the vast number of bindings for other libs. Bindings to Qt and other GUI libs, many game support libraries and and and. Ruby has much less. While much used bindings e.g. to Databases are of good quality I found niche libs to be better supported in Python even if for the same library there is also a Ruby binding.

So, I'd say both languages have its use and it is the task that defines which one to use. Both are easy enough to learn. I use them side-by-side. Ruby for scripting and Python for stand-alone apps.

YouTube URL in Video Tag

This would be easy to do :

<iframe width="420" height="345"
src="http://www.youtube.com/embed/XGSy3_Czz8k">
</iframe>

Is just an example.

Simple java program of pyramid

Try this one

 public static void main(String[] args) 
{
     int x=11;
     int y=x/2; // spaces
     int z=1; // *`s

     for(int i=0;i<5;i++)
    {
         for(int j=0;j<y;j++)
        {
             System.out.print(" ");
        }
        for(int k=0;k<z;k++)
        {
            System.out.print("*");
        }

        y=y-1;
        z=z+2;
        System.out.println();  
    }

}

ASP.NET MVC - passing parameters to the controller

Headspring created a nice library that allows you to add aliases to your parameters in attributes on the action. This looks like this:

[ParameterAlias("firstItem", "id", Order = 3)]
public ActionResult ViewStockNext(int firstItem)
{
    // Do some stuff
}

With this you don't have to alter your routing just to handle a different parameter name. The library also supports applying it multiple times so you can map several parameter spellings (handy when refactoring without breaking your public interface).

You can get it from Nuget and read Jeffrey Palermo's article on it here

How to get current local date and time in Kotlin

Try this :

 val sdf = SimpleDateFormat("dd/M/yyyy hh:mm:ss")
 val currentDate = sdf.format(Date())
 System.out.println(" C DATE is  "+currentDate)

Passing event and argument to v-on in Vue.js

Depending on what arguments you need to pass, especially for custom event handlers, you can do something like this:

<div @customEvent='(arg1) => myCallback(arg1, arg2)'>Hello!</div>

Get first date of current month in java

If you also want the time is set to 0 the code is:

import java.util.*;
import java.text.*;

public class DateCalculations {
  public static void main(String[] args) {

    Calendar aCalendar = Calendar.getInstance();

    aCalendar.set(Calendar.DATE, 1);
    aCalendar.set(Calendar.HOUR_OF_DAY, 0);
    aCalendar.set(Calendar.MINUTE, 0);
    aCalendar.set(Calendar.SECOND, 0);

    Date firstDateOfCurrentMonth = aCalendar.getTime();

    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss zZ");
    sdf.setTimeZone(TimeZone.getTimeZone("UTC"));

    String dayFirst = sdf.format(firstDateOfCurrentMonth);
    System.out.println(dayFirst);
  }
}

You can check online easily without compiling by using: http://www.browxy.com/

Plot a horizontal line using matplotlib

Use matplotlib.pyplot.hlines:

  • Plot multiple horizontal lines by passing a list to the y parameter.
  • y can be passed as a single location: y=40
  • y can be passed as multiple locations: y=[39, 40, 41]
  • If you're a plotting a figure with something like fig, ax = plt.subplots(), then replace plt.hlines or plt.axhline with ax.hlines or ax.axhline, respectively.
  • matplotlib.pyplot.axhline can only plot a single location (e.g. y=40)

plt.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)

plt.figure(figsize=(6, 3))
plt.hlines(y=39.5, xmin=100, xmax=175, colors='aqua', linestyles='-', lw=2, label='Single Short Line')
plt.hlines(y=[39, 40, 41], xmin=[0, 25, 50], xmax=[len(xs)], colors='purple', linestyles='--', lw=2, label='Multiple Lines')
plt.legend(bbox_to_anchor=(1.04,0.5), loc="center left", borderaxespad=0)

enter image description here

ax.plot

import numpy as np
import matplotlib.pyplot as plt

xs = np.linspace(1, 21, 200)
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(6, 6))

ax1.hlines(y=40, xmin=0, xmax=len(xs), colors='r', linestyles='--', lw=2)
ax1.set_title('One Line')

ax2.hlines(y=[39, 40, 41], xmin=0, xmax=len(xs), colors='purple', linestyles='--', lw=2)
ax2.set_title('Multiple Lines')

plt.tight_layout()
plt.show()

enter image description here

Time Series Axis

  • xmin and xmax will accept a date like '2020-09-10' or datetime(2020, 9, 10)
    • xmin=datetime(2020, 9, 10), xmax=datetime(2020, 9, 10) + timedelta(days=3)
    • Given date = df.index[9], xmin=date, xmax=date + pd.Timedelta(days=3), where the index is a DatetimeIndex.
import pandas_datareader as web  # conda or pip install this; not part of pandas
import pandas as pd
import matplotlib.pyplot as plt

# get test data
df = web.DataReader('^gspc', data_source='yahoo', start='2020-09-01', end='2020-09-28').iloc[:, :2]

# plot dataframe
ax = df.plot(figsize=(9, 6), title='S&P 500', ylabel='Price')

# add horizontal line
ax.hlines(y=3450, xmin='2020-09-10', xmax='2020-09-17', color='purple', label='test')

ax.legend()
plt.show()

enter image description here

  • Sample time series data if web.DataReader doesn't work.
data = {pd.Timestamp('2020-09-01 00:00:00'): {'High': 3528.03, 'Low': 3494.6}, pd.Timestamp('2020-09-02 00:00:00'): {'High': 3588.11, 'Low': 3535.23}, pd.Timestamp('2020-09-03 00:00:00'): {'High': 3564.85, 'Low': 3427.41}, pd.Timestamp('2020-09-04 00:00:00'): {'High': 3479.15, 'Low': 3349.63}, pd.Timestamp('2020-09-08 00:00:00'): {'High': 3379.97, 'Low': 3329.27}, pd.Timestamp('2020-09-09 00:00:00'): {'High': 3424.77, 'Low': 3366.84}, pd.Timestamp('2020-09-10 00:00:00'): {'High': 3425.55, 'Low': 3329.25}, pd.Timestamp('2020-09-11 00:00:00'): {'High': 3368.95, 'Low': 3310.47}, pd.Timestamp('2020-09-14 00:00:00'): {'High': 3402.93, 'Low': 3363.56}, pd.Timestamp('2020-09-15 00:00:00'): {'High': 3419.48, 'Low': 3389.25}, pd.Timestamp('2020-09-16 00:00:00'): {'High': 3428.92, 'Low': 3384.45}, pd.Timestamp('2020-09-17 00:00:00'): {'High': 3375.17, 'Low': 3328.82}, pd.Timestamp('2020-09-18 00:00:00'): {'High': 3362.27, 'Low': 3292.4}, pd.Timestamp('2020-09-21 00:00:00'): {'High': 3285.57, 'Low': 3229.1}, pd.Timestamp('2020-09-22 00:00:00'): {'High': 3320.31, 'Low': 3270.95}, pd.Timestamp('2020-09-23 00:00:00'): {'High': 3323.35, 'Low': 3232.57}, pd.Timestamp('2020-09-24 00:00:00'): {'High': 3278.7, 'Low': 3209.45}, pd.Timestamp('2020-09-25 00:00:00'): {'High': 3306.88, 'Low': 3228.44}, pd.Timestamp('2020-09-28 00:00:00'): {'High': 3360.74, 'Low': 3332.91}}

df = pd.DataFrame.from_dict(data, 'index')

PHP Using RegEx to get substring of a string

<?php
$string = "producturl.php?id=736375493?=tm";
preg_match('~id=(\d+)~', $string, $m );
var_dump($m[1]); // $m[1] is your string
?>

How do I search for a pattern within a text file using Python combining regex & string/file operations and store instances of the pattern?

import re
pattern = re.compile("<(\d{4,5})>")

for i, line in enumerate(open('test.txt')):
    for match in re.finditer(pattern, line):
        print 'Found on line %s: %s' % (i+1, match.group())

A couple of notes about the regex:

  • You don't need the ? at the end and the outer (...) if you don't want to match the number with the angle brackets, but only want the number itself
  • It matches either 4 or 5 digits between the angle brackets

Update: It's important to understand that the match and capture in a regex can be quite different. The regex in my snippet above matches the pattern with angle brackets, but I ask to capture only the internal number, without the angle brackets.

More about regex in python can be found here : Regular Expression HOWTO

How to enter a formula into a cell using VBA?

I would do it like this:

Worksheets("EmployeeCosts").Range("B" & var1a).Formula = _
Replace("=SUM(H5:H{SOME_VAR})","{SOME_VAR}",var1a)

In case you have some more complex formula it will be handy

How to support HTTP OPTIONS verb in ASP.NET MVC/WebAPI application

As Daniel A. White said in his comment, the OPTIONS request is most likely created by the client as part of a cross domain JavaScript request. This is done automatically by Cross Origin Resource Sharing (CORS) compliant browsers. The request is a preliminary or pre-flight request, made before the actual AJAX request to determine which request verbs and headers are supported for CORS. The server can elect to support it for none, all or some of the HTTP verbs.

To complete the picture, the AJAX request has an additional "Origin" header, which identified where the original page which is hosting the JavaScript was served from. The server can elect to support request from any origin, or just for a set of known, trusted origins. Allowing any origin is a security risk since is can increase the risk of Cross site Request Forgery (CSRF).

So, you need to enable CORS.

Here is a link that explains how to do this in ASP.Net Web API

http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api#enable-cors

The implementation described there allows you to specify, amongst other things

  • CORS support on a per-action, per-controller or global basis
  • The supported origins
  • When enabling CORS a a controller or global level, the supported HTTP verbs
  • Whether the server supports sending credentials with cross-origin requests

In general, this works fine, but you need to make sure you are aware of the security risks, especially if you allow cross origin requests from any domain. Think very carefully before you allow this.

In terms of which browsers support CORS, Wikipedia says the following engines support it:

  • Gecko 1.9.1 (FireFox 3.5)
  • WebKit (Safari 4, Chrome 3)
  • MSHTML/Trident 6 (IE10) with partial support in IE8 and 9
  • Presto (Opera 12)

http://en.wikipedia.org/wiki/Cross-origin_resource_sharing#Browser_support

Check if a row exists, otherwise insert

I assume a single row for each flight? If so:

IF EXISTS (SELECT * FROM Bookings WHERE FLightID = @Id)
BEGIN
    --UPDATE HERE
END
ELSE
BEGIN
   -- INSERT HERE
END

I assume what I said, as your way of doing things can overbook a flight, as it will insert a new row when there are 10 tickets max and you are booking 20.

Decimal separator comma (',') with numberDecimal inputType in EditText

Martins answer won't work if you are instantiating the EditText programmatically. I went ahead and modified the included DigitsKeyListener class from API 14 to allow for both comma and period as decimal separator.

To use this, call setKeyListener() on the EditText, e.g.

// Don't allow for signed input (minus), but allow for decimal points
editText.setKeyListener( new MyDigitsKeyListener( false, true ) );

However, you still have to use Martin's trick in the TextChangedListener where you replace commas with periods

import android.text.InputType;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.method.NumberKeyListener;
import android.view.KeyEvent;

class MyDigitsKeyListener extends NumberKeyListener {

    /**
     * The characters that are used.
     *
     * @see KeyEvent#getMatch
     * @see #getAcceptedChars
     */
    private static final char[][] CHARACTERS = new char[][] {
        new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' },
        new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-' },
        new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', ',' },
        new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '-', '.', ',' },
    };

    private char[] mAccepted;
    private boolean mSign;
    private boolean mDecimal;

    private static final int SIGN = 1;
    private static final int DECIMAL = 2;

    private static MyDigitsKeyListener[] sInstance = new MyDigitsKeyListener[4];

    @Override
    protected char[] getAcceptedChars() {
        return mAccepted;
    }

    /**
     * Allocates a DigitsKeyListener that accepts the digits 0 through 9.
     */
    public MyDigitsKeyListener() {
        this(false, false);
    }

    /**
     * Allocates a DigitsKeyListener that accepts the digits 0 through 9,
     * plus the minus sign (only at the beginning) and/or decimal point
     * (only one per field) if specified.
     */
    public MyDigitsKeyListener(boolean sign, boolean decimal) {
        mSign = sign;
        mDecimal = decimal;

        int kind = (sign ? SIGN : 0) | (decimal ? DECIMAL : 0);
        mAccepted = CHARACTERS[kind];
    }

    /**
     * Returns a DigitsKeyListener that accepts the digits 0 through 9.
     */
    public static MyDigitsKeyListener getInstance() {
        return getInstance(false, false);
    }

    /**
     * Returns a DigitsKeyListener that accepts the digits 0 through 9,
     * plus the minus sign (only at the beginning) and/or decimal point
     * (only one per field) if specified.
     */
    public static MyDigitsKeyListener getInstance(boolean sign, boolean decimal) {
        int kind = (sign ? SIGN : 0) | (decimal ? DECIMAL : 0);

        if (sInstance[kind] != null)
            return sInstance[kind];

        sInstance[kind] = new MyDigitsKeyListener(sign, decimal);
        return sInstance[kind];
    }

    /**
     * Returns a DigitsKeyListener that accepts only the characters
     * that appear in the specified String.  Note that not all characters
     * may be available on every keyboard.
     */
    public static MyDigitsKeyListener getInstance(String accepted) {
        // TODO: do we need a cache of these to avoid allocating?

        MyDigitsKeyListener dim = new MyDigitsKeyListener();

        dim.mAccepted = new char[accepted.length()];
        accepted.getChars(0, accepted.length(), dim.mAccepted, 0);

        return dim;
    }

    public int getInputType() {
        int contentType = InputType.TYPE_CLASS_NUMBER;
        if (mSign) {
            contentType |= InputType.TYPE_NUMBER_FLAG_SIGNED;
        }
        if (mDecimal) {
            contentType |= InputType.TYPE_NUMBER_FLAG_DECIMAL;
        }
        return contentType;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end,
                               Spanned dest, int dstart, int dend) {
        CharSequence out = super.filter(source, start, end, dest, dstart, dend);

        if (mSign == false && mDecimal == false) {
            return out;
        }

        if (out != null) {
            source = out;
            start = 0;
            end = out.length();
        }

        int sign = -1;
        int decimal = -1;
        int dlen = dest.length();

        /*
         * Find out if the existing text has '-' or '.' characters.
         */

        for (int i = 0; i < dstart; i++) {
            char c = dest.charAt(i);

            if (c == '-') {
                sign = i;
            } else if (c == '.' || c == ',') {
                decimal = i;
            }
        }
        for (int i = dend; i < dlen; i++) {
            char c = dest.charAt(i);

            if (c == '-') {
                return "";    // Nothing can be inserted in front of a '-'.
            } else if (c == '.' ||  c == ',') {
                decimal = i;
            }
        }

        /*
         * If it does, we must strip them out from the source.
         * In addition, '-' must be the very first character,
         * and nothing can be inserted before an existing '-'.
         * Go in reverse order so the offsets are stable.
         */

        SpannableStringBuilder stripped = null;

        for (int i = end - 1; i >= start; i--) {
            char c = source.charAt(i);
            boolean strip = false;

            if (c == '-') {
                if (i != start || dstart != 0) {
                    strip = true;
                } else if (sign >= 0) {
                    strip = true;
                } else {
                    sign = i;
                }
            } else if (c == '.' || c == ',') {
                if (decimal >= 0) {
                    strip = true;
                } else {
                    decimal = i;
                }
            }

            if (strip) {
                if (end == start + 1) {
                    return "";  // Only one character, and it was stripped.
                }

                if (stripped == null) {
                    stripped = new SpannableStringBuilder(source, start, end);
                }

                stripped.delete(i - start, i + 1 - start);
            }
        }

        if (stripped != null) {
            return stripped;
        } else if (out != null) {
            return out;
        } else {
            return null;
        }
    }
}