Programs & Examples On #Stdstring

std::string is the C++ standard library's byte-based "string" type, defined in the header.

Is it possible to use std::string in a constexpr?

As of C++20, yes.

As of C++17, you can use string_view:

constexpr std::string_view sv = "hello, world";

A string_view is a string-like object that acts as an immutable, non-owning reference to any sequence of char objects.

Alternative to itoa() for converting integer to string C++?

The best answer, IMO, is the function provided here:

http://www.jb.man.ac.uk/~slowe/cpp/itoa.html

It mimics the non-ANSI function provided by many libs.

char* itoa(int value, char* result, int base);

It's also lightning fast and optimizes well under -O3, and the reason you're not using c++ string_format() ... or sprintf is that they are too slow, right?

convert a char* to std::string

std::string has a constructor for this:

const char *s = "Hello, World!";
std::string str(s);

Note that this construct deep copies the character list at s and s should not be nullptr, or else behavior is undefined.

Remove First and Last Character C++

std::string trimmed(std::string str ) {
if(str.length() == 0 ) { return "" ; }
else if ( str == std::string(" ") ) { return "" ; } 
else {
    while(str.at(0) == ' ') { str.erase(0, 1);}
    while(str.at(str.length()-1) == ' ') { str.pop_back() ; }
    return str ;
    } 
}

How do you convert a C++ string to an int?

Perhaps I am misunderstanding the question, by why exactly would you not want to use atoi? I see no point in reinventing the wheel.

Am I just missing the point here?

How to replace all occurrences of a character in string?

std::string doesn't contain such function but you could use stand-alone replace function from algorithm header.

#include <algorithm>
#include <string>

void some_func() {
  std::string s = "example string";
  std::replace( s.begin(), s.end(), 'x', 'y'); // replace all 'x' to 'y'
}

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

AGE is defined as "42" so the line:

str += "Do you feel " + AGE + " years old?";

is converted to:

str += "Do you feel " + "42" + " years old?";

Which isn't valid since "Do you feel " and "42" are both const char[]. To solve this, you can make one a std::string, or just remove the +:

// 1.
str += std::string("Do you feel ") + AGE + " years old?";

// 2.
str += "Do you feel " AGE " years old?";

I want to convert std::string into a const wchar_t *

You can use the ATL text conversion macros to convert a narrow (char) string to a wide (wchar_t) one. For example, to convert a std::string:

#include <atlconv.h>
...
std::string str = "Hello, world!";
CA2W pszWide(str.c_str());
loadU(pszWide);

You can also specify a code page, so if your std::string contains UTF-8 chars you can use:

CA2W pszWide(str.c_str(), CP_UTF8);

Very useful but Windows only.

How do you append an int to a string in C++?

Another possibility is Boost.Format:

#include <boost/format.hpp>
#include <iostream>
#include <string>

int main() {
  int i = 4;
  std::string text = "Player";
  std::cout << boost::format("%1% %2%\n") % text % i;
}

How to get the number of characters in a std::string?

Simplest way to get length of string without bothering about std namespace is as follows

string with/without spaces

#include <iostream>
#include <string>
using namespace std;
int main(){
    string str;
    getline(cin,str);
    cout<<"Length of given string is"<<str.length();
    return 0;
}

string without spaces

#include <iostream>
#include <string>
using namespace std;
int main(){
    string str;
    cin>>str;
    cout<<"Length of given string is"<<str.length();
    return 0;
}

What's the best way to trim std::string?

Trim C++11 implementation:

static void trim(std::string &s) {
     s.erase(s.begin(), std::find_if_not(s.begin(), s.end(), [](char c){ return std::isspace(c); }));
     s.erase(std::find_if_not(s.rbegin(), s.rend(), [](char c){ return std::isspace(c); }).base(), s.end());
}

What does string::npos mean in this code?

found will be npos in case of failure to find the substring in the search string.

Concatenating strings doesn't work as expected

I would do this:

std::string a("Hello ");
std::string b("World");
std::string c = a + b;

Which compiles in VS2008.

How to concatenate a std::string and an int?

If you'd like to use + for concatenation of anything which has an output operator, you can provide a template version of operator+:

template <typename L, typename R> std::string operator+(L left, R right) {
  std::ostringstream os;
  os << left << right;
  return os.str();
}

Then you can write your concatenations in a straightforward way:

std::string foo("the answer is ");
int i = 42;
std::string bar(foo + i);    
std::cout << bar << std::endl;

Output:

the answer is 42

This isn't the most efficient way, but you don't need the most efficient way unless you're doing a lot of concatenation inside a loop.

How do you convert CString and std::string std::wstring to each other?

All other answers didn't quite address what I was looking for which was to convert CString on the fly as opposed to store the result in a variable.

The solution is similar to above but we need one more step to instantiate a nameless object. I am illustrating with an example. Here is my function which needs std::string but I have CString.

void CStringsPlayDlg::writeLog(const std::string &text)
{
    std::string filename = "c:\\test\\test.txt";

    std::ofstream log_file(filename.c_str(), std::ios_base::out | std::ios_base::app);

    log_file << text << std::endl;
}

How to call it when you have a CString?

std::string firstName = "First";
CString lastName = _T("Last");

writeLog( firstName + ", " + std::string( CT2A( lastName ) ) );     

Note that the last line is not a direct typecast but we are creating a nameless std::string object and supply the CString via its constructor.

std::string formatting like sprintf

Based on the answer provided by Erik Aronesty:

std::string string_format(const std::string &fmt, ...) {
    std::vector<char> str(100,'\0');
    va_list ap;
    while (1) {
        va_start(ap, fmt);
        auto n = vsnprintf(str.data(), str.size(), fmt.c_str(), ap);
        va_end(ap);
        if ((n > -1) && (size_t(n) < str.size())) {
            return str.data();
        }
        if (n > -1)
            str.resize( n + 1 );
        else
            str.resize( str.size() * 2);
    }
    return str.data();
}

This avoids the need to cast away const from the result of .c_str() which was in the original answer.

c++ integer->std::string conversion. Simple function?

Not really, in the standard. Some implementations have a nonstandard itoa() function, and you could look up Boost's lexical_cast, but if you stick to the standard it's pretty much a choice between stringstream and sprintf() (snprintf() if you've got it).

How do you see the entire command history in interactive Python?

A simple function to get the history similar to unix/bash version.

Hope it helps some new folks.

def ipyhistory(lastn=None):
    """
    param: lastn Defaults to None i.e full history. If specified then returns lastn records from history.
           Also takes -ve sequence for first n history records.
    """
    import readline
    assert lastn is None or isinstance(lastn, int), "Only integers are allowed."
    hlen = readline.get_current_history_length()
    is_neg = lastn is not None and lastn < 0
    if not is_neg:
        flen = len(str(hlen)) if not lastn else len(str(lastn))
        for r in range(1,hlen+1) if not lastn else range(1, hlen+1)[-lastn:]:
            print(": ".join([str(r if not lastn else r + lastn - hlen ).rjust(flen), readline.get_history_item(r)]))
    else:
        flen = len(str(-hlen))
        for r in range(1, -lastn + 1):
            print(": ".join([str(r).rjust(flen), readline.get_history_item(r)]))

Snippet: Tested with Python3. Let me know if there are any glitches with python2. Samples:

Full History : ipyhistory()

Last 10 History: ipyhistory(10)

First 10 History: ipyhistory(-10)

Hope it helps fellas.

jquery $(this).id return Undefined

Hiya demo http://jsfiddle.net/LYTbc/

this is a reference to the DOM element, so you can wrap it directly.

attr api: http://api.jquery.com/attr/

The .attr() method gets the attribute value for only the first element in the matched set.

have a nice one, cheers!

code

$(document).ready(function () {
    $(".inputs").click(function () {
         alert(this.id);

        alert(" or " + $(this).attr("id"));

    });

});?

Execute action when back bar button of UINavigationController is pressed

You can subclass UINavigationController and override popViewController(animated: Bool). Beside being able to execute some code there you can also prevent the user from going back altogether, for instance to prompt to save or discard his current work.

Sample implementation where you can set a popHandler that gets set/cleared by pushed controllers.

class NavigationController: UINavigationController
{
    var popHandler: (() -> Bool)?

    override func popViewController(animated: Bool) -> UIViewController?
    {
        guard self.popHandler?() != false else
        {
            return nil
        }
        self.popHandler = nil
        return super.popViewController(animated: animated)
    }
}

And sample usage from a pushed controller that tracks unsaved work.

let hasUnsavedWork: Bool = // ...
(self.navigationController as! NavigationController).popHandler = hasUnsavedWork ?
    {
        // Prompt saving work here with an alert

        return false // Prevent pop until as user choses to save or discard

    } : nil // No unsaved work, we clear popHandler to let it pop normally

As a nice touch, this will also get called by interactivePopGestureRecognizer when the user tries to go back using a swipe gesture.

Leap year calculation

Will it not be much better if we make one step further. Assuming every 3200 year as no leap year, the length of the year will come

364.999696 + 1/3200 = 364.999696 + .0003125 = 365.0000085

and after this the adjustment will be required after around 120000 years.

How can I install the VS2017 version of msbuild on a build server without installing the IDE?

The Visual Studio Build tools are a different download than the IDE. They appear to be a pretty small subset, and they're called Build Tools for Visual Studio 2019 (download).

You can use the GUI to do the installation, or you can script the installation of msbuild:

vs_buildtools.exe --add Microsoft.VisualStudio.Workload.MSBuildTools --quiet

Microsoft.VisualStudio.Workload.MSBuildTools is a "wrapper" ID for the three subcomponents you need:

  • Microsoft.Component.MSBuild
  • Microsoft.VisualStudio.Component.CoreBuildTools
  • Microsoft.VisualStudio.Component.Roslyn.Compiler

You can find documentation about the other available CLI switches here.

The build tools installation is much quicker than the full IDE. In my test, it took 5-10 seconds. With --quiet there is no progress indicator other than a brief cursor change. If the installation was successful, you should be able to see the build tools in %programfiles(x86)%\Microsoft Visual Studio\2019\BuildTools\MSBuild\Current\Bin.

If you don't see them there, try running without --quiet to see any error messages that may occur during installation.

Python Pandas Counting the Occurrences of a Specific value

Try this:

(df[education]=='9th').sum()

Eclipse gives “Java was started but returned exit code 13”

This problem happened because either u install new version of jdk so you have both 32bit version and 64bit

how to solve the problem is just go open computer & go to c then you will see location

after that you probably use 32 bit so just chose C:\Program Files and there you will find folder called java

in it location 2

so you have many different version of jdk so easily chose jre7 and to to bin and you will find javaw.exe in it like loaction 3

now only just take that path copy and go to start type eclipse.ini you will see text file just open it and before -vmargs

write -vm enter path like photo finally

now just open eclipse again and have fun :D

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

Finally found out what to do. Added the -std=c++0x compiler argument under Project Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous. It works now!

But how to add this flag by default for all C++ projects? Anybody?

How to find the privileges and roles granted to a user in Oracle?

The only visible result I was able to understand was first to connect with the user I wanted to get the rights, then with the following query:

SELECT GRANTEE, PRIVILEGE, TABLE_NAME FROM USER_TAB_PRIVS;

Javascript split regex question

or just use for date strings 2015-05-20 or 2015.05.20

date.split(/\.|-/);

Editing the date formatting of x-axis tick labels in matplotlib

In short:

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

Many examples on the matplotlib website. The one I most commonly use is here

'Use of Unresolved Identifier' in Swift

I did a stupid mistake. I forgot to mention the class as public or open while updating code in cocoapod workspace.

Please do check whether accesor if working in separate workspace.

How to configure PostgreSQL to accept all incoming connections

0.0.0.0/0 for all IPv4 addresses

::0/0 for all IPv6 addresses

all to match any IP address

samehost to match any of the server's own IP addresses

samenet to match any address in any subnet that the server is directly connected to.

e.g.

host    all             all             0.0.0.0/0            md5

C# List<> Sort by x then y

For versions of .Net where you can use LINQ OrderBy and ThenBy (or ThenByDescending if needed):

using System.Linq;
....
List<SomeClass>() a;
List<SomeClass> b = a.OrderBy(x => x.x).ThenBy(x => x.y).ToList();

Note: for .Net 2.0 (or if you can't use LINQ) see Hans Passant answer to this question.

What's the difference between Docker Compose vs. Dockerfile

In Microservices world (having a common shared codebase), each Microservice would have a Dockerfile whereas at the root level (generally outside of all Microservices and where your parent POM resides) you would define a docker-compose.yml to group all Microservices into a full-blown app.

In your case "Docker Compose" is preferred over "Dockerfile". Think "App" Think "Compose".

What is SaaS, PaaS and IaaS? With examples

Following link gives very good explanation on SaaS, PaaS and Iaas.. http://opensourceforgeeks.blogspot.in/2015/01/difference-between-saas-paas-and-iaas.html

Just some brief:


IaaS, here vendor provides infra to user where an user gets hardware/virtualization infra, storage and Networking infra.

PaaS, here vendor provides platform to user where an user gets all required things for their work like OS, Database, Execution Environment along with IaaS provided environment. So pass is platform + IaaS.

SaaS seems to be quite wide area where vendor provides almost everything from infra to platform to software. So SaaS is Iaas+PaaS along with different softwares like ms office, virtual box etc..

How do I add a delay in a JavaScript loop?

In my opinion, the simpler and most elegant way to add a delay in a loop is like this:

names = ['John', 'Ana', 'Mary'];

names.forEach((name, i) => {
 setTimeout(() => {
  console.log(name);
 }, i * 1000);  // one sec interval
});

How can I make my string property nullable?

It's been a while when the question has been asked and C# changed not much but became a bit better. Take a look Nullable reference types (C# reference)

string notNull = "Hello";
string? nullable = default;
notNull = nullable!; // null forgiveness

C# as a language a "bit" outdated from modern languages and became misleading.

for instance in typescript, swift there's a "?" to clearly say it's a nullable type, be careful. It's pretty clear and it's awesome. C# doesn't/didn't have this ability, as a result, a simple contract IPerson very misleading. As per C# FirstName and LastName could be null but is it true? is per business logic FirstName/LastName really could be null? the answer is we don't know because C# doesn't have the ability to say it directly.

interface IPerson
{
  public string FirstName;
  public string LastName;
}

Import Error: No module named numpy

You installed the Numpy Version for Python 2.6 - so you can only use it with Python 2.6. You have to install Numpy for Python 3.x, e.g. that one: http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/numpy-1.6.1-win32-superpack-python3.2.exe/download

For an overview of the different versions, see here: http://sourceforge.net/projects/numpy/files/NumPy/1.6.1/

Where can I download mysql jdbc jar from?

Here's a one-liner using Maven:

mvn dependency:get -Dartifact=mysql:mysql-connector-java:5.1.38

Then, with default settings, it's available in:

$HOME/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar

Just replace the version number if you need a different one.

How can I count the occurrences of a list item?

Use Counter if you are using Python 2.7 or 3.x and you want the number of occurrences for each element:

>>> from collections import Counter
>>> z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
>>> Counter(z)
Counter({'blue': 3, 'red': 2, 'yellow': 1})

When is layoutSubviews called?

I tracked the solution down to Interface Builder's insistence that springs cannot be changed on a view that has the simulated screen elements turned on (status bar, etc.). Since the springs were off for the main view, that view could not change size and hence was scrolled down in its entirety when the in-call bar appeared.

Turning the simulated features off, then resizing the view and setting the springs correctly caused the animation to occur and my method to be called.

An extra problem in debugging this is that the simulator quits the app when the in-call status is toggled via the menu. Quit app = no debugger.

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

Just use indexing

df.iloc[:-1,:]

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

Best way to create enum of strings?

Custom String Values for Enum

from http://javahowto.blogspot.com/2006/10/custom-string-values-for-enum.html

The default string value for java enum is its face value, or the element name. However, you can customize the string value by overriding toString() method. For example,

public enum MyType {
  ONE {
      public String toString() {
          return "this is one";
      }
  },

  TWO {
      public String toString() {
          return "this is two";
      }
  }
}

Running the following test code will produce this:

public class EnumTest {
  public static void main(String[] args) {
      System.out.println(MyType.ONE);
      System.out.println(MyType.TWO);
  }
}


this is one
this is two

How to store custom objects in NSUserDefaults

Taking @chrissr's answer and running with it, this code can be implemented into a nice category on NSUserDefaults to save and retrieve custom objects:

@interface NSUserDefaults (NSUserDefaultsExtensions)

- (void)saveCustomObject:(id<NSCoding>)object
                     key:(NSString *)key;
- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key;

@end


@implementation NSUserDefaults (NSUserDefaultsExtensions)


- (void)saveCustomObject:(id<NSCoding>)object
                     key:(NSString *)key {
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    [self setObject:encodedObject forKey:key];
    [self synchronize];

}

- (id<NSCoding>)loadCustomObjectWithKey:(NSString *)key {
    NSData *encodedObject = [self objectForKey:key];
    id<NSCoding> object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
}

@end

Usage:

[[NSUserDefaults standardUserDefaults] saveCustomObject:myObject key:@"myKey"];

Check if a temporary table exists and delete if it exists before creating a temporary table

The statement should be of the order

  1. Alter statement for the table
  2. GO
  3. Select statement.

Without 'GO' in between, the whole thing will be considered as one single script and when the select statement looks for the column,it won't be found.

With 'GO' , it will consider the part of the script up to 'GO' as one single batch and will execute before getting into the query after 'GO'.

How to execute INSERT statement using JdbcTemplate class from Spring Framework

You'll need a datasource for working with JdbcTemplate.

JdbcTemplate template = new JdbcTemplate(yourDataSource);

template.update(
    new PreparedStatementCreator() {
        public PreparedStatement createPreparedStatement(Connection connection)
            throws SQLException {

            PreparedStatement statement = connection.prepareStatement(ourInsertQuery);
            //statement.setLong(1, beginning); set parameters you need in your insert

            return statement;
        }
    });

How to get time (hour, minute, second) in Swift 3 using NSDate?

This might be handy for those who want to use the current date in more than one class.

extension String {


func  getCurrentTime() -> String {

    let date = Date()
    let calendar = Calendar.current


    let year = calendar.component(.year, from: date)
    let month = calendar.component(.month, from: date)
    let day = calendar.component(.day, from: date)
    let hour = calendar.component(.hour, from: date)
    let minutes = calendar.component(.minute, from: date)
    let seconds = calendar.component(.second, from: date)

    let realTime = "\(year)-\(month)-\(day)-\(hour)-\(minutes)-\(seconds)"

    return realTime
}

}

Usage

        var time = ""
        time = time.getCurrentTime()
        print(time)   // 1900-12-09-12-59

How can I convert the "arguments" object to an array in JavaScript?

Use:

function sortArguments() {
  return arguments.length === 1 ? [arguments[0]] :
                 Array.apply(null, arguments).sort();
}

Array(arg1, arg2, ...) returns [arg1, arg2, ...]

Array(str1) returns [str1]

Array(num1) returns an array that has num1 elements

You must check number of arguments!

Array.slice version (slower):

function sortArguments() {
  return Array.prototype.slice.call(arguments).sort();
}

Array.push version (slower, faster than slice):

function sortArguments() {
  var args = [];
  Array.prototype.push.apply(args, arguments);
  return args.sort();
}

Move version (slower, but small size is faster):

function sortArguments() {
  var args = [];
  for (var i = 0; i < arguments.length; ++i)
    args[i] = arguments[i];
  return args.sort();
}

Array.concat version (slowest):

function sortArguments() {
  return Array.prototype.concat.apply([], arguments).sort();
}

Check if list contains element that contains a string and get that element

The basic answer is: you need to iterate through loop and check any element contains the specified string. So, let's say the code is:

foreach(string item in myList)
{
    if(item.Contains(myString))
       return item;
}

The equivalent, but terse, code is:

mylist.Where(x => x.Contains(myString)).FirstOrDefault();

Here, x is a parameter that acts like "item" in the above code.

Angular: Cannot find a differ supporting object '[object Object]'

I think that the object you received in your response payload isn't an array. Perhaps the array you want to iterate is contained into an attribute. You should check the structure of the received data...

You could try something like that:

getusers() {
  this.http.get(`https://api.github.com/search/users?q=${this.input1.value}`)
    .map(response => response.json().items) // <------
    .subscribe(
      data => this.users = data,
      error => console.log(error)
    );
}

Edit

Following the Github doc (developer.github.com/v3/search/#search-users), the format of the response is:

{
  "total_count": 12,
  "incomplete_results": false,
  "items": [
    {
      "login": "mojombo",
      "id": 1,
      (...)
      "type": "User",
      "score": 105.47857
    }
  ]
}

So the list of users is contained into the items field and you should use this:

getusers() {
  this.http.get(`https://api.github.com/search/users?q=${this.input1.value}`)
    .map(response => response.json().items) // <------
    .subscribe(
      data => this.users = data,
      error => console.log(error)
    );
}

How to remove first 10 characters from a string?

The Substring has a parameter called startIndex. Set it according to the index you want to start at.

pip install fails with "connection error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:598)"

You can specify a cert with this param:

pip --cert /etc/ssl/certs/FOO_Root_CA.pem install linkchecker

See: Docs » Reference Guide » pip

If specifying your company's root cert doesn't work maybe the cURL one will work: http://curl.haxx.se/ca/cacert.pem

You must use a PEM file and not a CRT file. If you have a CRT file you will need to convert the file to PEM There are reports in the comments that this now works with a CRT file but I have not verified.

Also check: SSL Cert Verification.

How do I count occurrence of duplicate items in array

Count duplicate element of an array in PHP without using in-built function

$arraychars=array("or","red","yellow","green","red","yellow","yellow");
$arrCount=array();
        for($i=0;$i<$arrlength-1;$i++)
        {
          $key=$arraychars[$i];
          if($arrCount[$key]>=1)
            {
              $arrCount[$key]++;
            } else{
              $arrCount[$key]=1;
        }
        echo $arraychars[$i]."<br>";
     }
        echo "<pre>";
        print_r($arrCount);

Get height and width of a layout programmatically

Just wanted to add an answer here, since Koltin has some convenience methods to do this, which are a lot less ugly than adding and removing a onGlobalLayoutListener:

view.doOnLayout {
    it.measuredWidth
    it.measuredHeight
}

You can see more of the convinience methods here.

Adding to an ArrayList Java

Array list can be implemented by the following code:

Arraylist<String> list = new ArrayList<String>();
list.add(value1);
list.add(value2);
list.add(value3);
list.add(value4);

What is the most efficient way to loop through dataframes with pandas?

The newest versions of pandas now include a built-in function for iterating over rows.

for index, row in df.iterrows():

    # do some logic here

Or, if you want it faster use itertuples()

But, unutbu's suggestion to use numpy functions to avoid iterating over rows will produce the fastest code.

How to extract code of .apk file which is not working?

Any .apk file from market or unsigned

  1. If you apk is downloaded from market and hence signed Install Astro File Manager from market. Open Astro > Tools > Application Manager/Backup and select the application to backup on to the SD card . Mount phone as USB drive and access 'backupsapps' folder to find the apk of target app (lets call it app.apk) . Copy it to your local drive same is the case of unsigned .apk.

  2. Download Dex2Jar zip from this link: SourceForge

  3. Unzip the downloaded zip file.

  4. Open command prompt & write the following command on reaching to directory where dex2jar exe is there and also copy the apk in same directory.

    dex2jar targetapp.apk file(./dex2jar app.apk on terminal)

  5. http://jd.benow.ca/ download decompiler from this link.

  6. Open ‘targetapp.apk.dex2jar.jar’ with jd-gui File > Save All Sources to sava the class files in jar to java files.

changing kafka retention period during runtime

The correct config key is retention.ms

$ bin/kafka-topics.sh --zookeeper zk.prod.yoursite.com --alter --topic as-access --config retention.ms=86400000
Updated config for topic "my-topic".

How do I add a placeholder on a CharField in Django?

For a ModelForm, you can use the Meta class thus:

from django import forms

from .models import MyModel

class MyModelForm(forms.ModelForm):
    class Meta:
        model = MyModel
        widgets = {
            'name': forms.TextInput(attrs={'placeholder': 'Name'}),
            'description': forms.Textarea(
                attrs={'placeholder': 'Enter description here'}),
        }

Insert Unicode character into JavaScript

The answer is correct, but you don't need to declare a variable. A string can contain your character:

"This string contains omega, that looks like this: \u03A9"

Unfortunately still those codes in ASCII are needed for displaying UTF-8, but I am still waiting (since too many years...) the day when UTF-8 will be same as ASCII was, and ASCII will be just a remembrance of the past.

How to check if a file is empty in Bash?

I came here looking for how to delete empty __init__.py files as they are implicit in Python 3.3+ and ended up using:

find -depth '(' -type f  -name __init__.py ')' -print0 |
  while IFS= read -d '' -r file; do if [[ ! -s $file ]]; then rm $file; fi; done

Also (at least in zsh) using $path as the variable also breaks your $PATH env and so it'll break your open shell. Anyway, thought I'd share!

How to use 'git pull' from the command line?

Try setting the HOME environment variable in Windows to your home folder (c:\users\username).

( you can confirm that this is the problem by doing echo $HOME in git bash and echo %HOME% in cmd - latter might not be available )

Is there a method to generate a UUID with go language

gofrs/uuid is the replacement for satori/go.uuid, which is the most starred UUID package for Go. It supports UUID versions 1-5 and is RFC 4122 and DCE 1.1 compliant.

import "github.com/gofrs/uuid"

// Create a Version 4 UUID, panicking on error
u := uuid.Must(uuid.NewV4())

Get Month name from month number

You want GetAbbreviatedMonthName

Why cannot cast Integer to String in java?

You can't cast explicitly anything to a String that isn't a String. You should use either:

"" + myInt;

or:

Integer.toString(myInt);

or:

String.valueOf(myInt);

I prefer the second form, but I think it's personal choice.

Edit OK, here's why I prefer the second form. The first form, when compiled, could instantiate a StringBuffer (in Java 1.4) or a StringBuilder in 1.5; one more thing to be garbage collected. The compiler doesn't optimise this as far as I could tell. The second form also has an analogue, Integer.toString(myInt, radix) that lets you specify whether you want hex, octal, etc. If you want to be consistent in your code (purely aesthetically, I guess) the second form can be used in more places.

Edit 2 I assumed you meant that your integer was an int and not an Integer. If it's already an Integer, just use toString() on it and be done.

Attribute Error: 'list' object has no attribute 'split'

The problem is that readlines is a list of strings, each of which is a line of filename. Perhaps you meant:

for line in readlines:
    Type = line.split(",")
    x = Type[1]
    y = Type[2]
    print(x,y)

How to create a file in Ruby

Try

File.open("out.txt", "w") do |f|     
  f.write(data_you_want_to_write)   
end

without using the

File.new "out.txt"

How to turn on WCF tracing?

The following configuration taken from MSDN can be applied to enable tracing on your WCF service.

<configuration>
  <system.diagnostics>
    <sources>
      <source name="System.ServiceModel"
              switchValue="Information, ActivityTracing"
              propagateActivity="true" >
        <listeners>
             <add name="xml"/>
        </listeners>
      </source>
      <source name="System.ServiceModel.MessageLogging">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
      <source name="myUserTraceSource"
              switchValue="Information, ActivityTracing">
        <listeners>
            <add name="xml"/>
        </listeners>
      </source>
    </sources>
    <sharedListeners>
        <add name="xml"
             type="System.Diagnostics.XmlWriterTraceListener"
             initializeData="Error.svclog" />
    </sharedListeners>
  </system.diagnostics>
</configuration>

To view the log file, you can use "C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\SvcTraceViewer.exe".

If "SvcTraceViewer.exe" is not on your system, you can download it from the "Microsoft Windows SDK for Windows 7 and .NET Framework 4" package here:

Windows SDK Download

You don't have to install the entire thing, just the ".NET Development / Tools" part.

When/if it bombs out during installation with a non-sensical error, Petopas' answer to Windows 7 SDK Installation Failure solved my issue.

How can I get query parameters from a URL in Vue.js?

Without vue-route, split the URL

var vm = new Vue({
  ....
  created()
  {
    let uri = window.location.href.split('?');
    if (uri.length == 2)
    {
      let vars = uri[1].split('&');
      let getVars = {};
      let tmp = '';
      vars.forEach(function(v){
        tmp = v.split('=');
        if(tmp.length == 2)
        getVars[tmp[0]] = tmp[1];
      });
      console.log(getVars);
      // do 
    }
  },
  updated(){
  },

Another solution https://developer.mozilla.org/en-US/docs/Web/API/HTMLHyperlinkElementUtils/search:

var vm = new Vue({
  ....
  created()
  {
    let uri = window.location.search.substring(1); 
    let params = new URLSearchParams(uri);
    console.log(params.get("var_name"));
  },
  updated(){
  },

grep's at sign caught as whitespace

After some time with Google I asked on the ask ubuntu chat room.

A user there was king enough to help me find the solution I was looking for and i wanted to share so that any following suers running into this may find it:

grep -P "(^|\s)abc(\s|$)" gives the result I was looking for. -P is an experimental implementation of perl regexps.

grepping for abc and then using filters like grep -v '@abc' (this is far from perfect...) should also work, but my patch does something similar.

How to get disk capacity and free space of remote computer

PowerShell Fun

Get-WmiObject win32_logicaldisk -Computername <ServerName> -Credential $(get-credential) | Select DeviceID,VolumeName,FreeSpace,Size | where {$_.DeviceID -eq "C:"}

How does it work - requestLocationUpdates() + LocationRequest/Listener

You are implementing LocationListener in your activity MainActivity. The call for concurrent location updates will therefor be like this:

mLocationClient.requestLocationUpdates(mLocationRequest, this);

Be sure that the LocationListener you're implementing is from the google api, that is import this:

import com.google.android.gms.location.LocationListener;

and not this:

import android.location.LocationListener;

and it should work just fine.

It's also important that the LocationClient really is connected before you do this. I suggest you don't call it in the onCreate or onStart methods, but in onResume. It is all explained quite well in the tutorial for Google Location Api: https://developer.android.com/training/location/index.html

python: creating list from string

If you need to convert some of them to numbers and don't know in advance which ones, some additional code will be needed. Try something like this:

b = []
for x in a:
    temp = []
    items = x.split(",")
    for item in items:
        try:
            n = int(item)
        except ValueError:
            temp.append(item)
        else:
            temp.append(n)
    b.append(temp)

This is longer than the other answers, but it's more versatile.

Is it possible for UIStackView to scroll?

Just add this to viewdidload:

let insets = UIEdgeInsetsMake(20.0, 0.0, 0.0, 0.0)
scrollVIew.contentInset = insets
scrollVIew.scrollIndicatorInsets = insets

source: https://developer.apple.com/library/ios/documentation/UserExperience/Conceptual/AutolayoutPG/LayoutUsingStackViews.html

How do you use the ? : (conditional) operator in JavaScript?

 (sunday == 'True') ? sun="<span class='label label-success'>S</span>" : sun="<span class='label label-danger'>S</span>";

 sun = "<span class='label " + ((sunday === 'True' ? 'label-success' : 'label-danger') + "'>S</span>"

How to define the css :hover state in a jQuery selector?

Well, you can't add styling using pseudo selectors like :hover, :after, :nth-child, or anything like that using jQuery.

If you want to add a CSS rule like that you have to create a <style> element and add that :hover rule to it just like you would in CSS. Then you would have to add that <style> element to the page.

Using the .hover function seems to be more appropriate if you can't just add the css to a stylesheet, but if you insist you can do:

$('head').append('<style>.myclass:hover div {background-color : red;}</style>')

If you want to read more on adding CSS with javascript you can check out one of David Walsh's Blog posts.

What's the pythonic way to use getters and setters?

Properties are pretty useful since you can use them with assignment but then can include validation as well. You can see this code where you use the decorator @property and also @<property_name>.setter to create the methods:

# Python program displaying the use of @property 
class AgeSet:
    def __init__(self):
        self._age = 0

    # using property decorator a getter function
    @property
    def age(self):
        print("getter method called")
        return self._age

    # a setter function
    @age.setter
    def age(self, a):
        if(a < 18):
            raise ValueError("Sorry your age is below eligibility criteria")
        print("setter method called")
        self._age = a

pkj = AgeSet()

pkj.age = int(input("set the age using setter: "))

print(pkj.age)

There are more details in this post I wrote about this as well: https://pythonhowtoprogram.com/how-to-create-getter-setter-class-properties-in-python-3/

How do I include image files in Django templates?

I tried various method it didn't work.But this worked.Hope it will work for you as well. The file/directory must be at this locations:

projec/your_app/templates project/your_app/static

settings.py

import os    
PROJECT_DIR = os.path.realpath(os.path.dirname(_____file_____))
STATIC_ROOT = '/your_path/static/'

example:

STATIC_ROOT = '/home/project_name/your_app/static/'    
STATIC_URL = '/static/'    
STATICFILES_DIRS =(     
PROJECT_DIR+'/static',    
##//don.t forget comma    
)
TEMPLATE_DIRS = (    
 PROJECT_DIR+'/templates/',    
)

proj/app/templates/filename.html

inside body

{% load staticfiles %}

//for image

img src="{% static "fb.png" %}" alt="image here"

//note that fb.png is at /home/project/app/static/fb.png

If fb.png was inside /home/project/app/static/image/fb.png then

img src="{% static "images/fb.png" %}" alt="image here" 

How to extract a floating number from a string

Another approach that may be more readable is simple type conversion. I've added a replacement function to cover instances where people may enter European decimals:

>>> for possibility in "Current Level: -13.2 db or 14,2 or 3".split():
...     try:
...         str(float(possibility.replace(',', '.')))
...     except ValueError:
...         pass
'-13.2'
'14.2'
'3.0'

This has disadvantages too however. If someone types in "1,000", this will be converted to 1. Also, it assumes that people will be inputting with whitespace between words. This is not the case with other languages, such as Chinese.

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

You can just create the required CORS configuration as a bean. As per the code below this will allow all requests coming from any origin. This is good for development but insecure. Spring Docs

@Bean
WebMvcConfigurer corsConfigurer() {
    return new WebMvcConfigurer() {
        @Override
        void addCorsMappings(CorsRegistry registry) {
            registry.addMapping("/**")
                    .allowedOrigins("*")
        }
    }
}

What does the "~" (tilde/squiggle/twiddle) CSS selector mean?

Good to also check the other combinators in the family and to get back to what is this specific one.

  • ul li
  • ul > li
  • ul + ul
  • ul ~ ul

Example checklist:

  • ul li - Looking inside - Selects all the li elements placed (anywhere) inside the ul; Descendant selector
  • ul > li - Looking inside - Selects only the direct li elements of ul; i.e. it will only select direct children li of ul; Child Selector or Child combinator selector
  • ul + ul - Looking outside - Selects the ul immediately following the ul; It is not looking inside, but looking outside for the immediately following element; Adjacent Sibling Selector
  • ul ~ ul - Looking outside - Selects all the ul which follows the ul doesn't matter where it is, but both ul should be having the same parent; General Sibling Selector

The one we are looking at here is General Sibling Selector

iOS: Convert UTC NSDate to local Timezone

Convert the date from the UTC calendar to one with the appropriate local NSTimeZone.

Subversion ignoring "--password" and "--username" options

I had a similar problem, I wanted to use a different user name for a svn+ssh repository. In the end, I used svn relocate (as described in in this answer. In my case, I'm using svn 1.6.11 and did the following:

svn switch --relocate \
    svn+ssh://olduser@svnserver/path/to/repo \
    svn+ssh://newuser@svnserver/path/to/repo

where svn+ssh://olduser@svnserver/path/to/repo can be found in the URL: line output of svn info command. This command asked me for the password of newuser.

Note that this change is persistent, i.e. if you want only temporarily switch to the new username with this method, you'll have to issue a similar command again after svn update etc.

Auto-expanding layout with Qt-Designer

Set the horizontalPolicy & VerticalPolicy for the controls/widgets to "Preferred".

Sending an HTTP POST request on iOS

Objective C

Post API with parameters and validate with url to navigate if json
response key with status:"success"

NSString *string= [NSString stringWithFormat:@"url?uname=%@&pass=%@&uname_submit=Login",self.txtUsername.text,self.txtPassword.text];
    NSLog(@"%@",string);
    NSURL *url = [NSURL URLWithString:string];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSURLResponse *response;
    NSError *err;
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&err];
    NSLog(@"responseData: %@", responseData);
    NSString *str = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"responseData: %@", str);
        NSDictionary* json = [NSJSONSerialization JSONObjectWithData:responseData
                                                         options:kNilOptions
                                                           error:nil];
    NSDictionary* latestLoans = [json objectForKey:@"status"];
    NSString *str2=[NSString stringWithFormat:@"%@", latestLoans];
    NSString *str3=@"success";
    if ([str3 isEqualToString:str2 ])
    {
        [self performSegueWithIdentifier:@"move" sender:nil];
        NSLog(@"successfully.");
    }
    else
    {
        UIAlertController *alert= [UIAlertController
                                 alertControllerWithTitle:@"Try Again"
                                 message:@"Username or Password is Incorrect."
                                 preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction* ok = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault
                                                   handler:^(UIAlertAction * action){
                                                       [self.view endEditing:YES];
                                                   }
                             ];
        [alert addAction:ok];
        [[UIView appearanceWhenContainedIn:[UIAlertController class], nil] setTintColor:[UIColor redColor]];
        [self presentViewController:alert animated:YES completion:nil];
        [self.view endEditing:YES];
      }

JSON Response : {"status":"success","user_id":"58","user_name":"dilip","result":"You have been logged in successfully"} Working code

**

Can a local variable's memory be accessed outside its scope?

It's 'Dirty' way of using memory addresses. When you return an address (pointer) you don't know whether it belongs to local scope of a function. It's just an address. Now that you invoked the 'foo' function, that address (memory location) of 'a' was already allocated there in the (safely, for now at least) addressable memory of your application (process). After the 'foo' function returned, the address of 'a' can be considered 'dirty' but it's there, not cleaned up, nor disturbed/modified by expressions in other part of program (in this specific case at least). A C/C++ compiler doesn't stop you from such 'dirty' access (might warn you though, if you care). You can safely use (update) any memory location that is in the data segment of your program instance (process) unless you protect the address by some means.

Flask example with POST

Here is the example in which you can easily find the way to use Post,GET method and use the same way to add other curd operations as well..

#libraries to include

import os
from flask import request, jsonify
from app import app, mongo
import logger
ROOT_PATH = os.environ.get('ROOT_PATH')<br>
@app.route('/get/questions/', methods=['GET', 'POST','DELETE', 'PATCH'])
    def question():
    # request.args is to get urls arguments 


    if request.method == 'GET':
        start = request.args.get('start', default=0, type=int)
        limit_url = request.args.get('limit', default=20, type=int)
        questions = mongo.db.questions.find().limit(limit_url).skip(start);
        data = [doc for doc in questions]
        return jsonify(isError= False,
                    message= "Success",
                    statusCode= 200,
                    data= data), 200

# request.form to get form parameter

    if request.method == 'POST':
        average_time = request.form.get('average_time')
        choices = request.form.get('choices')
        created_by = request.form.get('created_by')
        difficulty_level = request.form.get('difficulty_level')
        question = request.form.get('question')
        topics = request.form.get('topics')

    ##Do something like insert in DB or Render somewhere etc. it's up to you....... :)

python: Appending a dictionary to a list - I see a pointer like behavior

You are correct in that your list contains a reference to the original dictionary.

a.append(b.copy()) should do the trick.

Bear in mind that this makes a shallow copy. An alternative is to use copy.deepcopy(b), which makes a deep copy.

Can I check if Bootstrap Modal Shown / Hidden?

Use hasClass('in'). It will return true if modal is in OPEN state.

E.g:

if($('.modal').hasClass('in')){
   //Do something here
}

How to get setuptools and easy_install?

apt-get install python-setuptools python-pip

or

apt-get install python3-setuptools python3-pip

you'd also want to install the python packages...

Is it possible to implement a Python for range loop without an iterator variable?

If do_something is a simple function or can be wrapped in one, a simple map() can do_something range(some_number) times:

# Py2 version - map is eager, so it can be used alone
map(do_something, xrange(some_number))

# Py3 version - map is lazy, so it must be consumed to do the work at all;
# wrapping in list() would be equivalent to Py2, but if you don't use the return
# value, it's wastefully creating a temporary, possibly huge, list of junk.
# collections.deque with maxlen 0 can efficiently run a generator to exhaustion without
# storing any of the results; the itertools consume recipe uses it for that purpose.
from collections import deque

deque(map(do_something, range(some_number)), 0)

If you want to pass arguments to do_something, you may also find the itertools repeatfunc recipe reads well:

To pass the same arguments:

from collections import deque
from itertools import repeat, starmap

args = (..., my args here, ...)

# Same as Py3 map above, you must consume starmap (it's a lazy generator, even on Py2)
deque(starmap(do_something, repeat(args, some_number)), 0)

To pass different arguments:

argses = [(1, 2), (3, 4), ...]

deque(starmap(do_something, argses), 0)

How do I insert an image in an activity with android studio?

since you followed the tutorial, I presume you have a screen that says Hello World.

that means you have some code in your layout xml that looks like this

<TextView        
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

you want to display an image, so instead of TextView you want to have ImageView. and instead of a text attribute you want an src attribute, that links to your drawable resource

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/cool_pic"
/>

How to vertically center <div> inside the parent element with CSS?

In my firefox and chrome work this:

CSS:

display: flex;
justify-content: center;     // vertical align
align-items: center;         // horizontal align

Pass by pointer & Pass by reference

In fact, most compilers emit the same code for both functions calls, because references are generally implemented using pointers.

Following this logic, when an argument of (non-const) reference type is used in the function body, the generated code will just silently operate on the address of the argument and it will dereference it. In addition, when a call to such a function is encountered, the compiler will generate code that passes the address of the arguments instead of copying their value.

Basically, references and pointers are not very different from an implementation point of view, the main (and very important) difference is in the philosophy: a reference is the object itself, just with a different name.

References have a couple more advantages compared to pointers (e. g. they can't be NULL, so they are safer to use). Consequently, if you can use C++, then passing by reference is generally considered more elegant and it should be preferred. However, in C, there's no passing by reference, so if you want to write C code (or, horribile dictu, code that compiles with both a C and a C++ compiler, albeit that's not a good idea), you'll have to restrict yourself to using pointers.

How to set a timer in android

Standard Java way to use timers via java.util.Timer and java.util.TimerTask works fine in Android, but you should be aware that this method creates a new thread.

You may consider using the very convenient Handler class (android.os.Handler) and send messages to the handler via sendMessageAtTime(android.os.Message, long) or sendMessageDelayed(android.os.Message, long). Once you receive a message, you can run desired tasks. Second option would be to create a Runnable object and schedule it via Handler's functions postAtTime(java.lang.Runnable, long) or postDelayed(java.lang.Runnable, long).

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

If you need to open XLS files rather than XLSX files, http://npoi.codeplex.com/ is a great choice. We've used it to good effect on our projects.

How to copy marked text in notepad++

As of Notepad++ 5.9 they added a feature to 'Remove Unmarked Lines' which can be used to strip away everything that you don't want along with some search and replaces for the other text on each value line.

  1. Use the Search-->Find-->Mark functionality to mark each line you want to keep/copy and remember to tick 'Bookmark Line' before marking the text
  2. Select Search-->Bookmark-->Remove Unmarked Lines
  3. Use Search-->Find-->Replace to replace other text you do not want to keep/copy with nothing
  4. Save the remaining text or copy it.

You can also do a similar thing using Search-->Bookmark-->Copy Bookmarked Lines

So technically you still cannot copy marked text, but you can bookmark lines with marked text and then perform various operations on bookmarked or unmarked lines.

Directory index forbidden by Options directive

The Problem

Indexes visible in a web browser for directories that do not contain an index.html or index.php file.

I had a lot of trouble with the configuration on Scientific Linux's httpd web server to stop showing these indexes.

The Configuration that did not work

httpd.conf virtual host directory directives:

<Directory /home/mydomain.com/htdocs>
    Options FollowSymLinks
    AllowOverride all
    Require all granted
</Directory>

and the addition of the following line to .htaccess:

Options -Indexes

Directory indexes were still showing up. .htaccess settings weren't working!

How could that be, other settings in .htaccess were working, so why not this one? What's going? It should be working! %#$&^$%@# !!

The Fix

Change httpd.conf's Options line to:

Options +FollowSymLinks

and restart the webserver.

From Apache's core mod page: ( https://httpd.apache.org/docs/2.4/mod/core.html#options )

Mixing Options with a + or - with those without is not valid syntax and will be rejected during server startup by the syntax check with an abort.

Voilà directory indexes were no longer showing up for directories that did not contain an index.html or index.php file.

Now What! A New Wrinkle

New entries started to show up in the 'error_log' when such a directory access was attempted:

[Fri Aug 19 02:57:39.922872 2016] [autoindex:error] [pid 12479] [client aaa.bbb.ccc.ddd:xxxxx] AH01276: Cannot serve directory /home/mydomain.com/htdocs/dir-without-index-file/: No matching DirectoryIndex (index.html,index.php) found, and server-generated directory index forbidden by Options directive

This entry is from the Apache module 'autoindex' with a LogLevel of 'error' as indicated by [autoindex:error] of the error message---the format is [module_name:loglevel].

To stop these new entries from being logged, the LogLevel needs to be changed to a higher level (e.g. 'crit') to log fewer---only more serious error messages.

Apache 2.4 LogLevels

See Apache 2.4's core directives for LogLevel.

emerg, alert, crit, error, warn, notice, info, debug, trace1, trace2, trace3, tracr4, trace5, trace6, trace7, trace8

Each level deeper into the list logs all the messages of any previous level(s).

Apache 2.4's default level is 'warn'. Therefore, all messages classified as emerg, alert, crit, error, and warn are written to error_log.

Additional Fix to Stop New error_log Entries

Added the following line inside the <Directory>..</Directory> section of httpd.conf:

LogLevel crit

The Solution 1

My virtual host's httpd.conf <Directory>..</Directory> configuration:

<Directory /home/mydomain.com/htdocs>
    Options +FollowSymLinks
    AllowOverride all
    Require all granted
    LogLevel crit
</Directory>

and adding to /home/mydomain.com/htdocs/.htaccess, the root directory of your website's .htaccess file:

Options -Indexes

If you don't mind the 'error' level messages, omit

LogLevel crit

Scientific Linux - Solution 2 - Disables mod_autoindex

No more autoindex'ing of directories inside your web space. No changes to .htaccess. But, need access to the httpd configuration files in /etc/httpd

  1. Edit /etc/httpd/conf.modules.d/00-base.conf and comment the line:

    LoadModule autoindex_module modules/mod_autoindex.so
    

    by adding a # in front of it then save the file.

  2. In the directory /etc/httpd/conf.d rename (mv)

    sudo mv autoindex.conf autoindex.conf.<something_else>
    
  3. Restart httpd:

    sudo httpd -k restart
    

    or

    sudo apachectl restart
    

The autoindex_mod is now disabled.

Linux distros with ap2dismod/ap2enmod Commands

Disable autoindex module enter the command

    sudo a2dismod autoindex

to enable autoindex module enter

    sudo a2enmod autoindex

Which is the best Linux C/C++ debugger (or front-end to gdb) to help teaching programming?

You may want to check out Eclipse CDT. It provides a C/C++ IDE that runs on multiple platforms (e.g. Windows, Linux, Mac OS X, etc.). Debugging with Eclipse CDT is comparable to using other tools such as Visual Studio.

You can check out the Eclipse CDT Debug tutorial that also includes a number of screenshots.

How can I extract a number from a string in JavaScript?

You need to add "(/\d+/g)" which will remove all non-number text, but it will still be a string at this point. If you create a variable and "parseInt" through the match, you can set the new variables to the array values. Here is an example of how I got it to work:

    var color = $( this ).css( "background-color" );
    var r = parseInt(color.match(/\d+/g)[0]);
    var g = parseInt(color.match(/\d+/g)[1]);
    var b = parseInt(color.match(/\d+/g)[2]);

Request is not available in this context

This worked for me - if you have to log in Application_Start, do it before you modify the context. You will get a log entry, just with no source, like:

2019-03-12 09:35:43,659 INFO (null) - Application Started

I generally log both the Application_Start and Session_Start, so I see more detail in the next message

2019-03-12 09:35:45,064 INFO ~/Leads/Leads.aspx - Session Started (Local)

        protected void Application_Start(object sender, EventArgs e)
        {
            log4net.Config.XmlConfigurator.Configure();
            log.Info("Application Started");
            GlobalContext.Properties["page"] = new GetCurrentPage();
        }

        protected void Session_Start(object sender, EventArgs e)
        {
            Globals._Environment = WebAppConfig.getEnvironment(Request.Url.AbsoluteUri, Properties.Settings.Default.LocalOverride);
            log.Info(string.Format("Session Started ({0})", Globals._Environment));
        }


How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

How to set a radio button in Android

btnDisplay.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {

            // get selected radio button from radioGroup
        int selectedId = radioSexGroup.getCheckedRadioButtonId();

        // find the radiobutton by returned id
            radioSexButton = (RadioButton) findViewById(selectedId);

        Toast.makeText(MyAndroidAppActivity.this,
            radioSexButton.getText(), Toast.LENGTH_SHORT).show();

    }

});

Delete rows with foreign key in PostgreSQL

It means that in table kontakty you have a row referencing the row in osoby you want to delete. You have do delete that row first or set a cascade delete on the relation between tables.

Powodzenia!

postgresql - replace all instances of a string within text field

You want to use postgresql's replace function:

replace(string text, from text, to text)

for instance :

UPDATE <table> SET <field> = replace(<field>, 'cat', 'dog')

Be aware, though, that this will be a string-to-string replacement, so 'category' will become 'dogegory'. the regexp_replace function may help you define a stricter match pattern for what you want to replace.

How to use a WSDL

In visual studio.

  • Create or open a project.
  • Right-click project from solution explorer.
  • Select "Add service refernce"
  • Paste the address with WSDL you received.
  • Click OK.

If no errors, you should be able to see the service reference in the object browser and all related methods.

UTF-8 problems while reading CSV file with fgetcsv

In my case the source file has windows-1250 encoding and iconv prints tons of notices about illegal characters in input string...

So this solution helped me a lot:

/**
 * getting CSV array with UTF-8 encoding
 *
 * @param   resource    &$handle
 * @param   integer     $length
 * @param   string      $separator
 *
 * @return  array|false
 */
private function fgetcsvUTF8(&$handle, $length, $separator = ';')
{
    if (($buffer = fgets($handle, $length)) !== false)
    {
        $buffer = $this->autoUTF($buffer);
        return str_getcsv($buffer, $separator);
    }
    return false;
}

/**
 * automatic convertion windows-1250 and iso-8859-2 info utf-8 string
 *
 * @param   string  $s
 *
 * @return  string
 */
private function autoUTF($s)
{
    // detect UTF-8
    if (preg_match('#[\x80-\x{1FF}\x{2000}-\x{3FFF}]#u', $s))
        return $s;

    // detect WINDOWS-1250
    if (preg_match('#[\x7F-\x9F\xBC]#', $s))
        return iconv('WINDOWS-1250', 'UTF-8', $s);

    // assume ISO-8859-2
    return iconv('ISO-8859-2', 'UTF-8', $s);
}

Response to @manvel's answer - use str_getcsv instead of explode - because of cases like this:

some;nice;value;"and;here;comes;combinated;value";and;some;others

explode will explode string into parts:

some
nice
value
"and
here
comes
combinated
value"
and
some
others

but str_getcsv will explode string into parts:

some
nice
value
and;here;comes;combinated;value
and
some
others

Java Date - Insert into database

VALUES ('"+user+"' , '"+FirstTest+"'  , '"+LastTest+"'..............etc)

You can use it to insert variables into sql query.

Read contents of a local file into a variable in Rails

I think you should consider using IO.binread("/path/to/file") if you have a recent ruby interpreter (i.e. >= 1.9.2)

You could find IO class documentation here http://www.ruby-doc.org/core-2.1.2/IO.html

Get String in YYYYMMDD format from JS date object?

From ES6 onwards you can use template strings to make it a little shorter:

var now = new Date();
var todayString = `${now.getFullYear()}-${now.getMonth()}-${now.getDate()}`;

This solution does not zero pad. Look to the other good answers to see how to do that.

Are dictionaries ordered in Python 3.6+?

To fully answer this question in 2020, let me quote several statements from official Python docs:

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

Changed in version 3.7: Dictionary order is guaranteed to be insertion order.

Changed in version 3.8: Dictionaries are now reversible.

Dictionaries and dictionary views are reversible.

A statement regarding OrderedDict vs Dict:

Ordered dictionaries are just like regular dictionaries but have some extra capabilities relating to ordering operations. They have become less important now that the built-in dict class gained the ability to remember insertion order (this new behavior became guaranteed in Python 3.7).

How do I monitor all incoming http requests?

Use TcpView to see ports listening and connections. This will not give you the requests though.

In order to see requests, you need reverse of a proxy which I do not know of any such tools.

Use tracing to give you parts of the requests (first 1KB of the request).

printf formatting (%d versus %u)

You can find a list of formatting escapes on this page.

%d is a signed integer, while %u is an unsigned integer. Pointers (when treated as numbers) are usually non-negative.

If you actually want to display a pointer, use the %p format specifier.

Error: [ng:areq] from angular controller

I've gotten that error twice:

1) When I wrote:

var app = module('flapperNews', []);

instead of:

var app = angular.module('flapperNews', []);

2) When I copy and pasted some html, and the controller name in the html did not exactly match the controller name in my app.js file, for instance:

index.html:

<script src="app.js"></script>
...
...
<body ng-app="flapperNews" ng-controller="MainCtrl">

app.js:

var app = angular.module('flapperNews', []);

app.controller('MyCtrl', ....

In the html, the controller name is "MainCtrl", and in the js I used the name "MyCtrl".

There is actually an error message embedded in the error url:

Error: [ng:areq] http://errors.angularjs.org/1.3.2/ng/areq?p0=MainCtrl&p1=not%20a%20function%2C%20got%20undefined

Here it is without the hieroglyphics:

MainCtrl not a function got undefined

In other words, "There is no function named MainCtrl. Check your spelling."

Bash: Syntax error: redirection unexpected

You can get the output of that command and put it in a variable. then use heredoc. for example:

nc -l -p 80 <<< "tested like a charm";

can be written like:

nc -l -p 80 <<EOF
tested like a charm
EOF

and like this (this is what you want):

text="tested like a charm"
nc -l -p 80 <<EOF
$text
EOF

Practical example in busybox under docker container:

kasra@ubuntu:~$ docker run --rm -it busybox
/ # nc -l -p 80 <<< "tested like a charm";
sh: syntax error: unexpected redirection


/ # nc -l -p 80 <<EOL
> tested like a charm
> EOL
^Cpunt!       => socket listening, no errors. ^Cpunt! is result of CTRL+C signal.


/ # text="tested like a charm"
/ # nc -l -p 80 <<EOF
> $text
> EOF
^Cpunt!

ALTER TABLE add constraint

ALTER TABLE `User`
ADD CONSTRAINT `user_properties_foreign`
FOREIGN KEY (`properties`)
REFERENCES `Properties` (`ID`)
ON DELETE NO ACTION
ON UPDATE NO ACTION;

Convert Uri to String and String to Uri

This will get the file path from the MediaProvider, DownloadsProvider, and ExternalStorageProvider, while falling back to the unofficial ContentProvider method you mention.

   /**
 * Get a file path from a Uri. This will get the the path for Storage Access
 * Framework Documents, as well as the _data field for the MediaStore and
 * other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @author paulburke
 */
public static String getPath(final Context context, final Uri uri) {

    final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;

    // DocumentProvider
    if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
        // ExternalStorageProvider
        if (isExternalStorageDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            if ("primary".equalsIgnoreCase(type)) {
                return Environment.getExternalStorageDirectory() + "/" + split[1];
            }

            // TODO handle non-primary volumes
        }
        // DownloadsProvider
        else if (isDownloadsDocument(uri)) {

            final String id = DocumentsContract.getDocumentId(uri);
            final Uri contentUri = ContentUris.withAppendedId(
                    Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));

            return getDataColumn(context, contentUri, null, null);
        }
        // MediaProvider
        else if (isMediaDocument(uri)) {
            final String docId = DocumentsContract.getDocumentId(uri);
            final String[] split = docId.split(":");
            final String type = split[0];

            Uri contentUri = null;
            if ("image".equals(type)) {
                contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            } else if ("video".equals(type)) {
                contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
            } else if ("audio".equals(type)) {
                contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
            }

            final String selection = "_id=?";
            final String[] selectionArgs = new String[] {
                    split[1]
            };

            return getDataColumn(context, contentUri, selection, selectionArgs);
        }
    }
    // MediaStore (and general)
    else if ("content".equalsIgnoreCase(uri.getScheme())) {
        return getDataColumn(context, uri, null, null);
    }
    // File
    else if ("file".equalsIgnoreCase(uri.getScheme())) {
        return uri.getPath();
    }

    return null;
}

/**
 * Get the value of the data column for this Uri. This is useful for
 * MediaStore Uris, and other file-based ContentProviders.
 *
 * @param context The context.
 * @param uri The Uri to query.
 * @param selection (Optional) Filter used in the query.
 * @param selectionArgs (Optional) Selection arguments used in the query.
 * @return The value of the _data column, which is typically a file path.
 */
public static String getDataColumn(Context context, Uri uri, String selection,
        String[] selectionArgs) {

    Cursor cursor = null;
    final String column = "_data";
    final String[] projection = {
            column
    };

    try {
        cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                null);
        if (cursor != null && cursor.moveToFirst()) {
            final int column_index = cursor.getColumnIndexOrThrow(column);
            return cursor.getString(column_index);
        }
    } finally {
        if (cursor != null)
            cursor.close();
    }
    return null;
}


/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is ExternalStorageProvider.
 */
public static boolean isExternalStorageDocument(Uri uri) {
    return "com.android.externalstorage.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is DownloadsProvider.
 */
public static boolean isDownloadsDocument(Uri uri) {
    return "com.android.providers.downloads.documents".equals(uri.getAuthority());
}

/**
 * @param uri The Uri to check.
 * @return Whether the Uri authority is MediaProvider.
 */
public static boolean isMediaDocument(Uri uri) {
    return "com.android.providers.media.documents".equals(uri.getAuthority());
}

I want to convert std::string into a const wchar_t *

First convert it to std::wstring:

std::wstring widestr = std::wstring(str.begin(), str.end());

Then get the C string:

const wchar_t* widecstr = widestr.c_str();

This only works for ASCII strings, but it will not work if the underlying string is UTF-8 encoded. Using a conversion routine like MultiByteToWideChar() ensures that this scenario is handled properly.

Convert blob URL to normal URL

Found this answer here and wanted to reference it as it appear much cleaner than the accepted answer:

function blobToDataURL(blob, callback) {
  var fileReader = new FileReader();
  fileReader.onload = function(e) {callback(e.target.result);}
  fileReader.readAsDataURL(blob);
}

How can I enable Assembly binding logging?

  1. Create a new Application Pool

  2. Go to the Advanced Settings of this application pool

  3. Set the Enable 32-Bit Application to True

  4. Point your web application to use this new Pool

Screenshot (IIS-ApplicationPool)

Breaking out of a nested loop

Well, goto, but that is ugly, and not always possible. You can also place the loops into a method (or an anon-method) and use return to exit back to the main code.

    // goto
    for (int i = 0; i < 100; i++)
    {
        for (int j = 0; j < 100; j++)
        {
            goto Foo; // yeuck!
        }
    }
Foo:
    Console.WriteLine("Hi");

vs:

// anon-method
Action work = delegate
{
    for (int x = 0; x < 100; x++)
    {
        for (int y = 0; y < 100; y++)
        {
            return; // exits anon-method
        }
    }
};
work(); // execute anon-method
Console.WriteLine("Hi");

Note that in C# 7 we should get "local functions", which (syntax tbd etc) means it should work something like:

// local function (declared **inside** another method)
void Work()
{
    for (int x = 0; x < 100; x++)
    {
        for (int y = 0; y < 100; y++)
        {
            return; // exits local function
        }
    }
};
Work(); // execute local function
Console.WriteLine("Hi");

Automating running command on Linux from Windows using PuTTY

Code:

using System;
using System.Diagnostics;
namespace playSound
{
    class Program
    {
        public static void Main(string[] args)
        {
            Console.WriteLine(args[0]);

            Process amixerMediaProcess = new Process();
            amixerMediaProcess.StartInfo.CreateNoWindow = false;
            amixerMediaProcess.StartInfo.UseShellExecute = false;
            amixerMediaProcess.StartInfo.ErrorDialog = false;
            amixerMediaProcess.StartInfo.RedirectStandardOutput = false;
            amixerMediaProcess.StartInfo.RedirectStandardInput = false;
            amixerMediaProcess.StartInfo.RedirectStandardError = false;
            amixerMediaProcess.EnableRaisingEvents = true;

            amixerMediaProcess.StartInfo.Arguments = string.Format("{0}","-ssh username@"+args[0]+" -pw password -m commands.txt");
            amixerMediaProcess.StartInfo.FileName = "plink.exe";
            amixerMediaProcess.Start();


            Console.Write("Presskey to continue . . . ");
            Console.ReadKey(true);
    }
}

}

Sample commands.txt:

ps

Link: https://huseyincakir.wordpress.com/2015/08/27/send-commands-to-a-remote-device-over-puttyssh-putty-send-command-from-command-line/

Use Device Login on Smart TV / Console

They change it again. At this moment documentation does not fit actual situation.

Commonly all works as expected with one small difference. Login from Devices config now moves to Products -> Facebook Login.

So you need to:

  • get your App id from headline,
  • get Client Token from app Settings -> Advanced. There is also Native or desktop app? question/config. I turn it on.
  • Add product (just click on Add product and then Get started on Facebook login. Move back to your app config, click to newly added Facebook login and you'll see your Login from Devices config.

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

To make use of regular expressions directly in Excel formulas the following UDF (user defined function) can be of help. It more or less directly exposes regular expression functionality as an excel function.

How it works

It takes 2-3 parameters.

  1. A text to use the regular expression on.
  2. A regular expression.
  3. A format string specifying how the result should look. It can contain $0, $1, $2, and so on. $0 is the entire match, $1 and up correspond to the respective match groups in the regular expression. Defaults to $0.

Some examples

Extracting an email address:

=regex("Peter Gordon: [email protected], 47", "\w+@\w+\.\w+")
=regex("Peter Gordon: [email protected], 47", "\w+@\w+\.\w+", "$0")

Results in: [email protected]

Extracting several substrings:

=regex("Peter Gordon: [email protected], 47", "^(.+): (.+), (\d+)$", "E-Mail: $2, Name: $1")

Results in: E-Mail: [email protected], Name: Peter Gordon

To take apart a combined string in a single cell into its components in multiple cells:

=regex("Peter Gordon: [email protected], 47", "^(.+): (.+), (\d+)$", "$" & 1)
=regex("Peter Gordon: [email protected], 47", "^(.+): (.+), (\d+)$", "$" & 2)

Results in: Peter Gordon [email protected] ...

How to use

To use this UDF do the following (roughly based on this Microsoft page. They have some good additional info there!):

  1. In Excel in a Macro enabled file ('.xlsm') push ALT+F11 to open the Microsoft Visual Basic for Applications Editor.
  2. Add VBA reference to the Regular Expressions library (shamelessly copied from Portland Runners++ answer):
    1. Click on Tools -> References (please excuse the german screenshot) Tools -> References
    2. Find Microsoft VBScript Regular Expressions 5.5 in the list and tick the checkbox next to it.
    3. Click OK.
  3. Click on Insert Module. If you give your module a different name make sure the Module does not have the same name as the UDF below (e.g. naming the Module Regex and the function regex causes #NAME! errors).

    Second icon in the icon row -> Module

  4. In the big text window in the middle insert the following:

    Function regex(strInput As String, matchPattern As String, Optional ByVal outputPattern As String = "$0") As Variant
        Dim inputRegexObj As New VBScript_RegExp_55.RegExp, outputRegexObj As New VBScript_RegExp_55.RegExp, outReplaceRegexObj As New VBScript_RegExp_55.RegExp
        Dim inputMatches As Object, replaceMatches As Object, replaceMatch As Object
        Dim replaceNumber As Integer
    
        With inputRegexObj
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = matchPattern
        End With
        With outputRegexObj
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
            .Pattern = "\$(\d+)"
        End With
        With outReplaceRegexObj
            .Global = True
            .MultiLine = True
            .IgnoreCase = False
        End With
    
        Set inputMatches = inputRegexObj.Execute(strInput)
        If inputMatches.Count = 0 Then
            regex = False
        Else
            Set replaceMatches = outputRegexObj.Execute(outputPattern)
            For Each replaceMatch In replaceMatches
                replaceNumber = replaceMatch.SubMatches(0)
                outReplaceRegexObj.Pattern = "\$" & replaceNumber
    
                If replaceNumber = 0 Then
                    outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).Value)
                Else
                    If replaceNumber > inputMatches(0).SubMatches.Count Then
                        'regex = "A to high $ tag found. Largest allowed is $" & inputMatches(0).SubMatches.Count & "."
                        regex = CVErr(xlErrValue)
                        Exit Function
                    Else
                        outputPattern = outReplaceRegexObj.Replace(outputPattern, inputMatches(0).SubMatches(replaceNumber - 1))
                    End If
                End If
            Next
            regex = outputPattern
        End If
    End Function
    
  5. Save and close the Microsoft Visual Basic for Applications Editor window.

How to let PHP to create subdomain automatically for each user?

I do it a little different from Mark. I pass the entire domain and grab the subdomain in php.

RewriteCond {REQUEST_URI} !\.(png|gif|jpg)$
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ /index.php?uri=$1&hostName=%{HTTP_HOST}

This ignores images and maps everything else to my index.php file. So if I go to

http://fred.mywebsite.com/album/Dance/now

I get back

http://fred.mywebsite.com/index.php?uri=album/Dance/now&hostName=fred.mywebsite.com

Then in my index.php code i just explode my username off of the hostName. This gives me nice pretty SEO URLs.

django import error - No module named core.management

Store the python python path in a variable and execute.This would include the otherwise missing packages.

python_path= `which python` 
$python_path manage.py runserver

Evenly space multiple views within a container view

Here is yet another answer. I was answering a similar question and saw link referenced to this question. I didnt see any answer similar to mine. So, I thought of writing it here.

  class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.whiteColor()
        setupViews()
    }

    var constraints: [NSLayoutConstraint] = []

    func setupViews() {

        let container1 = createButtonContainer(withButtonTitle: "Button 1")
        let container2 = createButtonContainer(withButtonTitle: "Button 2")
        let container3 = createButtonContainer(withButtonTitle: "Button 3")
        let container4 = createButtonContainer(withButtonTitle: "Button 4")

        view.addSubview(container1)
        view.addSubview(container2)
        view.addSubview(container3)
        view.addSubview(container4)

        [

            // left right alignment
            container1.leftAnchor.constraintEqualToAnchor(view.leftAnchor, constant: 20),
            container1.rightAnchor.constraintEqualToAnchor(view.rightAnchor, constant: -20),
            container2.leftAnchor.constraintEqualToAnchor(container1.leftAnchor),
            container2.rightAnchor.constraintEqualToAnchor(container1.rightAnchor),
            container3.leftAnchor.constraintEqualToAnchor(container1.leftAnchor),
            container3.rightAnchor.constraintEqualToAnchor(container1.rightAnchor),
            container4.leftAnchor.constraintEqualToAnchor(container1.leftAnchor),
            container4.rightAnchor.constraintEqualToAnchor(container1.rightAnchor),


            // place containers one after another vertically
            container1.topAnchor.constraintEqualToAnchor(view.topAnchor),
            container2.topAnchor.constraintEqualToAnchor(container1.bottomAnchor),
            container3.topAnchor.constraintEqualToAnchor(container2.bottomAnchor),
            container4.topAnchor.constraintEqualToAnchor(container3.bottomAnchor),
            container4.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor),


            // container height constraints
            container2.heightAnchor.constraintEqualToAnchor(container1.heightAnchor),
            container3.heightAnchor.constraintEqualToAnchor(container1.heightAnchor),
            container4.heightAnchor.constraintEqualToAnchor(container1.heightAnchor)
            ]
            .forEach { $0.active = true }
    }


    func createButtonContainer(withButtonTitle title: String) -> UIView {
        let view = UIView(frame: .zero)
        view.translatesAutoresizingMaskIntoConstraints = false

        let button = UIButton(type: .System)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle(title, forState: .Normal)
        view.addSubview(button)

        [button.centerYAnchor.constraintEqualToAnchor(view.centerYAnchor),
            button.leftAnchor.constraintEqualToAnchor(view.leftAnchor),
            button.rightAnchor.constraintEqualToAnchor(view.rightAnchor)].forEach { $0.active = true }

        return view
    }
}

enter image description here

And again, this can be done quite easily with iOS9 UIStackViews as well.

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = UIColor.greenColor()
        setupViews()
    }

    var constraints: [NSLayoutConstraint] = []

    func setupViews() {

        let container1 = createButtonContainer(withButtonTitle: "Button 1")
        let container2 = createButtonContainer(withButtonTitle: "Button 2")
        let container3 = createButtonContainer(withButtonTitle: "Button 3")
        let container4 = createButtonContainer(withButtonTitle: "Button 4")

        let stackView = UIStackView(arrangedSubviews: [container1, container2, container3, container4])
        stackView.translatesAutoresizingMaskIntoConstraints = false
        stackView.axis = .Vertical
        stackView.distribution = .FillEqually
        view.addSubview(stackView)

        [stackView.topAnchor.constraintEqualToAnchor(view.topAnchor),
            stackView.bottomAnchor.constraintEqualToAnchor(view.bottomAnchor),
            stackView.leftAnchor.constraintEqualToAnchor(view.leftAnchor, constant: 20),
            stackView.rightAnchor.constraintEqualToAnchor(view.rightAnchor, constant: -20)].forEach { $0.active = true }
    }


    func createButtonContainer(withButtonTitle title: String) -> UIView {
        let button = UIButton(type: .Custom)
        button.translatesAutoresizingMaskIntoConstraints = false
        button.backgroundColor = UIColor.redColor()
        button.setTitleColor(UIColor.whiteColor(), forState: .Normal)
        button.setTitle(title, forState: .Normal)
        let buttonContainer = UIStackView(arrangedSubviews: [button])
        buttonContainer.distribution = .EqualCentering
        buttonContainer.alignment = .Center
        buttonContainer.translatesAutoresizingMaskIntoConstraints = false
        return buttonContainer
    }
}

Notice that it is exact same approach as above. It adds four container views which are filled equally and a view is added to each stack view which is aligned in center. But, this version of UIStackView reduces some code and looks nice.

Change image size with JavaScript

If you want to resize an image after it is loaded, you can attach to the onload event of the <img> tag. Note that it may not be supported in all browsers (Microsoft's reference claims it is part of the HTML 4.0 spec, but the HTML 4.0 spec doesn't list the onload event for <img>).

The code below is tested and working in: IE 6, 7 & 8, Firefox 2, 3 & 3.5, Opera 9 & 10, Safari 3 & 4 and Google Chrome:

<img src="yourImage.jpg" border="0" height="real_height" width="real_width"
    onload="resizeImg(this, 200, 100);">

<script type="text/javascript">
function resizeImg(img, height, width) {
    img.height = height;
    img.width = width;
}
</script>

JSON forEach get Key and Value

Try something like this:

var prop;
for(prop in obj) {
    if(!obj.hasOwnProperty(prop)) continue;

    console.log(prop + " - "+ obj[prop]);
}

How do I add FTP support to Eclipse?

I'm not sure if this works for you, but when I do small solo PHP projects with Eclipse, the first thing I set up is an Ant script for deploying the project to a remote testing environment. I code away locally, and whenever I want to test it, I just hit the shortcut which updates the remote site.

Eclipse has good Ant support out of the box, and the scripts aren't hard to make.

How to remove/ignore :hover css style on touch devices

try this:

@media (hover:<s>on-demand</s>) {
    button:hover {
        background-color: #color-when-NOT-touch-device;
    }
}

UPDATE: unfortunately W3C has removed this property from the specs (https://github.com/w3c/csswg-drafts/commit/2078b46218f7462735bb0b5107c9a3e84fb4c4b1).

Is there a way to get a <button> element to link to a location without wrapping it in an <a href ... tag?

Here it is using jQuery. See it in action at http://jsfiddle.net/sQnSZ/

<button id="x">test</button>

$('#x').click(function(){
    location.href='http://cnn.com'
})

ngOnInit not being called when Injectable class is Instantiated

I don't know about all the lifecycle hooks, but as for destruction, ngOnDestroy actually get called on Injectable when it's provider is destroyed (for example an Injectable supplied by a component).

From the docs :

Lifecycle hook that is called when a directive, pipe or service is destroyed.

Just in case anyone is interested in destruction check this question:

C# DropDownList with a Dictionary as DataSource

If the DropDownList is declared in your aspx page and not in the codebehind, you can do it like this.

.aspx:

<asp:DropDownList ID="ddlStatus" runat="server" DataSource="<%# Statuses %>"
     DataValueField="Key" DataTextField="Value"></asp:DropDownList>

.aspx.cs:

protected void Page_Load(object sender, EventArgs e)
{
    ddlStatus.DataBind();
    // or use Page.DataBind() to bind everything
}

public Dictionary<int, string> Statuses
{
    get 
    {
        // do database/webservice lookup here to populate Dictionary
    }
};

Android sqlite how to check if a record exists

public static boolean CheckIsDataAlreadyInDBorNot(String TableName,
        String dbfield, String fieldValue) {
    SQLiteDatabase sqldb = EGLifeStyleApplication.sqLiteDatabase;
    String Query = "Select * from " + TableName + " where " + dbfield + " = " + fieldValue;
    Cursor cursor = sqldb.rawQuery(Query, null);
        if(cursor.getCount() <= 0){
            cursor.close();
            return false;
        }
    cursor.close();
    return true;
}

I hope this is useful to you... This function returns true if record already exists in db. Otherwise returns false.

What is InputStream & Output Stream? Why and when do we use them?

Stream: In laymen terms stream is data , most generic stream is binary representation of data.

Input Stream : If you are reading data from a file or any other source , stream used is input stream. In a simpler terms input stream acts as a channel to read data.

Output Stream : If you want to read and process data from a source (file etc) you first need to save the data , the mean to store data is output stream .

Check date with todays date

I assume you are using integers to represent your year, month, and day? If you want to remain consistent, use the Date methods.

Calendar cal = new Calendar();
int currentYear, currentMonth, currentDay; 
currentYear = cal.get(Calendar.YEAR); 
currentMonth = cal.get(Calendar.MONTH); 
currentDay = cal.get(Calendar.DAY_OF_WEEK);

     if(startYear < currentYear)
                {
                    message = message + "Start Date is Before Today" + "\n";
                }
            else if(startMonth < currentMonth && startYear <= currentYear)
                    {
                        message = message + "Start Date is Before Today" + "\n";
                    }
            else if(startDay < currentDay && startMonth <= currentMonth && startYear <= currentYear)
                        {
                            message = message + "Start Date is Before Today" + "\n";
                        }

Get root view from current activity

Just incase Someone needs an easier way:

The following code gives a view of the whole activity:

View v1 = getWindow().getDecorView().getRootView();

To get a certian view in the activity,for example an imageView inside the activity, simply add the id of that view you want to get:

View v1 = getWindow().getDecorView().getRootView().findViewById(R.id.imageView1);

Hope this helps somebody

Adding <script> to WordPress in <head> element

If you are ok using an external plugin to do that you can use Header and Footer Scripts plugin

From the description:

Many WordPress Themes do not have any options to insert header and footer scripts in your site or . It helps you to keep yourself from theme lock. But, sometimes it also causes some pain for many. like where should I insert Google Analytics code (or any other web-analytics codes). This plugin is one stop and lightweight solution for that. With this "Header and Footer Script" plugin will be able to inject HTML tags, JS and CSS codes to and easily.

Remove a file from the list that will be committed

if you did a git add and you haven't pushed anything yet, you just have to do this to unstage it from your commit.

git reset HEAD <file>

Manually install Gradle and use it in Android Studio

https://services.gradle.org/distributions/

Download The Latest Gradle Distribution File and Extract It, Then Copy all Files and Paste it Under:

C:\Users\{USERNAME}\.gradle\wrapper\dists\

How do I concatenate strings with variables in PowerShell?

Try the Join-Path cmdlet:

Get-ChildItem c:\code\*\bin\* -Filter *.dll | Foreach-Object {
    Join-Path -Path  $_.DirectoryName -ChildPath "$buildconfig\$($_.Name)" 
}

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

If you use the Angular CLI to create your components, let's say CarComponent, it attaches app to the selector name (i.e app-car) and this throws the above error when you reference the component in the parent view. Therefore you either have to change the selector name in the parent view to let's say <app-car></app-car> or change the selector in the CarComponent to selector: 'car'

What represents a double in sql server?

Also, here is a good answer for SQL-CLR Type Mapping with a useful chart.

From that post (by David): enter image description here

TNS-12505: TNS:listener does not currently know of SID given in connect descriptor

in Windows in the search option Go to administrative tools>component services>OracleServiceXE(start this service)

Auto Increment after delete in MySQL

What you are trying to do is very dangerous. Think about this carefully. There is a very good reason for the default behaviour of auto increment.

Consider this:

A record is deleted in one table that has a relationship with another table. The corresponding record in the second table cannot be deleted for auditing reasons. This record becomes orphaned from the first table. If a new record is inserted into the first table, and a sequential primary key is used, this record is now linked to the orphan. Obviously, this is bad. By using an auto incremented PK, an id that has never been used before is always guaranteed. This means that orphans remain orphans, which is correct.

How to change the style of alert box?

Not possible. If you want to customize the dialog's visual appearance, you need to use a JS-based solution like jQuery.UI dialog.

Redirect echo output in shell script to logfile

I tried to manage using the below command. This will write the output in log file as well as print on console.

#!/bin/bash

# Log Location on Server.
LOG_LOCATION=/home/user/scripts/logs
exec > >(tee -i $LOG_LOCATION/MylogFile.log)
exec 2>&1

echo "Log Location should be: [ $LOG_LOCATION ]"

Please note: This is bash code so if you run it using sh it will through syntax error

How can I send mail from an iPhone application

If you want to send email from your application, the above code is the only way to do it unless you code your own mail client (SMTP) inside your app, or have a server send the mail for you.

For example, you could code your app to invoke a URL on your server which would send the mail for you. Then you simply call the URL from your code.

Note that with the above code you can't attach anything to the email, which the SMTP client method would allow you to do, as well as the server-side method.

Find duplicate characters in a String and count the number of occurances using Java

 void Findrepeter(){
    String s="mmababctamantlslmag";
    int distinct = 0 ;

    for (int i = 0; i < s.length(); i++) {

        for (int j = 0; j < s.length(); j++) {

            if(s.charAt(i)==s.charAt(j))
            {
                distinct++;

            }
        }   
        System.out.println(s.charAt(i)+"--"+distinct);
        String d=String.valueOf(s.charAt(i)).trim();
        s=s.replaceAll(d,"");
        distinct = 0;

    }

}

Global environment variables in a shell script

#!/bin/bash
export FOO=bar

or

#!/bin/bash
FOO=bar
export FOO

man export:

The shell shall give the export attribute to the variables corresponding to the specified names, which shall cause them to be in the environment of subsequently executed commands. If the name of a variable is followed by = word, then the value of that variable shall be set to word.

How to debug in Android Studio using adb over WiFi

I'm using AS 3.2.1, and was about to try some of the plugins, but was hesitant realizing the plugins are able to monitor any data..

It's actually really simple doing it via the Terminal tab in AS:

  1. Turn on debugging over WiFi in your phone
    • Go to developer options and turn on "ADB over network"
    • You'll see the exact address and port to use when connecting
  2. Go to the Terminal tab in Android Studio
  3. Type adb tcpip 5555
  4. Type your ip address as seen in developer options i.e. adb connect 192.168.1.101
  5. Now you'll see your device in AS "Select deployment target" dialog

PHP preg replace only allow numbers

This should do what you want:

preg_replace("/[^0-9]/", "",$c);

Ways to circumvent the same-origin policy

The most recent way of overcoming the same-origin policy that I've found is http://anyorigin.com/

The site's made so that you just give it any url and it generates javascript/jquery code for you that lets you get the html/data, regardless of it's origin. In other words, it makes any url or webpage a JSONP request.

I've found it pretty useful :)

Here's some example javascript code from anyorigin:

$.getJSON('http://anyorigin.com/get?url=google.com&callback=?', function(data){
    $('#output').html(data.contents);
});

How to remove any URL within a string in Python

I know this has already been answered and its stupid late but I think this should be here. This is a regex that matches any kind of url.

[^ ]+\.[^ ]+

It can be used like

re.sub('[^ ]+\.[^ ]+','',sentence)

Accessing value inside nested dictionaries

The answer was given already by either Sivasubramaniam Arunachalam or ch3ka.

I am just adding a performances view of the answer.

dicttest={}
dicttest['ligne1']={'ligne1.1':'test','ligne1.2':'test8'}
%timeit dicttest['ligne1']['ligne1.1']
%timeit dicttest.get('ligne1').get('ligne1.1')

gives us :

112 ns ± 29.7 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

235 ns ± 9.82 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

How to create a new schema/new user in Oracle Database 11g?

SQL> select Username from dba_users
  2  ;

USERNAME
------------------------------
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL
MDSYS

USERNAME
------------------------------
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR

16 rows selected.

SQL> create user testdb identified by password;

User created.

SQL> select username from dba_users;

USERNAME
------------------------------
TESTDB
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL

USERNAME
------------------------------
MDSYS
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR

17 rows selected.

SQL> grant create session to testdb;

Grant succeeded.

SQL> create tablespace testdb_tablespace
  2  datafile 'testdb_tabspace.dat'
  3  size 10M autoextend on;

Tablespace created.

SQL> create temporary tablespace testdb_tablespace_temp
  2  tempfile 'testdb_tabspace_temp.dat'
  3  size 5M autoextend on;

Tablespace created.

SQL> drop user testdb;

User dropped.

SQL> create user testdb
  2  identified by password
  3  default tablespace testdb_tablespace
  4  temporary tablespace testdb_tablespace_temp;

User created.

SQL> grant create session to testdb;

Grant succeeded.

SQL> grant create table to testdb;

Grant succeeded.

SQL> grant unlimited tablespace to testdb;

Grant succeeded.

SQL>

Convert Decimal to Varchar

I think CAST(ROUND(yourColumn,2) as varchar) should do the job.

But why do you want to do this presentational formatting in T-SQL?

jQuery object equality

Since jQuery 1.6, you can use .is. Below is the answer from over a year ago...

var a = $('#foo');
var b = a;


if (a.is(b)) {
    // the same object!
}

If you want to see if two variables are actually the same object, eg:

var a = $('#foo');
var b = a;

...then you can check their unique IDs. Every time you create a new jQuery object it gets an id.

if ($.data(a) == $.data(b)) {
    // the same object!
}

Though, the same could be achieved with a simple a === b, the above might at least show the next developer exactly what you're testing for.

In any case, that's probably not what you're after. If you wanted to check if two different jQuery objects contain the same set of elements, the you could use this:

$.fn.equals = function(compareTo) {
  if (!compareTo || this.length != compareTo.length) {
    return false;
  }
  for (var i = 0; i < this.length; ++i) {
    if (this[i] !== compareTo[i]) {
      return false;
    }
  }
  return true;
};

Source

var a = $('p');
var b = $('p');
if (a.equals(b)) {
    // same set
}

Combining two sorted lists in Python

If you want to do it in a manner more consistent with learning what goes on in the iteration try this

def merge_arrays(a, b):
    l= []

    while len(a) > 0 and len(b)>0:
        if a[0] < b[0]: l.append(a.pop(0))    
        else:l.append(b.pop(0))

    l.extend(a+b)
    print( l )

Difference in months between two dates

Here is my contribution to get difference in Months that I've found to be accurate:

namespace System
{
     public static class DateTimeExtensions
     {
         public static Int32 DiffMonths( this DateTime start, DateTime end )
         {
             Int32 months = 0;
             DateTime tmp = start;

             while ( tmp < end )
             {
                 months++;
                 tmp = tmp.AddMonths( 1 );
             }

             return months;
        }
    }
}

Usage:

Int32 months = DateTime.Now.DiffMonths( DateTime.Now.AddYears( 5 ) );

You can create another method called DiffYears and apply exactly the same logic as above and AddYears instead of AddMonths in the while loop.

Execute Stored Procedure from a Function

EDIT: I haven't tried this, so I can't vouch for it! And you already know you shouldn't be doing this, so please don't do it. BUT...

Try looking here: http://sqlblog.com/blogs/denis_gobo/archive/2008/05/08/6703.aspx

The key bit is this bit which I have attempted to tweak for your purposes:

DECLARE @SQL varchar(500)

SELECT @SQL = 'osql -S' +@@servername +' -E -q "exec dbName..sprocName "'

EXEC master..xp_cmdshell @SQL

How do I return the response from an asynchronous call?

Using ES2017 you should have this as the function declaration

async function foo() {
    var response = await $.ajax({url: '...'})
    return response;
}

And executing it like this.

(async function() {
    try {
        var result = await foo()
        console.log(result)
    } catch (e) {}
})()

Or the Promise syntax

foo().then(response => {
    console.log(response)

}).catch(error => {
    console.log(error)

})

Set the default value in dropdownlist using jQuery

$('#userZipFiles option').prop('selected', function() {
        return this.defaultSelected;
    });     

How do I vertically align text in a div?

This is the cleanest solution I have found (Internet Explorer 9+) and adds a fix for the "off by .5 pixel" issue by using transform-style that other answers had omitted.

.parent-element {
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

.element {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

Source: Vertical align anything with just 3 lines of CSS

Maintaining the final state at end of a CSS3 animation

Try adding animation-fill-mode: forwards;. For example like this:

-webkit-animation: bubble 1.0s forwards; /* for less modern browsers */
        animation: bubble 1.0s forwards;

Top 1 with a left join

Because the TOP 1 from the ordered sub-query does not have profile_id = 'u162231993' Remove where u.id = 'u162231993' and see results then.

Run the sub-query separately to understand what's going on.

How can I show the table structure in SQL Server query?

Try this query:

DECLARE @table_name SYSNAME
SELECT @table_name = 'dbo.test_table'

DECLARE 
      @object_name SYSNAME
    , @object_id INT

SELECT 
      @object_name = '[' + s.name + '].[' + o.name + ']'
    , @object_id = o.[object_id]
FROM sys.objects o WITH (NOWAIT)
JOIN sys.schemas s WITH (NOWAIT) ON o.[schema_id] = s.[schema_id]
WHERE s.name + '.' + o.name = @table_name
    AND o.[type] = 'U'
    AND o.is_ms_shipped = 0

DECLARE @SQL NVARCHAR(MAX) = ''

;WITH index_column AS 
(
    SELECT 
          ic.[object_id]
        , ic.index_id
        , ic.is_descending_key
        , ic.is_included_column
        , c.name
    FROM sys.index_columns ic WITH (NOWAIT)
    JOIN sys.columns c WITH (NOWAIT) ON ic.[object_id] = c.[object_id] AND ic.column_id = c.column_id
    WHERE ic.[object_id] = @object_id
)
SELECT @SQL = 'CREATE TABLE ' + @object_name + CHAR(13) + '(' + CHAR(13) + STUFF((
    SELECT CHAR(9) + ', [' + c.name + '] ' + 
        CASE WHEN c.is_computed = 1
            THEN 'AS ' + cc.[definition] 
            ELSE UPPER(tp.name) + 
                CASE WHEN tp.name IN ('varchar', 'char', 'varbinary', 'binary', 'text')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('nvarchar', 'nchar', 'ntext')
                       THEN '(' + CASE WHEN c.max_length = -1 THEN 'MAX' ELSE CAST(c.max_length / 2 AS VARCHAR(5)) END + ')'
                     WHEN tp.name IN ('datetime2', 'time2', 'datetimeoffset') 
                       THEN '(' + CAST(c.scale AS VARCHAR(5)) + ')'
                     WHEN tp.name = 'decimal' 
                       THEN '(' + CAST(c.[precision] AS VARCHAR(5)) + ',' + CAST(c.scale AS VARCHAR(5)) + ')'
                    ELSE ''
                END +
                CASE WHEN c.collation_name IS NOT NULL THEN ' COLLATE ' + c.collation_name ELSE '' END +
                CASE WHEN c.is_nullable = 1 THEN ' NULL' ELSE ' NOT NULL' END +
                CASE WHEN dc.[definition] IS NOT NULL THEN ' DEFAULT' + dc.[definition] ELSE '' END + 
                CASE WHEN ic.is_identity = 1 THEN ' IDENTITY(' + CAST(ISNULL(ic.seed_value, '0') AS CHAR(1)) + ',' + CAST(ISNULL(ic.increment_value, '1') AS CHAR(1)) + ')' ELSE '' END 
        END + CHAR(13)
    FROM sys.columns c WITH (NOWAIT)
    JOIN sys.types tp WITH (NOWAIT) ON c.user_type_id = tp.user_type_id
    LEFT JOIN sys.computed_columns cc WITH (NOWAIT) ON c.[object_id] = cc.[object_id] AND c.column_id = cc.column_id
    LEFT JOIN sys.default_constraints dc WITH (NOWAIT) ON c.default_object_id != 0 AND c.[object_id] = dc.parent_object_id AND c.column_id = dc.parent_column_id
    LEFT JOIN sys.identity_columns ic WITH (NOWAIT) ON c.is_identity = 1 AND c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
    WHERE c.[object_id] = @object_id
    ORDER BY c.column_id
    FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, CHAR(9) + ' ')
    + ISNULL((SELECT CHAR(9) + ', CONSTRAINT [' + k.name + '] PRIMARY KEY (' + 
                    (SELECT STUFF((
                         SELECT ', [' + c.name + '] ' + CASE WHEN ic.is_descending_key = 1 THEN 'DESC' ELSE 'ASC' END
                         FROM sys.index_columns ic WITH (NOWAIT)
                         JOIN sys.columns c WITH (NOWAIT) ON c.[object_id] = ic.[object_id] AND c.column_id = ic.column_id
                         WHERE ic.is_included_column = 0
                             AND ic.[object_id] = k.parent_object_id 
                             AND ic.index_id = k.unique_index_id     
                         FOR XML PATH(N''), TYPE).value('.', 'NVARCHAR(MAX)'), 1, 2, ''))
            + ')' + CHAR(13)
            FROM sys.key_constraints k WITH (NOWAIT)
            WHERE k.parent_object_id = @object_id 
                AND k.[type] = 'PK'), '') + ')'  + CHAR(13)

PRINT @SQL

Output:

CREATE TABLE [dbo].[test_table]
(
      [WorkOutID] BIGINT NOT NULL IDENTITY(1,1)
    , [DateOut] DATETIME NOT NULL
    , [EmployeeID] INT NOT NULL
    , [IsMainWorkPlace] BIT NOT NULL DEFAULT((1))
    , [WorkPlaceUID] UNIQUEIDENTIFIER NULL
    , [WorkShiftCD] NVARCHAR(10) COLLATE Cyrillic_General_CI_AS NULL
    , [CategoryID] INT NULL
    , CONSTRAINT [PK_WorkOut] PRIMARY KEY ([WorkOutID] ASC)
)

Also read this:

http://www.c-sharpcorner.com/UploadFile/67b45a/how-to-generate-a-create-table-script-for-an-existing-table/

Python threading.timer - repeat function every 'n' seconds

I have implemented a class that works as a timer.

I leave the link here in case anyone needs it: https://github.com/ivanhalencp/python/tree/master/xTimer

Git clone particular version of remote repository

You can solve it like this:

git reset --hard sha

where sha e.g.: 85a108ec5d8443626c690a84bc7901195d19c446

You can get the desired sha with the command:

git log

How do I copy to the clipboard in JavaScript?

It seems I misread the question, but for reference, you can extract a range of the DOM (not to the clipboard; compatible with all modern browsers), and combine it with the oncopy, onpaste, and onbeforepaste events to get the clipboard behaviour. Here's the code to achieve this:

function clipBoard(sCommand) {
  var oRange = contentDocument.createRange();
  oRange.setStart(startNode, startOffset);
  oRange.setEnd(endNode, endOffset);

  /* This is where the actual selection happens.
     in the above, startNode and endNode are
     DOM nodes defining the beginning and
     end of the "selection" respectively.

     startOffset and endOffset are constants
     that are defined as follows:

         END_TO_END: 2
         END_TO_START: 3
         NODE_AFTER: 1
         NODE_BEFORE: 0
         NODE_BEFORE_AND_AFTER: 2
         NODE_INSIDE: 3
         START_TO_END: 1
         START_TO_START: 0

     And it would be used like oRange.START_TO_END
  */

  switch(sCommand) {

    case "cut":
      this.oFragment = oRange.extractContents();
      oRange.collapse();
      break;

    case "copy":
      this.oFragment = oRange.cloneContents();
      break;

    case "paste":
      oRange.deleteContents();
      var cloneFragment = this.oFragment.cloneNode(true)
      oRange.insertNode(cloneFragment);
      oRange.collapse();
      break;
  }
}

How to normalize a signal to zero mean and unit variance?

You can determine the mean of the signal, and just subtract that value from all the entries. That will give you a zero mean result.

To get unit variance, determine the standard deviation of the signal, and divide all entries by that value.

How can I remove space (margin) above HTML header?

Try:

h1 {
    margin-top: 0;
}

You're seeing the effects of margin collapsing.

Create new project on Android, Error: Studio Unknown host 'services.gradle.org'

I have same problem after update android studio to 1.5, and i fix it by update the gradle location,

  1. Go to File->Setting->Build, Execution, Deployment->Build Tools->Gradle
  2. Under Project level Setting find gradle directory

Hope this method works for you,

How do I write the 'cd' command in a makefile?

To change dir

foo: 
    $(MAKE) -C mydir

multi:
    $(MAKE) -C / -C my-custom-dir   ## Equivalent to /my-custom-dir

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

Since GDB 7.5 you can use these native Convenience Functions:

$_memeq(buf1, buf2, length)
$_regex(str, regex)
$_streq(str1, str2)
$_strlen(str)

Seems quite less problematic than having to execute a "foreign" strcmp() on the process' stack each time the breakpoint is hit. This is especially true for debugging multithreaded processes.

Note your GDB needs to be compiled with Python support, which is not an issue with current linux distros. To be sure, you can check it by running show configuration inside GDB and searching for --with-python. This little oneliner does the trick, too:

$ gdb -n -quiet -batch -ex 'show configuration' | grep 'with-python'
             --with-python=/usr (relocatable)

For your demo case, the usage would be

break <where> if $_streq(x, "hello")

or, if your breakpoint already exists and you just want to add the condition to it

condition <breakpoint number> $_streq(x, "hello")

$_streq only matches the whole string, so if you want something more cunning you should use $_regex, which supports the Python regular expression syntax.

python NameError: global name '__file__' is not defined

I had the same problem with PyInstaller and Py2exe so I came across the resolution on the FAQ from cx-freeze.

When using your script from the console or as an application, the functions hereunder will deliver you the "execution path", not the "actual file path":

print(os.getcwd())
print(sys.argv[0])
print(os.path.dirname(os.path.realpath('__file__')))

Source:
http://cx-freeze.readthedocs.org/en/latest/faq.html

Your old line (initial question):

def read(*rnames):
return open(os.path.join(os.path.dirname(__file__), *rnames)).read()

Substitute your line of code with the following snippet.

def find_data_file(filename):
    if getattr(sys, 'frozen', False):
        # The application is frozen
        datadir = os.path.dirname(sys.executable)
    else:
        # The application is not frozen
        # Change this bit to match where you store your data files:
        datadir = os.path.dirname(__file__)

    return os.path.join(datadir, filename)

With the above code you could add your application to the path of your os, you could execute it anywhere without the problem that your app is unable to find it's data/configuration files.

Tested with python:

  • 3.3.4
  • 2.7.13

String to LocalDate

As you use Joda Time, you should use DateTimeFormatter:

final DateTimeFormatter dtf = DateTimeFormatter.ofPattern("yyyy-MMM-dd");
final LocalDate dt = dtf.parseLocalDate(yourinput);

If using Java 8 or later, then refer to hertzi's answer

What's the key difference between HTML 4 and HTML 5?

From Wikipedia:

  • New parsing rules oriented towards flexible parsing and compatibility
  • New elements – section, video, progress, nav, meter, time, aside, canvas
  • New input attributes – dates and times, email, url
  • New attributes – ping, charset, async
  • Global attributes (that can be applied for every element) – id, tabindex, repeat
  • Deprecated elements dropped – center, font, strike

How to get the second column from command output?

Or use sed & regex.

<some_command> | sed 's/^.* \(".*"$\)/\1/'

Is ini_set('max_execution_time', 0) a bad idea?

At the risk of irritating you;

You're asking the wrong question. You don't need a reason NOT to deviate from the defaults, but the other way around. You need a reason to do so. Timeouts are absolutely essential when running a web server and to disable that setting without a reason is inherently contrary to good practice, even if it's running on a web server that happens to have a timeout directive of its own.

Now, as for the real answer; probably it doesn't matter at all in this particular case, but it's bad practice to go by the setting of a separate system. What if the script is later run on a different server with a different timeout? If you can safely say that it will never happen, fine, but good practice is largely about accounting for seemingly unlikely events and not unnecessarily tying together the settings and functionality of completely different systems. The dismissal of such principles is responsible for a lot of pointless incompatibilities in the software world. Almost every time, they are unforeseen.

What if the web server later is set to run some other runtime environment which only inherits the timeout setting from the web server? Let's say for instance that you later need a 15-year-old CGI program written in C++ by someone who moved to a different continent, that has no idea of any timeout except the web server's. That might result in the timeout needing to be changed and because PHP is pointlessly relying on the web server's timeout instead of its own, that may cause problems for the PHP script. Or the other way around, that you need a lesser web server timeout for some reason, but PHP still needs to have it higher.

It's just not a good idea to tie the PHP functionality to the web server because the web server and PHP are responsible for different roles and should be kept as functionally separate as possible. When the PHP side needs more processing time, it should be a setting in PHP simply because it's relevant to PHP, not necessarily everything else on the web server.

In short, it's just unnecessarily conflating the matter when there is no need to.

Last but not least, 'stillstanding' is right; you should at least rather use set_time_limit() than ini_set().

Hope this wasn't too patronizing and irritating. Like I said, probably it's fine under your specific circumstances, but it's good practice to not assume your circumstances to be the One True Circumstance. That's all. :)

Sorting an IList in C#

This question inspired me to write a blog post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/

I think that, ideally, the .NET Framework would include a static sorting method that accepts an IList<T>, but the next best thing is to create your own extension method. It's not too hard to create a couple of methods that will allow you to sort an IList<T> as you would a List<T>. As a bonus you can overload the LINQ OrderBy extension method using the same technique, so that whether you're using List.Sort, IList.Sort, or IEnumerable.OrderBy, you can use the exact same syntax.

public static class SortExtensions
{
    //  Sorts an IList<T> in place.
    public static void Sort<T>(this IList<T> list, Comparison<T> comparison)
    {
        ArrayList.Adapter((IList)list).Sort(new ComparisonComparer<T>(comparison));
    }

    // Sorts in IList<T> in place, when T is IComparable<T>
    public static void Sort<T>(this IList<T> list) where T: IComparable<T>
    {
        Comparison<T> comparison = (l, r) => l.CompareTo(r);
        Sort(list, comparison);

    }

    // Convenience method on IEnumerable<T> to allow passing of a
    // Comparison<T> delegate to the OrderBy method.
    public static IEnumerable<T> OrderBy<T>(this IEnumerable<T> list, Comparison<T> comparison)
    {
        return list.OrderBy(t => t, new ComparisonComparer<T>(comparison));
    }
}

// Wraps a generic Comparison<T> delegate in an IComparer to make it easy
// to use a lambda expression for methods that take an IComparer or IComparer<T>
public class ComparisonComparer<T> : IComparer<T>, IComparer
{
    private readonly Comparison<T> _comparison;

    public ComparisonComparer(Comparison<T> comparison)
    {
        _comparison = comparison;
    }

    public int Compare(T x, T y)
    {
        return _comparison(x, y);
    }

    public int Compare(object o1, object o2)
    {
        return _comparison((T)o1, (T)o2);
    }
}

With these extensions, sort your IList just like you would a List:

IList<string> iList = new []
{
    "Carlton", "Alison", "Bob", "Eric", "David"
};

// Use the custom extensions:

// Sort in-place, by string length
iList.Sort((s1, s2) => s1.Length.CompareTo(s2.Length));

// Or use OrderBy()
IEnumerable<string> ordered = iList.OrderBy((s1, s2) => s1.Length.CompareTo(s2.Length));

There's more info in the post: http://blog.velir.com/index.php/2011/02/17/ilistt-sorting-a-better-way/

Get selected value in dropdown list using JavaScript

In more modern browsers, querySelector allows us to retrieve the selected option in one statement, using the :checked pseudo-class. From the selected option, we can gather whatever information we need:

_x000D_
_x000D_
const opt = document.querySelector('#ddlViewBy option:checked');_x000D_
// opt is now the selected option, so_x000D_
console.log(opt.value, 'is the selected value');_x000D_
console.log(opt.text, "is the selected option's text");
_x000D_
<select id="ddlViewBy">_x000D_
  <option value="1">test1</option>_x000D_
  <option value="2" selected="selected">test2</option>_x000D_
  <option value="3">test3</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Passive Link in Angular 2 - <a href=""> equivalent

In my case deleting href attribute solve problem as long there is a click function assign to a.

Are HTTPS URLs encrypted?

As the other answers have already pointed out, https "URLs" are indeed encrypted. However, your DNS request/response when resolving the domain name is probably not, and of course, if you were using a browser, your URLs might be recorded too.

How can I specify a branch/tag when adding a Git submodule?

The only effect of choosing a branch for a submodule is that, whenever you pass the --remote option in the git submodule update command line, Git will check out in detached HEAD mode (if the default --checkout behavior is selected) the latest commit of that selected remote branch.

You must be particularly careful when using this remote branch tracking feature for Git submodules if you work with shallow clones of submodules. The branch you choose for this purpose in submodule settings IS NOT the one that will be cloned during git submodule update --remote. If you pass also the --depth parameter and you do not instruct Git about which branch you want to clone -- and actually you cannot in the git submodule update command line!! -- , it will implicitly behave like explained in the git-clone(1) documentation for git clone --single-branch when the explicit --branch parameter is missing, and therefore it will clone the primary branch only.

With no surprise, after the clone stage performed by the git submodule update command, it will finally try to check out the latest commit for the remote branch you previously set up for the submodule, and, if this is not the primary one, it is not part of your local shallow clone, and therefore it will fail with

fatal: Needed a single revision

Unable to find current origin/NotThePrimaryBranch revision in submodule path 'mySubmodule'

Adding hours to JavaScript Date object?

If someone is still looking at this issue, the easiest way to do is

var d = new Date();
d = new Date(d.setHours(d.getHours() + 2));

it will add 2 hours in current time. Value of d = Sat Jan 30 2021 23:41:43 GMT+0500 (Pakistan Standard Time) Value of d after adding 2 hours = Sun Jan 31 2021 01:41:43 GMT+0500 (Pakistan Standard Time)

Python SQLite: database is locked

I'm presuming you are actually using sqlite3 even though your code says otherwise. Here are some things to check:

  1. That you don't have a hung process sitting on the file (unix: $ fuser cache.db should say nothing)
  2. There isn't a cache.db-journal file in the directory with cache.db; this would indicate a crashed session that hasn't been cleaned up properly.
  3. Ask the database shell to check itself: $ sqlite3 cache.db "pragma integrity_check;"
  4. Backup the database $ sqlite3 cache.db ".backup cache.db.bak"
  5. Remove cache.db as you probably have nothing in it (if you are just learning) and try your code again
  6. See if the backup works $ sqlite3 cache.db.bak ".schema"

Failing that, read Things That Can Go Wrong and How to Corrupt Your Database Files

Why doesn't TFS get latest get the latest?

just want to add TFS MSBuild does not support special characters on folders i.e. "@"

i had experienced in the past where one of our project folders named as External@Project1

we created a TFS Build definition to run a custom msbuild file then the workspace folder is not getting any contents at the External@Project1 folder during workspace get latest. It seems that tfs get is failing but does not show any error.

after some trial and error and renaming the folder to _Project1. voila we got files on the the folder (_Project1).

Can you style an html radio button to look like a checkbox?

Very simple idea using a table and no Javascript. Am I being too simplistic?

<style type="text/css" media="screen">
#ageBox {display: none;}
</style>

<style type="text/css" media="print">
#ageButton {display: none;}
</style>

<tr><td>Age:</td>

<td id="ageButton">
<input type="radio" name="userAge" value="18-24">18-24
<input type="radio" name="userAge" value="25-34">25-34

<td id="ageBox">
<input type="checkbox">18-24
<input type="checkbox">25-34

</td></tr>

is vs typeof

Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.

is tells you if the object implements ClassA anywhere in its type heirarchy. GetType() tells you about the most-derived type.

Not the same thing.

Change Row background color based on cell value DataTable

Callback for whenever a TR element is created for the table's body.

$('#example').dataTable( {
      "createdRow": function( row, data, dataIndex ) {
        if ( data[4] == "A" ) {
          $(row).addClass( 'important' );
        }
      }
    } );

https://datatables.net/reference/option/createdRow

How to Resize image in Swift?

Swift 4 Solution-

Use this function

func image(with image: UIImage, scaledTo newSize: CGSize) -> UIImage {
    UIGraphicsBeginImageContextWithOptions(newSize, false, 1.0)
    image.draw(in: CGRect(x: 0, y: 0, width: newSize.width, height: newSize.height))
    let newImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    drawingImageView.image = newImage
    return newImage ?? UIImage()
}

Calling a function:-

image(with: predictionImage, scaledTo: CGSize(width: 28.0, height: 28.0)

here 28.0 is the pixel size that you want to set

Does reading an entire file leave the file handle open?

Well, if you have to read file line by line to work with each line, you can use

with open('Path/to/file', 'r') as f:
    s = f.readline()
    while s:
        # do whatever you want to
        s = f.readline()

Or even better way:

with open('Path/to/file') as f:
    for line in f:
        # do whatever you want to

Select data from "show tables" MySQL query

SELECT * FROM INFORMATION_SCHEMA.TABLES

That should be a good start. For more, check INFORMATION_SCHEMA Tables.

How to pass parameters using ui-sref in ui-router to controller

I've created an example to show how to. Updated state definition would be:

  $stateProvider
    .state('home', {
      url: '/:foo?bar',
      views: {
        '': {
          templateUrl: 'tpl.home.html',
          controller: 'MainRootCtrl'

        },
        ...
      }

And this would be the controller:

.controller('MainRootCtrl', function($scope, $state, $stateParams) {
    //..
    var foo = $stateParams.foo; //getting fooVal
    var bar = $stateParams.bar; //getting barVal
    //..
    $scope.state = $state.current
    $scope.params = $stateParams; 
})

What we can see is that the state home now has url defined as:

url: '/:foo?bar',

which means, that the params in url are expected as

/fooVal?bar=barValue

These two links will correctly pass arguments into the controller:

<a ui-sref="home({foo: 'fooVal1', bar: 'barVal1'})">
<a ui-sref="home({foo: 'fooVal2', bar: 'barVal2'})">

Also, the controller does consume $stateParams instead of $stateParam.

Link to doc:

You can check it here

params : {}

There is also new, more granular setting params : {}. As we've already seen, we can declare parameters as part of url. But with params : {} configuration - we can extend this definition or even introduce paramters which are not part of the url:

.state('other', {
    url: '/other/:foo?bar',
    params: { 
        // here we define default value for foo
        // we also set squash to false, to force injecting
        // even the default value into url
        foo: {
          value: 'defaultValue',
          squash: false,
        },
        // this parameter is now array
        // we can pass more items, and expect them as []
        bar : { 
          array : true,
        },
        // this param is not part of url
        // it could be passed with $state.go or ui-sref 
        hiddenParam: 'YES',
      },
    ...

Settings available for params are described in the documentation of the $stateProvider

Below is just an extract

  • value - {object|function=}: specifies the default value for this parameter. This implicitly sets this parameter as optional...
  • array - {boolean=}: (default: false) If true, the param value will be treated as an array of values.
  • squash - {bool|string=}: squash configures how a default parameter value is represented in the URL when the current parameter value is the same as the default value.

We can call these params this way:

// hidden param cannot be passed via url
<a href="#/other/fooVal?bar=1&amp;bar=2">
// default foo is skipped
<a ui-sref="other({bar: [4,5]})">

Check it in action here

Pass a reference to DOM object with ng-click

The angular way is shown in the angular docs :)

https://docs.angularjs.org/api/ng/directive/ngReadonly

Here is the example they use:

<body>
    Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
    <input type="text" ng-readonly="checked" value="I'm Angular"/>
</body>

Basically the angular way is to create a model object that will hold whether or not the input should be readonly and then set that model object accordingly. The beauty of angular is that most of the time you don't need to do any dom manipulation. You just have angular render the view they way your model is set (let angular do the dom manipulation for you and keep your code clean).

So basically in your case you would want to do something like below or check out this working example.

<button ng-click="isInput1ReadOnly = !isInput1ReadOnly">Click Me</button>
<input type="text" ng-readonly="isInput1ReadOnly" value="Angular Rules!"/>

What’s the best RESTful method to return total number of items in an object?

Interesting discussion regarding Designing REST API for returning count of multiple objects: https://groups.google.com/g/api-craft/c/qbI2QRrpFew/m/h30DYnrqEwAJ?pli=1

As an API consumer, I would expect each count value to be represented either as a subresource to the countable resource (i.e. GET /tasks/count for a count of tasks), or as a field in a bigger aggregation of metadata related to the concerned resource (i.e. GET /tasks/metadata). By scoping related endpoints under the same parent resource (i.e. /tasks), the API becomes intuitive, and the purpose of an endpoint can (usually) be inferred from its path and HTTP method.

Additional thoughts:

  1. If each individual count is only useful in combination with other counts (for a statistics dashboard, for example), you could possibly expose a single endpoint which aggregates and returns all counts at once.
  2. If you have an existing endpoint for listing all resources (i.e. GET /tasks for listing all tasks), the count could be included in the response as metadata, either as HTTP headers or in the response body. Doing this will incur unnecessary load on the API, which might be negligible depending on your use case.

Android YouTube app Play Video Intent

/**
 * Intent to open a YouTube Video
 * 
 * @param pm
 *            The {@link PackageManager}.
 * @param url
 *            The URL or YouTube video ID.
 * @return the intent to open the YouTube app or Web Browser to play the video
 */
public static Intent newYouTubeIntent(PackageManager pm, String url) {
    Intent intent;
    if (url.length() == 11) {
        // youtube video id
        intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + url));
    } else {
        // url to video
        intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
    }
    try {
        if (pm.getPackageInfo("com.google.android.youtube", 0) != null) {
            intent.setPackage("com.google.android.youtube");
        }
    } catch (NameNotFoundException e) {
    }
    return intent;
}

SQL ORDER BY multiple columns

Yes, the sorting is different.

Items in the ORDER BY list are applied in order.
Later items only order peers left from the preceding step.

Why don't you just try?

How do I vertically center an H1 in a div?

HTML

<div id='sample'>
<span class='vertical'>Test Message</span>
</div>

CSS

    #sample 
    {
        height:100px;
         width:100%;
        background-color:#003366;
        display:table;
        text-align: center;

    }
    .vertical 
    {
           color:white;
         display:table-cell;
        vertical-align:middle;
}

Fiddle : Demo

How do you UDP multicast in Python?

This example doesn't work for me, for an obscure reason.

Not obscure, it's simple routing.

On OpenBSD

route add -inet 224.0.0.0/4 224.0.0.1

You can set the route to a dev on Linux

route add -net 224.0.0.0 netmask 240.0.0.0 dev wlp2s0

force all multicast traffic to one interface on Linux

   ifconfig wlp2s0 allmulti

tcpdump is super simple

tcpdump -n multicast

In your code you have:

while True:
  # For Python 3, change next line to "print(sock.recv(10240))"

Why 10240?

multicast packet size should be 1316 bytes

How to change RGB color to HSV?

The EasyRGB has many color space conversions. Here is the code for the RGB->HSV conversion.

In JavaScript, why is "0" equal to false, but when tested by 'if' it is not false by itself?

The "if" expression tests for truthiness, while the double-equal tests for type-independent equivalency. A string is always truthy, as others here have pointed out. If the double-equal were testing both of its operands for truthiness and then comparing the results, then you'd get the outcome you were intuitively assuming, i.e. ("0" == true) === true. As Doug Crockford says in his excellent JavaScript: the Good Parts, "the rules by which [== coerces the types of its operands] are complicated and unmemorable.... The lack of transitivity is alarming." It suffices to say that one of the operands is type-coerced to match the other, and that "0" ends up being interpreted as a numeric zero, which is in turn equivalent to false when coerced to boolean (or false is equivalent to zero when coerced to a number).

How can I declare optional function parameters in JavaScript?

With ES6: This is now part of the language:

function myFunc(a, b = 0) {
   // function body
}

Please keep in mind that ES6 checks the values against undefined and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).


With ES5:

function myFunc(a,b) {
  b = b || 0;

  // b will be set either to b or to 0.
}

This works as long as all values you explicitly pass in are truthy. Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''

It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.

How to set upload_max_filesize in .htaccess?

If your web server is running php5, I believe you must use php5_value. This resolved the same error I received when using php_value.

Error message "No exports were found that match the constraint contract name"

If you have VS 2013, you have to go to: %LOCALAPPDATA%\Microsoft\VisualStudio\12.0 then rename the ComponentModelCache folder.

Visual Studio C# IntelliSense not automatically displaying

This may be due to the solution configuration changed to Release Mode instead of debug. Right click on solution -> Properties -> Configuration Properties -> Set Configuration To Debug if it is in Release.

Convert Java Object to JsonNode in Jackson

As of Jackson 1.6, you can use:

JsonNode node = mapper.valueToTree(map);

or

JsonNode node = mapper.convertValue(object, JsonNode.class);

Source: is there a way to serialize pojo's directly to treemodel?

JSON, REST, SOAP, WSDL, and SOA: How do they all link together

WSDL: Stands for Web Service Description Language

In SOAP(simple object access protocol), when you use web service and add a web service to your project, your client application(s) doesn't know about web service Functions. Nowadays it's somehow old-fashion and for each kind of different client you have to implement different WSDL files. For example you cannot use same file for .Net and php client. The WSDL file has some descriptions about web service functions. The type of this file is XML. SOAP is an alternative for REST.

REST: Stands for Representational State Transfer

It is another kind of API service, it is really easy to use for clients. They do not need to have special file extension like WSDL files. The CRUD operation can be implemented by different HTTP Verbs(GET for Reading, POST for Creation, PUT or PATCH for Updating and DELETE for Deleting the desired document) , They are based on HTTP protocol and most of times the response is in JSON or XML format. On the other hand the client application have to exactly call the related HTTP Verb via exact parameters names and types. Due to not having special file for definition, like WSDL, it is a manually job using the endpoint. But it is not a big deal because now we have a lot of plugins for different IDEs to generating the client-side implementation.

SOA: Stands for Service Oriented Architecture

Includes all of the programming with web services concepts and architecture. Imagine that you want to implement a large-scale application. One practice can be having some different services, called micro-services and the whole application mechanism would be calling needed web service at the right time. Both REST and SOAP web services are kind of SOA.

JSON: Stands for javascript Object Notation

when you serialize an object for javascript the type of object format is JSON. imagine that you have the human class :

class Human{
 string Name;
 string Family;
 int Age;
}

and you have some instances from this class :

Human h1 = new Human(){
  Name='Saman',
  Family='Gholami',
  Age=26
}

when you serialize the h1 object to JSON the result is :

  [h1:{Name:'saman',Family:'Gholami',Age:'26'}, ...]

javascript can evaluate this format by eval() function and make an associative array from this JSON string. This one is different concept in comparison to other concepts I described formerly.

Warning:No JDK specified for module 'Myproject'.when run my project in Android studio

My issue was solved by simply refreshing the modules View > Maven Projects. There is refresh icon which refreshes your entire project(s)

How I got this error : I imported a project (Let's call this A which is main project) first and added the remaining projects (B,C,D etc) as modules to this one as I needed all my projects to be shown in one package folder. I deleted the old (A) Project and cloned it again from repo. The IntelliJ reloaded the (A) project but when I try to run, the project wasn't compiling saying "Warning:No JDK specified for module 'B'".

Connect over ssh using a .pem file

For AWS if the user is ubuntu use the following to connect to remote server.

chmod 400 mykey.pem

ssh -i mykey.pem ubuntu@your-ip

What is the easiest way to initialize a std::vector with hardcoded elements?

A more recent duplicate question has this answer by Viktor Sehr. For me, it is compact, visually appealing (looks like you are 'shoving' the values in), doesn't require c++11 or a third party module, and avoids using an extra (written) variable. Below is how I am using it with a few changes. I may switch to extending the function of vector and/or va_arg in the future intead.


// Based on answer by "Viktor Sehr" on Stack Overflow
// https://stackoverflow.com/a/8907356
//
template <typename T>
class mkvec {
public:
    typedef mkvec<T> my_type;
    my_type& operator<< (const T& val) {
        data_.push_back(val);
        return *this;
    }
    my_type& operator<< (const std::vector<T>& inVector) {
        this->data_.reserve(this->data_.size() + inVector.size());
        this->data_.insert(this->data_.end(), inVector.begin(), inVector.end());
        return *this;
    }
    operator std::vector<T>() const {
        return data_;
    }
private:
    std::vector<T> data_;
};

std::vector<int32_t>    vec1;
std::vector<int32_t>    vec2;

vec1 = mkvec<int32_t>() << 5 << 8 << 19 << 79;  
// vec1 = (5,8,19,79)
vec2 = mkvec<int32_t>() << 1 << 2 << 3 << vec1 << 10 << 11 << 12;  
// vec2 = (1,2,3,5,8,19,79,10,11,12)

History or log of commands executed in Git

A log of your commands may be available in your shell history.

history

If seeing the list of executed commands fly by isn't for you, export the list into a file.

history > path/to/file

You can restrict the exported dump to only show commands with "git" in them by piping it with grep

history | grep "git " > path/to/file

The history may contain lines formatted as such

518  git status -s
519  git commit -am "injects sriracha to all toppings, as required"

Using the number you can re-execute the command with an exclamation mark

$ !518
git status -s

Difference between wait and sleep

Wait() and sleep() Differences?

Thread.sleep() Once its work completed then only its release the lock to everyone. until its never release the lock to anyone.

  Sleep() take the key, its never release the key to anyone, when its work completed then only its release then only take the key waiting stage threads.

Object.wait() When its going to waiting stage, its will be release the key and its waiting for some of the seconds based on the parameter.

For Example:

you are take the coffee in yours right hand, you can take another anyone of the same hand, when will your put down then only take another object same type here. also. this is sleep() you sleep time you didn't any work, you are doing only sleeping.. same here also.

wait(). when you are put down and take another one mean while you are waiting , that's wait

you are play movie or anything in yours system same as player you can't play more than one at a time right, thats its here, when you close and choose another anyone movie or song mean while is called wait

Maven: best way of linking custom external JAR to my project?

Don't use systemPath. Contrary to what people have said here, you can put an external jar in a folder under your checked-out project directory and haven Maven find it like other dependencies. Here are two crucial steps:

  1. Use "mvn install:install-file" with -DlocalRepositoryPath.
  2. Configure a repository to point to that path in your POM.

It is fairly straightforward and you can find a step-by-step example here: http://randomizedsort.blogspot.com/2011/10/configuring-maven-to-use-local-library.html