Programs & Examples On #Tiddlywiki

TiddlyWiki is a complete wiki application in a single HTML file, which includes user content. TiddlyWiki favors portability over collaborative editing (but implementations vary).

Difference between IISRESET and IIS Stop-Start command

I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:

Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:

  • NET STOP iisadmin /y
  • NET START w3svc

There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.

KB:https://support.microsoft.com/en-ca/help/969864/using-iisreset-exe-to-restart-internet-information-services-iis-result

Selecting rows where remainder (modulo) is 1 after division by 2?

select * from table where value % 2 = 1 works fine in mysql.

Paging UICollectionView by cells, not screen

This is a straight way to do this.

The case is simple, but finally quite common ( typical thumbnails scroller with fixed cell size and fixed gap between cells )

var itemCellSize: CGSize = <your cell size>
var itemCellsGap: CGFloat = <gap in between>

override func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
    let pageWidth = (itemCellSize.width + itemCellsGap)
    let itemIndex = (targetContentOffset.pointee.x) / pageWidth
    targetContentOffset.pointee.x = round(itemIndex) * pageWidth - (itemCellsGap / 2)
}

// CollectionViewFlowLayoutDelegate

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    return itemCellSize
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
    return itemCellsGap
}

Note that there is no reason to call a scrollToOffset or dive into layouts. The native scrolling behaviour already does everything.

Cheers All :)

react change class name on state change

Below is a fully functional example of what I believe you're trying to do (with a functional snippet).

Explanation

Based on your question, you seem to be modifying 1 property in state for all of your elements. That's why when you click on one, all of them are being changed.

In particular, notice that the state tracks an index of which element is active. When MyClickable is clicked, it tells the Container its index, Container updates the state, and subsequently the isActive property of the appropriate MyClickables.

Example

_x000D_
_x000D_
class Container extends React.Component {_x000D_
  state = {_x000D_
    activeIndex: null_x000D_
  }_x000D_
_x000D_
  handleClick = (index) => this.setState({ activeIndex: index })_x000D_
_x000D_
  render() {_x000D_
    return <div>_x000D_
      <MyClickable name="a" index={0} isActive={ this.state.activeIndex===0 } onClick={ this.handleClick } />_x000D_
      <MyClickable name="b" index={1} isActive={ this.state.activeIndex===1 } onClick={ this.handleClick }/>_x000D_
      <MyClickable name="c" index={2} isActive={ this.state.activeIndex===2 } onClick={ this.handleClick }/>_x000D_
    </div>_x000D_
  }_x000D_
}_x000D_
_x000D_
class MyClickable extends React.Component {_x000D_
  handleClick = () => this.props.onClick(this.props.index)_x000D_
  _x000D_
  render() {_x000D_
    return <button_x000D_
      type='button'_x000D_
      className={_x000D_
        this.props.isActive ? 'active' : 'album'_x000D_
      }_x000D_
      onClick={ this.handleClick }_x000D_
    >_x000D_
      <span>{ this.props.name }</span>_x000D_
    </button>_x000D_
  }_x000D_
}_x000D_
_x000D_
ReactDOM.render(<Container />, document.getElementById('app'))
_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}_x000D_
_x000D_
.album>span:after {_x000D_
  content: ' (an album)';_x000D_
}_x000D_
_x000D_
.active {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
.active>span:after {_x000D_
  content: ' ACTIVE';_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.6.1/react-dom.min.js"></script>_x000D_
<div id="app"></div>
_x000D_
_x000D_
_x000D_

Update: "Loops"

In response to a comment about a "loop" version, I believe the question is about rendering an array of MyClickable elements. We won't use a loop, but map, which is typical in React + JSX. The following should give you the same result as above, but it works with an array of elements.

// New render method for `Container`
render() {
  const clickables = [
    { name: "a" },
    { name: "b" },
    { name: "c" },
  ]

  return <div>
      { clickables.map(function(clickable, i) {
          return <MyClickable key={ clickable.name }
            name={ clickable.name }
            index={ i }
            isActive={ this.state.activeIndex === i }
            onClick={ this.handleClick }
          />
        } )
      }
  </div>
}

String comparison technique used by Python

Take a look also at How do I sort unicode strings alphabetically in Python? where the discussion is about sorting rules given by the Unicode Collation Algorithm (http://www.unicode.org/reports/tr10/).

To reply to the comment

What? How else can ordering be defined other than left-to-right?

by S.Lott, there is a famous counter-example when sorting French language. It involves accents: indeed, one could say that, in French, letters are sorted left-to-right and accents right-to-left. Here is the counter-example: we have e < é and o < ô, so you would expect the words cote, coté, côte, côté to be sorted as cote < coté < côte < côté. Well, this is not what happens, in fact you have: cote < côte < coté < côté, i.e., if we remove "c" and "t", we get oe < ôe < oé < ôé, which is exactly right-to-left ordering.

And a last remark: you shouldn't be talking about left-to-right and right-to-left sorting but rather about forward and backward sorting.

Indeed there are languages written from right to left and if you think Arabic and Hebrew are sorted right-to-left you may be right from a graphical point of view, but you are wrong on the logical level!

Indeed, Unicode considers character strings encoded in logical order, and writing direction is a phenomenon occurring on the glyph level. In other words, even if in the word ???? the letter shin appears on the right of the lamed, logically it occurs before it. To sort this word one will first consider the shin, then the lamed, then the vav, then the mem, and this is forward ordering (although Hebrew is written right-to-left), while French accents are sorted backwards (although French is written left-to-right).

Error message Strict standards: Non-static method should not be called statically in php

If scope resolution :: had to be used outside the class then the respective function or variable should be declared as static

class Foo { 
        //Static variable 
        public static $static_var = 'static variable'; 
        //Static function 
        static function staticValue() { return 'static function'; } 

        //function 
        function Value() { return 'Object'; } 
} 



 echo Foo::$static_var . "<br/>"; echo Foo::staticValue(). "<br/>"; $foo = new Foo(); echo $foo->Value();

<div style display="none" > inside a table not working

Semantically what you are trying is invalid html, table element cannot have a div element as a direct child. What you can do is, get your div element inside a td element and than try to hide it

Passing data from controller to view in Laravel

Try with this code:

return View::make('user/regprofile', array
    (
        'students' => $students
    )
);

Or if you want to pass more variables into view:

return View::make('user/regprofile', array
    (
        'students'    =>  $students,
        'variable_1'  =>  $variable_1,
        'variable_2'  =>  $variable_2
    )
);

What is the difference between dynamic and static polymorphism in Java?

In simple terms :

Static polymorphism : Same method name is overloaded with different type or number of parameters in same class (different signature). Targeted method call is resolved at compile time.

Dynamic polymorphism: Same method is overridden with same signature in different classes. Type of object on which method is being invoked is not known at compile time but will be decided at run time.

Generally overloading won't be considered as polymorphism.

From java tutorial page :

Subclasses of a class can define their own unique behaviors and yet share some of the same functionality of the parent class

How to disable back swipe gesture in UINavigationController on iOS 7

it works for me in ios 10 and later :

- (void)viewWillAppear:(BOOL)animated {
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }

}

it doesnt work on viewDidLoad() method.

Which Ruby version am I really running?

If you have access to a console in the context you are investigating, you can determine which version you are running by printing the value of the global constant RUBY_VERSION.

Display PDF file inside my android application

This is the perfect solution that worked for me without any 3rd party library.

Rendering a PDF Document in Android Activity/Fragment (Using PdfRenderer)

Finding the Eclipse Version Number

Here is a working code snippet that will print out the full version of currently running Eclipse (or any RCP-based application).

String product = System.getProperty("eclipse.product");
IExtensionRegistry registry = Platform.getExtensionRegistry();
IExtensionPoint point = registry.getExtensionPoint("org.eclipse.core.runtime.products");
Logger log = LoggerFactory.getLogger(getClass());
if (point != null) {
  IExtension[] extensions = point.getExtensions();
  for (IExtension ext : extensions) {
    if (product.equals(ext.getUniqueIdentifier())) {
      IContributor contributor = ext.getContributor();
      if (contributor != null) {
        Bundle bundle = Platform.getBundle(contributor.getName());
        if (bundle != null) {
          System.out.println("bundle version: " + bundle.getVersion());
        }
      }
    }
  }
}

It looks up the currently running "product" extension and takes the version of contributing plugin.

On Eclipse Luna 4.4.0, it gives the result of 4.4.0.20140612-0500 which is correct.

What is Python used for?

Python is a dynamic, strongly typed, object oriented, multipurpose programming language, designed to be quick (to learn, to use, and to understand), and to enforce a clean and uniform syntax.

  1. Python is dynamically typed: it means that you don't declare a type (e.g. 'integer') for a variable name, and then assign something of that type (and only that type). Instead, you have variable names, and you bind them to entities whose type stays with the entity itself. a = 5 makes the variable name a to refer to the integer 5. Later, a = "hello" makes the variable name a to refer to a string containing "hello". Static typed languages would have you declare int a and then a = 5, but assigning a = "hello" would have been a compile time error. On one hand, this makes everything more unpredictable (you don't know what a refers to). On the other hand, it makes very easy to achieve some results a static typed languages makes very difficult.
  2. Python is strongly typed. It means that if a = "5" (the string whose value is '5') will remain a string, and never coerced to a number if the context requires so. Every type conversion in python must be done explicitly. This is different from, for example, Perl or Javascript, where you have weak typing, and can write things like "hello" + 5 to get "hello5".
  3. Python is object oriented, with class-based inheritance. Everything is an object (including classes, functions, modules, etc), in the sense that they can be passed around as arguments, have methods and attributes, and so on.
  4. Python is multipurpose: it is not specialised to a specific target of users (like R for statistics, or PHP for web programming). It is extended through modules and libraries, that hook very easily into the C programming language.
  5. Python enforces correct indentation of the code by making the indentation part of the syntax. There are no control braces in Python. Blocks of code are identified by the level of indentation. Although a big turn off for many programmers not used to this, it is precious as it gives a very uniform style and results in code that is visually pleasant to read.
  6. The code is compiled into byte code and then executed in a virtual machine. This means that precompiled code is portable between platforms.

Python can be used for any programming task, from GUI programming to web programming with everything else in between. It's quite efficient, as much of its activity is done at the C level. Python is just a layer on top of C. There are libraries for everything you can think of: game programming and openGL, GUI interfaces, web frameworks, semantic web, scientific computing...

Get underlined text with Markdown

In Jupyter Notebooks you can use Markdown in the following way for underlined text. This is similar to HTML5: (<u> and </u>).

<u>Underlined Words Here</u>

Create list or arrays in Windows Batch

Array type does not exist

There is no 'array' type in batch files, which is both an upside and a downside at times, but there are workarounds.

Here's a link that offers a few suggestions for creating a system for yourself similar to an array in a batch: http://hypftier.de/en/batch-tricks-arrays.

  • As for echoing to a file echo variable >> filepath works for echoing the contents of a variable to a file,
  • and echo. (the period is not a typo) works for echoing a newline character.

I think that these two together should work to accomplish what you need.

Further reading

How to sum columns in a dataTable?

There is also a way to do this without loops using the DataTable.Compute Method. The following example comes from that page. You can see that the code used is pretty simple.:

private void ComputeBySalesSalesID(DataSet dataSet)
{
    // Presumes a DataTable named "Orders" that has a column named "Total."
    DataTable table;
    table = dataSet.Tables["Orders"];

    // Declare an object variable. 
    object sumObject;
    sumObject = table.Compute("Sum(Total)", "EmpID = 5");
}

I must add that if you do not need to filter the results, you can always pass an empty string:

sumObject = table.Compute("Sum(Total)", "")

postgresql: INSERT INTO ... (SELECT * ...)

If you are looking for PERFORMANCE, give where condition inside the db link query. Otherwise it fetch all data from the foreign table and apply the where condition.

INSERT INTO tblA (id,time) 
SELECT id, time FROM  dblink('dbname=dbname port=5432 host=10.10.90.190 user=postgresuser password=pass123', 
'select id, time from tblB  where time>'''||1000||'''')
AS t1(id integer, time integer)  

React Native Responsive Font Size

Need to use this way I have used this one and it's working fine.

react-native-responsive-screen npm install react-native-responsive-screen --save

Just like I have a device 1080x1920

The vertical number we calculate from height **hp**
height:200
200/1920*100 = 10.41% - height:hp("10.41%")


The Horizontal number we calculate from width **wp**
width:200
200/1080*100 = 18.51% - Width:wp("18.51%")

It's working for all device

I want to compare two lists in different worksheets in Excel to locate any duplicates

Without VBA...

If you can use a helper column, you can use the MATCH function to test if a value in one column exists in another column (or in another column on another worksheet). It will return an Error if there is no match

To simply identify duplicates, use a helper column

Assume data in Sheet1, Column A, and another list in Sheet2, Column A. In your helper column, row 1, place the following formula:

=If(IsError(Match(A1, 'Sheet2'!A:A,False)),"","Duplicate")

Drag/copy this forumla down, and it should identify the duplicates.

To highlight cells, use conditional formatting:

With some tinkering, you can use this MATCH function in a Conditional Formatting rule which would highlight duplicate values. I would probably do this instead of using a helper column, although the helper column is a great way to "see" results before you make the conditional formatting rule.

Something like:

=NOT(ISERROR(MATCH(A1, 'Sheet2'!A:A,FALSE)))

Conditional formatting for Excel 2010

For Excel 2007 and prior, you cannot use conditional formatting rules that reference other worksheets. In this case, use the helper column and set your formatting rule in column A like:

=B1="Duplicate"

This screenshot is from the 2010 UI, but the same rule should work in 2007/2003 Excel.

Conditional formatting using helper column for rule

ExpressJS How to structure an application?

Sails.js structure looks nice and clean to me, so I use MVC style structure for my express projects, similar to sails.js.

project_root  
|  
|_ _ app  
|_ _ |_ _ controllers  
|_ _ |_ _ |_ _ UserController.js  
|_ _ |_ _ middlewares  
|_ _ |_ _ |_ _ error.js  
|_ _ |_ _ |_ _ logger.js  
|_ _ |_ _ models  
|_ _ |_ _ |_ _ User.js  
|_ _ |_ _ services  
|_ _ |_ _ |_ _ DatabaseService.js  
|  
|_ _ config  
|_ _ |_ _ constants.js  
|_ _ |_ _ index.js  
|_ _ |_ _ routes.js  
|  
|_ _ public  
|_ _ |_ _ css  
|_ _ |_ _ images  
|_ _ |_ _ js  
|  
|_ _ views  
|_ _ |_ _ user  
|_ _ |_ _ |_ _ index.ejs  

App folder - contains overall login for application.
Config folder - contains app configurations, constants, routes.
Public folder - contains styles, images, scripts etc.
Views folder - contains views for each model (if any)

Boilerplate project could be found here,
https://github.com/abdulmoiz251/node-express-rest-api-boilerplate

Preferred way of loading resources in Java

I tried a lot of ways and functions that suggested above, but they didn't work in my project. Anyway I have found solution and here it is:

try {
    InputStream path = this.getClass().getClassLoader().getResourceAsStream("img/left-hand.png");
    img = ImageIO.read(path);
} catch (IOException e) {
    e.printStackTrace();
}

When should I use h:outputLink instead of h:commandLink?

I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink

MySQL Workbench: How to keep the connection alive

I had a similar problem where CREATE FULLTEXT timed out after 30 seconds:

error

Setting DBMS connection read timeout interval to 0 under Edit -> Preferences -> SQL Editor fixed the issue for me:

fix error

Also, I did not have to restart mysql workbench for this to work.

How do I do a simple 'Find and Replace" in MsSQL?

The following query replace each and every a character with a b character.

UPDATE 
    YourTable
SET 
    Column1 = REPLACE(Column1,'a','b')
WHERE 
    Column1 LIKE '%a%'

This will not work on SQL server 2003.

static constructors in C++? I need to initialize private static objects

A static constructor can be emulated by using a friend class or nested class as below.

class ClassStatic{
private:
    static char *str;
public:
    char* get_str() { return str; }
    void set_str(char *s) { str = s; }
    // A nested class, which used as static constructor
    static class ClassInit{
    public:
        ClassInit(int size){ 
            // Static constructor definition
            str = new char[size];
            str = "How are you?";
        }
    } initializer;
};

// Static variable creation
char* ClassStatic::str; 
// Static constructor call
ClassStatic::ClassInit ClassStatic::initializer(20);

int main() {
    ClassStatic a;
    ClassStatic b;
    std::cout << "String in a: " << a.get_str() << std::endl;
    std::cout << "String in b: " << b.get_str() << std::endl;
    a.set_str("I am fine");
    std::cout << "String in a: " << a.get_str() << std::endl;
    std::cout << "String in b: " << b.get_str() << std::endl;
    std::cin.ignore();
}

Output:

String in a: How are you?
String in b: How are you?
String in a: I am fine
String in b: I am fine

Using Cookie in Asp.Net Mvc 4

We are using Response.SetCookie() for update the old one cookies and Response.Cookies.Add() are use to add the new cookies. Here below code CompanyId is update in old cookie[OldCookieName].

HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.

Swift extract regex matches

@p4bloch if you want to capture results from a series of capture parentheses, then you need to use the rangeAtIndex(index) method of NSTextCheckingResult, instead of range. Here's @MartinR 's method for Swift2 from above, adapted for capture parentheses. In the array that is returned, the first result [0] is the entire capture, and then individual capture groups begin from [1]. I commented out the map operation (so it's easier to see what I changed) and replaced it with nested loops.

func matches(for regex: String!, in text: String!) -> [String] {

    do {
        let regex = try NSRegularExpression(pattern: regex, options: [])
        let nsString = text as NSString
        let results = regex.matchesInString(text, options: [], range: NSMakeRange(0, nsString.length))
        var match = [String]()
        for result in results {
            for i in 0..<result.numberOfRanges {
                match.append(nsString.substringWithRange( result.rangeAtIndex(i) ))
            }
        }
        return match
        //return results.map { nsString.substringWithRange( $0.range )} //rangeAtIndex(0)
    } catch let error as NSError {
        print("invalid regex: \(error.localizedDescription)")
        return []
    }
}

An example use case might be, say you want to split a string of title year eg "Finding Dory 2016" you could do this:

print ( matches(for: "^(.+)\\s(\\d{4})" , in: "Finding Dory 2016"))
// ["Finding Dory 2016", "Finding Dory", "2016"]

Remove duplicates from a list of objects based on property in Java 8

Another version which is simple

BiFunction<TreeSet<Employee>,List<Employee> ,TreeSet<Employee>> appendTree = (y,x) -> (y.addAll(x))? y:y;

TreeSet<Employee> outputList = appendTree.apply(new TreeSet<Employee>(Comparator.comparing(p->p.getId())),personList);

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It happens because of not very straight forward Servlet specification. If you are working with a native HttpServletRequest implementation you cannot get both the URL encode body and the parameters. Spring does some workarounds, which make it even more strange and nontransparent.

In such cases Spring (version 3.2.4) re-renders a body for you using data from the getParameterMap() method. It mixes GET and POST parameters and breaks the parameter order. The class, which is responsible for the chaos is ServletServerHttpRequest. Unfortunately it cannot be replaced, but the class StringHttpMessageConverter can be.

The clean solution is unfortunately not simple:

  1. Replacing StringHttpMessageConverter. Copy/Overwrite the original class adjusting method readInternal().
  2. Wrapping HttpServletRequest overwriting getInputStream(), getReader() and getParameter*() methods.

In the method StringHttpMessageConverter#readInternal following code must be used:

    if (inputMessage instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest oo = (ServletServerHttpRequest)inputMessage;
        input = oo.getServletRequest().getInputStream();
    } else {
        input = inputMessage.getBody();
    }

Then the converter must be registered in the context.

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true/false">
        <bean class="my-new-converter-class"/>
   </mvc:message-converters>
</mvc:annotation-driven>

The step two is described here: Http Servlet request lose params from POST body after read it once

How to hide Android soft keyboard on EditText

Simply use below method

private fun hideKeyboard(activity: Activity, editText: EditText) {
    editText.clearFocus()
    (activity.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager).hideSoftInputFromWindow(editText.windowToken, 0)
}

How to convert string to integer in C#

int i;

string result = Something;

i = Convert.ToInt32(result);

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Suppose I have the following table T:

a   b
--------
1   abc
1   def
1   ghi
2   jkl
2   mno
2   pqr

And I do the following query:

SELECT a, b
FROM T
GROUP BY a

The output should have two rows, one row where a=1 and a second row where a=2.

But what should the value of b show on each of these two rows? There are three possibilities in each case, and nothing in the query makes it clear which value to choose for b in each group. It's ambiguous.

This demonstrates the single-value rule, which prohibits the undefined results you get when you run a GROUP BY query, and you include any columns in the select-list that are neither part of the grouping criteria, nor appear in aggregate functions (SUM, MIN, MAX, etc.).

Fixing it might look like this:

SELECT a, MAX(b) AS x
FROM T
GROUP BY a

Now it's clear that you want the following result:

a   x
--------
1   ghi
2   pqr

Adjusting and image Size to fit a div (bootstrap)

If any of you looking for Bootstrap-4. Here it is

<div class="row no-gutters">
    <div class="col-10">
        <img class="img-fluid" src="/resources/img1.jpg" alt="">
    </div>
</div>

How many characters in varchar(max)

For future readers who need this answer quickly:

2^31-1 = 2.147.483.647 characters

Figuring out whether a number is a Double in Java

Use regular expression to achieve this task. Please refer the below code.

public static void main(String[] args) {
    try {

        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
        System.out.print("Enter your content: ");
        String data = reader.readLine();            
        boolean b1 = Pattern.matches("^\\d+$", data);
        boolean b2 = Pattern.matches("[0-9a-zA-Z([+-]?\\d*\\.+\\d*)]*", data); 
        boolean b3 = Pattern.matches("^([+-]?\\d*\\.+\\d*)$", data);
        if(b1) {
            System.out.println("It is integer.");
        } else if(b2) {
            System.out.println("It is String. ");
        } else if(b3) {
            System.out.println("It is Float. ");
        }           
    } catch (IOException ex) {
        Logger.getLogger(TypeOF.class.getName()).log(Level.SEVERE, null, ex);
    }
}

Convert a row of a data frame to vector

Note that you have to be careful if your row contains a factor. Here is an example:

df_1 = data.frame(V1 = factor(11:15),
                  V2 = 21:25)
df_1[1,] %>% as.numeric() # you expect 11 21 but it returns 
[1] 1 21

Here is another example (by default data.frame() converts characters to factors)

df_2 = data.frame(V1 = letters[1:5],
                  V2 = 1:5)
df_2[3,] %>% as.numeric() # you expect to obtain c 3 but it returns
[1] 3 3
df_2[3,] %>% as.character() # this won't work neither
[1] "3" "3"

To prevent this behavior, you need to take care of the factor, before extracting it:

df_1$V1 = df_1$V1 %>% as.character() %>% as.numeric()
df_2$V1 = df_2$V1 %>% as.character()
df_1[1,] %>% as.numeric()
[1] 11  21
df_2[3,] %>% as.character()
[1] "c" "3"

Matching strings with wildcard

Often, wild cards operate with two type of jokers:

  ? - any character  (one and only one)
  * - any characters (zero or more)

so you can easily convert these rules into appropriate regular expression:

  // If you want to implement both "*" and "?"
  private static String WildCardToRegular(String value) {
    return "^" + Regex.Escape(value).Replace("\\?", ".").Replace("\\*", ".*") + "$"; 
  }

  // If you want to implement "*" only
  private static String WildCardToRegular(String value) {
    return "^" + Regex.Escape(value).Replace("\\*", ".*") + "$"; 
  }

And then you can use Regex as usual:

  String test = "Some Data X";

  Boolean endsWithEx = Regex.IsMatch(test, WildCardToRegular("*X"));
  Boolean startsWithS = Regex.IsMatch(test, WildCardToRegular("S*"));
  Boolean containsD = Regex.IsMatch(test, WildCardToRegular("*D*"));

  // Starts with S, ends with X, contains "me" and "a" (in that order) 
  Boolean complex = Regex.IsMatch(test, WildCardToRegular("S*me*a*X"));

Remove carriage return in Unix

If you are running an X environment and have a proper editor (visual studio code), then I would follow the reccomendation:

Visual Studio Code: How to show line endings

Just go to the bottom right corner of your screen, visual studio code will show you both the file encoding and the end of line convention followed by the file, an just with a simple click you can switch that around.

Just use visual code as your replacement for notepad++ on a linux environment and you are set to go.

Check if a parameter is null or empty in a stored procedure

If you want to use a parameter is Optional so use it.

CREATE PROCEDURE uspGetAddress @City nvarchar(30) = NULL, @AddressLine1 nvarchar(60) = NULL
    AS
    SELECT *
    FROM AdventureWorks.Person.Address
    WHERE City = ISNULL(@City,City)
    AND AddressLine1 LIKE '%' + ISNULL(@AddressLine1 ,AddressLine1) + '%'
    GO

What is the meaning of CTOR?

Type "ctor" and press the TAB key twice this will add the default constructor automatically

Changing SVG image color with javascript

Here's a full example that shows how to modify the fill color of an svg referenced via <embed>, <object> and <iframe>.

Also see How to apply a style to an embedded SVG?

spring autowiring with unique beans: Spring expected single matching bean but found 2

If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that

@Component
public class SuggestionService {

declares a bean of type SuggestionService, and of name suggestionService. It's equivalent to

@Component("suggestionService")
public class SuggestionService {

or to

<bean id="suggestionService" .../>

You're redefining another bean of the same type, but with a different name, in the XML:

<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
    ...
</bean>

So, either specify the name of the bean in the annotation to be SuggestionService, or use the ID suggestionService in the XML (don't forget to also modify the <ref> element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.

Sending data from HTML form to a Python script in Flask

You need a Flask view that will receive POST data and an HTML form that will send it.

from flask import request

@app.route('/addRegion', methods=['POST'])
def addRegion():
    ...
    return (request.form['projectFilePath'])
<form action="{{ url_for('addRegion') }}" method="post">
    Project file path: <input type="text" name="projectFilePath"><br>
    <input type="submit" value="Submit">
</form>

How do I get the current time zone of MySQL?

Insert a dummy record into one of your databases that has a timestamp Select that record and get value of timestamp. Delete that record. Gets for sure the timezone that the server is using to write data and ignores PHP timezones.

What is the C++ function to raise a number to a power?

Note that the use of pow(x,y) is less efficient than x*x*x y times as shown and answered here https://stackoverflow.com/a/2940800/319728.

So if you're going for efficiency use x*x*x.

Jquery function BEFORE form submission

Aghhh... i was missing some code when i first tried the .submit function.....

This works:

$('#create-card-process.design').submit(function() {
    var textStyleCSS = $("#cover-text").attr('style');
    var textbackgroundCSS = $("#cover-text-wrapper").attr('style');
    $("#cover_text_css").val(textStyleCSS);
    $("#cover_text_background_css").val(textbackgroundCSS);
});

Thanks for all the comments.

Have log4net use application config file for configuration data

All appender names must be reflected in the root section.
In your case the appender name is EventLogAppender but in the <root> <appender-ref .. section it is named as ConsoleAppender. They need to match.

You can add multiple appenders to your log config but you need to register each of them in the <root> section.

<appender-ref ref="ConsoleAppender" />
<appender-ref ref="EventLogAppender" />

You can also refer to the apache documentation on configuring log4net.

glob exclude pattern

As mentioned by the accepted answer, you can't exclude patterns with glob, so the following is a method to filter your glob result.

The accepted answer is probably the best pythonic way to do things but if you think list comprehensions look a bit ugly and want to make your code maximally numpythonic anyway (like I did) then you can do this (but note that this is probably less efficient than the list comprehension method):

import glob

data_files = glob.glob("path_to_files/*.fits")

light_files = np.setdiff1d( data_files, glob.glob("*BIAS*"))
light_files = np.setdiff1d(light_files, glob.glob("*FLAT*"))

(In my case, I had some image frames, bias frames, and flat frames all in one directory and I just wanted the image frames)

Install pdo for postgres Ubuntu

PDO driver for PostgreSQL is now included in the debian package php5-dev. The above steps using Pecl no longer works.

Setting environment variables via launchd.conf no longer works in OS X Yosemite/El Capitan/macOS Sierra/Mojave?

Create an environment.plist file in ~/Library/LaunchAgents/ with this content:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
  <key>Label</key>
  <string>my.startup</string>
  <key>ProgramArguments</key>
  <array>
    <string>sh</string>
    <string>-c</string>
    <string>
    launchctl setenv PRODUCTS_PATH /Users/mortimer/Projects/my_products
    launchctl setenv ANDROID_NDK_HOME /Applications/android-ndk
    launchctl setenv PATH $PATH:/Applications/gradle/bin
    </string>

  </array>
  <key>RunAtLoad</key>
  <true/>
</dict>
</plist>

You can add many launchctl commands inside the <string></string> block.

The plist will activate after system reboot. You can also use launchctl load ~/Library/LaunchAgents/environment.plist to launch it immediately.

[Edit]

The same solution works in El Capitan too.

Xcode 7.0+ doesn't evaluate environment variables by default. The old behaviour can be enabled with this command:

defaults write com.apple.dt.Xcode UseSanitizedBuildSystemEnvironment -bool NO

[Edit]

There a couple of situations where this doesn't quite work. If the computer is restarted and "Reopen windows when logging back in" is selected, the reopened windows may not see the variables (Perhaps they are opened before the agent is run). Also, if you log in via ssh, the variables will not be set (so you'll need to set them in ~/.bash_profile). Finally, this doesn't seem to work for PATH on El Capitan and Sierra. That needs to be set via 'launchctl config user path ...' and in /etc/paths.

define a List like List<int,string>?

Not sure about your specific scenario, but you have three options:

1.) use Dictionary<..,..>
2.) create a wrapper class around your values and then you can use List
3.) use Tuple

How do I determine k when using k-means clustering?

km=[]
for i in range(num_data.shape[1]):
    kmeans = KMeans(n_clusters=ncluster[i])#we take number of cluster bandwidth theory
    ndata=num_data[[i]].dropna()
    ndata['labels']=kmeans.fit_predict(ndata.values)
    cluster=ndata
    co=cluster.groupby(['labels'])[cluster.columns[0]].count()#count for frequency
    me=cluster.groupby(['labels'])[cluster.columns[0]].median()#median
    ma=cluster.groupby(['labels'])[cluster.columns[0]].max()#Maximum
    mi=cluster.groupby(['labels'])[cluster.columns[0]].min()#Minimum
    stat=pd.concat([mi,ma,me,co],axis=1)#Add all column
    stat['variable']=stat.columns[1]#Column name change
    stat.columns=['Minimum','Maximum','Median','count','variable']
    l=[]
    for j in range(ncluster[i]):
        n=[mi.loc[j],ma.loc[j]] 
        l.append(n)

    stat['Class']=l
    stat=stat.sort(['Minimum'])
    stat=stat[['variable','Class','Minimum','Maximum','Median','count']]
    if missing_num.iloc[i]>0:
        stat.loc[ncluster[i]]=0
        if stat.iloc[ncluster[i],5]==0:
            stat.iloc[ncluster[i],5]=missing_num.iloc[i]
            stat.iloc[ncluster[i],0]=stat.iloc[0,0]
    stat['Percentage']=(stat[[5]])*100/count_row#Freq PERCENTAGE
    stat['Cumulative Percentage']=stat['Percentage'].cumsum()
    km.append(stat)
cluster=pd.concat(km,axis=0)## see documentation for more info
cluster=cluster.round({'Minimum': 2, 'Maximum': 2,'Median':2,'Percentage':2,'Cumulative Percentage':2})

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

There's an easier way than the other answers that doesn't require you to name the resource explicitly or worry about exceptions with package names. It also works if you have used a string directly instead of a resource.

Just do:

public static String getApplicationName(Context context) {
    ApplicationInfo applicationInfo = context.getApplicationInfo();
    int stringId = applicationInfo.labelRes;
    return stringId == 0 ? applicationInfo.nonLocalizedLabel.toString() : context.getString(stringId);
}

Hope this helps.

Edit

In light of the comment from Snicolas, I've modified the above so that it doesn't try to resolve the id if it is 0. Instead it uses, nonLocalizedLabel as a backoff. No need for wrapping in try/catch.

Functional, Declarative, and Imperative Programming

Declarative programming is programming by expressing some timeless logic between the input and the output, for instance, in pseudocode, the following example would be declarative:

def factorial(n):
  if n < 2:
    return 1
  else:
    return factorial(n-1)

output = factorial(argvec[0])

We just define a relationship called the 'factorial' here, and defined the relationship between the output and the input as the that relationship. As should be evident here, about any structured language allows declarative programming to some extend. A central idea of declarative programming is immutable data, if you assign to a variable, you only do so once, and then never again. Other, stricter definitions entail that there may be no side-effects at all, these languages are some times called 'purely declarative'.

The same result in an imperative style would be:

a = 1
b = argvec[0]
while(b < 2):
  a * b--

output = a

In this example, we expressed no timeless static logical relationship between the input and the output, we changed memory addresses manually until one of them held the desired result. It should be evident that all languages allow declarative semantics to some extend, but not all allow imperative, some 'purely' declarative languages permit side effects and mutation altogether.

Declarative languages are often said to specify 'what must be done', as opposed to 'how to do it', I think that is a misnomer, declarative programs still specify how one must get from input to output, but in another way, the relationship you specify must be effectively computable (important term, look it up if you don't know it). Another approach is nondeterministic programming, that really just specifies what conditions a result much meet, before your implementation just goes to exhaust all paths on trial and error until it succeeds.

Purely declarative languages include Haskell and Pure Prolog. A sliding scale from one and to the other would be: Pure Prolog, Haskell, OCaml, Scheme/Lisp, Python, Javascript, C--, Perl, PHP, C++, Pascall, C, Fortran, Assembly

Delegation: EventEmitter or Observable in Angular

I found out another solution for this case without using Reactivex neither services. I actually love the rxjx API however I think it goes best when resolving an async and/or complex function. Using It in that way, Its pretty exceeded to me.

What I think you are looking for is for a broadcast. Just that. And I found out this solution:

<app>
  <app-nav (selectedTab)="onSelectedTab($event)"></app-nav>
       // This component bellow wants to know when a tab is selected
       // broadcast here is a property of app component
  <app-interested [broadcast]="broadcast"></app-interested>
</app>

 @Component class App {
   broadcast: EventEmitter<tab>;

   constructor() {
     this.broadcast = new EventEmitter<tab>();
   }

   onSelectedTab(tab) {
     this.broadcast.emit(tab)
   }    
 }

 @Component class AppInterestedComponent implements OnInit {
   broadcast: EventEmitter<Tab>();

   doSomethingWhenTab(tab){ 
      ...
    }     

   ngOnInit() {
     this.broadcast.subscribe((tab) => this.doSomethingWhenTab(tab))
   }
 }

This is a full working example: https://plnkr.co/edit/xGVuFBOpk2GP0pRBImsE

Understanding colors on Android (six characters)

On Android the color can be declared in the following format

#AARRGGBB

AA - is the bit that’s of most interest to us, it stands for alpha channel

RR GG BB - red, green & blue channels respectively

Now in order to add transparency to our color we need to prepend it with hexadecimal value representing the alpha (transparency).

For example if you want to set 80% transparency value to black color (#000000) you need to prepend it with CC, as a result we end up with the following color resource #CC000000.

You can read about it in more detail on my blog https://androidexplained.github.io/android/ui/2020/10/12/hex-color-code-transparency.html

What's the difference between "git reset" and "git checkout"?

The two commands (reset and checkout) are completely different.

checkout X IS NOT reset --hard X

If X is a branch name, checkout X will change the current branch while reset --hard X will not.

What do the icons in Eclipse mean?

I can't find a way to create a table with icons in SO, so I am uploading 2 images. Objects Icons

Decorator icons

Sending email through Gmail SMTP server with C#

I had also try to many solution but make some changes it will work

host = smtp.gmail.com
port = 587
username = [email protected]
password = password
enabledssl = true

with smtpclient above parameters are work in gmail

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

I had the same problem. i was using windows8 with 64 bit OS. I just changed the path to Program Files(*86) and then it started work. I put this line in eclipse.ini file like,

-vm
 C:\Program Files (x86)\Java\jre7\bin\javaw.exe

break statement in "if else" - java

The issue is that you are trying to have multiple statements in an if without using {}. What you currently have is interpreted like:

if( choice==5 )
{
    System.out.println( ... );
}
break;
else
{
    //...
}

You really want:

if( choice==5 )
{
    System.out.println( ... );
    break;
}
else
{
    //...
}

Also, as Farce has stated, it would be better to use else if for all the conditions instead of if because if choice==1, it will still go through and check if choice==5, which would fail, and it will still go into your else block.

if( choice==1 )
    //...
else if( choice==2 )
    //...
else if( choice==3 )
    //...
else if( choice==4 )
    //...
else if( choice==5 )
{
    //...
}
else
    //...

A more elegant solution would be using a switch statement. However, break only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:

LOOP:
for(;;)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch( choice )
    {
        case 1:
            playGame();
            break;
        case 2:
            loadGame();
            break;
        case 2:
            options();
            break;
        case 4:
            credits();
            break;
        case 5:
            System.out.println("End of Game\n Thank you for playing with us!");
            break LOOP;
        default:
            System.out.println( ... );
    }
}

Instead of labeling the loop, you could also use a flag to tell the loop to stop.

bool finished = false;
while( !finished )
{
    switch( choice )
    {
        // ...
        case 5:
            System.out.println( ... )
            finished = true;
            break;
        // ...
    }
}

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

Building on @Prasath's answer. This is how you do it in Swift:

if application.respondsToSelector("isRegisteredForRemoteNotifications")
{
    // iOS 8 Notifications
    application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: (.Badge | .Sound | .Alert), categories: nil));
    application.registerForRemoteNotifications()
}
else
{
    // iOS < 8 Notifications
    application.registerForRemoteNotificationTypes(.Badge | .Sound | .Alert)
}

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

You need to access image IDs using R.mipmap.yourImageName

How to update core-js to core-js@3 dependency?

For npm

 npm install --save core-js@^3

for yarn

yarn add core-js@^3

You can't specify target table for update in FROM clause

If you are trying to read fieldA from tableA and save it on fieldB on the same table, when fieldc = fieldd you might want consider this.

UPDATE tableA,
    tableA AS tableA_1 
SET 
    tableA.fieldB= tableA_1.filedA
WHERE
    (((tableA.conditionFild) = 'condition')
        AND ((tableA.fieldc) = tableA_1.fieldd));

Above code copies the value from fieldA to fieldB when condition-field met your condition. this also works in ADO (e.g access )

source: tried myself

how to open popup window using jsp or jquery?

<a href="javaScript:{openPopUp();}"></a>
<form action="actionName">
<div id="divId" style="display:none;">
UsreName:<input type="text" name="userName"/>
</div>
</form>

function openPopUp()
{
  $('#divId').css('display','block');
$('#divId').dialog();
}

implement addClass and removeClass functionality in angular2

Try to use it via [ngClass] property:

<div class="button" [ngClass]="{active: isOn, disabled: isDisabled}"
         (click)="toggle(!isOn)">
         Click me!
     </div>`,

No Network Security Config specified, using platform default - Android Log

This occurs to the api 28 and above, because doesn't accept http anymore, you need to change if you want to accept http or localhost requests.

  1. Create an XML file Create XML file

  2. Add the following code on the new XML file you created Add base-config

  3. Add this on AndroidManifest.xml Add this code line

bootstrap datepicker change date event doesnt fire up when manually editing dates or clearing date

I was using AngularJS and AngularStrap 2.3.7 and trying to catch the 'change' event by listening to a <form> element (not the input itself) and none of the answers here worked for me. I tried to do:

$(form).on('change change.dp dp.change changeDate' function () {...})

And nothing would fire. I ended up listening to the focus and blur events and setting a custom property before/after on the element itself:

// special hack to make bs-datepickers fire change events
// use timeout to make sure they all exist first
$timeout(function () {  
    $('input[bs-datepicker]').on('focus', function (e){
        e.currentTarget.focusValue = e.currentTarget.value;
    });        
    $('input[bs-datepicker]').on('blur', function (e){
        if (e.currentTarget.focusValue !== e.currentTarget.value) {
            var event = new Event('change', { bubbles: true });
            e.currentTarget.dispatchEvent(event);
        }
    });
})

This basically manually checks the value before and after the focus and blur and dispatches a new 'change' event. The { bubbles: true } bit is what got the form to detect the change. If you have any datepicker elements inside of an ng-if you'll need to wrap the listeners in a $timeout to make sure the digest happens first so all of your datepicker elements exist.

Hope this helps someone!

what does numpy ndarray shape do?

.shape() gives the actual shape of your array in terms of no of elements in it, No of rows/No of Columns. The answer you get is in the form of tuples.

For Example: 1D ARRAY:

d=np.array([1,2,3,4])
print(d)
(1,)

Output: (4,) ie the number4 denotes the no of elements in the 1D Array.

2D Array:

e=np.array([[1,2,3],[4,5,6]])   
print(e)
(2,3)

Output: (2,3) ie the number of rows and the number of columns.

The number of elements in the final output will depend on the number of rows in the Array....it goes on increasing gradually.

html "data-" attribute as javascript parameter

JS:

function fun(obj) {
    var uid= $(obj).data('uid');
    var name= $(obj).data('name');
    var value= $(obj).data('value');
}

Django - Reverse for '' not found. '' is not a valid view function or pattern name

In my case, I don't put namespace_name in the url tag ex: {% url 'url_name or pattern name' %}. you have to specify the namespace_name like: {% url 'namespace_name:url_name or pattern name' %}.

Explanation: In project urls.py path('', include('blog.urls',namespace='blog')), and in app's urls.py you have to specify the app_name. like app_name = 'blog'. namespace_name is the app_name.

You have not concluded your merge (MERGE_HEAD exists)

This worked for me:

git log
`git reset --hard <089810b5be5e907ad9e3b01f>`
git pull
git status

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

I ran into a very similar issue.

I needed to use an old 32-bit DLL within a Web Application that was being developed on a 64-bit machine. I registered the 32-bit DLL into the windows\sysWOW64 folder using the version of regsrv32 in that folder.

Calls to the third party DLL worked from unit tests in Visual Studio but failed from the Web Application hosted in IIS on the same machine with the 80040154 error.

Changing the application pool to "Enable 32-Bit Applications" resolved the issue.

YAML Multi-Line Arrays

Following Works for me and its good from readability point of view when array element values are small:

key: [string1, string2, string3, string4, string5, string6]

Note:snakeyaml implementation used

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

MomentJS getting JavaScript Date in UTC

Calling toDate will create a copy (the documentation is down-right wrong about it not being a copy), of the underlying JS Date object. JS Date object is stored in UTC and will always print to eastern time. Without getting into whether .utc() modifies the underlying object that moment wraps use the code below.

You don't need moment for this.

new Date().getTime()

This works, because JS Date at its core is in UTC from the Unix Epoch. It's extraordinarily confusing and I believe a big flaw in the interface to mix local and UTC times like this with no descriptions in the methods.

Get file name from a file location in Java

new File(absolutePath).getName();

How do relative file paths work in Eclipse?

A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.

New run configurations default to using the project directory for the working directory, though this can also be changed.

This code shows the difference between the working directory, and the location of where the class was loaded from:

public class TellMeMyWorkingDirectory {
    public static void main(String[] args) {
        System.out.println(new java.io.File("").getAbsolutePath());
        System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
    }
}

The output is likely to be something like:

C:\your\project\directory
/C:/your/project/directory/bin/

Binding arrow keys in JS/jQuery

With coffee & Jquery

  $(document).on 'keydown', (e) ->
    switch e.which
      when 37 then console.log('left key')
      when 38 then console.log('up key')
      when 39 then console.log('right key')
      when 40 then console.log('down key')
    e.preventDefault()

How To Create Table with Identity Column

CREATE TABLE [dbo].[History](
    [ID] [int] IDENTITY(1,1) NOT NULL,
    [RequestID] [int] NOT NULL,
    [EmployeeID] [varchar](50) NOT NULL,
    [DateStamp] [datetime] NOT NULL,
 CONSTRAINT [PK_History] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON)
) ON [PRIMARY]

Updating Anaconda fails: Environment Not Writable Error

In my case somehow CONDA_ENVS_PATH was removed, so I was having NotWritableError. So I fixed the error by specifying

CONDA_ENVS_PATH=~/my-envs:/opt/anaconda/envs

in the .bashrc file

How to hide the title bar for an Activity in XML with existing custom theme

I believe there is just one line answer for this in 2020

Add the following line to the styles.xml

<item name="windowNoTitle">true</item>

How to get the size of a string in Python?

If you are talking about the length of the string, you can use len():

>>> s = 'please answer my question'
>>> len(s)  # number of characters in s
25

If you need the size of the string in bytes, you need sys.getsizeof():

>>> import sys
>>> sys.getsizeof(s)
58

Also, don't call your string variable str. It shadows the built-in str() function.

What is the canonical way to check for errors using the CUDA runtime API?

The solution discussed here worked well for me. This solution uses built-in cuda functions and is very simple to implement.

The relevant code is copied below:

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

__global__ void foo(int *ptr)
{
  *ptr = 7;
}

int main(void)
{
  foo<<<1,1>>>(0);

  // make the host block until the device is finished with foo
  cudaDeviceSynchronize();

  // check for error
  cudaError_t error = cudaGetLastError();
  if(error != cudaSuccess)
  {
    // print the CUDA error message and exit
    printf("CUDA error: %s\n", cudaGetErrorString(error));
    exit(-1);
  }

  return 0;
}

How to add external library in IntelliJ IDEA?

A better way in long run is to integrate Gradle in your project environment. Its a build tool for Java, and now being used a lot in the android development space.

You will need to make a .gradle file and list your library dependencies. Then, all you would need to do is import the project in IntelliJ using Gradle.

Cheers

POST data to a URL in PHP

Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.

Here's a pretty good walkthrough of both

Execute specified function every X seconds

The most beginner-friendly solution is:

Drag a Timer from the Toolbox, give it a Name, set your desired Interval, and set "Enabled" to True. Then double-click the Timer and Visual Studio (or whatever you are using) will write the following code for you:

private void wait_Tick(object sender, EventArgs e)
{
    refreshText(); // Add the method you want to call here.
}

No need to worry about pasting it into the wrong code block or something like that.

How do I get the height and width of the Android Navigation Bar programmatically?

In my case where I wanted to have something like this:

Screenshot

I had to follow the same thing as suggested by @Mdlc but probably slightly simpler (targeting only >= 21):

    //kotlin
    val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val realSize = Point()
    windowManager.defaultDisplay.getRealSize(realSize);
    val usableRect = Rect()
    windowManager.defaultDisplay.getRectSize(usableRect)
    Toast.makeText(this, "Usable Screen: " + usableRect + " real:"+realSize, Toast.LENGTH_LONG).show()

    window.decorView.setPadding(usableRect.left, usableRect.top, realSize.x - usableRect.right, realSize.y - usableRect.bottom)

It works on landscape too:

landscape

Edit The above solution does not work correctly in multi-window mode where the usable rectangle is not smaller just due to the navigation bar but also because of custom window size. One thing that I noticed is that in multi-window the navigation bar is not hovering over the app so even with no changes to DecorView padding we have the correct behaviour:

Multi-window with no changes to decor view padding Single-window with no changes to decor view padding

Note the difference between how navigation bar is hovering over the bottom of the app in these to scenarios. Fortunately, this is easy to fix. We can check if app is multi window. The code below also includes the part to calculate and adjust the position of toolbar (full solution: https://stackoverflow.com/a/14213035/477790)

    // kotlin
    // Let the window flow into where window decorations are
    window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN)
    window.addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS)

    // calculate where the bottom of the page should end up, considering the navigation bar (back buttons, ...)
    val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManager
    val realSize = Point()
    windowManager.defaultDisplay.getRealSize(realSize);
    val usableRect = Rect()
    windowManager.defaultDisplay.getRectSize(usableRect)
    Toast.makeText(this, "Usable Screen: " + usableRect + " real:" + realSize, Toast.LENGTH_LONG).show()

    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N || !isInMultiWindowMode) {
        window.decorView.setPadding(usableRect.left, usableRect.top, realSize.x - usableRect.right, realSize.y - usableRect.bottom)
        // move toolbar/appbar further down to where it should be and not to overlap with status bar
        val layoutParams = ConstraintLayout.LayoutParams(appBarLayout.layoutParams as ConstraintLayout.LayoutParams)
        layoutParams.topMargin = getSystemSize(Constants.statusBarHeightKey)
        appBarLayout.layoutParams = layoutParams
    }

Result on Samsung popup mode:

enter image description here

Google drive limit number of download

Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:

The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.

Bandwidth limits

Limit                          Per hour            Per day
Download via web client        750 MB              1250 MB
Upload via web client          300 MB              500 MB
POP and IMAP bandwidth limits

Limit                Per day
Download via IMAP    2500 MB
Download via POP     1250 MB
Upload via IMAP      500 MB

check out this link

What is a good game engine that uses Lua?

I can second the previous posters enthusiasm for the Gideros Lua game engine, whilst focusing currently on Mobile (iOS and Android - Windows phone 8 is in the works), desktop support for Mac, PC (possibly Linux) is also planned for the not too distant future.

Google for "Gideros Mobile"

Parsing a CSV file using NodeJS

  • This solution uses csv-parser instead of csv-parse used in some of the answers above.
  • csv-parser came around 2 years after csv-parse.
  • Both of them solve the same purpose, but personally I have found csv-parser better, as it is easy to handle headers through it.

Install the csv-parser first:

npm install csv-parser

So suppose you have a csv-file like this:

NAME, AGE
Lionel Messi, 31
Andres Iniesta, 34

You can perform the required operation as:

const fs = require('fs'); 
const csv = require('csv-parser');

fs.createReadStream(inputFilePath)
.pipe(csv())
.on('data', function(data){
    try {
        console.log("Name is: "+data.NAME);
        console.log("Age is: "+data.AGE);

        //perform the operation
    }
    catch(err) {
        //error handler
    }
})
.on('end',function(){
    //some final operation
});  

For further reading refer

How to "z-index" to make a menu always on top of the content

you could put the style in container div menu with:

<div style="position:relative; z-index:10">
   ...
   <!--html menu-->
   ...
</div>

before enter image description here

after

enter image description here

Refresh Excel VBA Function Results

Some more information on the F9 keyboard shortcuts for calculation in Excel

  • F9 Recalculates all worksheets in all open workbooks
  • Shift+ F9 Recalculates the active worksheet
  • Ctrl+Alt+ F9 Recalculates all worksheets in all open workbooks (Full recalculation)
  • Shift + Ctrl+Alt+ F9 Rebuilds the dependency tree and does a full recalculation

How to set session timeout dynamically in Java web applications?

I need to give my user a web interface to change the session timeout interval. So, different installations of the web application would be able to have different timeouts for their sessions, but their web.xml cannot be different.

your question is simple, you need session timeout interval should be configurable at run time and configuration should be done through web interface and there shouldn't be overhead of restarting the server.

I am extending Michaels answer to address your question.

Logic: You need to store configured value in either .properties file or to database. On server start read that stored value and copy to a variable use that variable until server is UP. As config is updated update variable also. Thats it.

Expaination

In MyHttpSessionListener class 1. create a static variable with name globalSessionTimeoutInterval.

  1. create a static block(executed for only for first time of class is being accessed) and read timeout value from config.properties file and set value to globalSessionTimeoutInterval variable.

  2. Now use that value to set maxInactiveInterval

  3. Now Web part i.e, Admin configuration page

    a. Copy configured value to static variable globalSessionTimeoutInterval.

    b. Write same value to config.properties file. (consider server is restarted then globalSessionTimeoutInterval will be loaded with value present in config.properties file)

  4. Alternative .properties file OR storing it into database. Choice is yours.

Logical code for achieving the same

public class MyHttpSessionListener implements HttpSessionListener 
{
  public static Integer globalSessionTimeoutInterval = null;

  static
  {
      globalSessionTimeoutInterval =  Read value from .properties file or database;
  }
  public void sessionCreated(HttpSessionEvent event)
  {
      event.getSession().setMaxInactiveInterval(globalSessionTimeoutInterval);
  }

  public void sessionDestroyed(HttpSessionEvent event) {}

}

And in your Configuration Controller or Configuration servlet

String valueReceived = request.getParameter(timeoutValue);
if(valueReceived  != null)
{
    MyHttpSessionListener.globalSessionTimeoutInterval = Integer.parseInt(timeoutValue);
          //Store valueReceived to config.properties file or database
}

Object Required Error in excel VBA

The Set statement is only used for object variables (like Range, Cell or Worksheet in Excel), while the simple equal sign '=' is used for elementary datatypes like Integer. You can find a good explanation for when to use set here.

The other problem is, that your variable g1val isn't actually declared as Integer, but has the type Variant. This is because the Dim statement doesn't work the way you would expect it, here (see example below). The variable has to be followed by its type right away, otherwise its type will default to Variant. You can only shorten your Dim statement this way:

Dim intColumn As Integer, intRow As Integer  'This creates two integers

For this reason, you will see the "Empty" instead of the expected "0" in the Watches window.

Try this example to understand the difference:

Sub Dimming()

  Dim thisBecomesVariant, thisIsAnInteger As Integer
  Dim integerOne As Integer, integerTwo As Integer

  MsgBox TypeName(thisBecomesVariant)  'Will display "Empty"
  MsgBox TypeName(thisIsAnInteger )  'Will display "Integer"
  MsgBox TypeName(integerOne )  'Will display "Integer"
  MsgBox TypeName(integerTwo )  'Will display "Integer"

  'By assigning an Integer value to a Variant it becomes Integer, too
  thisBecomesVariant = 0
  MsgBox TypeName(thisBecomesVariant)  'Will display "Integer"

End Sub

Two further notices on your code:

First remark: Instead of writing

'If g1val is bigger than the value in the current cell
If g1val > Cells(33, i).Value Then
  g1val = g1val   'Don't change g1val
Else
  g1val = Cells(33, i).Value  'Otherwise set g1val to the cell's value
End If

you could simply write

'If g1val is smaller or equal than the value in the current cell
If g1val <= Cells(33, i).Value Then
  g1val = Cells(33, i).Value  'Set g1val to the cell's value 
End If

Since you don't want to change g1val in the other case.

Second remark: I encourage you to use Option Explicit when programming, to prevent typos in your program. You will then have to declare all variables and the compiler will give you a warning if a variable is unknown.

Export DataTable to Excel File

Working code for Excel Export

 try
        {
            DataTable dt = DS.Tables[0];
            string attachment = "attachment; filename=log.xls";
            Response.ClearContent();
            Response.AddHeader("content-disposition", attachment);
            Response.ContentType = "application/vnd.ms-excel";
            string tab = "";
            foreach (DataColumn dc in dt.Columns)
            {
                Response.Write(tab + dc.ColumnName);
                tab = "\t";
            }
            Response.Write("\n");
            int i;
            foreach (DataRow dr in dt.Rows)
            {
                tab = "";
                for (i = 0; i < dt.Columns.Count; i++)
                {
                    Response.Write(tab + dr[i].ToString());
                    tab = "\t";
                }
                Response.Write("\n");
            }
            Response.End();
        }
        catch (Exception Ex)
        { }

Redirect stderr to stdout in C shell

I think this is the correct answer for csh.

xxx >/dev/stderr

Note most csh are really tcsh in modern environments:

rmockler> ls -latr /usr/bin/csh

lrwxrwxrwx 1 root root 9 2011-05-03 13:40 /usr/bin/csh -> /bin/tcsh

using a backtick embedded statement to portray this as follows:

echo "`echo 'standard out1'` `echo 'error out1' >/dev/stderr` `echo 'standard out2'`" | tee -a /tmp/test.txt ; cat /tmp/test.txt

if this works for you please bump up to 1. The other suggestions don't work for my csh environment.

PDO with INSERT INTO through prepared statements

I have just rewritten the code to the following:

    $dbhost = "localhost";
    $dbname = "pdo";
    $dbusername = "root";
    $dbpassword = "845625";

    $link = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbusername, $dbpassword);
    $link->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    $statement = $link->prepare("INSERT INTO testtable(name, lastname, age)
        VALUES(?,?,?)");

    $statement->execute(array("Bob","Desaunois",18));

And it seems to work now. BUT. if I on purpose cause an error to occur, it does not say there is any. The code works, but still; should I encounter more errors, I will not know why.

Python Timezone conversion

import datetime
import pytz

def convert_datetime_timezone(dt, tz1, tz2):
    tz1 = pytz.timezone(tz1)
    tz2 = pytz.timezone(tz2)

    dt = datetime.datetime.strptime(dt,"%Y-%m-%d %H:%M:%S")
    dt = tz1.localize(dt)
    dt = dt.astimezone(tz2)
    dt = dt.strftime("%Y-%m-%d %H:%M:%S")

    return dt

-

  • dt: date time string
  • tz1: initial time zone
  • tz2: target time zone

-

> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "PST8PDT")
'2017-05-13 05:56:32'

> convert_datetime_timezone("2017-05-13 14:56:32", "Europe/Berlin", "UTC")
'2017-05-13 12:56:32'

-

> pytz.all_timezones[0:10]
['Africa/Abidjan',
 'Africa/Accra',
 'Africa/Addis_Ababa',
 'Africa/Algiers',
 'Africa/Asmara',
 'Africa/Asmera',
 'Africa/Bamako',
 'Africa/Bangui',
 'Africa/Banjul',
 'Africa/Bissau']

How to run multiple SQL commands in a single SQL connection?

This is likely to be attacked via SQL injection by the way. It'd be worth while reading up on that and adjusting your queries accordingly.

Maybe look at even creating a stored proc for this and using something like sp_executesql which can provide some protection against this when dynamic sql is a requirement (ie. unknown table names etc). For more info, check out this link.

Add another class to a div

In the DOM, the class of an element is just each class separated by a space. You would just need to implement the parsing logic to insert / remove the classes as necesary.

I wonder though... why wouldn't you want to use jQuery? It makes this kind of problem trivially easy.

ImageView in circular through xml

Best Solution courtesy https://www.youtube.com/watch?v=0MHoNU7ytaw the width and height of the card view determine the size of the images it contains set up is as follows:

  1. Add Dependency to Gradle(Module)
  2. Add the xml code to activity.xml or fragment.xml file
    implementation 'androidx.cardview:cardview:1.0.0'

   <androidx.cardview.widget.CardView
      android:layout_width="300dp"
      android:layout_height="270dp"
      android:layout_gravity="center"
      app:cardCornerRadius="150dp"
      app:cardBackgroundColor="@color/trans"
      >
    <ImageView
        android:id="@+id/resultImage"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:src="@drawable/congrats"
        android:layout_gravity="center">

    </ImageView>


  </androidx.cardview.widget.CardView>```

Get list of all input objects using JavaScript, without accessing a form object

(See update at end of answer.)

You can get a NodeList of all of the input elements via getElementsByTagName (DOM specification, MDC, MSDN), then simply loop through it:

var inputs, index;

inputs = document.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
}

There I've used it on the document, which will search the entire document. It also exists on individual elements (DOM specification), allowing you to search only their descendants rather than the whole document, e.g.:

var container, inputs, index;

// Get the container element
container = document.getElementById('container');

// Find its child `input` elements
inputs = container.getElementsByTagName('input');
for (index = 0; index < inputs.length; ++index) {
    // deal with inputs[index] element.
}

...but you've said you don't want to use the parent form, so the first example is more applicable to your question (the second is just there for completeness, in case someone else finding this answer needs to know).


Update: getElementsByTagName is an absolutely fine way to do the above, but what if you want to do something slightly more complicated, like just finding all of the checkboxes instead of all of the input elements?

That's where the useful querySelectorAll comes in: It lets us get a list of elements that match any CSS selector we want. So for our checkboxes example:

var checkboxes = document.querySelectorAll("input[type=checkbox]");

You can also use it at the element level. For instance, if we have a div element in our element variable, we can find all of the spans with the class foo that are inside that div like this:

var fooSpans = element.querySelectorAll("span.foo");

querySelectorAll and its cousin querySelector (which just finds the first matching element instead of giving you a list) are supported by all modern browsers, and also IE8.

Include PHP inside JavaScript (.js) files

There is not any safe way to include php file into js.

One thing you can do as define your php file data as javascript global variable in php file. for example i have three variable which i want to use as js.

abc.php

<?php
$abc = "Abc";
$number = 052;
$mydata = array("val1","val2","val3");
?>
<script type="text/javascript">
var abc = '<?php echo $abc?>';
var number = '<?php echo $number ?>';
var mydata = <?php echo json_encode($mydata); ?>;
</script>

After use it directly in your js file wherever you want to use.

abc.js

function test(){
   alert('Print php variable : '+ abc +', '+number); 
}

function printArrVar(){
  alert('print php array variable : '+ JSON.stringify(mydata)); 
}

Beside If you have any critical data which you don't want to show publicly then you can encrypt data with js. and also get original value of it's from js so no one can get it's original value. if they show into publicly.

this is the standard way you can call php script data into js file without including js into php code or php script into js.

How to set aliases in the Git Bash for Windows?

Using Windows and MINGW64 GitBash ((mintty 3.2.0), i found the file under:

C:\Users\<user name>\AppData\Local\Programs\Git\etc\profile.d\aliases.sh

Just add the alias there and i worked for me

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

Even if above solutions don't work, check permissions to destination file of aws ec2 instance. May be you can try with- sudo chmod 777 -R destinationFolder/*

Change background color of R plot

adjustcolor("blanchedalmond",alpha.f = 0.3)

The above function provides a color code which corresponds to a transparent version of the input color (In this case the input color is "blanchedalmond.").

Input alpha values range on a scale of 0 to 1, 0 being completely transparent and 1 being completely opaque. (In this case, the code for the translucent shad of "blanchedalmond" given an alpha of .3 is "#FFEBCD4D." Be sure to include the hashtag symbol). You can make the new translucent color into the background color by using this function provided by joran earlier in this thread:

rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "blanchedalmond")

By using a translucent color, you can be sure that the graph's data can still be seen underneath after the background color is applied. Hope this helps!

How to find out what type of a Mat object is with Mat::type() in OpenCV

In OpenCV header "types_c.h" there are a set of defines which generate these, the format is CV_bits{U|S|F}C<number_of_channels>
So for example CV_8UC3 means 8 bit unsigned chars, 3 colour channels - each of these names map onto an arbitrary integer with the macros in that file.

Edit: See "types_c.h" for example:

#define CV_8UC3 CV_MAKETYPE(CV_8U,3)
#define CV_MAKETYPE(depth,cn) (CV_MAT_DEPTH(depth) + (((cn)-1) << CV_CN_SHIFT))

eg.
depth = CV_8U = 0
cn = 3
CV_CN_SHIFT = 3

CV_MAT_DEPTH(0) = 0
(((cn)-1) << CV_CN_SHIFT) = (3-1) << 3 = 2<<3 = 16

So CV_8UC3 = 16 but you aren't supposed to use this number, just check type() == CV_8UC3 if you need to know what type an internal OpenCV array is.
Remember OpenCV will convert the jpeg into BGR (or grey scale if you pass '0' to imread) - so it doesn't tell you anything about the original file.

Android Notification Sound

On Oreo (Android 8) and above it should be done for custom sound in this way (notification channels):

Uri soundUri = Uri.parse(
                         "android.resource://" + 
                         getApplicationContext().getPackageName() +
                         "/" + 
                         R.raw.push_sound_file);

AudioAttributes audioAttributes = new AudioAttributes.Builder()
            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
            .setUsage(AudioAttributes.USAGE_ALARM)
            .build();

// Creating Channel
NotificationChannel channel = new NotificationChannel("YOUR_CHANNEL_ID",
                                                      "YOUR_CHANNEL_NAME",
                                                      NotificationManager.IMPORTANCE_HIGH);
channel.setSound(soundUri, audioAttributes);

((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE))
                                           .createNotificationChannel(notificationChannel);

resize font to fit in a div (on one line)

I had a similar issue, which made me write my own plugin for this. Have a look at jquery-quickfit (which is quite similar to Robert Koritnik's solution, which I really like).

In order to prevent the headline to span multiple lines, just add a css style of:

white-space:nowrap;

to the element.

After including jquery and quickfit in the header. You can trigger quickfit with:

$('h1').quickfit();

It meassures and calculates a size invariant meassure for each letter of the text to fit and uses this to calculate the next best font-size which fits the text into the container.

The calculations are cached, which makes it very fast when dealing having to fit multiple text or having to fit a text multiple times, like e.g., on window resize (there is almost no performance penalty on resize).

Demo for a similar situation as yours

Further documentation, examples and source code are on the project page.

How can I set a dynamic model name in AngularJS?

What I ended up doing is something like this:

In the controller:

link: function($scope, $element, $attr) {
  $scope.scope = $scope;  // or $scope.$parent, as needed
  $scope.field = $attr.field = '_suffix';
  $scope.subfield = $attr.sub_node;
  ...

so in the templates I could use totally dynamic names, and not just under a certain hard-coded element (like in your "Answers" case):

<textarea ng-model="scope[field][subfield]"></textarea>

Hope this helps.

Python+OpenCV: cv2.imwrite

This following code should extract face in images and save faces on disk

def detect(image):
    image_faces = []
    bitmap = cv.fromarray(image)
    faces = cv.HaarDetectObjects(bitmap, cascade, cv.CreateMemStorage(0))
    if faces:
        for (x,y,w,h),n in faces:
            image_faces.append(image[y:(y+h), x:(x+w)])
            #cv2.rectangle(image,(x,y),(x+w,y+h),(255,255,255),3)
    return image_faces

if __name__ == "__main__":
    cam = cv2.VideoCapture(0)
    while 1:
        _,frame =cam.read()
        image_faces = []
        image_faces = detect(frame)
        for i, face in enumerate(image_faces):
            cv2.imwrite("face-" + str(i) + ".jpg", face)

        #cv2.imshow("features", frame)
        if cv2.waitKey(1) == 0x1b: # ESC
            print 'ESC pressed. Exiting ...'
            break

Expected response code 250 but got code "530", with message "530 5.7.1 Authentication required

Yep, and if you have tried all the above solutions (what's more likely to happen) and none work for you, it may happen that Guzzle is not installed.

Laravel ships mailing tools, by which is required the Guzzle framework, but it won't be installed, and AS OF the documentation, will have to install it manually: https://laravel.com/docs/master/mail#driver-prerequisites

composer require guzzlehttp/guzzle

Angular get object from array by Id

CASE - 1

Using array.filter() We can get an array of objects which will match with our condition.
see the working example.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function filter(){
  console.clear();
  var filter_id = document.getElementById("filter").value;
  var filter_array = questions.filter(x => x.id == filter_id);
  console.log(filter_array);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
}
_x000D_
<div>
  <label for="filter"></label>
  <input id="filter" type="number" name="filter" placeholder="Enter id which you want to filter">
  <button onclick="filter()">Filter</button>
</div>
_x000D_
_x000D_
_x000D_

CASE - 2

Using array.find() we can get first matched item and break the iteration.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function find(){
  console.clear();
  var find_id = document.getElementById("find").value;
  var find_object = questions.find(x => x.id == find_id);
  console.log(find_object);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
  width: 200px;
}
_x000D_
<div>
  <label for="find"></label>
  <input id="find" type="number" name="find" placeholder="Enter id which you want to find">
  <button onclick="find()">Find</button>
</div>
_x000D_
_x000D_
_x000D_

How do I decrease the size of my sql server log file?

This is one of the best suggestion in which is done using query. Good for those who has a lot of databases just like me. Can run it using a script.

https://medium.com/@bharatdwarkani/shrinking-sql-server-db-log-file-size-sql-server-db-maintenance-7ddb0c331668

USE DatabaseName;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE DatabaseName
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DatabaseName_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE DatabaseName
SET RECOVERY FULL;
GO

Is there a 'foreach' function in Python 3?

This does the foreach in python 3

test = [0,1,2,3,4,5,6,7,8,"test"]

for fetch in test:
    print(fetch)

Xcode source automatic formatting

We can use Xcode Formatter which uses uncrustify to easily format your source code as your team exactly wants to be!.

Installation The recommended way is to clone GitHub project or download it from https://github.com/octo-online/Xcode-formatter and add the CodeFormatter directory in your Xcode project to get : Xcode shortcut-based code formatting: a shortcut to format modified sources in the current workspace automatic code formatting: add a build phase to your project to format current sources when application builds all sources formatting: format all your code with one command line your formatting rules shared by project: edit and use a same configuration file with your project dev team 1) How to setup the code formatter for your project Install uncrustify The simplest way is to use brew: $ brew install uncrustify

To install brew: $ ruby –e “$(curl –fsSkl raw.github.com/mxcl/homebrew/go)”

Check that uncrustify is located in /usr/local/bin $ which uncrustify

If your uncrustify version is lower than 0.60, you might have to install it manually since modern Objective-C syntax has been added recently. Add CodeFormatter directory beside your .xcodeproj file

Check that your Xcode application is named "Xcode" (default name) You can see this name in the Applications/ directory (or your custom Xcode installation directory). Be carefull if you have multiple instances of Xcode on your mac: ensure that project's one is actually named "Xcode"! (Why this ? This name is used to find currently opened Xcode files. See CodeFormatter/Uncrustify_opened_Xcode_sources.workflow appleScript). Install the automator service Uncrustify_opened_Xcode_sources.workflow Copy this file to your ~/Library/Services/ folder (create this folder if needed).Be careful : by double-clicking the .workflow file, you will install it but the file will be removed! Be sure to leave a copy of it for other users.

How to format opened files when building the project Add a build phase "run script" containing the following line:

sh CodeFormatter/scripts/formatOpendSources.sh

How to format files in command line

To format currently opened files, use formatOpenedSources.sh:

$sh CodeFormatter/scripts/formatOpendSources.sh

To format all files, use formatAllSources.sh:

$sh CodeFormatter/scripts/formatAllSources.sh PATH

PATH must be replaced by your sources path.

E:g; if project name is TestApp then the command will be

$sh CodeFormatter/scripts/formatAllSources.sh TestApp

it will look for all files in the project and will format all the files as configured in uncrustify_objective_c.cfg file.

How to change formatter’s rules

Edit CodeFormatter/uncrustify_objective_c.cfg open with TextEdit

How to transform numpy.matrix or array to scipy sparse matrix

You can pass a numpy array or matrix as an argument when initializing a sparse matrix. For a CSR matrix, for example, you can do the following.

>>> import numpy as np
>>> from scipy import sparse
>>> A = np.array([[1,2,0],[0,0,3],[1,0,4]])
>>> B = np.matrix([[1,2,0],[0,0,3],[1,0,4]])

>>> A
array([[1, 2, 0],
       [0, 0, 3],
       [1, 0, 4]])

>>> sA = sparse.csr_matrix(A)   # Here's the initialization of the sparse matrix.
>>> sB = sparse.csr_matrix(B)

>>> sA
<3x3 sparse matrix of type '<type 'numpy.int32'>'
        with 5 stored elements in Compressed Sparse Row format>

>>> print sA
  (0, 0)        1
  (0, 1)        2
  (1, 2)        3
  (2, 0)        1
  (2, 2)        4

Remove privileges from MySQL database

As a side note, the reason revoke usage on *.* from 'phpmyadmin'@'localhost'; does not work is quite simple : There is no grant called USAGE.

The actual named grants are in the MySQL Documentation

The grant USAGE is a logical grant. How? 'phpmyadmin'@'localhost' has an entry in mysql.user where user='phpmyadmin' and host='localhost'. Any row in mysql.user semantically means USAGE. Running DROP USER 'phpmyadmin'@'localhost'; should work just fine. Under the hood, it's really doing this:

DELETE FROM mysql.user WHERE user='phpmyadmin' and host='localhost';
DELETE FROM mysql.db   WHERE user='phpmyadmin' and host='localhost';
FLUSH PRIVILEGES;

Therefore, the removal of a row from mysql.user constitutes running REVOKE USAGE, even though REVOKE USAGE cannot literally be executed.

Difference between "managed" and "unmanaged"

Managed code is a differentiation coined by Microsoft to identify computer program code that requires and will only execute under the "management" of a Common Language Runtime virtual machine (resulting in Bytecode).

http://en.wikipedia.org/wiki/Managed_code

http://www.developer.com/net/cplus/article.php/2197621/Managed-Unmanaged-Native-What-Kind-of-Code-Is-This.htm

Is it possible to install another version of Python to Virtualenv?

First of all, Thank you DTing for awesome answer. It's pretty much perfect.

For those who are suffering from not having GCC access in shared hosting, Go for ActivePython instead of normal python like Scott Stafford mentioned. Here are the commands for that.

wget http://downloads.activestate.com/ActivePython/releases/2.7.13.2713/ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

tar -zxvf ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785.tar.gz

cd ActivePython-2.7.13.2713-linux-x86_64-glibc-2.3.6-401785

./install.sh

It will ask you path to python directory. Enter

../../.localpython

Just replace above as Step 1 in DTing's answer and go ahead with Step 2 after that. Please note that ActivePython package URL may change with new release. You can always get new URL from here : http://www.activestate.com/activepython/downloads

Based on URL you need to change the name of tar and cd command based on file received.

How to get video duration, dimension and size in PHP?

https://github.com/JamesHeinrich/getID3 download getid3 zip and than only getid3 named folder copy paste in project folder and use it as below show...

<?php
        require_once('/fire/scripts/lib/getid3/getid3/getid3.php');
        $getID3 = new getID3();
        $filename="/fire/My Documents/video/ferrari1.mpg";
        $fileinfo = $getID3->analyze($filename);

        $width=$fileinfo['video']['resolution_x'];
        $height=$fileinfo['video']['resolution_y'];

        echo $fileinfo['video']['resolution_x']. 'x'. $fileinfo['video']['resolution_y'];
        echo '<pre>';print_r($fileinfo);echo '</pre>';
?>

How to loop through all the files in a directory in c # .net?

You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.

http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori

How to ssh connect through python Paramiko with ppk public key

To create a valid DSA format private key supported by Paramiko in Puttygen.

Click on Conversions then Export OpenSSH Key

enter image description here

Generating PDF files with JavaScript

Another javascript library worth mentioning is pdfmake.

The browser support does not appear to be as strong as jsPDF, nor does there seem to be an option for shapes, but the options for formatting text are more advanced then the options currently available in jsPDF.

CSS transition effect makes image blurry / moves image 1px, in Chrome?

I cheated problem using transition by steps, not smoothly

transition-timing-function: steps(10, end);

It is not a solving, it is a cheating and can not be applied everywhere.

I can't explain it, but it works for me. None of another answers helps me (OSX, Chrome 63, Non-Retina display).

https://jsfiddle.net/tuzae6a9/6/

Can Android Studio be used to run standard Java projects?

Spent a day on finding the easiest way to do this. The purpose was to find the fastest way to achieve this goal. I couldn't make it as fast as running javac command from terminal or compiling from netbeans or sublime text 3. But still got a good speed with android studio.

This looks ruff and tuff way but since we don't initiate projects on daily bases that is why I am okay to do this.

I downloaded IntelliJ IDEA community version and created a simply java project. I added a main class and tested a run. Then simply closed IntelliJ IDEA and opened Android Studio and opened the same project there. Then I had to simply attach JDK where IDE helped me by showing a list of available JDKs and I selected 1.8 and then it compiled well. I can now open any main file and press Control+Shift+R to run that main file.

Then I copied all my Java files into src folder by Mac OS Finder. And I am able to compile anything I want to.

There is nothing related to Gradle or Android and compile speed is pretty good.

Thanks buddies

How can I change eclipse's Internal Browser from IE to Firefox on Windows XP?

I don't know if this will help, but here's the SWT FAQ question How do I use Mozilla as the Browser's underlying renderer?

Edit: Having researched this further, it sounds like this isn't possible in Eclipse 3.4, but may be slated for a later release.

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

Trying to build HelloWorld app on Ubuntu 16.04. Got error with drawable/icon. Solution could be:

cp ./platforms/android/build/intermediates/exploded-aar/com.android.support/design/25.3.1/res/drawable/navigation_empty_icon.xml    ./platforms/android/build/intermediates/exploded-aar/com.android.support/design/25.3.1/res/drawable/icon.xml

So, it look like icon.xml file missed.

How to send a GET request from PHP?

Depending on whether your php setup allows fopen on URLs, you could also simply fopen the url with the get arguments in the string (such as http://example.com?variable=value )

Edit: Re-reading the question I'm not certain whether you're looking to pass variables or not - if you're not you can simply send the fopen request containg http://example.com/filename.xml - feel free to ignore the variable=value part

How to validate a url in Python? (Malformed or not)

EDIT

As pointed out by @Kwame , the below code does validate the url even if the .com or .co etc are not present.

also pointed out by @Blaise, URLs like https://www.google is a valid URL and you need to do a DNS check for checking if it resolves or not, separately.

This is simple and works:

So min_attr contains the basic set of strings that needs to be present to define the validity of a URL, i.e http:// part and google.com part.

urlparse.scheme stores http:// and

urlparse.netloc store the domain name google.com

from urlparse import urlparse
def url_check(url):

    min_attr = ('scheme' , 'netloc')
    try:
        result = urlparse(url)
        if all([result.scheme, result.netloc]):
            return True
        else:
            return False
    except:
        return False

all() returns true if all the variables inside it return true. So if result.scheme and result.netloc is present i.e. has some value then the URL is valid and hence returns True.

What are the uses of "using" in C#?

Just adding a little something that I was surprised did not come up. The most interesting feature of using (in my opinion) is that no mater how you exit the using block, it will always dispose the object. This includes returns and exceptions.

using (var db = new DbContext())
{
    if(db.State == State.Closed) throw new Exception("Database connection is closed.");
    return db.Something.ToList();
}

It doesn't matter if the exception is thrown or the list is returned. The DbContext object will always be disposed.

How to create a QR code reader in a HTML5 website?

Reader they show at http://www.webqr.com/index.html works like a charm, but literaly, you need the one on the webpage, the github version it's really hard to make it work, however, it is possible. The best way to go is reverse-engineer the example shown at the webpage.

However, to edit and get the full potential out of it, it's not so easy. At some point I may post the stripped-down reverse-engineered QR reader, but in the meantime have some fun hacking the code.

Happy coding.

How can you change Network settings (IP Address, DNS, WINS, Host Name) with code in C#

A far more clear solution is to use the command netsh to change the IP (or setting it back to DHCP)

netsh interface ip set address "Local Area Connection" static 192.168.0.10 255.255.255.0

Where "Local Area Connection" is the name of the network adapter. You could find it in the windows Network Connections, sometimes it is simply named "Ethernet".

Here are two methods to set the IP and also to set the IP back to DHCP "Obtain an IP address automatically"

public bool SetIP(string networkInterfaceName, string ipAddress, string subnetMask, string gateway = null)
{
    var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
    var ipProperties = networkInterface.GetIPProperties();
    var ipInfo = ipProperties.UnicastAddresses.FirstOrDefault(ip => ip.Address.AddressFamily == AddressFamily.InterNetwork);
    var currentIPaddress = ipInfo.Address.ToString();
    var currentSubnetMask = ipInfo.IPv4Mask.ToString();
    var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;

    if (!isDHCPenabled && currentIPaddress == ipAddress && currentSubnetMask == subnetMask)
        return true;    // no change necessary

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" static {ipAddress} {subnetMask}" + (string.IsNullOrWhiteSpace(gateway) ? "" : $"{gateway} 1")) { Verb = "runas" }
    };
    process.Start();
    var successful = process.ExitCode == 0;
    process.Dispose();
    return successful;
}

public bool SetDHCP(string networkInterfaceName)
{
    var networkInterface = NetworkInterface.GetAllNetworkInterfaces().FirstOrDefault(nw => nw.Name == networkInterfaceName);
    var ipProperties = networkInterface.GetIPProperties();
    var isDHCPenabled = ipProperties.GetIPv4Properties().IsDhcpEnabled;

    if (isDHCPenabled)
        return true;    // no change necessary

    var process = new Process
    {
        StartInfo = new ProcessStartInfo("netsh", $"interface ip set address \"{networkInterfaceName}\" dhcp") { Verb = "runas" }
    };
    process.Start();
    var successful = process.ExitCode == 0;
    process.Dispose();
    return successful;
}

What exactly is nullptr?

Why nullptr in C++11? What is it? Why is NULL not sufficient?

C++ expert Alex Allain says it perfectly here (my emphasis added in bold):

...imagine you have the following two function declarations:

void func(int n); 
void func(char *s);

func( NULL ); // guess which function gets called?

Although it looks like the second function will be called--you are, after all, passing in what seems to be a pointer--it's really the first function that will be called! The trouble is that because NULL is 0, and 0 is an integer, the first version of func will be called instead. This is the kind of thing that, yes, doesn't happen all the time, but when it does happen, is extremely frustrating and confusing. If you didn't know the details of what is going on, it might well look like a compiler bug. A language feature that looks like a compiler bug is, well, not something you want.

Enter nullptr. In C++11, nullptr is a new keyword that can (and should!) be used to represent NULL pointers; in other words, wherever you were writing NULL before, you should use nullptr instead. It's no more clear to you, the programmer, (everyone knows what NULL means), but it's more explicit to the compiler, which will no longer see 0s everywhere being used to have special meaning when used as a pointer.

Allain ends his article with:

Regardless of all this--the rule of thumb for C++11 is simply to start using nullptr whenever you would have otherwise used NULL in the past.

(My words):

Lastly, don't forget that nullptr is an object--a class. It can be used anywhere NULL was used before, but if you need its type for some reason, it's type can be extracted with decltype(nullptr), or directly described as std::nullptr_t, which is simply a typedef of decltype(nullptr).

References:

  1. Cprogramming.com: Better types in C++11 - nullptr, enum classes (strongly typed enumerations) and cstdint
  2. https://en.cppreference.com/w/cpp/language/decltype
  3. https://en.cppreference.com/w/cpp/types/nullptr_t

How do I make a WinForms app go Full Screen

A tested and simple solution

I've been looking for an answer for this question in SO and some other sites, but one gave an answer was very complex to me and some others answers simply doesn't work correctly, so after a lot code testing I solved this puzzle.

Note: I'm using Windows 8 and my taskbar isn't on auto-hide mode.

I discovered that setting the WindowState to Normal before performing any modifications will stop the error with the not covered taskbar.

The code

I created this class that have two methods, the first enters in the "full screen mode" and the second leaves the "full screen mode". So you just need to create an object of this class and pass the Form you want to set full screen as an argument to the EnterFullScreenMode method or to the LeaveFullScreenMode method:

class FullScreen
{
    public void EnterFullScreenMode(Form targetForm)
    {
        targetForm.WindowState = FormWindowState.Normal;
        targetForm.FormBorderStyle = FormBorderStyle.None;
        targetForm.WindowState = FormWindowState.Maximized;
    }

    public void LeaveFullScreenMode(Form targetForm)
    {
        targetForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Sizable;
        targetForm.WindowState = FormWindowState.Normal;
    }
}

Usage example

    private void fullScreenToolStripMenuItem_Click(object sender, EventArgs e)
    {
        FullScreen fullScreen = new FullScreen();

        if (fullScreenMode == FullScreenMode.No)  // FullScreenMode is an enum
        {
            fullScreen.EnterFullScreenMode(this);
            fullScreenMode = FullScreenMode.Yes;
        }
        else
        {
            fullScreen.LeaveFullScreenMode(this);
            fullScreenMode = FullScreenMode.No;
        }
    }

I have placed this same answer on another question that I'm not sure if is a duplicate or not of this one. (Link to the other question: How to display a Windows Form in full screen on top of the taskbar?)

What data type to use for hashed password field and what length?

Always use a password hashing algorithm: Argon2, scrypt, bcrypt or PBKDF2.

Argon2 won the 2015 password hashing competition. Scrypt, bcrypt and PBKDF2 are older algorithms that are considered less preferred now, but still fundamentally sound, so if your platform doesn't support Argon2 yet, it's ok to use another algorithm for now.

Never store a password directly in a database. Don't encrypt it, either: otherwise, if your site gets breached, the attacker gets the decryption key and so can obtain all passwords. Passwords MUST be hashed.

A password hash has different properties from a hash table hash or a cryptographic hash. Never use an ordinary cryptographic hash such as MD5, SHA-256 or SHA-512 on a password. A password hashing algorithm uses a salt, which is unique (not used for any other user or in anybody else's database). The salt is necessary so that attackers can't just pre-calculate the hashes of common passwords: with a salt, they have to restart the calculation for every account. A password hashing algorithm is intrinsically slow — as slow as you can afford. Slowness hurts the attacker a lot more than you because the attacker has to try many different passwords. For more information, see How to securely hash passwords.

A password hash encodes four pieces of information:

  • An indicator of which algorithm is used. This is necessary for agility: cryptographic recommendations change over time. You need to be able to transition to a new algorithm.
  • A difficulty or hardness indicator. The higher this value, the more computation is needed to calculate the hash. This should be a constant or a global configuration value in the password change function, but it should increase over time as computers get faster, so you need to remember the value for each account. Some algorithms have a single numerical value, others have more parameters there (for example to tune CPU usage and RAM usage separately).
  • The salt. Since the salt must be globally unique, it has to be stored for each account. The salt should be generated randomly on each password change.
  • The hash proper, i.e. the output of the mathematical calculation in the hashing algorithm.

Many libraries include a pair functions that conveniently packages this information as a single string: one that takes the algorithm indicator, the hardness indicator and the password, generates a random salt and returns the full hash string; and one that takes a password and the full hash string as input and returns a boolean indicating whether the password was correct. There's no universal standard, but a common encoding is

$algorithm$parameters$salt$output

where algorithm is a number or a short alphanumeric string encoding the choice of algorithm, parameters is a printable string, and salt and output are encoded in Base64 without terminating =.

16 bytes are enough for the salt and the output. (See e.g. recommendations for Argon2.) Encoded in Base64, that's 21 characters each. The other two parts depend on the algorithm and parameters, but 20–40 characters are typical. That's a total of about 82 ASCII characters (CHAR(82), and no need for Unicode), to which you should add a safety margin if you think it's going to be difficult to enlarge the field later.

If you encode the hash in a binary format, you can get it down to 1 byte for the algorithm, 1–4 bytes for the hardness (if you hard-code some of the parameters), and 16 bytes each for the salt and output, for a total of 37 bytes. Say 40 bytes (BINARY(40)) to have at least a couple of spare bytes. Note that these are 8-bit bytes, not printable characters, in particular the field can include null bytes.

Note that the length of the hash is completely unrelated to the length of the password.

open existing java project in eclipse

  1. File -> Import -> Existing Project into Workspace
  2. Browse for that directory.

Alternative: Check out the code in SVN to some folder

  1. Create a new folder in windows
  2. In eclipse File -> switchWorkspace -> newFolderName
  3. close the welcome window in eclipse
  4. In eclipse File -> Import -> Existing project into workspce-> select root dir -> browse and show the svn checkout folder

Message: Trying to access array offset on value of type null

This happens because $cOTLdata is not null but the index 'char_data' does not exist. Previous versions of PHP may have been less strict on such mistakes and silently swallowed the error / notice while 7.4 does not do this anymore.

To check whether the index exists or not you can use isset():

isset($cOTLdata['char_data'])

Which means the line should look something like this:

$len = isset($cOTLdata['char_data']) ? count($cOTLdata['char_data']) : 0;

Note I switched the then and else cases of the ternary operator since === null is essentially what isset already does (but in the positive case).

Send password when using scp to copy files from one server to another

You should use better authentication with open keys. In these case you need no password and no expect.

If you want it with expect, use this script (see answer Automate scp file transfer using a shell script ):

#!/usr/bin/expect -f

# connect via scp
    spawn scp "[email protected]:/home/santhosh/file.dmp" /u01/dumps/file.dmp
#######################
expect {
-re ".*es.*o.*" {
    exp_send "yes\r"
    exp_continue
}
-re ".*sword.*" {
    exp_send "PASSWORD\r"
}
}
interact

Also, you can use pexpect (python module):

def doScp(user,password, host, path, files):
 fNames = ' '.join(files)
 print fNames
 child = pexpect.spawn('scp %s %s@%s:%s' % (fNames, user, host,path))
 print 'scp %s %s@%s:%s' % (fNames, user, host,path)
    i = child.expect(['assword:', r"yes/no"], timeout=30)
    if i == 0:
        child.sendline(password)
    elif i == 1:
        child.sendline("yes")
        child.expect("assword:", timeout=30)
        child.sendline(password)
    data = child.read()
    print data
    child.close()

log4j configuration via JVM argument(s)?

Do you have a log4j configuration file ? Just reference it using

-Dlog4j.configuration={path to file}

where {path to file} should be prefixed with file:

Edit: If you are working with log4j2, you need to use

-Dlog4j.configurationFile={path to file}

Taken from answer https://stackoverflow.com/a/34001970/552525

Rails DB Migration - How To Drop a Table?

ActiveRecord::Base.connection.drop_table :table_name

failed to push some refs to [email protected]

Also, make sure your branch is clean and there is nothing unstaged you can check with git status stash or commit the changes then run the comand

OVER clause in Oracle

Another way to use OVER is to have a result column in your select operate on another "partition", so to say.

This:

SELECT 
    name, 
    ssn, 
    case 
      when ( count(*) over (partition by ssn) ) > 1      
      then 1
      else 0
    end AS hasDuplicateSsn
FROM table;

returns 1 in hasDuplicateSsn for each row whose ssn is shared by another row. Great for making "tags" for data for different error reports and such.

exit application when click button - iOS

You can use exit method to quit an ios app :

exit(0);

You should say same alert message and ask him to quit

Another way is by using [[NSThread mainThread] exit]

However you should not do this way

According to Apple, your app should not terminate on its own. Since the user did not hit the Home button, any return to the Home screen gives the user the impression that your app crashed. This is confusing, non-standard behavior and should be avoided.

How can I get city name from a latitude and longitude point?

Following Code Works Fine to Get City Name (Using Google Map Geo API) :

HTML

<p><button onclick="getLocation()">Get My Location</button></p>
<p id="demo"></p>
<script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>

SCRIPT

var x=document.getElementById("demo");
function getLocation(){
    if (navigator.geolocation){
        navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
    else{
        x.innerHTML="Geolocation is not supported by this browser.";
    }
}

function showPosition(position){
    lat=position.coords.latitude;
    lon=position.coords.longitude;
    displayLocation(lat,lon);
}

function showError(error){
    switch(error.code){
        case error.PERMISSION_DENIED:
            x.innerHTML="User denied the request for Geolocation."
        break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML="Location information is unavailable."
        break;
        case error.TIMEOUT:
            x.innerHTML="The request to get user location timed out."
        break;
        case error.UNKNOWN_ERROR:
            x.innerHTML="An unknown error occurred."
        break;
    }
}

function displayLocation(latitude,longitude){
    var geocoder;
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(latitude, longitude);

    geocoder.geocode(
        {'latLng': latlng}, 
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var add= results[0].formatted_address ;
                    var  value=add.split(",");

                    count=value.length;
                    country=value[count-1];
                    state=value[count-2];
                    city=value[count-3];
                    x.innerHTML = "city name is: " + city;
                }
                else  {
                    x.innerHTML = "address not found";
                }
            }
            else {
                x.innerHTML = "Geocoder failed due to: " + status;
            }
        }
    );
}

regex string replace

Your character class (the part in the square brackets) is saying that you want to match anything except 0-9 and a-z and +. You aren't explicit about how many a-z or 0-9 you want to match, but I assume the + means you want to replace strings of at least one alphanumeric character. It should read instead:

str = str.replace(/[^-a-z0-9]+/g, "");

Also, if you need to match upper-case letters along with lower case, you should use:

str = str.replace(/[^-a-zA-Z0-9]+/g, "");

PHP - how to create a newline character?

w3school offered this way:

echo nl2br("One line.\n Another line.");

by use of this function you can do it..i tried other ways that said above but they wont help me..

How to make popup look at the centre of the screen?

/*--------  Bootstrap Modal Popup in Center of Screen --------------*/
/*---------------extra css------*/
.modal {
    text-align: center;
    padding: 0 !important;
}
.modal:before {
    content: '';
    display: inline-block;
    height: 100%;
    vertical-align: middle;
    margin-right: -4px;
}
.modal-dialog {
    display: inline-block;
    text-align: left;
    vertical-align: middle;
}
/*----- Modal Popup -------*/
<div class="modal fade" role="dialog">
    <div class="modal-dialog" >
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">×</span>
                </button>
                <h5 class="modal-title">Header</h5>
            </div>
            <div class="modal-body">
               body here     
             </div>
        <div class="modal-footer">            
            <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
        </div>
    </div>
</div>
</div>

How to redirect 404 errors to a page in ExpressJS?

you can error handling according to content-type

Additionally, handling according to status code.

app.js

import express from 'express';

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// when status is 404, error handler
app.use(function(err, req, res, next) {
    // set locals, only providing error in development
    res.locals.message = err.message;
    res.locals.error = req.app.get('env') === 'development' ? err : {};

    // render the error page
    res.status(err.status || 500);
    if( 404 === err.status  ){
        res.format({
            'text/plain': () => {
                res.send({message: 'not found Data'});
            },
            'text/html': () => {
                res.render('404.jade');
            },
            'application/json': () => {
                res.send({message: 'not found Data'});
            },
            'default': () => {
                res.status(406).send('Not Acceptable');
            }
        })
    }

    // when status is 500, error handler
    if(500 === err.status) {
        return res.send({message: 'error occur'});
    }
});

404.jade

doctype html

html
  head
    title 404 Not Found

    meta(http-equiv="Content-Type" content="text/html; charset=utf-8")
    meta(name = "viewport" content="width=device-width, initial-scale=1.0 user-scalable=no")

  body
      h2 Not Found Page
      h2 404 Error Code

If you can using res.format, You can write simple error handling code.

Recommendation res.format() instead of res.accepts().

If the 500 error occurs in the previous code, if(500 == err.status){. . . } is called

selecting from multi-index pandas

Understanding how to access multi-indexed pandas DataFrame can help you with all kinds of task like that.

Copy paste this in your code to generate example:

# hierarchical indices and columns
index = pd.MultiIndex.from_product([[2013, 2014], [1, 2]],
                                   names=['year', 'visit'])
columns = pd.MultiIndex.from_product([['Bob', 'Guido', 'Sue'], ['HR', 'Temp']],
                                     names=['subject', 'type'])

# mock some data
data = np.round(np.random.randn(4, 6), 1)
data[:, ::2] *= 10
data += 37

# create the DataFrame
health_data = pd.DataFrame(data, index=index, columns=columns)
health_data

Will give you table like this:

enter image description here

Standard access by column

health_data['Bob']
type       HR   Temp
year visit      
2013    1   22.0    38.6
        2   52.0    38.3
2014    1   30.0    38.9
        2   31.0    37.3


health_data['Bob']['HR']
year  visit
2013  1        22.0
      2        52.0
2014  1        30.0
      2        31.0
Name: HR, dtype: float64

# filtering by column/subcolumn - your case:
health_data['Bob']['HR']==22
year  visit
2013  1         True
      2        False
2014  1        False
      2        False

health_data['Bob']['HR'][2013]    
visit
1    22.0
2    52.0
Name: HR, dtype: float64

health_data['Bob']['HR'][2013][1]
22.0

Access by row

health_data.loc[2013]
subject Bob Guido   Sue
type    HR  Temp    HR  Temp    HR  Temp
visit                       
1   22.0    38.6    40.0    38.9    53.0    37.5
2   52.0    38.3    42.0    34.6    30.0    37.7

health_data.loc[2013,1] 
subject  type
Bob      HR      22.0
         Temp    38.6
Guido    HR      40.0
         Temp    38.9
Sue      HR      53.0
         Temp    37.5
Name: (2013, 1), dtype: float64

health_data.loc[2013,1]['Bob']
type
HR      22.0
Temp    38.6
Name: (2013, 1), dtype: float64

health_data.loc[2013,1]['Bob']['HR']
22.0

Slicing multi-index

idx=pd.IndexSlice
health_data.loc[idx[:,1], idx[:,'HR']]
    subject Bob Guido   Sue
type    HR  HR  HR
year    visit           
2013    1   22.0    40.0    53.0
2014    1   30.0    52.0    45.0

CodeIgniter: "Unable to load the requested class"

If you're using a linux server for your application then it is necessary to use lowercase file name and class name to avoid this issue.

Ex.

Filename: csvsample.php

class csvsample {

}

In bootstrap how to add borders to rows without adding up?

Here is one solution:

div.row { 
  border: 1px solid;
  border-bottom: 0px;
}
.container div.row:last-child {
  border-bottom: 1px solid;
}

I'm not 100% its the most effiecent, but it works :D

http://jsfiddle.net/aaronmallen/7cb3Y/2/

How to restore the dump into your running mongodb

You can also restore your downloaded Atlas Backup .wt WiredTiger files (which unzips or untar as a restore folder) to your local MongoDB.

First, make a backup of your /data/db path. Call it /data_20200407/db. Second, copy paste all the .wt files from your Atlas Backup restore folder into your local /data/db path. Restart your Ubuntu or MongoDB server. Start your Mongo shell and you should have those restored files there.

How to clone an InputStream?

You can't clone it, and how you are going to solve your problem depends on what the source of the data is.

One solution is to read all data from the InputStream into a byte array, and then create a ByteArrayInputStream around that byte array, and pass that input stream into your method.

Edit 1: That is, if the other method also needs to read the same data. I.e you want to "reset" the stream.

how to change color of TextinputLayout's label and edittext underline android

Works for me. If you trying EditText with Label and trying change to underline color use this. Change to TextInputEditText instead EditText.

           <com.google.android.material.textfield.TextInputLayout
                android:id="@+id/editTextTextPersonName3"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginStart="@dimen/_16sdp"
                android:layout_marginLeft="@dimen/_16sdp"
                android:layout_marginTop="@dimen/_16sdp"
                android:layout_marginEnd="@dimen/_8sdp"
                android:layout_marginRight="@dimen/_8sdp"
                android:textColorHint="@color/white"
                app:layout_constraintEnd_toStartOf="@+id/guideline3"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent">

                <EditText
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:backgroundTint="@color/white"
                    android:hint="Lastname"
                    android:textSize="@dimen/_14sdp"
                    android:inputType="textPersonName"
                    android:textColor="@color/white"
                    android:textColorHint="@color/white" />
            </com.google.android.material.textfield.TextInputLayout>

Installation of SQL Server Business Intelligence Development Studio

I figured it out and posted the answer in Can't run Business Intelligence Development Studio, file is not found.

I had this same problem. I am running .NET framework 3.5, SQL Server 2005, and Visual Studio 2008. While I was trying to run SQL Server Business Intelligence Development Studio the icon was grayed out and the devenv.exe file was not found.

I hope this helps.

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

Could not load file or assembly 'Microsoft.ReportViewer.Webforms' or

Could not load file or assembly 'Microsoft.ReportViewer.Common'

This issue occured for me in Visual studio 2015.

Reason:

the reference for Microsoft.ReportViewer.Webforms dll is missing.

Possible Fix

Step1:

To add "Microsoft.ReportViewer.Webforms.dll" to the solution.

Navigate to Nuget Package Manager Console as

"Tools-->NugetPackageManager-->Package Manager Console".

Then enter the following command in console as below

PM>Install-Package Microsoft.ReportViewer.Runtime.WebForms

Then it will install the Reportviewer.webforms dll in "..\packages\Microsoft.ReportViewer.Runtime.WebForms.12.0.2402.15\lib" (Your project folder path)

and ReportViewer.Runtime.Common dll in "..\packages\Microsoft.ReportViewer.Runtime.Common.12.0.2402.15\lib". (Your project folder path)

Step2:-

Remove the existing reference of "Microsoft.ReportViewer.WebForms". we need to refer these dll files in our Solution as "Right click Solution >References-->Add reference-->browse ". Add both the dll files from the above paths.

Step3:

Change the web.Config File to point out to Visual Studio 2015. comment out both the Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common version 11.0.0.0 and Uncomment both the Microsoft.ReportViewer.WebForms and Microsoft.ReportViewer.Common Version=12.0.0.0. as attached in screenshot.

Microsoft.ReportViewer.Webforms/Microsoft.ReportViewer.Common

Also refer the link below.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

How to take input in an array + PYTHON?

You want this - enter N and then take N number of elements.I am considering your input case is just like this

5
2 3 6 6 5

have this in this way in python 3.x (for python 2.x use raw_input() instead if input())

Python 3

n = int(input())
arr = input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])

Python 2

n = int(raw_input())
arr = raw_input()   # takes the whole line of n numbers
l = list(map(int,arr.split(' '))) # split those numbers with space( becomes ['2','3','6','6','5']) and then map every element into int (becomes [2,3,6,6,5])

Parameter in like clause JPQL

Just leave out the ''

LIKE %:code%

Java escape JSON String?

public static String ecapse(String jsString) {
    jsString = jsString.replace("\\", "\\\\");
    jsString = jsString.replace("\"", "\\\"");
    jsString = jsString.replace("\b", "\\b");
    jsString = jsString.replace("\f", "\\f");
    jsString = jsString.replace("\n", "\\n");
    jsString = jsString.replace("\r", "\\r");
    jsString = jsString.replace("\t", "\\t");
    jsString = jsString.replace("/", "\\/");
    return jsString;
}

Delegates in swift?

First class:

protocol NetworkServiceDelegate: class {

    func didCompleteRequest(result: String)
}


class NetworkService: NSObject {

    weak var delegate: NetworkServiceDelegate?

    func fetchDataFromURL(url : String) {
        delegate?.didCompleteRequest(url)
    }
}

Second class:

class ViewController: UIViewController, NetworkServiceDelegate {

    let network = NetworkService()

    override func viewDidLoad() {
        super.viewDidLoad()
        network.delegate = self
        network.fetchDataFromURL("Success!")
    }



    func didCompleteRequest(result: String) {
        print(result)
    }


}

How to set table name in dynamic SQL query?

To help guard against SQL injection, I normally try to use functions wherever possible. In this case, you could do:

...
SET @TableName = '<[db].><[schema].>tblEmployees'
SET @TableID   = OBJECT_ID(TableName) --won't resolve if malformed/injected.
...
SET @SQLQuery = 'SELECT * FROM ' + OBJECT_NAME(@TableID) + ' WHERE EmployeeID = @EmpID' 

Application_Start not firing?

I had this problem when trying to initialize log4net. I decided to just make a static constructor for the Global.asax

static Global(){
//Do your initialization here statically
}

What's the actual use of 'fail' in JUnit test case?

I think the usual use case is to call it when no exception was thrown in a negative test.

Something like the following pseudo-code:

test_addNilThrowsNullPointerException()
{
    try {
        foo.add(NIL);                      // we expect a NullPointerException here
        fail("No NullPointerException");   // cause the test to fail if we reach this            
     } catch (NullNullPointerException e) {
        // OK got the expected exception
    }
}

How can I set the 'backend' in matplotlib in Python?

FYI, I found I needed to put matplotlib.use('Agg') first in Python import order. For what I was doing (unit testing needed to be headless) that meant putting

import matplotlib
matplotlib.use('Agg')

at the top of my master test script. I didn't have to touch any other files.

how to play video from url

You can do it using FullscreenVideoView class. Its a small library project. It's video progress dialog is build in. it's gradle is :

compile 'com.github.rtoshiro.fullscreenvideoview:fullscreenvideoview:1.1.0'

your VideoView xml is like this

<com.github.rtoshiro.view.video.FullscreenVideoLayout
        android:id="@+id/videoview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

In your activity , initialize it using this way:

    FullscreenVideoLayout videoLayout;

videoLayout = (FullscreenVideoLayout) findViewById(R.id.videoview);
        videoLayout.setActivity(this);

        Uri videoUri = Uri.parse("YOUR_VIDEO_URL");
        try {
            videoLayout.setVideoURI(videoUri);

        } catch (IOException e) {
            e.printStackTrace();
        }

That's it. Happy coding :)

If want to know more then visit here

Edit: gradle path has been updated. compile it now

compile 'com.github.rtoshiro.fullscreenvideoview:fullscreenvideoview:1.1.2'

Difference between using Throwable and Exception in a try catch

By catching Throwable it includes things that subclass Error. You should generally not do that, except perhaps at the very highest "catch all" level of a thread where you want to log or otherwise handle absolutely everything that can go wrong. It would be more typical in a framework type application (for example an application server or a testing framework) where it can be running unknown code and should not be affected by anything that goes wrong with that code, as much as possible.

Slidedown and slideup layout with animation

I had a similar requirement in the app I am working on. And, I found a third-party library which does a slide-up, slide-down and slide-right in Android.

Refer to the link for more details: https://github.com/mancj/SlideUp-Android

To set up the library(copied from the ReadMe portion of its Github page on request):

Get SlideUp library

Add the JitPack repository to your build file. Add it in your root build.gradle at the end of repositories:

allprojects {
  repositories {
    ...
    maven { url 'https://jitpack.io' }
    maven { url "https://maven.google.com" } // or google() in AS 3.0
  }
}

Add the dependency (in the Module gradle)

dependencies {
    compile 'com.github.mancj:SlideUp-Android:2.2.1'
    compile 'ru.ztrap:RxSlideUp2:2.x.x' //optional, for reactive listeners based on RxJava-2
    compile 'ru.ztrap:RxSlideUp:1.x.x' //optional, for reactive listeners based on RxJava
}

To add the SlideUp into your project, follow these three simple steps:

Step 1:

create any type of layout

<LinearLayout
  android:id="@+id/slideView"
  android:layout_width="match_parent"
  android:layout_height="match_parent"/>

Step 2:

Find that view in your activity/fragment

View slideView = findViewById(R.id.slideView);

Step 3:

Create a SlideUp object and pass in your view

slideUp = new SlideUpBuilder(slideView)
                .withStartState(SlideUp.State.HIDDEN)
                .withStartGravity(Gravity.BOTTOM)

                //.withSlideFromOtherView(anotherView)
                //.withGesturesEnabled()
                //.withHideSoftInputWhenDisplayed()
                //.withInterpolator()
                //.withAutoSlideDuration()
                //.withLoggingEnabled()
                //.withTouchableAreaPx()
                //.withTouchableAreaDp()
                //.withListeners()
                //.withSavedState()
                .build();

You may also refer to the sample project on the link. I found it quite useful.

How to convert a Base64 string into a Bitmap image to show it in a ImageView?

You can just basically revert your code using some other built in methods.

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

Statistics: combinations in Python

If your program has an upper bound to n (say n <= N) and needs to repeatedly compute nCr (preferably for >>N times), using lru_cache can give you a huge performance boost:

from functools import lru_cache

@lru_cache(maxsize=None)
def nCr(n, r):
    return 1 if r == 0 or r == n else nCr(n - 1, r - 1) + nCr(n - 1, r)

Constructing the cache (which is done implicitly) takes up to O(N^2) time. Any subsequent calls to nCr will return in O(1).

How to display a list of images in a ListView in Android?

I'd start with something like this (and if there is something wrong with my code, I'd of course appreciate any comment):

public class ItemsList extends ListActivity {

private ItemsAdapter adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.items_list);

    this.adapter = new ItemsAdapter(this, R.layout.items_list_item, ItemManager.getLoadedItems());
    setListAdapter(this.adapter);
}

private class ItemsAdapter extends ArrayAdapter<Item> {

    private Item[] items;

    public ItemsAdapter(Context context, int textViewResourceId, Item[] items) {
        super(context, textViewResourceId, items);
        this.items = items;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        View v = convertView;
        if (v == null) {
            LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            v = vi.inflate(R.layout.items_list_item, null);
        }

        Item it = items[position];
        if (it != null) {
            ImageView iv = (ImageView) v.findViewById(R.id.list_item_image);
            if (iv != null) {
                iv.setImageDrawable(it.getImage());
            }
        }

        return v;
    }
}

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
    this.adapter.getItem(position).click(this.getApplicationContext());
}
}

E.g. extending ArrayAdapter with own type of Items (holding information about your pictures) and overriden getView() method, that prepares view for items within list. There is also method add() on ArrayAdapter to add items to the end of the list.

R.layout.items_list is simple layout with ListView

R.layout.items_list_item is layout representing one item in list

Can I position an element fixed relative to parent?

2016 Update

It's now possible in modern browsers to position an element fixed relative to its container. An element that has a transform property acts as the viewport for any of its fixed position child elements.

Or as the CSS Transforms Module puts it:

For elements whose layout is governed by the CSS box model, any value other than none for the transform property also causes the element to establish a containing block for all descendants. Its padding box will be used to layout for all of its absolute-position descendants, fixed-position descendants, and descendant fixed background attachments.

_x000D_
_x000D_
.context {_x000D_
  width: 300px;_x000D_
  height: 250px;_x000D_
  margin: 100px;_x000D_
  transform: translateZ(0);_x000D_
}_x000D_
.viewport {_x000D_
  width: 100%;_x000D_
  height: 100%;_x000D_
  border: 1px solid black;_x000D_
  overflow: scroll;_x000D_
}_x000D_
.centered {_x000D_
  position: fixed;_x000D_
  left: 50%;_x000D_
  bottom: 15px;_x000D_
  transform: translateX(-50%);_x000D_
}
_x000D_
<div class="context">_x000D_
  <div class="viewport">_x000D_
    <div class="canvas">_x000D_
_x000D_
      <table>_x000D_
        <tr>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
        </tr>_x000D_
_x000D_
        <tr>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
          <td>stuff</td>_x000D_
        </tr>_x000D_
      </table>_x000D_
_x000D_
      <button class="centered">OK</button>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

VideoView Full screen in android application

The below code worked.

    getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

Add this code before calling videoView.start(). With this the video activity runs in full screen mode in most of the cases. But if the title bar is still displayed then change your theme in your manifest to this.

    android:theme="@style/Theme.AppCompat.NoActionBar">

What HTTP traffic monitor would you recommend for Windows?

Try Wireshark:

Wireshark is the world's foremost network protocol analyzer, and is the de facto (and often de jure) standard across many industries and educational institutions.

There is a bit of a learning curve but it is far and away the best tool available.

How to get table list in database, using MS SQL 2008?

This query will get you all the tables in the database

USE [DatabaseName];

SELECT * FROM information_schema.tables;

Calling a particular PHP function on form submit

If you want to call a function on clicking of submit button then you have
to use ajax or jquery,if you want to call your php function after submission of form you can do that as :

<html>
<body>
<form method="post" action="display()">
<input type="text" name="studentname">
<input type="submit" value="click">
</form>
<?php
function display()
{
echo "hello".$_POST["studentname"];
}
if($_SERVER['REQUEST_METHOD']=='POST')
{
       display();
} 
?>
</body>
</html>

How to convert local time string to UTC?

One more example with pytz, but includes localize(), which saved my day.

import pytz, datetime
utc = pytz.utc
fmt = '%Y-%m-%d %H:%M:%S'
amsterdam = pytz.timezone('Europe/Amsterdam')

dt = datetime.datetime.strptime("2012-04-06 10:00:00", fmt)
am_dt = amsterdam.localize(dt)
print am_dt.astimezone(utc).strftime(fmt)
'2012-04-06 08:00:00'

Peak signal detection in realtime timeseries data

Instead of comparing a maxima to the mean, one can also compare the maxima to adjacent minima where the minima are only defined above a noise threshold. If the local maximum is > 3 times (or other confidence factor) either adjacent minima, then that maxima is a peak. The peak determination is more accurate with wider moving windows. The above uses a calculation centered on the middle of the window, by the way, rather than a calculation at the end of the window (== lag).

Note that a maxima has to be seen as an increase in signal before and a decrease after.

Handling urllib2's timeout? - Python

In Python 2.7.3:

import urllib2
import socket

class MyException(Exception):
    pass

try:
    urllib2.urlopen("http://example.com", timeout = 1)
except urllib2.URLError as e:
    print type(e)    #not catch
except socket.timeout as e:
    print type(e)    #catched
    raise MyException("There was an error: %r" % e)

How can I see function arguments in IPython Notebook Server 3?

Try Shift-Tab-Tab a bigger documentation appears, than with Shift-Tab. It's the same but you can scroll down.

Shift-Tab-Tab-Tab and the tooltip will linger for 10 seconds while you type.

Shift-Tab-Tab-Tab-Tab and the docstring appears in the pager (small part at the bottom of the window) and stays there.

How to transform currentTimeMillis to a readable date format?

It will work.

long yourmilliseconds = System.currentTimeMillis();
SimpleDateFormat sdf = new SimpleDateFormat("MMM dd,yyyy HH:mm");    
Date resultdate = new Date(yourmilliseconds);
System.out.println(sdf.format(resultdate));

How to debug Spring Boot application with Eclipse?

How to debug a remote staging or production Spring Boot application

Server-side

Let's assume you have successfully followed Spring Boot's guide on setting up your Spring Boot application as a service. Your application artifact resides in /srv/my-app/my-app.war, accompanied by a configuration file /srv/my-app/my-app.conf:

# This is file my-app.conf
# What can you do in this .conf file? The my-app.war is prepended with a SysV init.d script
# (yes, take a look into the war file with a text editor). As my-app.war is symlinked in the init.d directory, that init.d script
# gets executed. One of its step is actually `source`ing this .conf file. Therefore we can do anything in this .conf file that
# we can also do in a regular shell script.

JAVA_OPTS="-agentlib:jdwp=transport=dt_socket,address=localhost:8002,server=y,suspend=n"
export SPRING_PROFILES_ACTIVE=staging

When you restart your Spring Boot application with sudo service my-app restart, then in its log file located at /var/log/my-app.log should be a line saying Listening for transport dt_socket at address: 8002.

Client-side (developer machine)

Open an SSH port-forwarding tunnel to the server: ssh -L 8002:localhost:8002 [email protected]. Keep this SSH session running.

In Eclipse, from the toolbar, select Run -> Debug Configurations -> select Remote Java Application -> click the New button -> select as Connection Type Standard (Socket Attach), as Host localhost, and as Port 8002 (or whatever you have configured in the steps before). Click Apply and then Debug.

The Eclipse debugger should now connect to the remote server. Switching to the Debug perspective should show the connected JVM and its threads. Breakpoints should fire as soon as they are remotely triggered.

Why does Math.Round(2.5) return 2 instead of 3?

That's called rounding to even (or banker's rounding), which is a valid rounding strategy for minimizing accrued errors in sums (MidpointRounding.ToEven). The theory is that, if you always round a 0.5 number in the same direction, the errors will accrue faster (round-to-even is supposed to minimize that) (a).

Follow these links for the MSDN descriptions of:

  • Math.Floor, which rounds down towards negative infinity.
  • Math.Ceiling, which rounds up towards positive infinity.
  • Math.Truncate, which rounds up or down towards zero.
  • Math.Round, which rounds to the nearest integer or specified number of decimal places. You can specify the behavior if it's exactly equidistant between two possibilities, such as rounding so that the final digit is even ("Round(2.5,MidpointRounding.ToEven)" becoming 2) or so that it's further away from zero ("Round(2.5,MidpointRounding.AwayFromZero)" becoming 3).

The following diagram and table may help:

-3        -2        -1         0         1         2         3
 +--|------+---------+----|----+--|------+----|----+-------|-+
    a                     b       c           d            e

                       a=-2.7  b=-0.5  c=0.3  d=1.5  e=2.8
                       ======  ======  =====  =====  =====
Floor                    -3      -1      0      1      2
Ceiling                  -2       0      1      2      3
Truncate                 -2       0      0      1      2
Round(ToEven)            -3       0      0      2      3
Round(AwayFromZero)      -3      -1      0      2      3

Note that Round is a lot more powerful than it seems, simply because it can round to a specific number of decimal places. All the others round to zero decimals always. For example:

n = 3.145;
a = System.Math.Round (n, 2, MidpointRounding.ToEven);       // 3.14
b = System.Math.Round (n, 2, MidpointRounding.AwayFromZero); // 3.15

With the other functions, you have to use multiply/divide trickery to achieve the same effect:

c = System.Math.Truncate (n * 100) / 100;                    // 3.14
d = System.Math.Ceiling (n * 100) / 100;                     // 3.15

(a) Of course, that theory depends on the fact that your data has an fairly even spread of values across the even halves (0.5, 2.5, 4.5, ...) and odd halves (1.5, 3.5, ...).

If all the "half-values" are evens (for example), the errors will accumulate just as fast as if you always rounded up.

Error parsing XHTML: The content of elements must consist of well-formed character data or markup

Facelets is a XML based view technology which uses XHTML+XML to generate HTML output. XML has five special characters which has special treatment by the XML parser:

  • < the start of a tag.
  • > the end of a tag.
  • " the start and end of an attribute value.
  • ' the alternative start and end of an attribute value.
  • & the start of an entity (which ends with ;).

In case of <, the XML parser is implicitly looking for the tag name and the end tag >. However, in your particular case, you were using < as a JavaScript operator, not as an XML entity. This totally explains the XML parsing error you got:

The content of elements must consist of well-formed character data or markup.

In essence, you're writing JavaScript code in the wrong place, a XML document instead of a JS file, so you should be escaping all XML special characters accordingly. The < must be escaped as &lt;.

So, essentially, the

for (var i = 0; i < length; i++) {

must become

for (var i = 0; i &lt; length; i++) {

to make it XML-valid.

However, this makes the JavaScript code harder to read and maintain. As stated in Mozilla Developer Network's excellent document Writing JavaScript for XHTML, you should be placing the JavaScript code in a character data (CDATA) block. Thus, in JSF terms, that would be:

<h:outputScript>
    <![CDATA[
        // ...
    ]]>
</h:outputScript>

The XML parser will interpret the block's contents as "plain vanilla" character data and not as XML and hence interpret the XML special characters "as-is".

But, much better is to just put the JS code in its own JS file which you include by <script src>, or in JSF terms, the <h:outputScript>.

<h:outputScript name="functions.js" target="head" />

This way you don't need to worry about XML-special characters in your JS code. Additional advantage is that this gives the browser the opportunity to cache the JS file so that average response size is smaller.

See also:

Installing python module within code

import os
os.system('pip install requests')

I tried above for temporary solution instead of changing docker file. Hope these might be useful to some

Count number of occurrences by month

For anyone finding this post through Google (as I did) here's the correct formula for cell F5 in the above example:

=SUMPRODUCT((MONTH(Sheet1!$A$1:$A$50)=MONTH(DATEVALUE(E5&" 1")))*(Sheet1!$A$1:$A$50<>""))

Formula assumes a list of dates in Sheet1!A1:A50 and a month name or abbr ("April" or "Apr") in cell E5.

Input type DateTime - Value format?

That one shows up correctly as HTML5-Tag for those looking for this:

<input type="datetime" name="somedatafield" value="2011-12-21T11:33:23Z" />

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

In solution explorer, right-click References, then click to expand assemblies, find System.IO.Compression.FileSystem and make sure it's checked. Then you can use it in your class - using System.IO.Compression;

Add Reference Assembly Screenshot

How does Tomcat find the HOME PAGE of my Web App?

In any web application, there will be a web.xml in the WEB-INF/ folder.

If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml is under TOMCAT_HOME/conf/web.xml

Either way, the relevant lines of the web.xml are

<welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

so any file matching this pattern when found will be shown as the home page.

In Tomcat, a web.xml setting within your web app will override the default, if present.

Further Reading

How do I override the default home page loaded by Tomcat?

Android Completely transparent Status Bar?

The following code will create a fully transparent status bar:

package com.demo;

import android.app.Activity;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        if (Build.VERSION.SDK_INT >= 19 && Build.VERSION.SDK_INT < 21) {
            setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, true);
        }
        if (Build.VERSION.SDK_INT >= 19) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
        }
        if (Build.VERSION.SDK_INT >= 21) {
            setWindowFlag(this, WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS, false);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
    }

    public static void setWindowFlag(Activity activity, final int bits, boolean on) {
        Window win = activity.getWindow();
        WindowManager.LayoutParams winParams = win.getAttributes();
        if (on) {
            winParams.flags |= bits;
        } else {
            winParams.flags &= ~bits;
        }
        win.setAttributes(winParams);
    }
}

Difference between const reference and normal parameter

There are three methods you can pass values in the function

  1. Pass by value

    void f(int n){
        n = n + 10;
    }
    
    int main(){
        int x = 3;
        f(x);
        cout << x << endl;
    }
    

    Output: 3. Disadvantage: When parameter x pass through f function then compiler creates a copy in memory in of x. So wastage of memory.

  2. Pass by reference

    void f(int& n){
        n = n + 10;
    }
    
    int main(){
        int x = 3;
        f(x);
        cout << x << endl;
    }
    

    Output: 13. It eliminate pass by value disadvantage, but if programmer do not want to change the value then use constant reference

  3. Constant reference

    void f(const int& n){
        n = n + 10; // Error: assignment of read-only reference  ‘n’
    }
    
    int main(){
        int x = 3;
        f(x);
        cout << x << endl;
    }
    

    Output: Throw error at n = n + 10 because when we pass const reference parameter argument then it is read-only parameter, you cannot change value of n.

Calculate distance between two points in google maps V3

If you want to calculate it yourself, then you can use the Haversine formula:

var rad = function(x) {
  return x * Math.PI / 180;
};

var getDistance = function(p1, p2) {
  var R = 6378137; // Earth’s mean radius in meter
  var dLat = rad(p2.lat() - p1.lat());
  var dLong = rad(p2.lng() - p1.lng());
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
    Math.sin(dLong / 2) * Math.sin(dLong / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d; // returns the distance in meter
};

Get IP address of an interface on Linux

My 2 cents: the same code works even if iOS:

#include <arpa/inet.h>
#include <sys/socket.h>
#include <netdb.h>
#include <ifaddrs.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>



#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    showIP();
}



void showIP()
{
    struct ifaddrs *ifaddr, *ifa;
    int family, s;
    char host[NI_MAXHOST];

    if (getifaddrs(&ifaddr) == -1)
    {
        perror("getifaddrs");
        exit(EXIT_FAILURE);
    }


    for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next)
    {
        if (ifa->ifa_addr == NULL)
            continue;

        s=getnameinfo(ifa->ifa_addr,sizeof(struct sockaddr_in),host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST);

        if( /*(strcmp(ifa->ifa_name,"wlan0")==0)&&( */ ifa->ifa_addr->sa_family==AF_INET) // )
        {
            if (s != 0)
            {
                printf("getnameinfo() failed: %s\n", gai_strerror(s));
                exit(EXIT_FAILURE);
            }
            printf("\tInterface : <%s>\n",ifa->ifa_name );
            printf("\t  Address : <%s>\n", host);
        }
    }

    freeifaddrs(ifaddr);
}


@end

I simply removed the test against wlan0 to see data. ps You can remove "family"

How to remove an id attribute from a div using jQuery?

The capitalization is wrong, and you have an extra argument.

Do this instead:

$('img#thumb').removeAttr('id');

For future reference, there aren't any jQuery methods that begin with a capital letter. They all take the same form as this one, starting with a lower case, and the first letter of each joined "word" is upper case.

Redirecting a request using servlets and the "setHeader" method not working

Alternatively, you could try the following,

resp.setStatus(301);
resp.setHeader("Location", "index.jsp");
resp.setHeader("Connection", "close");

How to get docker-compose to always re-create containers from fresh images?

The only solution that worked for me was this command :

docker-compose build --no-cache

This will automatically pull fresh image from repo and won't use the cache version that is prebuild with any parameters you've been using before.