Programs & Examples On #Factory pattern

This tag is sometimes used to refer to the Factory Method pattern ([factory-method]) and sometimes used to refer to the Abstract Factory pattern ([abstract-factory]). Please use either of those tags instead of this one.

Factory Pattern. When to use factory methods?

One situation where I personally find separate Factory classes to make sense is when the final object you are trying to create relies on several other objects. E.g, in PHP: Suppose you have a House object, which in turn has a Kitchen and a LivingRoom object, and the LivingRoom object has a TV object inside as well.

The simplest method to achieve this is having each object create their children on their construct method, but if the properties are relatively nested, when your House fails creating you will probably spend some time trying to isolate exactly what is failing.

The alternative is to do the following (dependency injection, if you like the fancy term):

$TVObj = new TV($param1, $param2, $param3);
$LivingroomObj = new LivingRoom($TVObj, $param1, $param2);
$KitchenroomObj = new Kitchen($param1, $param2);
$HouseObj = new House($LivingroomObj, $KitchenroomObj);

Here if the process of creating a House fails there is only one place to look, but having to use this chunk every time one wants a new House is far from convenient. Enter the Factories:

class HouseFactory {
    public function create() {
        $TVObj = new TV($param1, $param2, $param3);
        $LivingroomObj = new LivingRoom($TVObj, $param1, $param2);
        $KitchenroomObj = new Kitchen($param1, $param2);
        $HouseObj = new House($LivingroomObj, $KitchenroomObj);

        return $HouseObj;
    }
}

$houseFactory = new HouseFactory();
$HouseObj = $houseFactory->create();

Thanks to the factory here the process of creating a House is abstracted (in that you don't need to create and set up every single dependency when you just want to create a House) and at the same time centralized which makes it easier to maintain. There are other reasons why using separate Factories can be beneficial (e.g. testability) but I find this specific use case to illustrate best how Factory classes can be useful.

Dependency Injection vs Factory Pattern

Using dependency injection is much better in my opinion if you are: 1. deploying your code in small partition, because it handles well in decoupling of one big code. 2. testability is one of the case DI is ok to use because you can mock easily the non decoupled objects. with the use of interfaces you can easily mock and test each objects. 3. you can simultaneously revised each part of the program without needing to code the other part of it since its loosely decoupled.

Implement a simple factory pattern with Spring 3 annotations

Following the answer from DruidKuma and jumping_monkey

You can also include optional and make your code a bit nicer and cleaner:

 public static MyService getService(String type) {
        return Optional.ofNullable(myServiceCache.get(type))
                .orElseThrow(() -> new RuntimeException("Unknown service type: " + type));
 }

What is the difference between Builder Design pattern and Factory Design pattern?

IMHO

Builder is some kind of more complex Factory.

But in Builder you can instantiate objects with using another factories, that are required to build final and valid object.

So, talking about "Creational Patterns" evolution by complexity you can think about it in this way:

Dependency Injection Container -> Service Locator -> Builder -> Factory

What are the differences between Abstract Factory and Factory design patterns?

I would favor Abstract Factory over Factory Method anytime. From Tom Dalling's example (great explanation btw) above, we can see that Abstract Factory is more composable in that all we need to do is passing a different Factory to the constructor (constructor dependency injection in use here). But Factory Method requires us to introduce a new class (more things to manage) and use subclassing. Always prefer composition over inheritance.

Bootstrap how to get text to vertical align in a div container

HTML:

First, we will need to add a class to your text container so that we can access and style it accordingly.

<div class="col-xs-5 textContainer">
     <h3 class="text-left">Link up with other gamers all over the world who share the same tastes in games.</h3>
</div>

CSS:

Next, we will apply the following styles to align it vertically, according to the size of the image div next to it.

.textContainer { 
    height: 345px; 
    line-height: 340px;
}

.textContainer h3 {
    vertical-align: middle;
    display: inline-block;
}

All Done! Adjust the line-height and height on the styles above if you believe that it is still slightly out of align.

WORKING EXAMPLE

ssh-copy-id no identities found error

Generating ssh keys on the client solved it for me

$ ssh-keygen -t rsa

Ruby: Easiest Way to Filter Hash Keys?

With Hash::select:

params = params.select { |key, value| /^choice\d+$/.match(key.to_s) }

Tool for sending multipart/form-data request

The usual error is one tries to put Content-Type: {multipart/form-data} into the header of the post request. That will fail, it is best to let Postman do it for you. For example:

Suggestion To Load Via Postman Body Part

Fails If In Header Common Error

Works should remove content type from the Header

How to solve PHP error 'Notice: Array to string conversion in...'

<?php
ob_start();
var_dump($_POST['C']);
$result = ob_get_clean();
?>

if you want to capture the result in a variable

SQL grammar for SELECT MIN(DATE)

You need to use GROUP BY instead of DISTINCT if you want to use aggregation functions.

SELECT title, MIN(date)
FROM table
GROUP BY title

Convert timestamp to string

new Date().toString();

http://www.mkyong.com/java/java-how-to-get-current-date-time-date-and-calender/

Dateformatter can make it to any string you want

Adding a tooltip to an input box

I know this is a question regarding the CSS.Tooltips library. However, for anyone else came here resulting from google search "tooltip for input box" like I did, here is the simplest way:

<input title="This is the text of the tooltip" value="44"/>

How to check certificate name and alias in keystore files?

In order to get all the details I had to add the -v option to romaintaz answer:

keytool -v -list -keystore <FileName>.keystore

How can I make a DateTimePicker display an empty string?

Just set the property as follows:

When the user press "clear button" or "delete key" do

dtpData.CustomFormat = " "  'An empty SPACE
dtpData.Format = DateTimePickerFormat.Custom

On DateTimePicker1_ValueChanged event do

dtpData.CustomFormat = "dd/MM/yyyy hh:mm:ss"

Run ScrollTop with offset of element by ID

No magic involved, just subtract from the offset top of the element

$('html, body').animate({scrollTop: $('#contact').offset().top -100 }, 'slow');

How to use this boolean in an if statement?

The problem here is

if (stop = true) is an assignation not a comparision.

Try if (stop == true)

Also take a look to the Top Ten Errors Java Programmers Make.

How to store JSON object in SQLite database

https://github.com/app-z/Json-to-SQLite

At first generate Plain Old Java Objects from JSON http://www.jsonschema2pojo.org/

Main method

void createDb(String dbName, String tableName, List dataList, Field[] fields){ ...

Fields name will create dynamically

How to return temporary table from stored procedure

YES YOU CAN.

In your stored procedure, you fill the table @tbRetour.

At the very end of your stored procedure, you write:

SELECT * FROM @tbRetour 

To execute the stored procedure, you write:

USE [...]
GO

DECLARE @return_value int

EXEC @return_value = [dbo].[getEnregistrementWithDetails]
@id_enregistrement_entete = '(guid)'

GO

Call Javascript function from URL/address bar

There isn't from a hyperlink, no. Not unless the page has script inside specifically for this and it's checking for some parameter....but for your question, no, there's no built-in support in browsers for this.

There are however bookmarklets you can bookmark to quickly run JavaScript functions from your address bar; not sure if that meets your needs, but it's as close as it gets.

NSString with \n or line break

I just ran into the same issue when overloading -description for a subclass of NSObject. In this situation I was able to use carriage return (\r) instead of newline (\n) to create a line break.

[NSString stringWithFormat:@"%@\r%@", mystring1,mystring2];

Spring Boot - How to get the running port

After Spring Boot 2, a lot has changed. The above given answers work prior to Spring Boot 2. Now if you are running your application with runtime arguments for the server port, then you will only get the static value with @Value("${server.port}"), that is mentioned in the application.properties file. Now to get the actual port in which the server is running, use the following method:

    @Autowired
    private ServletWebServerApplicationContext server;

    @GetMapping("/server-port")
    public String serverPort() {

        return "" + server.getWebServer().getPort();
    }

Also, if you are using your applications as Eureka/Discovery Clients with load balanced RestTemplate or WebClient, the above method will return the exact port number.

Retrieve the position (X,Y) of an HTML element relative to the browser window

This function returns an element's position relative to the whole document (page):

function getOffset(el) {
  const rect = el.getBoundingClientRect();
  return {
    left: rect.left + window.scrollX,
    top: rect.top + window.scrollY
  };
}

Using this we can get the X position:

getOffset(element).left

... or the Y position:

getOffset(element).top

Round a floating-point number down to the nearest integer?

One of these should work:

import math
math.trunc(1.5)
> 1
math.trunc(-1.5)
> -1
math.floor(1.5)
> 1
math.floor(-1.5)
> -2

Pass in an array of Deferreds to $.when()

If you're transpiling and have access to ES6, you can use spread syntax which specifically applies each iterable item of an object as a discrete argument, just the way $.when() needs it.

$.when(...deferreds).done(() => {
    // do stuff
});

MDN Link - Spread Syntax

HashMap with multiple values under the same key

You can do it implicitly.

// Create the map. There is no restriction to the size that the array String can have
HashMap<Integer, String[]> map = new HashMap<Integer, String[]>();

//initialize a key chosing the array of String you want for your values
map.put(1, new String[] { "name1", "name2" });

//edit value of a key
map.get(1)[0] = "othername";

This is very simple and effective. If you want values of diferent classes instead, you can do the following:

HashMap<Integer, Object[]> map = new HashMap<Integer, Object[]>();

Installed Java 7 on Mac OS X but Terminal is still using version 6

In my case, the issue was that Oracle was installing it to a different location than I was used to.

Download from Oracle: http://java.com/en/download/mac_download.jsp?locale=en

  1. Verify that it's installed properly by looking in System Prefs:

    • Command-Space to open Spotlight, type 'System Preferences', hit enter.
    • Click Java icon in bottom row. After the Java Control Panel opens, click 'Java' tab, 'View...', and verify that your install worked. You can see a 'Path' there also, which you can sub into the commands below in case they are different than mine.
  2. Verify that the version is as you expect (sub in your path as needed):

    /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java -version

  3. Create link from /usr/bin/java to your new install

    sudo ln -fs /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin/java /usr/bin/java

  4. Sanity check your version:

    java -version

What is the copy-and-swap idiom?

This answer is more like an addition and a slight modification to the answers above.

In some versions of Visual Studio (and possibly other compilers) there is a bug that is really annoying and doesn't make sense. So if you declare/define your swap function like this:

friend void swap(A& first, A& second) {

    std::swap(first.size, second.size);
    std::swap(first.arr, second.arr);

}

... the compiler will yell at you when you call the swap function:

enter image description here

This has something to do with a friend function being called and this object being passed as a parameter.


A way around this is to not use friend keyword and redefine the swap function:

void swap(A& other) {

    std::swap(size, other.size);
    std::swap(arr, other.arr);

}

This time, you can just call swap and pass in other, thus making the compiler happy:

enter image description here


After all, you don't need to use a friend function to swap 2 objects. It makes just as much sense to make swap a member function that has one other object as a parameter.

You already have access to this object, so passing it in as a parameter is technically redundant.

Java List.contains(Object with field value equal to x)

If you need to perform this List.contains(Object with field value equal to x) repeatedly, a simple and efficient workaround would be:

List<field obj type> fieldOfInterestValues = new ArrayList<field obj type>;
for(Object obj : List) {
    fieldOfInterestValues.add(obj.getFieldOfInterest());
}

Then the List.contains(Object with field value equal to x) would be have the same result as fieldOfInterestValues.contains(x);

How to get started with Windows 7 gadgets

Here's an MSDN article on Vista Gadgets. Some preliminary documentation on 7 gadgets, and changes. I think the only major changes are that Gadgets don't reside in the Sidebar anymore, and as such "dock/undock events" are now backwards-compatibility cludges that really shouldn't be used.

Best way to get started is probably to just tweak an existing gadget. There's an example gadget in the above link, or you could pick a different one out on your own.

Gadgets are written in HTML, CSS, and some IE scripting language (generally Javascript, but I believe VBScript also works). For really fancy things you might need to create an ActiveX object, so C#/C++ for COM could be useful to know.

Gadgets are packaged as ".gadget" files, which are just renamed Zip archives that contain a gadget manifest (gadget.xml) in their top level.

Get the decimal part from a double

You may remove the dot . from the double you are trying to get the decimals from using the Remove() function after converting the double to string so that you could do the operations required on it

Consider having a double _Double of value of 0.66781, the following code will only show the numbers after the dot . which are 66781

double _Double = 0.66781; //Declare a new double with a value of 0.66781
string _Decimals = _Double.ToString().Remove(0, _Double.ToString().IndexOf(".") + 1); //Remove everything starting with index 0 and ending at the index of ([the dot .] + 1) 

Another Solution

You may use the class Path as well which performs operations on string instances in a cross-platform manner

double _Double = 0.66781; //Declare a new double with a value of 0.66781
string Output = Path.GetExtension(D.ToString()).Replace(".",""); //Get (the dot and the content after the last dot available and replace the dot with nothing) as a new string object Output
//Do something

Create two-dimensional arrays and access sub-arrays in Ruby

Here's a 3D array case

class Array3D
   def initialize(d1,d2,d3)
    @data = Array.new(d1) { Array.new(d2) { Array.new(d3) } }
   end

  def [](x, y, z)
    @data[x][y][z]
  end

  def []=(x, y, z, value)
    @data[x][y][z] = value
  end
end

You can access subsections of each array just like any other Ruby array. @data[0..2][3..5][8..10] = 0 etc

What does "Content-type: application/json; charset=utf-8" really mean?

I was using HttpClient and getting back response header with content-type of application/json, I lost characters such as foreign languages or symbol that used unicode since HttpClient is default to ISO-8859-1. So, be explicit as possible as mentioned by @WesternGun to avoid any possible problem.

There is no way handle that due to server doesn't handle requested-header charset (method.setRequestHeader("accept-charset", "UTF-8");) for me and I had to retrieve response data as draw bytes and convert it into String using UTF-8. So, it is recommended to be explicit and avoid assumption of default value.

Transitions on the CSS display property

Edit: display none is not being applied in this example.

@keyframes hide {
  0% {
    display: block;
    opacity: 1;
  }
  99% {
    display: block;
  }
  100% {
    display: none;
    opacity: 0;
  }
}

What's happening above is that through 99% of the animation display is set to block while the opacity fades out. In the last moment display property is set to none.

And the most important bit is to retain the last frame after the animation ends using animation-fill-mode: forwards

.hide {
   animation: hide 1s linear;
   animation-fill-mode: forwards;
}

Here are two examples: https://jsfiddle.net/qwnz9tqg/3/

Recursively counting files in a Linux directory

This alternate approach with filtering for format counts all available grub kernel modules:

ls -l /boot/grub/*.mod | wc -l

How to grant remote access permissions to mysql server for user?

Try:

GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'Pa55w0rd' WITH GRANT OPTION;

Parsing Query String in node.js

require('url').parse('/status?name=ryan', {parseQueryString: true}).query

returns

{ name: 'ryan' }

ref: https://nodejs.org/api/url.html#url_urlobject_query

Google Map API v3 — set bounds and center

Use below one,

map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));

How to prevent line-break in a column of a table cell (not a single cell)?

There are a few ways to do this; none of them are the easy, obvious way.

Applying white-space:nowrap to a <col> won't work; only four CSS properties work on <col> elements - background-color, width, border, and visibility. IE7 and earlier used to support all properties, but that's because they used a strange table model. IE8 now matches everyone else.

So, how do you solve this?

Well, if you can ignore IE (including IE8), you can use the :nth-child() pseudoclass to select particular <td>s from each row. You'd use td:nth-child(2) { white-space:nowrap; }. (This works for this example, but would break if you had any rowspans or colspans involved.)

If you have to support IE, then you've got to go the long way around and apply a class to every <td> that you want to affect. It sucks, but them's the breaks.

In the long run, there are proposals to fix this lack in CSS, so that you can more easily apply styles to all the cells in a column. You'll be able to do something like td:nth-col(2) { white-space:nowrap; } and it would do what you want.

How do I execute multiple SQL Statements in Access' Query Editor?

"I hoped (and still hope) that there is something like my beloved SQL*Plus for Oracle that can execute a file with all kinds of SQL Statements."

If you're looking for a simple program that can import a file and execute the SQL statements in it, take a look at DBWConsole (freeware). I have used it to process DDL scripts (table schema) as well as action queries. It does not return data sets so it's not useful for SELECT queries. It supports single line comments prefixed by -- but not multi-line comments wrapped in /* */. It supports command line parameters.

enter image description here

If you want an interactive UI like Oracle SQL Developer or SSMS for Access then Matthew Lock's reference to WinSQL is what you should try.

How to replace a character from a String in SQL?

Use the REPLACE function.

eg: SELECT REPLACE ('t?es?t', '?', 'w');

Source

How to put a link on a button with bootstrap?

Combining the above answers i find a simply solution that probably will help you too:

<button type="submit" onclick="location.href = 'your_link';">Login</button>

by just adding inline JS code you can transform a button in a link and keeping his design.

How do I check whether a file exists without exceptions?

You can use the following open method to check if a file exists + readable:

file = open(inputFile, 'r')
file.close()

Parsing JSON with Unix tools

Using standard Unix tools available on most distro's. Also works well with backslashes (\) and quotes (")

WARNING: this doesn't come close to the power of jq and will only work with very simple JSON objects. It's an attempt to answer to the original question and in situations where you can't install additional tools.

function parse_json()
{
    echo $1 | \
    sed -e 's/[{}]/''/g' | \
    sed -e 's/", "/'\",\"'/g' | \
    sed -e 's/" ,"/'\",\"'/g' | \
    sed -e 's/" , "/'\",\"'/g' | \
    sed -e 's/","/'\"---SEPERATOR---\"'/g' | \
    awk -F=':' -v RS='---SEPERATOR---' "\$1~/\"$2\"/ {print}" | \
    sed -e "s/\"$2\"://" | \
    tr -d "\n\t" | \
    sed -e 's/\\"/"/g' | \
    sed -e 's/\\\\/\\/g' | \
    sed -e 's/^[ \t]*//g' | \
    sed -e 's/^"//'  -e 's/"$//'
}


parse_json '{"username":"john, doe","email":"[email protected]"}' username
parse_json '{"username":"john doe","email":"[email protected]"}' email

--- outputs ---

john, doe
[email protected]

Remove 'b' character do in front of a string literal in Python 3

Decoding is redundant

You only had this "error" in the first place, because of a misunderstanding of what's happening.

You get the b because you encoded to utf-8 and now it's a bytes object.

 >> type("text".encode("utf-8"))
 >> <class 'bytes'>

Fixes:

  1. You can just print the string first
  2. Redundantly decode it after encoding

How to convert a pymongo.cursor.Cursor into a dict?

The MongoDB find method does not return a single result, but a list of results in the form of a Cursor. This latter is an iterator, so you can go through it with a for loop.

For your case, just use the findOne method instead of find. This will returns you a single document as a dictionary.

Hidden property of a button in HTML

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>

function showButtons () { $('#b1, #b2, #b3').show(); }

</script>
<style type="text/css">
#b1, #b2, #b3 {
display: none;
}

</style>
</head>
<body>

<a href="#" onclick="showButtons();">Show me the money!</a>

<input type="submit" id="b1" value="B1" />
<input type="submit" id="b2" value="B2"/>
<input type="submit" id="b3" value="B3" />

</body>
</html>

Can CSS detect the number of children an element has?

If you are going to do it in pure CSS (using scss) but you have different elements/classes inside the same parent class you can use this version!!

  &:first-of-type:nth-last-of-type(1) {
    max-width: 100%;
  }

  @for $i from 2 through 10 {
    &:first-of-type:nth-last-of-type(#{$i}),
    &:first-of-type:nth-last-of-type(#{$i}) ~ & {
      max-width: (100% / #{$i});
    }
  }

Inline comments for Bash?

If you know a variable is empty, you could use it as a comment. Of course if it is not empty it will mess up your command.

ls -l ${1# -F is turned off} -a /etc

§ 10.2. Parameter Substitution

How do I loop through rows with a data reader in C#?

int count = reader.FieldCount;
while(reader.Read()) {
    for(int i = 0 ; i < count ; i++) {
        Console.WriteLine(reader.GetValue(i));
    }
}

Note; if you have multiple grids, then:

do {
    int count = reader.FieldCount;
    while(reader.Read()) {
        for(int i = 0 ; i < count ; i++) {
            Console.WriteLine(reader.GetValue(i));
        }
    }
} while (reader.NextResult())

Having services in React application

I also came from Angular.js area and the services and factories in React.js are more simple.

You can use plain functions or classes, callback style and event Mobx like me :)

_x000D_
_x000D_
// Here we have Service class > dont forget that in JS class is Function_x000D_
class HttpService {_x000D_
  constructor() {_x000D_
    this.data = "Hello data from HttpService";_x000D_
    this.getData = this.getData.bind(this);_x000D_
  }_x000D_
_x000D_
  getData() {_x000D_
    return this.data;_x000D_
  }_x000D_
}_x000D_
_x000D_
_x000D_
// Making Instance of class > it's object now_x000D_
const http = new HttpService();_x000D_
_x000D_
_x000D_
// Here is React Class extended By React_x000D_
class ReactApp extends React.Component {_x000D_
  state = {_x000D_
    data: ""_x000D_
  };_x000D_
_x000D_
  componentDidMount() {_x000D_
    const data = http.getData();_x000D_
_x000D_
    this.setState({_x000D_
      data: data_x000D_
    });_x000D_
  }_x000D_
_x000D_
  render() {_x000D_
    return <div>{this.state.data}</div>;_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<ReactApp />, document.getElementById("root"));
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width">_x000D_
  <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
  _x000D_
  <div id="root"></div>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Here is simple example :

How does Subquery in select statement work in oracle

In the Oracle RDBMS, it is possible to use a multi-row subquery in the select clause as long as the (sub-)output is encapsulated as a collection. In particular, a multi-row select clause subquery can output each of its rows as an xmlelement that is encapsulated in an xmlforest.

Python: How to ignore an exception and proceed?

There's a new way to do this coming in Python 3.4:

from contextlib import suppress

with suppress(Exception):
  # your code

Here's the commit that added it: http://hg.python.org/cpython/rev/406b47c64480

And here's the author, Raymond Hettinger, talking about this and all sorts of other Python hotness (relevant bit at 43:30): http://www.youtube.com/watch?v=OSGv2VnC0go

If you wanted to emulate the bare except keyword and also ignore things like KeyboardInterrupt—though you usually don't—you could use with suppress(BaseException).

Edit: Looks like ignored was renamed to suppress before the 3.4 release.

Python dictionary: Get list of values for list of keys

reduce(lambda x,y: mydict.get(y) and x.append(mydict[y]) or x, mykeys,[])

incase there are keys not in dict.

Facebook Graph API, how to get users email?

First, activate your application at the Facebook Developer center. Applications in development mode are not allowed to retrieve the e-mail field.

If the user is not logged in, you need to login and specify that your application/site will need the e-mail field.

FB.login(
    function(response) {
         console.log('Welcome!');
    },
    {scope: 'email'}
);

Then, after the login, or if the user is already logged, retrieve the e-mail using the Facebook API, specifying the field email:

FB.api('/me', {fields: 'name,email'}, (response) => {
    console.log(response.name + ', ' + response.email);
    console.log('full response: ', response);
});

NOT IN vs NOT EXISTS

In your specific example they are the same, because the optimizer has figured out what you are trying to do is the same in both examples. But it is possible that in non-trivial examples the optimizer may not do this, and in that case there are reasons to prefer one to other on occasion.

NOT IN should be preferred if you are testing multiple rows in your outer select. The subquery inside the NOT IN statement can be evaluated at the beginning of the execution, and the temporary table can be checked against each value in the outer select, rather than re-running the subselect every time as would be required with the NOT EXISTS statement.

If the subquery must be correlated with the outer select, then NOT EXISTS may be preferable, since the optimizer may discover a simplification that prevents the creation of any temporary tables to perform the same function.

How to hide a button programmatically?

public void OnClick(View.v)
Button b1 = (Button) findViewById(R.id.playButton);
b1.setVisiblity(View.INVISIBLE);

How do I compile and run a program in Java on my Mac?

Other solutions are good enough to answer your query. However, if you are looking for just one command to do that for you -

Create a file name "run", in directory where your Java files are. And save this in your file -

javac "$1.java"
if [ $? -eq 0 ]; then
  echo "--------Run output-------"
  java "$1"
fi

give this file run permission by running -

chmod 777 

Now you can run any of your files by merely running -

./run <yourfilename> (don't add .java in filename)

pip installs packages successfully, but executables not found from command line

I know the question asks about macOS, but here is a solution for Linux users who arrive here via Google.

I was having the issue described in this question, having installed the pdfx package via pip.

When I ran it however, nothing...

pip list | grep pdfx
pdfx (1.3.0)

Yet:

which pdfx
pdfx not found

The problem on Linux is that pip install ... drops scripts into ~/.local/bin and this is not on the default Debian/Ubuntu $PATH.

Here's a GitHub issue going into more detail: https://github.com/pypa/pip/issues/3813

To fix, just add ~/.local/bin to your $PATH, for example by adding the following line to your .bashrc file:

export PATH="$HOME/.local/bin:$PATH"

After that, restart your shell and things should work as expected.

How to use pull to refresh in Swift?

For the pull to refresh i am using

DGElasticPullToRefresh

https://github.com/gontovnik/DGElasticPullToRefresh

Installation

pod 'DGElasticPullToRefresh'

import DGElasticPullToRefresh

and put this function into your swift file and call this funtion from your

override func viewWillAppear(_ animated: Bool)

     func Refresher() {
      let loadingView = DGElasticPullToRefreshLoadingViewCircle()
      loadingView.tintColor = UIColor(red: 255.0/255.0, green: 255.0/255.0, blue: 255.0/255.0, alpha: 1.0)
      self.table.dg_addPullToRefreshWithActionHandler({ [weak self] () -> Void in

          //Completion block you can perfrom your code here.

           print("Stack Overflow")

           self?.table.dg_stopLoading()
           }, loadingView: loadingView)
      self.table.dg_setPullToRefreshFillColor(UIColor(red: 255.0/255.0, green: 57.0/255.0, blue: 66.0/255.0, alpha: 1))
      self.table.dg_setPullToRefreshBackgroundColor(self.table.backgroundColor!)
 }

And dont forget to remove reference while view will get dissapear

to remove pull to refresh put this code in to your

override func viewDidDisappear(_ animated: Bool)

override func viewDidDisappear(_ animated: Bool) {
      table.dg_removePullToRefresh()

 }

And it will looks like

enter image description here

Happy coding :)

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

The method tf.shape is a TensorFlow static method. However, there is also the method get_shape for the Tensor class. See

https://www.tensorflow.org/api_docs/python/tf/Tensor#get_shape

How to set a default Value of a UIPickerView

Swift solution:

Define an Outlet:

@IBOutlet weak var pickerView: UIPickerView!  // for example

Then in your viewWillAppear or your viewDidLoad, for example, you can use the following:

pickerView.selectRow(rowMin, inComponent: 0, animated: true)
pickerView.selectRow(rowSec, inComponent: 1, animated: true)

If you inspect the Swift 2.0 framework you'll see .selectRow defined as:

func selectRow(row: Int, inComponent component: Int, animated: Bool) 

option clicking .selectRow in Xcode displays the following:

enter image description here

How to get the selected date value while using Bootstrap Datepicker?

$("#startdate").data().datepicker.getFormattedDate('yyyy-mm-dd');

Adding a 'share by email' link to website

Easiest: http://www.addthis.com/

Best? Well. probably not, But If you don't want to design something bespoke this is the best there is...

foreach loop in angularjs

Questions 1 & 2

So basically, first parameter is the object to iterate on. It can be an array or an object. If it is an object like this :

var values = {name: 'misko', gender: 'male'};

Angular will take each value one by one the first one is name, the second is gender.

If your object to iterate on is an array (also possible), like this :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]

Angular.forEach will take one by one starting by the first object, then the second object.

For each of this object, it will so take them one by one and execute a specific code for each value. This code is called the iterator function. forEach is smart and behave differently if you are using an array of a collection. Here is some exemple :

var obj = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(obj, function(value, key) {
  console.log(key + ': ' + value);
});
// it will log two iteration like this
// name: misko
// gender: male

So key is the string value of your key and value is ... the value. You can use the key to access your value like this : obj['name'] = 'John'

If this time you display an array, like this :

var values = [{ "Name" : "Thomas", "Password" : "thomasTheKing" },
           { "Name" : "Linda", "Password" : "lindatheQueen" }];
angular.forEach(values, function(value, key){
     console.log(key + ': ' + value);
});
// it will log two iteration like this
// 0: [object Object]
// 1: [object Object]

So then value is your object (collection), and key is the index of your array since :

[{ "Name" : "Thomas", "Password" : "thomasTheKing" },
 { "Name" : "Linda", "Password" : "lindatheQueen" }]
// is equal to
{0: { "Name" : "Thomas", "Password" : "thomasTheKing" },
 1: { "Name" : "Linda", "Password" : "lindatheQueen" }}

I hope it answer your question. Here is a JSFiddle to run some code and test if you want : http://jsfiddle.net/ygahqdge/

Debugging your code

The problem seems to come from the fact $http.get() is an asynchronous request.

You send a query on your son, THEN when you browser end downloading it it execute success. BUT just after sending your request your perform a loop using angular.forEach without waiting the answer of your JSON.

You need to include the loop in the success function

var app = angular.module('testModule', [])
    .controller('testController', ['$scope', '$http', function($scope, $http){
    $http.get('Data/info.json').then(function(data){
         $scope.data = data;

         angular.forEach($scope.data, function(value, key){
         if(value.Password == "thomasTheKing")
           console.log("username is thomas");
         });
    });

});

This should work.

Going more deeply

The $http API is based on the deferred/promise APIs exposed by the $q service. While for simple usage patterns this doesn't matter much, for advanced usage it is important to familiarize yourself with these APIs and the guarantees they provide.

You can give a look at deferred/promise APIs, it is an important concept of Angular to make smooth asynchronous actions.

How can I issue a single command from the command line through sql plus?

Have you tried something like this?

sqlplus username/password@database < "EXECUTE some_proc /"

Seems like in UNIX you can do:

sqlplus username/password@database <<EOF
EXECUTE some_proc;
EXIT;
EOF

But I'm not sure what the windows equivalent of that would be.

regex pattern to match the end of a string

Something like this should work: /([^/]*)$

What language are you using? End-of-string regex signifiers can vary in different languages.

Is there a way to make a PowerShell script work by double clicking a .ps1 file?

You can use the Windows 'SendTo' functionality to make running PS1 scripts easier. Using this method you can right click on a PS1 script and execute. This is doesn't exactly answer the OP question but it is close. Hopefully, this is useful to others. BTW.. this is helpful for a variety of other tasks.

  • Locate / Search for Powershell.exe
  • Right click on Powershell.exe and choose Open File Location
  • Right click on Powershell.exe and choose Create Shortcut. Temporarily save some place like your desktop
  • You might want to open as Admin by default. Select Shortcut > Properties > Advanced > Open As Admin
  • Open the Sendto folder. Start > Run > Shell:Sendto
  • Move the Powershell.exe shortcut to the Sendto folder
  • You should now be able to right click on a PS1 script.
  • Right Click on a PS1 file, Select the SendTo context option > Select the Powershell shortcut
  • Your PS1 script should execute.

How do you cache an image in Javascript

There are a few things you can look at:

Pre-loading your images
Setting a cache time in an .htaccess file
File size of images and base64 encoding them.

Preloading: http://perishablepress.com/3-ways-preload-images-css-javascript-ajax/

Caching: http://www.askapache.com/htaccess/speed-up-sites-with-htaccess-caching.html

There are a couple different thoughts for base64 encoding, some say that the http requests bog down bandwidth, while others say that the "perceived" loading is better. I'll leave this up in the air.

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

I was trying some of the solutions here but then I actually came up with my own one. I hope this might be useful for the next one so I share it here:

def sort_correlation_matrix(correlation_matrix):
    cor = correlation_matrix.abs()
    top_col = cor[cor.columns[0]][1:]
    top_col = top_col.sort_values(ascending=False)
    ordered_columns = [cor.columns[0]] + top_col.index.tolist()
    return correlation_matrix[ordered_columns].reindex(ordered_columns)

Window vs Page vs UserControl for WPF navigation?

  • Window is like Windows.Forms.Form, so just a new window
  • Page is, according to online documentation:

    Encapsulates a page of content that can be navigated to and hosted by Windows Internet Explorer, NavigationWindow, and Frame.

    So you basically use this if going you visualize some HTML content

  • UserControl is for cases when you want to create some reusable component (but not standalone one) to use it in multiple different Windows

Named tuple and default values for optional keyword arguments

The answer by jterrace to use recordtype is great, but the author of the library recommends to use his namedlist project, which provides both mutable (namedlist) and immutable (namedtuple) implementations.

from namedlist import namedtuple
>>> Node = namedtuple('Node', ['val', ('left', None), ('right', None)])
>>> Node(3)
Node(val=3, left=None, right=None)
>>> Node(3, 'L')
Node(val=3, left=L, right=None)

C# List of objects, how do I get the sum of a property

Another alternative:

myPlanetsList.Select(i => i.Moons).Sum();

Bloomberg BDH function with ISIN

The problem is that an isin does not identify the exchange, only an issuer.

Let's say your isin is US4592001014 (IBM), one way to do it would be:

  • get the ticker (in A1):

    =BDP("US4592001014 ISIN", "TICKER") => IBM
    
  • get a proper symbol (in A2)

    =BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
    

    where XX depends on your terminal settings, which you can check on CNDF <Go>.

  • get the main exchange composite ticker, or whatever suits your need (in A3):

    =BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
    
  • and finally:

    =BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
    

byte[] to file in Java

File f = new File(fileName);    
byte[] fileContent = msg.getByteSequenceContent();    

Path path = Paths.get(f.getAbsolutePath());
try {
    Files.write(path, fileContent);
} catch (IOException ex) {
    Logger.getLogger(Agent2.class.getName()).log(Level.SEVERE, null, ex);
}

How can I set focus on an element in an HTML form using JavaScript?

For plain Javascript, try the following:

window.onload = function() {
  document.getElementById("TextBoxName").focus();
};

How do I generate sourcemaps when using babel and webpack?

Minimal webpack config for jsx with sourcemaps:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: `./src/index.jsx` ,
  output: {
    path:  path.resolve(__dirname,"build"),
    filename: "bundle.js"
  },
  devtool: 'eval-source-map',
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};

Running it:

Jozsefs-MBP:react-webpack-babel joco$ webpack -d
Hash: c75d5fb365018ed3786b
Version: webpack 1.13.2
Time: 3826ms
        Asset     Size  Chunks             Chunk Names
    bundle.js   1.5 MB       0  [emitted]  main
bundle.js.map  1.72 MB       0  [emitted]  main
    + 221 hidden modules
Jozsefs-MBP:react-webpack-babel joco$

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

Integer expression expected error in shell script

You can use this syntax:

#!/bin/bash

echo " Write in your age: "
read age

if [[ "$age" -le 7 || "$age" -ge 65 ]] ; then
    echo " You can walk in for free "
elif [[ "$age" -gt 7 && "$age" -lt 65 ]] ; then
    echo " You have to pay for ticket "
fi

How can I determine the type of an HTML element in JavaScript?

Sometimes you want element.constructor.name

document.createElement('div').constructor.name
// HTMLDivElement

document.createElement('a').constructor.name
// HTMLAnchorElement

document.createElement('foo').constructor.name
// HTMLUnknownElement

Git command to checkout any branch and overwrite local changes

git reset and git clean can be overkill in some situations (and be a huge waste of time).

If you simply have a message like "The following untracked files would be overwritten..." and you want the remote/origin/upstream to overwrite those conflicting untracked files, then git checkout -f <branch> is the best option.

If you're like me, your other option was to clean and perform a --hard reset then recompile your project.

How to subtract date/time in JavaScript?

If you wish to get difference in wall clock time, for local timezone and with day-light saving awareness.


Date.prototype.diffDays = function (date: Date): number {

    var utcThis = Date.UTC(this.getFullYear(), this.getMonth(), this.getDate(), this.getHours(), this.getMinutes(), this.getSeconds(), this.getMilliseconds());
    var utcOther = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds(), date.getMilliseconds());

    return (utcThis - utcOther) / 86400000;
};

Test


it('diffDays - Czech DST', function () {
    // expect this to parse as local time
    // with Czech calendar DST change happened 2012-03-25 02:00
    var pre = new Date('2012/03/24 03:04:05');
    var post = new Date('2012/03/27 03:04:05');

    // regardless DST, you still wish to see 3 days
    expect(pre.diffDays(post)).toEqual(-3);
});

Diff minutes or seconds is in same fashion.

Openssl is not recognized as an internal or external command

First navigate to your Java/jre/bin folder in cmd cd c:\Program Files (x86)\Java\jre7\bin

Then use : [change debug.keystore path to the correct location on your system] install openssl (for windows 32 or 64 as per your needs at c:\openssl )

keytool -exportcert -alias androiddebugkey -keystore "C:\Users\vibhor\.android\debug.keystore" | "c:\openssl\bin\openssl.exe" sha1 -binary | "c:\openssl\bin\openssl.exe" base64

So the whole command goes like this : [prompts to enter keystore password on execution ]

c:\Program Files (x86)\Java\jre7\bin>keytool -exportcert -alias androiddebugkey
-keystore "C:\Users\vibhor\.android\debug.keystore" | "c:\openssl\bin\openssl.ex
e" sha1 -binary | "c:\openssl\bin\openssl.exe" base64
Enter keystore password:

Using Spring MVC Test to unit test multipart POST request

Here's what worked for me, here I'm attaching a file to my EmailController under test. Also take a look at the postman screenshot on how I'm posting the data.

    @WebAppConfiguration
    @RunWith(SpringRunner.class)
    @SpringBootTest(
            classes = EmailControllerBootApplication.class
        )
    public class SendEmailTest {

        @Autowired
        private WebApplicationContext webApplicationContext;

        @Test
        public void testSend() throws Exception{
            String jsonStr = "{\"to\": [\"[email protected]\"],\"subject\": "
                    + "\"CDM - Spring Boot email service with attachment\","
                    + "\"body\": \"Email body will contain  test results, with screenshot\"}";

            Resource fileResource = new ClassPathResource(
                    "screen-shots/HomePage-attachment.png");

            assertNotNull(fileResource);

            MockMultipartFile firstFile = new MockMultipartFile( 
                       "attachments",fileResource.getFilename(),
                        MediaType.MULTIPART_FORM_DATA_VALUE,
                        fileResource.getInputStream());  
                        assertNotNull(firstFile);


            MockMvc mockMvc = MockMvcBuilders.
                  webAppContextSetup(webApplicationContext).build();

            mockMvc.perform(MockMvcRequestBuilders
                   .multipart("/api/v1/email/send")
                    .file(firstFile)
                    .param("data", jsonStr))
                    .andExpect(status().is(200));
            }
        }

Postman Request

Check if value already exists within list of dictionaries?

Maybe this helps:

a = [{ 'main_color': 'red', 'second_color':'blue'},
     { 'main_color': 'yellow', 'second_color':'green'},
     { 'main_color': 'yellow', 'second_color':'blue'}]

def in_dictlist((key, value), my_dictlist):
    for this in my_dictlist:
        if this[key] == value:
            return this
    return {}

print in_dictlist(('main_color','red'), a)
print in_dictlist(('main_color','pink'), a)

Error loading the SDK when Eclipse starts

I faced the same issue. To get rid of this issue, I followed the below steps and it worked for me.

  1. Close Eclipse
  2. Open file devices.xml(location of this will be shown in the error message) in a text editor.
  3. Comment out all tags contains d:skin
  4. Save files
  5. Reopen Eclipse

Viewing PDF in Windows forms using C#

you can use System.Diagnostics.Process.Start as well as WIN32 ShellExecute function by means of interop, for opening PDF files using the default viewer:

System.Diagnostics.Process.Start("SOMEAPP.EXE","Path/SomeFile.Ext");

[System.Runtime.InteropServices.DllImport("shell32. dll")]
private static extern long ShellExecute(Int32 hWnd, string lpOperation, 
                                    string lpFile, string lpParameters, 
                                        string lpDirectory, long nShowCmd);

Another approach is to place a WebBrowser Control into your Form and then use the Navigate method for opening the PDF file:

ThewebBrowserControl.Navigate(@"c:\the_file.pdf");

Is JavaScript object-oriented?

I think a lot of people answer this question "no" because JavaScript does not implement classes, in the traditional OO sense. Unfortunately (IMHO), that is coming in ECMAScript 4. Until then, viva la prototype! :-)

webpack: Module not found: Error: Can't resolve (with relative path)

Look the path for example this import is not correct import Navbar from '@/components/Navbar.vue' should look like this ** import Navbar from './components/Navbar.vue'**

How to scan multiple paths using the @ComponentScan annotation?

I use:

@ComponentScan(basePackages = {"com.package1","com.package2","com.package3", "com.packagen"})

How do you transfer or export SQL Server 2005 data to Excel

You could always use ADO to write the results out to the worksheet cells from a recordset object

c# search string in txt file

If you whant only one first string, you can use simple for-loop.

var lines = File.ReadAllLines(pathToTextFile);

var firstFound = false;
for(int index = 0; index < lines.Count; index++)
{
   if(!firstFound && lines[index].Contains("CustomerEN"))
   {
      firstFound = true;
   }
   if(firstFound && lines[index].Contains("CustomerCh"))
   {
      //do, what you want, and exit the loop
      // return lines[index];
   }
}

Change Active Menu Item on Page Scroll?

Just check my Code and Sniper and demo link :

    // Basice Code keep it 
    $(document).ready(function () {
        $(document).on("scroll", onScroll);

        //smoothscroll
        $('a[href^="#"]').on('click', function (e) {
            e.preventDefault();
            $(document).off("scroll");

            $('a').each(function () {
                $(this).removeClass('active');
            })
            $(this).addClass('active');

            var target = this.hash,
                menu = target;
            $target = $(target);
            $('html, body').stop().animate({
                'scrollTop': $target.offset().top+2
            }, 500, 'swing', function () {
                window.location.hash = target;
                $(document).on("scroll", onScroll);
            });
        });
    });

// Use Your Class or ID For Selection 

    function onScroll(event){
        var scrollPos = $(document).scrollTop();
        $('#menu-center a').each(function () {
            var currLink = $(this);
            var refElement = $(currLink.attr("href"));
            if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
                $('#menu-center ul li a').removeClass("active");
                currLink.addClass("active");
            }
            else{
                currLink.removeClass("active");
            }
        });
    }

demo live

_x000D_
_x000D_
$(document).ready(function () {_x000D_
    $(document).on("scroll", onScroll);_x000D_
    _x000D_
    //smoothscroll_x000D_
    $('a[href^="#"]').on('click', function (e) {_x000D_
        e.preventDefault();_x000D_
        $(document).off("scroll");_x000D_
        _x000D_
        $('a').each(function () {_x000D_
            $(this).removeClass('active');_x000D_
        })_x000D_
        $(this).addClass('active');_x000D_
      _x000D_
        var target = this.hash,_x000D_
            menu = target;_x000D_
        $target = $(target);_x000D_
        $('html, body').stop().animate({_x000D_
            'scrollTop': $target.offset().top+2_x000D_
        }, 500, 'swing', function () {_x000D_
            window.location.hash = target;_x000D_
            $(document).on("scroll", onScroll);_x000D_
        });_x000D_
    });_x000D_
});_x000D_
_x000D_
function onScroll(event){_x000D_
    var scrollPos = $(document).scrollTop();_x000D_
    $('#menu-center a').each(function () {_x000D_
        var currLink = $(this);_x000D_
        var refElement = $(currLink.attr("href"));_x000D_
        if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {_x000D_
            $('#menu-center ul li a').removeClass("active");_x000D_
            currLink.addClass("active");_x000D_
        }_x000D_
        else{_x000D_
            currLink.removeClass("active");_x000D_
        }_x000D_
    });_x000D_
}
_x000D_
body, html {_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
    height: 100%;_x000D_
    width: 100%;_x000D_
}_x000D_
.menu {_x000D_
    width: 100%;_x000D_
    height: 75px;_x000D_
    background-color: rgba(0, 0, 0, 1);_x000D_
    position: fixed;_x000D_
    background-color:rgba(4, 180, 49, 0.6);_x000D_
    -webkit-transition: all 0.4s ease;_x000D_
    -moz-transition: all 0.4s ease;_x000D_
    -o-transition: all 0.4s ease;_x000D_
    transition: all 0.4s ease;_x000D_
}_x000D_
.light-menu {_x000D_
    width: 100%;_x000D_
    height: 75px;_x000D_
    background-color: rgba(255, 255, 255, 1);_x000D_
    position: fixed;_x000D_
    background-color:rgba(4, 180, 49, 0.6);_x000D_
    -webkit-transition: all 0.4s ease;_x000D_
    -moz-transition: all 0.4s ease;_x000D_
    -o-transition: all 0.4s ease;_x000D_
    transition: all 0.4s ease;_x000D_
}_x000D_
#menu-center {_x000D_
    width: 980px;_x000D_
    height: 75px;_x000D_
    margin: 0 auto;_x000D_
}_x000D_
#menu-center ul {_x000D_
    margin: 0 0 0 0;_x000D_
}_x000D_
#menu-center ul li a{_x000D_
  padding: 32px 40px;_x000D_
}_x000D_
#menu-center ul li {_x000D_
    list-style: none;_x000D_
    margin: 0 0 0 -4px;_x000D_
    display: inline;_x000D_
_x000D_
}_x000D_
.active, #menu-center ul li a:hover  {_x000D_
    font-family:'Droid Sans', serif;_x000D_
    font-size: 14px;_x000D_
    color: #fff;_x000D_
    text-decoration: none;_x000D_
    line-height: 50px;_x000D_
 background-color: rgba(0, 0, 0, 0.12);_x000D_
 padding: 32px 40px;_x000D_
_x000D_
}_x000D_
a {_x000D_
    font-family:'Droid Sans', serif;_x000D_
    font-size: 14px;_x000D_
    color: black;_x000D_
    text-decoration: none;_x000D_
    line-height: 72px;_x000D_
}_x000D_
#home {_x000D_
    background-color: #286090;_x000D_
    height: 100vh;_x000D_
    width: 100%;_x000D_
    overflow: hidden;_x000D_
}_x000D_
#portfolio {_x000D_
    background: gray; _x000D_
    height: 100vh;_x000D_
    width: 100%;_x000D_
}_x000D_
#about {_x000D_
    background-color: blue;_x000D_
    height: 100vh;_x000D_
    width: 100%;_x000D_
}_x000D_
#contact {_x000D_
    background-color: rgb(154, 45, 45);_x000D_
    height: 100vh;_x000D_
    width: 100%;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- <div class="container"> --->_x000D_
   <div class="m1 menu">_x000D_
   <div id="menu-center">_x000D_
    <ul>_x000D_
     <li><a class="active" href="#home">Home</a>_x000D_
_x000D_
     </li>_x000D_
     <li><a href="#portfolio">Portfolio</a>_x000D_
_x000D_
     </li>_x000D_
     <li><a href="#about">About</a>_x000D_
_x000D_
     </li>_x000D_
     <li><a href="#contact">Contact</a>_x000D_
_x000D_
     </li>_x000D_
    </ul>_x000D_
   </div>_x000D_
   </div>_x000D_
   <div id="home"></div>_x000D_
   <div id="portfolio"></div>_x000D_
   <div id="about"></div>_x000D_
   <div id="contact"></div>
_x000D_
_x000D_
_x000D_

How to throw std::exceptions with variable messages?

The standard exceptions can be constructed from a std::string:

#include <stdexcept>

char const * configfile = "hardcode.cfg";
std::string const anotherfile = get_file();

throw std::runtime_error(std::string("Failed: ") + configfile);
throw std::runtime_error("Error: " + anotherfile);

Note that the base class std::exception can not be constructed thus; you have to use one of the concrete, derived classes.

Write to file, but overwrite it if it exists

In Bash, if you have set noclobber a la set -o noclobber, then you use the syntax >|

For example:

echo "some text" >| existing_file

This also works if the file doesn't exist yet


  • Check if noclobber is set with: set -o | grep noclobber

  • For a more detailed explanation on this special type of operator, see this post

  • For a more exhaustive list of redirection operators, refer to this post

Switching to a TabBar tab view programmatically?

Like Stuart Clark's solution but for Swift 3:

func setTab<T>(_ myClass: T.Type) {
    var i: Int = 0
    if let controllers = self.tabBarController?.viewControllers {
        for controller in controllers {
            if let nav = controller as? UINavigationController, nav.topViewController is T {
                break
            }
            i = i+1
        }
    }
    self.tabBarController?.selectedIndex = i
}

Use it like this:

setTab(MyViewController.self)

Please note that my tabController links to viewControllers behind navigationControllers. Without navigationControllers it would look like this:

if let controller is T {

mysqldump Error 1045 Access denied despite correct passwords etc

You need to put backslashes in your password that contain shell metacharacters, such as !#'"`&;

How to do a newline in output

I would like to share my experience with \n
I came to notice that "\n" works as-

puts "\n\n" // to provide 2 new lines

but not

p "\n\n"

also puts '\n\n'
Doesn't works.

Hope will work for you!!

Create an enum with string values

If what you want is mainly easy debug (with fairly type check) and don't need to specify special values for the enum, this is what I'm doing:

export type Enum = { [index: number]: string } & { [key: string]: number } | Object;

/**
 * inplace update
 * */
export function enum_only_string<E extends Enum>(e: E) {
  Object.keys(e)
    .filter(i => Number.isFinite(+i))
    .forEach(i => {
      const s = e[i];
      e[s] = s;
      delete e[i];
    });
}

enum AuthType {
  phone, email, sms, password
}
enum_only_string(AuthType);

If you want to support legacy code/data storage, you might keep the numeric keys.

This way, you can avoid typing the values twice.

program cant start because php5.dll is missing

I needed to change environment variable PATH and PHPRC. Also open new cmd.

I already had PHP installed and added EasyPHP when the problem came up. After I changed both variables to C:\Program Files (x86)\EasyPHP-DevServer-14.1VC9\binaries\php\php_runningversion it worked fine.

What is the difference between XML and XSD?

XML has a much wider application than f.ex. HTML. It doesn't have an intrinsic, or default "application". So, while you might not really care that web pages are also governed by what's allowed, from the author's side, you'll probably want to precisely define what an XML document may and may not contain.

It's like designing a database.

The thing about XML technologies is that they are textual in nature. With XSD, it means you have a data structure definition framework that can be "plugged in" to text processing tools like PHP. So not only can you manipulate the data itself, but also very easily change and document the structure, and even auto-generate front-ends.

Viewed like this, XSD is the "glue" or "middleware" between data (XML) and data-processing tools.

Return string Input with parse.string

If you're really bent upon converting Integer to String value, I suggest use String.valueOf(YourIntegerVariable). More details can be found at: http://www.tutorialspoint.com/java/java_string_valueof.htm

Cannot create SSPI context

We had this issue on instances in which we changed the service user from Domain1\ServiceUser to Domain2\ServiceUser. The SPNs remained registered under Domain1\ServiceUser, and never registered under Domain2\ServiceUser. We registered the SPNs under Domain2\ServiceUser, but the issue persisted. We then removed the SPNs under Domain1\ServiceUser, and the issue was resolved.

SQL Server, How to set auto increment after creating a table without data loss?

Changing the IDENTITY property is really a metadata only change. But to update the metadata directly requires starting the instance in single user mode and messing around with some columns in sys.syscolpars and is undocumented/unsupported and not something I would recommend or will give any additional details about.

For people coming across this answer on SQL Server 2012+ by far the easiest way of achieving this result of an auto incrementing column would be to create a SEQUENCE object and set the next value for seq as the column default.

Alternatively, or for previous versions (from 2005 onwards), the workaround posted on this connect item shows a completely supported way of doing this without any need for size of data operations using ALTER TABLE...SWITCH. Also blogged about on MSDN here. Though the code to achieve this is not very simple and there are restrictions - such as the table being changed can't be the target of a foreign key constraint.

Example code.

Set up test table with no identity column.

CREATE TABLE dbo.tblFoo 
(
bar INT PRIMARY KEY,
filler CHAR(8000),
filler2 CHAR(49)
)


INSERT INTO dbo.tblFoo (bar)
SELECT TOP (10000) ROW_NUMBER() OVER (ORDER BY (SELECT 0))
FROM master..spt_values v1, master..spt_values v2

Alter it to have an identity column (more or less instant).

BEGIN TRY;
    BEGIN TRANSACTION;

    /*Using DBCC CHECKIDENT('dbo.tblFoo') is slow so use dynamic SQL to
      set the correct seed in the table definition instead*/
    DECLARE @TableScript nvarchar(max)
    SELECT @TableScript = 
    '
    CREATE TABLE dbo.Destination(
        bar INT IDENTITY(' + 
                     CAST(ISNULL(MAX(bar),0)+1 AS VARCHAR) + ',1)  PRIMARY KEY,
        filler CHAR(8000),
        filler2 CHAR(49)
        )

        ALTER TABLE dbo.tblFoo SWITCH TO dbo.Destination;
    '       
    FROM dbo.tblFoo
    WITH (TABLOCKX,HOLDLOCK)

    EXEC(@TableScript)


    DROP TABLE dbo.tblFoo;

    EXECUTE sp_rename N'dbo.Destination', N'tblFoo', 'OBJECT';


    COMMIT TRANSACTION;
END TRY
BEGIN CATCH
    IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
    PRINT ERROR_MESSAGE();
END CATCH;

Test the result.

INSERT INTO dbo.tblFoo (filler,filler2) 
OUTPUT inserted.*
VALUES ('foo','bar')

Gives

bar         filler    filler2
----------- --------- ---------
10001       foo       bar      

Clean up

DROP TABLE dbo.tblFoo

How does one represent the empty char?

String before = EMPTY_SPACE+TAB+"word"+TAB+EMPTY_SPACE;

Where EMPTY_SPACE = " " (this is String) TAB = '\t' (this is Character)

String after = before.replaceAll(" ", "").replace('\t', '\0');

means after = "word"

How to remove all duplicate items from a list

In this way one can delete a particular item which is present multiple times in a list : Try deleting all 5

list1=[1,2,3,4,5,6,5,3,5,7,11,5,9,8,121,98,67,34,5,21]
print list1
n=input("item to be deleted : " )
for i in list1:
    if n in list1:
        list1.remove(n)
print list1

How to send UTF-8 email?

If not HTML, then UTF-8 is not recommended. koi8-r and windows-1251 only without problems. So use html mail.

$headers['Content-Type']='text/html; charset=UTF-8';
$body='<html><head><meta charset="UTF-8"><title>ESP Notufy - ESP ?????????</title></head><body>'.$text.'</body></html>';


$mail_object=& Mail::factory('smtp',
    array ('host' => $host,
        'auth' => true,
        'username' => $username,
        'password' => $password));
$mail_object->send($recipents, $headers, $body);
}

What's the difference between "Solutions Architect" and "Applications Architect"?

There are valid differences between types of architects:

Enterprise architects look at solutions for the enterprise aligining tightly with the enterprise strategy. Eg in a bank, they'll look at the complete IT landscape.

Solution architects focus on a particular solution, for example a new credit card acquiring system in a bank.

Domain architects focus on specific areas, for example an application architect or network architect.

Technical architects generally play the role of solution architects with less focus on the business aspect and more on the techology aspect.

Making a button invisible by clicking another button in HTML

Using jQuery!

var demoShow = function(){
    $("#p2").hide();
}

But I would recommend you give an id to your button on which you want an action to happen. For example:

<input type="button" id="p1" value="edit" />
<input type="button" id="p2" value="submit" name="submit" />

<script type="text/javascript"> 
$("#p1").click(function(){
    $("#p2").hide();
});
</script>

To show it again you can simply write: $("#p2").show();

How to access child's state in React?

As the previous answers saids, try to move the state to a top component and modify the state through callbacks passed to it's children.

In case that you really need to access to a child state that is declared as a functional component (hooks) you can declare a ref in the parent component, then pass it as a ref attribute to the child but you need to use React.forwardRef and then the hook useImperativeHandle to declare a function you can call in the parent component.

Take a look at the following example:

const Parent = () => {
    const myRef = useRef();
    return <Child ref={myRef} />;
}

const Child = React.forwardRef((props, ref) => {
    const [myState, setMyState] = useState('This is my state!');
    useImperativeHandle(ref, () => ({getMyState: () => {return myState}}), [myState]);
})

Then you should be able to get myState in the Parent component by calling: myRef.current.getMyState();

How to serve static files in Flask

The simplest way is create a static folder inside the main project folder. Static folder containing .css files.

main folder

/Main Folder
/Main Folder/templates/foo.html
/Main Folder/static/foo.css
/Main Folder/application.py(flask script)

Image of main folder containing static and templates folders and flask script

flask

from flask import Flask, render_template

app = Flask(__name__)

@app.route("/")
def login():
    return render_template("login.html")

html (layout)

<!DOCTYPE html>
<html>
    <head>
        <title>Project(1)</title>
        <link rel="stylesheet" href="/static/styles.css">
     </head>
    <body>
        <header>
            <div class="container">
                <nav>
                    <a class="title" href="">Kamook</a>
                    <a class="text" href="">Sign Up</a>
                    <a class="text" href="">Log In</a>
                </nav>
            </div>
        </header>  
        {% block body %}
        {% endblock %}
    </body>
</html>

html

{% extends "layout.html" %}

{% block body %}
    <div class="col">
        <input type="text" name="username" placeholder="Username" required>
        <input type="password" name="password" placeholder="Password" required>
        <input type="submit" value="Login">
    </div>
{% endblock %}

Formatting DataBinder.Eval data

Text='<%# DateTime.Parse(Eval("LastLoginDate").ToString()).ToString("MM/dd/yyyy hh:mm tt") %>'

This works for the format as you want

How to force table cell <td> content to wrap?

If you are using Bootstrap responsive table, just want to set the maximum width for one particular column and make text wrapping, making the the style of this column as following also works

max-width:someValue;
word-wrap:break-word

Difference between sh and bash

/bin/sh may or may not invoke the same program as /bin/bash.

sh supports at least the features required by POSIX (assuming a correct implementation). It may support extensions as well.

bash, the "Bourne Again Shell", implements the features required for sh plus bash-specific extensions. The full set of extensions is too long to describe here, and it varies with new releases. The differences are documented in the bash manual. Type info bash and read the "Bash Features" section (section 6 in the current version), or read the current documentation online.

When do you use Git rebase instead of Git merge?

This sentence gets it:

In general, the way to get the best of both worlds is to rebase local changes you’ve made, but haven’t shared yet, before you push them in order to clean up your story, but never rebase anything you’ve pushed somewhere.

Source: 3.6 Git Branching - Rebasing, Rebase vs. Merge

Spring Boot Rest Controller how to return different HTTP status codes?

There are different ways to return status code, 1 : RestController class should extends BaseRest class, in BaseRest class we can handle exception and return expected error codes. for example :

@RestController
@RequestMapping
class RestController extends BaseRest{

}

@ControllerAdvice
public class BaseRest {
@ExceptionHandler({Exception.class,...})
    @ResponseStatus(value=HttpStatus.INTERNAL_SERVER_ERROR)
    public ErrorModel genericError(HttpServletRequest request, 
            HttpServletResponse response, Exception exception) {
        
        ErrorModel error = new ErrorModel();
        resource.addError("error code", exception.getLocalizedMessage());
        return error;
    }

Calling an API from SQL Server stored procedure

Please see a link for more details.

Declare @Object as Int;
Declare @ResponseText as Varchar(8000);

Code Snippet
Exec sp_OACreate 'MSXML2.XMLHTTP', @Object OUT;
Exec sp_OAMethod @Object, 'open', NULL, 'get',
                 'http://www.webservicex.com/stockquote.asmx/GetQuote?symbol=MSFT', --Your Web Service Url (invoked)
                 'false'
Exec sp_OAMethod @Object, 'send'
Exec sp_OAMethod @Object, 'responseText', @ResponseText OUTPUT

Select @ResponseText

Exec sp_OADestroy @Object

How to check if memcache or memcached is installed for PHP?

Note that all of the class_exists, extensions_loaded, and function_exists only check the link between PHP and the memcache package.

To actually check whether memcache is installed you must either:

  • know the OS platform and use shell commands to check whether memcache package is installed
  • or test whether memcache connection can be established on the expected port

EDIT 2: OK, actually here's an easier complete solution:

if (class_exists('Memcache')) {
    $memcache = new Memcache;
    $isMemcacheAvailable = @$memcache->connect('localhost');
}
if ($isMemcacheAvailable) {
    //...
}

Outdated code below


EDIT: Actually you must force PHP to throw error on warnings first. Have a look at this SO question answer.

You can then test the connection via:

try {
    $memcache->connect('localhost');
} catch (Exception $e) {
    // well it's not here
}

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

You should in fact URI-encode the "invalid" characters. Since the string actually contains the complete URL, it's hard to properly URI-encode it. You don't know which slashes / should be taken into account and which not. You cannot predict that on a raw String beforehand. The problem really needs to be solved at a higher level. Where does that String come from? Is it hardcoded? Then just change it yourself accordingly. Does it come in as user input? Validate it and show error, let the user solve itself.

At any way, if you can ensure that it are only the spaces in URLs which makes it invalid, then you can also just do a string-by-string replace with %20:

URI uri = new URI(string.replace(" ", "%20"));

Or if you can ensure that it's only the part after the last slash which needs to be URI-encoded, then you can also just do so with help of android.net.Uri utility class:

int pos = string.lastIndexOf('/') + 1;
URI uri = new URI(string.substring(0, pos) + Uri.encode(string.substring(pos)));

Do note that URLEncoder is insuitable for the task as it's designed to encode query string parameter names/values as per application/x-www-form-urlencoded rules (as used in HTML forms). See also Java URL encoding of query string parameters.

Using switch statement with a range of value in each case?

Or you could use your solo cases as intended and use your default case to specify range instructions as :

switch(n) {
    case 1 : System.out.println("case 1"); break;
    case 4 : System.out.println("case 4"); break;
    case 99 : System.out.println("case 99"); break;
    default :
        if (n >= 10 && n <= 15)
            System.out.println("10-15 range"); 
        else if (n >= 100 && n <= 200)
            System.out.println("100-200 range");
        else
            System.out.println("Your default case");
        break;   
}

How to call a method in MainActivity from another class?

What I have done with no memory leaks or lint warnings is to use @f.trajkovski's method, but instead of using MainActivity, use WeakReference<MainActivity> instead.

public class MainActivity extends AppCompatActivity {
public static WeakReference<MainActivity> weakActivity;
// etc..
 public static MainActivity getmInstanceActivity() {
    return weakActivity.get();
}
}

Then in MainActivity OnCreate()

weakActivity = new WeakReference<>(MainActivity.this);

Then in another class

MainActivity.getmInstanceActivity().yourMethod();

Works like a charm

Using comma as list separator with AngularJS

I like simbu's approach, but I ain't comfortable to use first-child or last-child. Instead I only modify the content of a repeating list-comma class.

.list-comma + .list-comma::before {
    content: ', ';
}
<span class="list-comma" ng-repeat="destination in destinations">
    {{destination.name}}
</span>

C# ASP.NET MVC Return to Previous Page

For ASP.NET Core You can use asp-route-* attribute:

<form asp-action="Login" asp-route-previous="@Model.ReturnUrl">

An example: Imagine that you have a Vehicle Controller with actions

Index

Details

Edit

and you can edit any vehicle from Index or from Details, so if you clicked edit from index you must return to index after edit and if you clicked edit from details you must return to details after edit.

//In your viewmodel add the ReturnUrl Property
public class VehicleViewModel
{
     ..............
     ..............
     public string ReturnUrl {get;set;}
}



Details.cshtml
<a asp-action="Edit" asp-route-previous="Details" asp-route-id="@Model.CarId">Edit</a>

Index.cshtml
<a asp-action="Edit" asp-route-previous="Index" asp-route-id="@item.CarId">Edit</a>

Edit.cshtml
<form asp-action="Edit" asp-route-previous="@Model.ReturnUrl" class="form-horizontal">
        <div class="box-footer">
            <a asp-action="@Model.ReturnUrl" class="btn btn-default">Back to List</a>
            <button type="submit" value="Save" class="btn btn-warning pull-right">Save</button>
        </div>
    </form>

In your controller:

// GET: Vehicle/Edit/5
    public ActionResult Edit(int id,string previous)
    {
            var model = this.UnitOfWork.CarsRepository.GetAllByCarId(id).FirstOrDefault();
            var viewModel = this.Mapper.Map<VehicleViewModel>(model);//if you using automapper
    //or by this code if you are not use automapper
    var viewModel = new VehicleViewModel();

    if (!string.IsNullOrWhiteSpace(previous)
                viewModel.ReturnUrl = previous;
            else
                viewModel.ReturnUrl = "Index";
            return View(viewModel);
        }



[HttpPost]
    public IActionResult Edit(VehicleViewModel model, string previous)
    {
            if (!string.IsNullOrWhiteSpace(previous))
                model.ReturnUrl = previous;
            else
                model.ReturnUrl = "Index";
            ............. 
            .............
            return RedirectToAction(model.ReturnUrl);
    }

How to center a checkbox in a table cell?

This should work, I am using it:

<td align="center"> <input type="checkbox" name="myTextEditBox" value="checked" ></td>

Javascript/jQuery detect if input is focused

Using jQuery's .is( ":focus" )

$(".status").on("click","textarea",function(){
        if ($(this).is( ":focus" )) {
            // fire this step
        }else{
                    $(this).focus();
            // fire this step
    }

How do you check whether a number is divisible by another number (Python)?

For small numbers n%3 == 0 will be fine. For very large numbers I propose to calculate the cross sum first and then check if the cross sum is a multiple of 3:

def is_divisible_by_3(number):
    if sum(map(int, str(number))) % 3 != 0:
        my_bool = False
    return my_bool

Failed to resolve: com.google.firebase:firebase-core:16.0.1

I was able to solve the issue by following these steps-

1.) This error occurs when you didn't connect your project to firebase. Do that from Tools->Firebase if you are using Android studio version 2.2 or above.

2.) Make sure you have replaced the compile with implementation in dependencies in app/build.gradle

3.) Include your firebase dependency from the firebase docs. Everything should work fine now

jQuery issue - #<an Object> has no method

This usually has to do with a selector not being used properly. Check and make sure that you are using the jQuery selectors like intended. For example I had this problem when creating a click method:

$("[editButton]").click(function () {
    this.css("color", "red");
});

Because I was not using the correct selector method $(this) for jQuery it gave me the same error.

So simply enough, check your selectors!

Fit Image into PictureBox

You can set picturebox's SizeMode property to PictureSizeMode.Zoom, this will increase the size of smaller images or decrease the size of larger images to fill the PictureBox

Reliable way for a Bash script to get the full path to itself

I'm surprised that the realpath command hasn't been mentioned here. My understanding is that it is widely portable / ported.

Your initial solution becomes:

SCRIPT=`realpath $0`
SCRIPTPATH=`dirname $SCRIPT`

And to leave symbolic links unresolved per your preference:

SCRIPT=`realpath -s $0`
SCRIPTPATH=`dirname $SCRIPT`

Setting up foreign keys in phpMyAdmin?

Newer versions of phpMyAdmin don't have the "Relation View" option anymore, in which case you'll have to execute a statement to achieve the same thing. For example

ALTER TABLE employees
    ADD CONSTRAINT fk_companyid FOREIGN KEY (companyid)
    REFERENCES companies (id)
    ON DELETE CASCADE;

In this example, if a row from companies is deleted, all employees with that companyid are also deleted.

How to check a Long for null in java

Of course Primitive types cannot be null. But in Java 8 you can use Objects.isNull(longValue) to check. Ex. If(Objects.isNull(longValue))

How would you do a "not in" query with LINQ?

Example using List of int for simplicity.

List<int> list1 = new List<int>();
// fill data
List<int> list2 = new List<int>();
// fill data

var results = from i in list1
              where !list2.Contains(i)
              select i;

foreach (var result in results)
    Console.WriteLine(result.ToString());

How to convert string to Date in Angular2 \ Typescript?

You can use date filter to convert in date and display in specific format.

In .ts file (typescript):

let dateString = '1968-11-16T00:00:00' 
let newDate = new Date(dateString);

In HTML:

{{dateString |  date:'MM/dd/yyyy'}}

Below are some formats which you can implement :

Backend:

public todayDate = new Date();

HTML :

<select>
<option value=""></option>
<option value="MM/dd/yyyy">[{{todayDate | date:'MM/dd/yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy">[{{todayDate | date:'EEEE, MMMM d, yyyy'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm a'}}]</option>
<option value="EEEE, MMMM d, yyyy h:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy h:mm:ss a'}}]</option>
<option value="MM/dd/yyyy h:mm a">[{{todayDate | date:'MM/dd/yyyy h:mm a'}}]</option>
<option value="MM/dd/yyyy h:mm:ss a">[{{todayDate | date:'MM/dd/yyyy h:mm:ss a'}}]</option>
<option value="MMMM d">[{{todayDate | date:'MMMM d'}}]</option>   
<option value="yyyy-MM-ddTHH:mm:ss">[{{todayDate | date:'yyyy-MM-ddTHH:mm:ss'}}]</option>
<option value="h:mm a">[{{todayDate | date:'h:mm a'}}]</option>
<option value="h:mm:ss a">[{{todayDate | date:'h:mm:ss a'}}]</option>      
<option value="EEEE, MMMM d, yyyy hh:mm:ss a">[{{todayDate | date:'EEEE, MMMM d, yyyy hh:mm:ss a'}}]</option>
<option value="MMMM yyyy">[{{todayDate | date:'MMMM yyyy'}}]</option> 
</select>

Check whether a path is valid in Python without creating a file at the path's target

open(filename,'r')   #2nd argument is r and not w

will open the file or give an error if it doesn't exist. If there's an error, then you can try to write to the path, if you can't then you get a second error

try:
    open(filename,'r')
    return True
except IOError:
    try:
        open(filename, 'w')
        return True
    except IOError:
        return False

Also have a look here about permissions on windows

How can I output a UTF-8 CSV in PHP that Excel will read properly?

EASY solution for Mac Excel 2008: I struggled with this soo many times, but here was my easy fix: Open the .csv file in Textwrangler which should open your UTF-8 chars correctly. Now in the bottom status bar change the file format from "Unicode (UTF-8)" to "Western (ISO Latin 1)" and save the file. Now go to your Mac Excel 2008 and select File > Import > Select csv > Find your file > in File origin select "Windows (ANSI)" and voila the UTF-8 chars are showing correctly. At least it does for me...

Querying a linked sql server

SELECT * FROM [server].[database].[schema].[table]

This works for me. SSMS intellisense may still underline this as a syntax error, but it should work if your linked server is configured and your query is otherwise correct.

Apache won't follow symlinks (403 Forbidden)

With the option FollowSymLinks enabled:

$ rg "FollowSymLinks" /etc/httpd/
/etc/httpd/conf/httpd.conf
269:    Options Indexes FollowSymLinks

you need all the directories in symlink to be executable by the user httpd is using.

so for this general use case:

cd /path/to/your/web
sudo ln -s $PWD /srv/http/

You can check owner an permissions with namei:

$ namei -m /srv/http/web
f: /srv/http/web
 drwxr-xr-x /
 drwxr-xr-x srv
 drwxr-xr-x http
 lrwxrwxrwx web -> /path/to/your/web
   drwxr-xr-x /
   drwxr-xr-x path
   drwx------ to
   drwxr-xr-x your
   drwxr-xr-x web

In my case to directory was only executable for my user:

Enable execution by others solve it:

chmod o+x /path/to

See the non executable directory could be different, or you need to affect groups instead others, that depends on your case.

Is right click a Javascript event?

Easiest way to get right click done is using

 $('classx').on('contextmenu', function (event) {

 });

However this is not cross browser solution, browsers behave differently for this event especially firefox and IE. I would recommend below for a cross browser solution

$('classx').on('mousedown', function (event) {
    var keycode = ( event.keyCode ? event.keyCode : event.which );
    if (keycode === 3) {
       //your right click code goes here      
    }
});

How do I analyze a program's core dump file with GDB when it has command-line parameters?

From RMS's GDB debugger tutorial:

prompt > myprogram
Segmentation fault (core dumped)
prompt > gdb myprogram
...
(gdb) core core.pid
...

Make sure your file really is a core image -- check it using file.

How does the "position: sticky;" property work?

from my comment:

position:sticky needs a coordonate to tel where to stick

_x000D_
_x000D_
nav {_x000D_
  position: sticky;_x000D_
  top: 0;_x000D_
}_x000D_
_x000D_
.nav-selections {_x000D_
  text-transform: uppercase;_x000D_
  letter-spacing: 5px;_x000D_
  font: 18px "lato", sans-serif;_x000D_
  display: inline-block;_x000D_
  text-decoration: none;_x000D_
  color: white;_x000D_
  padding: 18px;_x000D_
  float: right;_x000D_
  margin-left: 50px;_x000D_
  transition: 1.5s;_x000D_
}_x000D_
_x000D_
.nav-selections:hover {_x000D_
  transition: 1.5s;_x000D_
  color: black;_x000D_
}_x000D_
_x000D_
ul {_x000D_
  background-color: #B79b58;_x000D_
  overflow: auto;_x000D_
}_x000D_
_x000D_
li {_x000D_
  list-style-type: none;_x000D_
}_x000D_
_x000D_
body {_x000D_
  height: 200vh;_x000D_
}
_x000D_
<nav>_x000D_
  <ul align="left">_x000D_
    <li><a href="#/contact" class="nav-selections" style="margin-right:35px;">Contact</a></li>_x000D_
    <li><a href="#/about" class="nav-selections">About</a></li>_x000D_
    <li><a href="#/products" class="nav-selections">Products</a></li>_x000D_
    <li><a href="#" class="nav-selections">Home</a></li>_x000D_
  </ul>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

There is polyfill to use for other browsers than FF and Chrome . This is an experimental rules that can be implemented or not at any time through browsers. Chrome add it a couple of years ago and then dropped it, it seems back ... but for how long ?

The closest would be position:relative + coordonates updated while scrolling once reached the sticky point, if you want to turn this into a javascript script

CSS image resize percentage of itself?

Although it does not answer the question directly, one way to scale images is relative to the size (especially width) of the viewport, which is mostly the use case for responsive design. No wrapper elements needed.

_x000D_
_x000D_
img {
    width: 50vw;
}
_x000D_
<img src="" />
_x000D_
_x000D_
_x000D_

Return rows in random order

To be efficient, and random, it might be best to have two different queries.

Something like...

SELECT table_id FROM table

Then, in your chosen language, pick a random id, then pull that row's data.

SELECT * FROM table WHERE table_id = $rand_id

But that's not really a good idea if you're expecting to have lots of rows in the table. It would be better if you put some kind of limit on what you randomly select from. For publications, maybe randomly pick from only items posted within the last year.

Is there any difference between DECIMAL and NUMERIC in SQL Server?

Joakim Backman's answer is specific, but this may bring additional clarity to it.

There is a minor difference. As per SQL For Dummies, 8th Edition (2013):

The DECIMAL data type is similar to NUMERIC. ... The difference is that your implementation may specify a precision greater than what you specify — if so, the implementation uses the greater precision. If you do not specify precision or scale, the implementation uses default values, as it does with the NUMERIC type.

It seems that the difference on some implementations of SQL is in data integrity. DECIMAL allows overflow from what is defined based on some system defaults, where as NUMERIC does not.

jQuery: If this HREF contains

Along with the points made by others, the $= selector is the "ends with" selector. You will want the *= (contains) selector, like so:

$('a').each(function() {
    if ($(this).is('[href*="?"')) {
        alert("Contains questionmark");
    }
});

Here's a live demo ->

As noted by Matt Ball, unless you will need to also manipulate links without a question mark (which may be the case, since you say your example is simplified), it would be less code and much faster to simply select only the links you want to begin with:

$('a[href*="?"]').each(function() {
    alert("Contains questionmark");
});

UILabel text margin

Subclassing is a little cumbersome for such a simple case. An alternative is to simply add the UILabel with no background set to a UIView with the background set. Set the label's x to 10 and make the outer view's size 20 pixels wider than the label.

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

You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/.

Your resource methods won't get hit, so their headers will never get set. The reason is that there is what's called a preflight request before the actual request, which is an OPTIONS request. So the error comes from the fact that the preflight request doesn't produce the necessary headers. check that you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

How to Maximize a firefox browser window using Selenium WebDriver with node.js

Call window as a function.

driver.manage().window().maximize();

linux/videodev.h : no such file or directory - OpenCV on ubuntu 11.04

v4l support has been dropped in recent kernel versions (including the one shipped with Ubuntu 11.04).

EDIT: Your question is connected to a recent message that was sent to the OpenCV users group, which has instructions to compile OpenCV 2.2 in Ubuntu 11.04. Your approach is not ideal.

ValueError: math domain error

Your code is doing a log of a number that is less than or equal to zero. That's mathematically undefined, so Python's log function raises an exception. Here's an example:

>>> from math import log
>>> log(-1)
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    log(-1)
ValueError: math domain error

Without knowing what your newtonRaphson2 function does, I'm not sure I can guess where the invalid x[2] value is coming from, but hopefully this will lead you on the right track.

How do I write data to csv file in columns and rows from a list in python?

Well, if you are writing to a CSV file, then why do you use space as a delimiter? CSV files use commas or semicolons (in Excel) as cell delimiters, so if you use delimiter=' ', you are not really producing a CSV file. You should simply construct csv.writer with the default delimiter and dialect. If you want to read the CSV file later into Excel, you could specify the Excel dialect explicitly just to make your intention clear (although this dialect is the default anyway):

example = csv.writer(open("test.csv", "wb"), dialect="excel")

Why doesn't wireshark detect my interface?

For *nix OSes, run wireshark with sudo privileges. You need to be superuser in order to be able to view interfaces. Just like running tcpdump -D vs sudo tcpdump -D, the first one won't show any of the interfaces, won't compalain/prompt for sudo privileges either.

So, from terminal, run:

$ sudo wireshark

500 internal server error at GetResponse()

Have you tried to specify UserAgent for your request? For example:

request.UserAgent = "Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)";

How to close a thread from within?

How about sys.exit() from the module sys.

If sys.exit() is executed from within a thread it will close that thread only.

This answer here talks about that: Why does sys.exit() not exit when called inside a thread in Python?

How can I add a new column and data to a datatable that already contains data?

Only you want to set default value parameter. This calling third overloading method.

dt.Columns.Add("MyRow", type(System.Int32),0);

python: changing row index of pandas data frame

When you are not sure of the number of rows, then you can do it this way:

followers_df.index = range(len(followers_df))

Android ListView with onClick items

You start new activities with intents. One method to send data to an intent is to pass a class that implements parcelable in the intent. Take note you are passing a copy of the class.

http://developer.android.com/reference/android/os/Parcelable.html

Here I have an onItemClick. I create intent and putExtra an entire class into the intent. The class I'm sending has implemented parcelable. Tip: You only need implement the parseable over what is minimally needed to re-create the class. Ie maybe a filename or something simple like a string something that a constructor can use to create the class. The new activity can later getExtras and it is essentially creating a copy of the class with its constructor method.

Here I launch the kmlreader class of my app when I recieve an onclick in the listview.

Note: below summary is a list of the class that I am passing so get(position) returns the class infact it is the same list that populates the listview

List<KmlSummary> summary = null;
...

public final static String EXTRA_KMLSUMMARY = "com.gosylvester.bestrides.util.KmlSummary";

...

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    lastshownitem = position;
    Intent intent = new Intent(context, KmlReader.class);
    intent.putExtra(ImageTextListViewActivity.EXTRA_KMLSUMMARY,
            summary.get(position));
    startActivity(intent);
}

later in the new activity I pull out the parseable class with

kmlSummary = intent.getExtras().getParcelable(
                ImageTextListViewActivity.EXTRA_KMLSUMMARY);

//note:
//KmlSummary implements parcelable.
//there is a constructor method for parcel in
// and a overridden writetoparcel method
// these are really easy to setup.

public KmlSummary(Parcel in) {
    this._id = in.readInt();
    this._description = in.readString();
    this._name = in.readString();
    this.set_bounds(in.readDouble(), in.readDouble(), in.readDouble(),
    in.readDouble());
    this._resrawid = in.readInt();
    this._resdrawableid = in.readInt();
     this._pathstring = in.readString();
    String s = in.readString();
    this.set_isThumbCreated(Boolean.parseBoolean(s));
}

@Override
public void writeToParcel(Parcel arg0, int arg1) {
    arg0.writeInt(this._id);
    arg0.writeString(this._description);
    arg0.writeString(this._name);
    arg0.writeDouble(this.get_bounds().southwest.latitude);
    arg0.writeDouble(this.get_bounds().southwest.longitude);
    arg0.writeDouble(this.get_bounds().northeast.latitude);
    arg0.writeDouble(this.get_bounds().northeast.longitude);
    arg0.writeInt(this._resrawid);
    arg0.writeInt(this._resdrawableid);
    arg0.writeString(this.get_pathstring());
    String s = Boolean.toString(this.isThumbCreated());
    arg0.writeString(s);
}

Good Luck Danny117

How do I remove repeated elements from ArrayList?

for(int a=0;a<myArray.size();a++){
        for(int b=a+1;b<myArray.size();b++){
            if(myArray.get(a).equalsIgnoreCase(myArray.get(b))){
                myArray.remove(b); 
                dups++;
                b--;
            }
        }
}

Storing WPF Image Resources

In code to load a resource in the executing assembly where my image Freq.png was in the folder Icons and defined as Resource:

this.Icon = new BitmapImage(new Uri(@"pack://application:,,,/" 
    + Assembly.GetExecutingAssembly().GetName().Name 
    + ";component/" 
    + "Icons/Freq.png", UriKind.Absolute)); 

I also made a function:

/// <summary>
/// Load a resource WPF-BitmapImage (png, bmp, ...) from embedded resource defined as 'Resource' not as 'Embedded resource'.
/// </summary>
/// <param name="pathInApplication">Path without starting slash</param>
/// <param name="assembly">Usually 'Assembly.GetExecutingAssembly()'. If not mentionned, I will use the calling assembly</param>
/// <returns></returns>
public static BitmapImage LoadBitmapFromResource(string pathInApplication, Assembly assembly = null)
{
    if (assembly == null)
    {
        assembly = Assembly.GetCallingAssembly();
    }

    if (pathInApplication[0] == '/')
    {
        pathInApplication = pathInApplication.Substring(1);
    }
    return new BitmapImage(new Uri(@"pack://application:,,,/" + assembly.GetName().Name + ";component/" + pathInApplication, UriKind.Absolute)); 
}

Usage (assumption you put the function in a ResourceHelper class):

this.Icon = ResourceHelper.LoadBitmapFromResource("Icons/Freq.png");

Note: see MSDN Pack URIs in WPF:
pack://application:,,,/ReferencedAssembly;component/Subfolder/ResourceFile.xaml

MySQL JOIN with LIMIT 1 on joined table

Accepted answer by @goggin13 looks wrong. Other solutions provided to-date will work, but suffer from the n+1 problem and as such, suffer a performance hit.

n+1 problem: If there are 100 categories, then we would have to do 1 select to get the categories, then for each of the 100 categories returned, we would need to do a select to get the products in that category. So 101 SELECT queries would be performed.

My alternative solution solves the n+1 problem and consequently should be significantly more performant as only 2 selects are being performed.

SELECT
  *
FROM
    (SELECT c.id, c.title, p.id AS product_id, p.title
    FROM categories AS c
    JOIN products AS p ON c.id = p.category_id
    ORDER BY c.id ASC) AS a 
GROUP BY id;

JPA mapping: "QuerySyntaxException: foobar is not mapped..."

You have declared your Class as:

@Table( name = "foobar" )
public class FooBar {

You need to write the Class Name for the search.
from FooBar

WordPress asking for my FTP credentials to install plugins

I did a local install of WordPress on Ubuntu 14.04 following the steps outlined here and simply running:

sudo chown -R www-data:www-data {path_to_your_project_directory}

solved my issue with downloading plugins. The only reason I'm leaving this post here is because when I googled my issue, this was one of the first results and it led me to the solution to my problem.

Hope this one helps to anyone!

How to clear Tkinter Canvas?

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

Android get image path from drawable as string

based on the some of above replies i improvised it a bit

create this method and call it by passing your resource

Reusable Method

public String getURLForResource (int resourceId) {
    //use BuildConfig.APPLICATION_ID instead of R.class.getPackage().getName() if both are not same
    return Uri.parse("android.resource://"+R.class.getPackage().getName()+"/" +resourceId).toString();
}

Sample call

getURLForResource(R.drawable.personIcon)

complete example of loading image

String imageUrl = getURLForResource(R.drawable.personIcon);
// Load image
 Glide.with(patientProfileImageView.getContext())
          .load(imageUrl)
          .into(patientProfileImageView);

you can move the function getURLForResource to a Util file and make it static so it can be reused

Why do we always prefer using parameters in SQL statements?

You are right, this is related to SQL injection, which is a vulnerability that allows a malicioius user to execute arbitrary statements against your database. This old time favorite XKCD comic illustrates the concept:

Her daughter is named Help I'm trapped in a driver's license factory.


In your example, if you just use:

var query = "SELECT empSalary from employee where salary = " + txtSalary.Text;
// and proceed to execute this query

You are open to SQL injection. For example, say someone enters txtSalary:

1; UPDATE employee SET salary = 9999999 WHERE empID = 10; --
1; DROP TABLE employee; --
// etc.

When you execute this query, it will perform a SELECT and an UPDATE or DROP, or whatever they wanted. The -- at the end simply comments out the rest of your query, which would be useful in the attack if you were concatenating anything after txtSalary.Text.


The correct way is to use parameterized queries, eg (C#):

SqlCommand query =  new SqlCommand("SELECT empSalary FROM employee 
                                    WHERE salary = @sal;");
query.Parameters.AddWithValue("@sal", txtSalary.Text);

With that, you can safely execute the query.

For reference on how to avoid SQL injection in several other languages, check bobby-tables.com, a website maintained by a SO user.

Python 3: EOF when reading a line (Sublime Text 2 is angry)

try:
    value = raw_input()
    do_stuff(value) # next line was found 
except (EOFError):
   break #end of file reached

This seems to be proper usage of raw_input when dealing with the end of the stream of input from piped input. [Refer this post][1]

ImportError: No Module named simplejson

Sometimes there is permission errors. Try:

sudo pip install simplejson

Hope it helps.

List of lists into numpy array

>>> numpy.array([[1, 2], [3, 4]]) 
array([[1, 2], [3, 4]])

Can someone give an example of cosine similarity, in a very simple, graphical way?

Using @Bill Bell example, two ways to do this in [R]

a = c(2,1,0,2,0,1,1,1)

b = c(2,1,1,1,1,0,1,1)

d = (a %*% b) / (sqrt(sum(a^2)) * sqrt(sum(b^2)))

or taking advantage of crossprod() method's performance...

e = crossprod(a, b) / (sqrt(crossprod(a, a)) * sqrt(crossprod(b, b)))

What is the use of ObservableCollection in .net?

class FooObservableCollection : ObservableCollection<Foo>
{
    protected override void InsertItem(int index, Foo item)
    {
        base.Add(index, Foo);

        if (this.CollectionChanged != null)
            this.CollectionChanged(this, new NotifyCollectionChangedEventArgs (NotifyCollectionChangedAction.Add, item, index);
    }
}

var collection = new FooObservableCollection();
collection.CollectionChanged += CollectionChanged;

collection.Add(new Foo());

void CollectionChanged (object sender, NotifyCollectionChangedEventArgs e)
{
    Foo newItem = e.NewItems.OfType<Foo>().First();
}

How do I force git pull to overwrite everything on every pull?

I'm not sure how to do it in one command but you could do something like:

git reset --hard
git pull

or even

git stash
git pull

IOS - How to segue programmatically using swift

Another option is to use modal segue

STEP 1: Go to the storyboard, and give the View Controller a Storyboard ID. You can find where to change the storyboard ID in the Identity Inspector on the right. Lets call the storyboard ID ModalViewController

STEP 2: Open up the 'sender' view controller (let's call it ViewController) and add this code to it

public class ViewController {
  override func viewDidLoad() {
    showModalView()
  }

  func showModalView() {
    if let mvc = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ModalViewController") as? ModalViewController {
      self.present(mvc, animated: true, completion: nil)
    }
  }
}

Note that the View Controller we want to open is also called ModalViewController

STEP 3: To close ModalViewController, add this to it

public class ModalViewController {
   @IBAction func closeThisViewController(_ sender: Any?) {
      self.presentingViewController?.dismiss(animated: true, completion: nil)
   }
}

Moving average or running mean

With @Aikude's variables, I wrote one-liner.

import numpy as np

mylist = [1, 2, 3, 4, 5, 6, 7]
N = 3

mean = [np.mean(mylist[x:x+N]) for x in range(len(mylist)-N+1)]
print(mean)

>>> [2.0, 3.0, 4.0, 5.0, 6.0]

When to use 'npm start' and when to use 'ng serve'?

There are more than that. The executed executables are different.

npm run start

will run your projects local executable which is located in your node_modules/.bin.

ng serve

will run another executable which is global.

It means if you clone and install an Angular project which is created with angular-cli version 5 and your global cli version is 7, then you may have problems with ng build.

NPM doesn't install module dependencies

You might need to install the grunt-cli, try this before doing a npm install:

sudo npm install -g grunt-cli

That fixes the grunt does not exit for me, you'll also need a valid grunt file.

Source: https://stackoverflow.com/a/16456467/241294

Behaviour of increment and decrement operators in Python

++ is not an operator. It is two + operators. The + operator is the identity operator, which does nothing. (Clarification: the + and - unary operators only work on numbers, but I presume that you wouldn't expect a hypothetical ++ operator to work on strings.)

++count

Parses as

+(+count)

Which translates to

count

You have to use the slightly longer += operator to do what you want to do:

count += 1

I suspect the ++ and -- operators were left out for consistency and simplicity. I don't know the exact argument Guido van Rossum gave for the decision, but I can imagine a few arguments:

  • Simpler parsing. Technically, parsing ++count is ambiguous, as it could be +, +, count (two unary + operators) just as easily as it could be ++, count (one unary ++ operator). It's not a significant syntactic ambiguity, but it does exist.
  • Simpler language. ++ is nothing more than a synonym for += 1. It was a shorthand invented because C compilers were stupid and didn't know how to optimize a += 1 into the inc instruction most computers have. In this day of optimizing compilers and bytecode interpreted languages, adding operators to a language to allow programmers to optimize their code is usually frowned upon, especially in a language like Python that is designed to be consistent and readable.
  • Confusing side-effects. One common newbie error in languages with ++ operators is mixing up the differences (both in precedence and in return value) between the pre- and post-increment/decrement operators, and Python likes to eliminate language "gotcha"-s. The precedence issues of pre-/post-increment in C are pretty hairy, and incredibly easy to mess up.

How to read a text-file resource into Java unit test?

First make sure that abc.xml is being copied to your output directory. Then you should use getResourceAsStream():

InputStream inputStream = 
    Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");

Once you have the InputStream, you just need to convert it into a string. This resource spells it out: http://www.kodejava.org/examples/266.html. However, I'll excerpt the relevent code:

public String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {        
        return "";
    }
}

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

Firebase (FCM) how to get token

for those who land here, up to now FirebaseInstanceIdService is deprecated now, use instead:

public class MyFirebaseMessagingService extends FirebaseMessagingService {
    @Override
    public void onNewToken(String token) {
        Log.d("MY_TOKEN", "Refreshed token: " + token);

        // If you want to send messages to this application instance or
        // manage this apps subscriptions on the server side, send the
        // Instance ID token to your app server.
        // sendRegistrationToServer(token);
    }
}

and declare in AndroidManifest

<application... >

<service android:name=".fcm.MyFirebaseMessagingService">
    <intent-filter>
                <action android:name="com.google.firebase.MESSAGING_EVENT" />
    </intent-filter>
</service>
</application>

how to insert a new line character in a string to PrintStream then use a scanner to re-read the file

The linefeed character \n is not the line separator in certain operating systems (such as windows, where it's "\r\n") - my suggestion is that you use \r\n instead, then it'll both see the line-break with only \n and \r\n, I've never had any problems using it.

Also, you should look into using a StringBuilder instead of concatenating the String in the while-loop at BookCatalog.toString(), it is a lot more effective. For instance:

public String toString() {
        BookNode current = front;
        StringBuilder sb = new StringBuilder();
        while (current!=null){
            sb.append(current.getData().toString()+"\r\n ");
            current = current.getNext();
        }
        return sb.toString();
}

Elegant way to check for missing packages and install them?

Although the answer of Shane is really good, for one of my project I needed to remove the ouput messages, warnings and install packages automagically. I have finally managed to get this script:

InstalledPackage <- function(package) 
{
    available <- suppressMessages(suppressWarnings(sapply(package, require, quietly = TRUE, character.only = TRUE, warn.conflicts = FALSE)))
    missing <- package[!available]
    if (length(missing) > 0) return(FALSE)
    return(TRUE)
}

CRANChoosen <- function()
{
    return(getOption("repos")["CRAN"] != "@CRAN@")
}

UsePackage <- function(package, defaultCRANmirror = "http://cran.at.r-project.org") 
{
    if(!InstalledPackage(package))
    {
        if(!CRANChoosen())
        {       
            chooseCRANmirror()
            if(!CRANChoosen())
            {
                options(repos = c(CRAN = defaultCRANmirror))
            }
        }

        suppressMessages(suppressWarnings(install.packages(package)))
        if(!InstalledPackage(package)) return(FALSE)
    }
    return(TRUE)
}

Use:

libraries <- c("ReadImages", "ggplot2")
for(library in libraries) 
{ 
    if(!UsePackage(library))
    {
        stop("Error!", library)
    }
}

Check for false

You can use something simpler:

if(!var){
    console.log('var is false'); 
}

How to change status bar color in Flutter?

This worked for me:

Import Service

import 'package:flutter/services.dart';

Then add:

@override
  Widget build(BuildContext context) {

    SystemChrome.setSystemUIOverlayStyle(SystemUiOverlayStyle(
      statusBarColor: Colors.white,
      statusBarBrightness: Brightness.dark,
    ));
    return MaterialApp(home: Scaffold(

Bootstrap Carousel : Remove auto slide

In Bootstrap v5 use: data-bs-interval="false"

<div id="carouselExampleCaptions" class="carousel" data-bs-ride="carousel" data-bs-interval="false">

SQL query to make all data in a column UPPER CASE?

Permanent:

UPDATE
  MyTable
SET
  MyColumn = UPPER(MyColumn)

Temporary:

SELECT
  UPPER(MyColumn) AS MyColumn
FROM
  MyTable

Python function overloading

Either use multiple keyword arguments in the definition, or create a Bullet hierarchy whose instances are passed to the function.

Drop all duplicate rows across multiple columns in Python Pandas

This is much easier in pandas now with drop_duplicates and the keep parameter.

import pandas as pd
df = pd.DataFrame({"A":["foo", "foo", "foo", "bar"], "B":[0,1,1,1], "C":["A","A","B","A"]})
df.drop_duplicates(subset=['A', 'C'], keep=False)

ASP.Net MVC: How to display a byte array image from model

I've created a helper method based in the asnwer below and I'm pretty glad that this helper can help as many as possible.

With a model:

 public class Images
 {
    [Key]
    public int ImagesId { get; set; }
    [DisplayName("Image")]
    public Byte[] Pic1 { get; set; }
  }

The helper is:

public static IHtmlString GetBytes<TModel, TValue>(this HtmlHelper<TModel> helper, System.Linq.Expressions.Expression<Func<TModel, TValue>> expression, byte[] array, string Id)
    {
        TagBuilder tb = new TagBuilder("img");
        tb.MergeAttribute("id", Id);
        var base64 = Convert.ToBase64String(array);
        var imgSrc = String.Format("data:image/gif;base64,{0}", base64);
        tb.MergeAttribute("src", imgSrc);
        return MvcHtmlString.Create(tb.ToString(TagRenderMode.SelfClosing));
    }

The view is receiving a: ICollection object so you need to used it in the view in a foreach statement:

 @foreach (var item in Model)
  @Html.GetBytes(itemP1 => item.Pic1, item.Graphics, "Idtag")
}

Set LIMIT with doctrine 2?

Your setMaxResults($limit) needs to be set on the object.

e.g.

$query_ids = $this->getEntityManager()
  ->createQuery(
    "SELECT e_.id
    FROM MuzichCoreBundle:Element e_
    WHERE [...]
    GROUP BY e_.id")
;
$query_ids->setMaxResults($limit);

Can (domain name) subdomains have an underscore "_" in it?

Most answers given here are false. It is perfectly legal to have an underscore in a domain name. Let me quote the standard, RFC 2181, section 11, "Name syntax":

The DNS itself places only one restriction on the particular labels that can be used to identify resource records. That one restriction relates to the length of the label and the full name. [...] Implementations of the DNS protocols must not place any restrictions on the labels that can be used. In particular, DNS servers must not refuse to serve a zone because it contains labels that might not be acceptable to some DNS client programs.

See also the original DNS specification, RFC 1034, section 3.5 "Preferred name syntax" but read it carefully.

Domains with underscores are very common in the wild. Check _jabber._tcp.gmail.com or _sip._udp.apnic.net.

Other RFC mentioned here deal with different things. The original question was for domain names. If the question is for host names (or for URLs, which include a host name), then this is different, the relevant standard is RFC 1123, section 2.1 "Host Names and Numbers" which limits host names to letters-digits-hyphen.

How to disable Paste (Ctrl+V) with jQuery?

_x000D_
_x000D_
$(document).ready(function(){_x000D_
   $('input').on("cut copy paste",function(e) {_x000D_
      e.preventDefault();_x000D_
   });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" />
_x000D_
_x000D_
_x000D_

ASP.NET MVC 4 Custom Authorize Attribute with Permission Codes (without roles)

Here is a modification for the prev. answer. The main difference is when the user is not authenticated, it uses the original "HandleUnauthorizedRequest" method to redirect to login page:

   protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
    {

        if (filterContext.HttpContext.User.Identity.IsAuthenticated) {

            filterContext.Result = new RedirectToRouteResult(
                        new RouteValueDictionary(
                            new
                            {
                                controller = "Account",
                                action = "Unauthorised"
                            })
                        );
        }
        else
        {
             base.HandleUnauthorizedRequest(filterContext);
        }
    }

Python: How would you save a simple settings/config file?

If you want to use something like an INI file to hold settings, consider using configparser which loads key value pairs from a text file, and can easily write back to the file.

INI file has the format:

[Section]
key = value
key with spaces = somevalue

Clearing my form inputs after submission

Try this:

function submitForm () {
    // your code

    $('form :input').attr('value', '');
}

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

How to create helper file full of functions in react native?

To achieve what you want and have a better organisation through your files, you can create a index.js to export your helper files.

Let's say you have a folder called /helpers. Inside this folder you can create your functions divided by content, actions, or anything you like.

Example:

/* Utils.js */
/* This file contains functions you can use anywhere in your application */

function formatName(label) {
   // your logic
}

function formatDate(date) {
   // your logic
}

// Now you have to export each function you want
export {
   formatName,
   formatDate,
};

Let's create another file which has functions to help you with tables:

/* Table.js */
/* Table file contains functions to help you when working with tables */

function getColumnsFromData(data) {
   // your logic
}

function formatCell(data) {
   // your logic
}

// Export each function
export {
   getColumnsFromData,
   formatCell,
};

Now the trick is to have a index.js inside the helpers folder:

/* Index.js */
/* Inside this file you will import your other helper files */

// Import each file using the * notation
// This will import automatically every function exported by these files
import * as Utils from './Utils.js';
import * as Table from './Table.js';

// Export again
export {
   Utils,
   Table,
};

Now you can import then separately to use each function:

import { Table, Utils } from 'helpers';

const columns = Table.getColumnsFromData(data);
Table.formatCell(cell);

const myName = Utils.formatName(someNameVariable);

Hope it can help to organise your files in a better way.

Get the _id of inserted document in Mongo database in NodeJS

Another way to do it in async function :

const express = require('express')
const path = require('path')
const db = require(path.join(__dirname, '../database/config')).db;
const router = express.Router()

// Create.R.U.D
router.post('/new-order', async function (req, res, next) {

    // security check
    if (Object.keys(req.body).length === 0) {
        res.status(404).send({
            msg: "Error",
            code: 404
        });
        return;
    }

    try {

        // operations
        let orderNumber = await db.collection('orders').countDocuments()
        let number = orderNumber + 1
        let order = {
            number: number,
            customer: req.body.customer,
            products: req.body.products,
            totalProducts: req.body.totalProducts,
            totalCost: req.body.totalCost,
            type: req.body.type,
            time: req.body.time,
            date: req.body.date,
            timeStamp: Date.now(),

        }

        if (req.body.direction) {
            order.direction = req.body.direction
        }

        if (req.body.specialRequests) {
            order.specialRequests = req.body.specialRequests
        }

        // Here newOrder will store some informations in result of this process.
        // You can find the inserted id and some informations there too.
        
        let newOrder = await db.collection('orders').insertOne({...order})

        if (newOrder) {

            // MARK: Server response
            res.status(201).send({
                msg: `Order N°${number} created : id[${newOrder.insertedId}]`,
                code: 201
            });

        } else {

            // MARK: Server response
            res.status(404).send({
                msg: `Order N°${number} not created`,
                code: 404
            });

        }

    } catch (e) {
        print(e)
        return
    }

})

// C.Read.U.D


// C.R.Update.D


// C.R.U.Delete



module.exports = router;

Remove trailing spaces automatically or with a shortcut

Menu FilePreferenceSettings

Enter image description here

Check the "Trim Trailing Whitespace" option - "When enabled, will trim trailing whitespace when saving a file".

Jquery asp.net Button Click Event via ajax

I like Gromer's answer, but it leaves me with a question: What if I have multiple 'btnAwesome's in different controls?

To cater for that possibility, I would do the following:

$(document).ready(function() {
  $('#<%=myButton.ClientID %>').click(function() {
    // Do client side button click stuff here.
  });
});

It's not a regex match, but in my opinion, a regex match isn't what's needed here. If you're referencing a particular button, you want a precise text match such as this.

If, however, you want to do the same action for every btnAwesome, then go with Gromer's answer.

Jquery, set value of td in a table?

$("#button_id").click(function(){ $("#detailInfo").html("WHAT YOU WANT") })

sorting integers in order lowest to highest java

Take Inputs from User and Insertion Sort. Here is how it works:

package com.learning.constructor;

import java.util.Scanner;



public class InsertionSortArray {

public static void main(String[] args) {    

Scanner s=new Scanner(System.in);

System.out.println("enter number of elements");

int n=s.nextInt();


int arr[]=new int[n];

System.out.println("enter elements");

for(int i=0;i<n;i++){//for reading array
    arr[i]=s.nextInt();

}

System.out.print("Your Array Is: ");
//for(int i: arr){ //for printing array
for (int i = 0; i < arr.length; i++){
    System.out.print(arr[i] + ",");

}
System.out.println("\n");        

    int[] input = arr;
    insertionSort(input);
}

private static void printNumbers(int[] input) {

    for (int i = 0; i < input.length; i++) {
        System.out.print(input[i] + ", ");
    }
    System.out.println("\n");
}

public static void insertionSort(int array[]) {
    int n = array.length;
    for (int j = 1; j < n; j++) {
        int key = array[j];
        int i = j-1;
        while ( (i > -1) && ( array [i] > key ) ) {
            array [i+1] = array [i];
            i--;
        }
        array[i+1] = key;
        printNumbers(array);
    }
}

}

How to set session attribute in java?

By Java class, I am assuming you mean a Servlet class as setting session attribute in arbitrary Java class does not make sense.You can do something like this in your servlet's doGet/doPost methods

public void doGet(HttpServletRequest request, HttpServletResponse response) {

    HttpSession session = request.getSession();
    String username = (String)request.getAttribute("un");
    session.setAttribute("UserName", username);
}

Convert List into Comma-Separated String

Using String.Join

string.Join<string>(",", lst );

Using Linq Aggregation

lst .Aggregate((a, x) => a + "," + x);