Programs & Examples On #Lwp useragent

The easiest way to transform collection to array?

Alternative solution to the updated question using Java 8:

Bar[] result = foos.stream()
    .map(x -> new Bar(x))
    .toArray(size -> new Bar[size]);

Get first word of string

To get first word of string you can do this:

let myStr = "Hello World"
let firstWord = myStr.split(" ")[0]

How to use Session attributes in Spring-mvc

If you want to delete object after each response you don't need session,

If you want keep object during user session , There are some ways:

  1. directly add one attribute to session:

    @RequestMapping(method = RequestMethod.GET)
    public String testMestod(HttpServletRequest request){
       ShoppingCart cart = (ShoppingCart)request.getSession().setAttribute("cart",value);
       return "testJsp";
    }
    

    and you can get it from controller like this :

    ShoppingCart cart = (ShoppingCart)session.getAttribute("cart");
    
  2. Make your controller session scoped

    @Controller
    @Scope("session")
    
  3. Scope the Objects ,for example you have user object that should be in session every time:

    @Component
    @Scope("session")
    public class User
     {
        String user;
        /*  setter getter*/
      }
    

    then inject class in each controller that you want

       @Autowired
       private User user
    

    that keeps class on session.

  4. The AOP proxy injection : in spring -xml:

    <beans xmlns="http://www.springframework.org/schema/beans"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xmlns:aop="http://www.springframework.org/schema/aop"
      xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
        http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop-3.1.xsd">
    
      <bean id="user"    class="com.User" scope="session">     
          <aop:scoped-proxy/>
      </bean>
    </beans>
    

    then inject class in each controller that you want

    @Autowired
    private User user
    

5.Pass HttpSession to method:

 String index(HttpSession session) {
            session.setAttribute("mySessionAttribute", "someValue");
            return "index";
        }

6.Make ModelAttribute in session By @SessionAttributes("ShoppingCart"):

  public String index (@ModelAttribute("ShoppingCart") ShoppingCart shoppingCart, SessionStatus sessionStatus) {
//Spring V4
//you can modify session status  by sessionStatus.setComplete();
}

or you can add Model To entire Controller Class like,

@Controller
    @SessionAttributes("ShoppingCart")
    @RequestMapping("/req")
    public class MYController {

        @ModelAttribute("ShoppingCart")
        public Visitor getShopCart (....) {
            return new ShoppingCart(....); //get From DB Or Session
        }  
      }

each one has advantage and disadvantage:

@session may use more memory in cloud systems it copies session to all nodes, and direct method (1 and 5) has messy approach, it is not good to unit test.

To access session jsp

<%=session.getAttribute("ShoppingCart.prop")%>

in Jstl :

<c:out value="${sessionScope.ShoppingCart.prop}"/>

in Thymeleaf:

<p th:text="${session.ShoppingCart.prop}" th:unless="${session == null}"> . </p>

What is the function of FormulaR1C1?

FormulaR1C1 has the same behavior as Formula, only using R1C1 style annotation, instead of A1 annotation. In A1 annotation you would use:

Worksheets("Sheet1").Range("A5").Formula = "=A4+A10"

In R1C1 you would use:

Worksheets("Sheet1").Range("A5").FormulaR1C1 = "=R4C1+R10C1"

It doesn't act upon row 1 column 1, it acts upon the targeted cell or range. Column 1 is the same as column A, so R4C1 is the same as A4, R5C2 is B5, and so forth.

The command does not change names, the targeted cell changes. For your R2C3 (also known as C2) example :

Worksheets("Sheet1").Range("C2").FormulaR1C1 = "=your formula here"

What is the difference between background, backgroundTint, backgroundTintMode attributes in android layout xml?

The backgroundTint attribute will help you to add a tint(shade) to the background. You can provide a color value for the same in the form of - "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

The backgroundTintMode on the other hand will help you to apply the background tint. It must have constant values like src_over, src_in, src_atop, etc.

Refer this to get a clear idea of the the constant values that can be used. Search for the backgroundTint attribute and the description along with various attributes will be available.

Tomcat 7.0.43 "INFO: Error parsing HTTP request header"

In our case it turned out that the error happened because we have a custom filter in our application which does HttpServletResponse sendRedirect() to other url.

For some reason, the redirection is not closing the keep-alive status of the connection, hence the timeout exception.

We checked with Tomcat Docs and when we disabled the maxKeepAliveRequests by setting it's value to 1 and the error stopped showing up.

For now we do not have the actual solution to the error.

Spring Boot - How to get the running port

Starting with Spring Boot 1.4.0 you can use this in your test:

import org.springframework.boot.context.embedded.LocalServerPort;

@SpringBootTest(classes = {Application.class}, webEnvironment = WebEnvironment.RANDOM_PORT)
public class MyTest {

  @LocalServerPort
  int randomPort;

  // ...
}

Error : ORA-01704: string literal too long

INSERT INTO table(clob_column) SELECT TO_CLOB(q'[chunk1]') || TO_CLOB(q'[chunk2]') ||
            TO_CLOB(q'[chunk3]') || TO_CLOB(q'[chunk4]') FROM DUAL;

Right way to reverse a pandas DataFrame?

None of the existing answers resets the index after reversing the dataframe.

For this, do the following:

 data[::-1].reset_index()

Here's a utility function that also removes the old index column, as per @Tim's comment:

def reset_my_index(df):
  res = df[::-1].reset_index(drop=True)
  return(res)

Simply pass your dataframe into the function

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

You need to use bindValue, not bindParam

bindParam takes a variable by reference, and doesn't pull in a value at the time of calling bindParam. I found this in a comment on the PHP docs:

bindValue(':param', null, PDO::PARAM_INT);

P.S. You may be tempted to do this bindValue(':param', null, PDO::PARAM_NULL); but it did not work for everybody (thank you Will Shaver for reporting.)

How can I read numeric strings in Excel cells as string (not numbers)?

It looks like this can't be done in the current version of POI, based on the fact that this bug:

https://issues.apache.org/bugzilla/show_bug.cgi?id=46136

is still outstanding.

How do I retrieve query parameters in Spring Boot?

To accept both @PathVariable and @RequestParam in the same /user endpoint:

@GetMapping(path = {"/user", "/user/{data}"})
public void user(@PathVariable(required=false,name="data") String data,
                 @RequestParam(required=false) Map<String,String> qparams) {
    qparams.forEach((a,b) -> {
        System.out.println(String.format("%s -> %s",a,b));
    }
  
    if (data != null) {
        System.out.println(data);
    }
}

Testing with curl:

  • curl 'http://localhost:8080/user/books'
  • curl 'http://localhost:8080/user?book=ofdreams&name=nietzsche'

Minimum and maximum date

To augment T.J.'s answer, exceeding the min/max values generates an Invalid Date.

_x000D_
_x000D_
let maxDate = new Date(8640000000000000);_x000D_
let minDate = new Date(-8640000000000000);_x000D_
_x000D_
console.log(new Date(maxDate.getTime()).toString());_x000D_
console.log(new Date(maxDate.getTime() - 1).toString());_x000D_
console.log(new Date(maxDate.getTime() + 1).toString()); // Invalid Date_x000D_
_x000D_
console.log(new Date(minDate.getTime()).toString());_x000D_
console.log(new Date(minDate.getTime() + 1).toString());_x000D_
console.log(new Date(minDate.getTime() - 1).toString()); // Invalid Date
_x000D_
_x000D_
_x000D_

What is the --save option for npm install?

Update as of npm 5:

As of npm 5.0.0, installed modules are added as a dependency by default, so the --save option is no longer needed. The other save options still exist and are listed in the documentation for npm install.


Original Answer:

To add package in dependencies:

npm install my_dep --save

or

npm install my_dep -S

or

npm i my_dep -S

To add package in devDependencies

npm install my_test_framework --save-dev

or

npm install my_test_framework -D

or

npm i my_test_framework -D

package.json enter image description here

How to run an external program, e.g. notepad, using hyperlink?

Make a batch file and call the bacth file in Window.open. Here how it works

  1. make a file in notepad
  2. write your script : start wmplayer "\dotnet\sc\1234.mp4" /fullscreen
  3. save as : test.bat in \dotnet\sc\test.bat

in html

window.open('file://dotnet/sc/test.bat')

Enjoy..

Check if a property exists in a class

This answers a different question:

If trying to figure out if an OBJECT (not class) has a property,

OBJECT.GetType().GetProperty("PROPERTY") != null

returns true if (but not only if) the property exists.

In my case, I was in an ASP.NET MVC Partial View and wanted to render something if either the property did not exist, or the property (boolean) was true.

@if ((Model.GetType().GetProperty("AddTimeoffBlackouts") == null) ||
        Model.AddTimeoffBlackouts)

helped me here.

Edit: Nowadays, it's probably smart to use the nameof operator instead of the stringified property name.

Matplotlib discrete colorbar

You could follow this example:

#!/usr/bin/env python
"""
Use a pcolor or imshow with a custom colormap to make a contour plot.

Since this example was initially written, a proper contour routine was
added to matplotlib - see contour_demo.py and
http://matplotlib.sf.net/matplotlib.pylab.html#-contour.
"""

from pylab import *


delta = 0.01
x = arange(-3.0, 3.0, delta)
y = arange(-3.0, 3.0, delta)
X,Y = meshgrid(x, y)
Z1 = bivariate_normal(X, Y, 1.0, 1.0, 0.0, 0.0)
Z2 = bivariate_normal(X, Y, 1.5, 0.5, 1, 1)
Z = Z2 - Z1 # difference of Gaussians

cmap = cm.get_cmap('PiYG', 11)    # 11 discrete colors

im = imshow(Z, cmap=cmap, interpolation='bilinear',
            vmax=abs(Z).max(), vmin=-abs(Z).max())
axis('off')
colorbar()

show()

which produces the following image:

poormans_contour

Understanding the main method of python

Python does not have a defined entry point like Java, C, C++, etc. Rather it simply executes a source file line-by-line. The if statement allows you to create a main function which will be executed if your file is loaded as the "Main" module rather than as a library in another module.

To be clear, this means that the Python interpreter starts at the first line of a file and executes it. Executing lines like class Foobar: and def foobar() creates either a class or a function and stores them in memory for later use.

Exposing the current state name with ui router

this is how I do it

JAVASCRIPT:

var module = angular.module('yourModuleName', ['ui.router']);

module.run( ['$rootScope', '$state', '$stateParams',
                      function ($rootScope,   $state,   $stateParams) {
    $rootScope.$state = $state;
    $rootScope.$stateParams = $stateParams; 
}
]);

HTML:

<pre id="uiRouterInfo">
      $state = {{$state.current.name}}
      $stateParams = {{$stateParams}}
      $state full url = {{ $state.$current.url.source }}    
</pre>

EXAMPLE

http://plnkr.co/edit/LGMZnj?p=preview

What is the incentive for curl to release the library for free?

I'm Daniel Stenberg.

I made curl

I founded the curl project back in 1998, I wrote the initial curl version and I created libcurl. I've written more than half of all the 24,000 commits done in the source code repository up to this point in time. I'm still the lead developer of the project. To a large extent, curl is my baby.

I shipped the first version of curl as open source since I wanted to "give back" to the open source world that had given me so much code already. I had used so much open source and I wanted to be as cool as the other open source authors.

Thanks to it being open source, literally thousands of people have been able to help us out over the years and have improved the products, the documentation. the web site and just about every other detail around the project. curl and libcurl would never have become the products that they are today were they not open source. The list of contributors now surpass 1900 names and currently the list grows with a few hundred names per year.

Thanks to curl and libcurl being open source and liberally licensed, they were immediately adopted in numerous products and soon shipped by operating systems and Linux distributions everywhere thus getting a reach beyond imagination.

Thanks to them being "everywhere", available and liberally licensed they got adopted and used everywhere and by everyone. It created a defacto transfer library standard.

At an estimated six billion installations world wide, we can safely say that curl is the most widely used internet transfer library in the world. It simply would not have gone there had it not been open source. curl runs in billions of mobile phones, a billion Windows 10 installations, in a half a billion games and several hundred million TVs - and more.

Should I have released it with proprietary license instead and charged users for it? It never occured to me, and it wouldn't have worked because I would never had managed to create this kind of stellar project on my own. And projects and companies wouldn't have used it.

Why do I still work on curl?

Now, why do I and my fellow curl developers still continue to develop curl and give it away for free to the world?

  1. I can't speak for my fellow project team members. We all participate in this for our own reasons.
  2. I think it's still the right thing to do. I'm proud of what we've accomplished and I truly want to make the world a better place and I think curl does its little part in this.
  3. There are still bugs to fix and features to add!
  4. curl is free but my time is not. I still have a job and someone still has to pay someone for me to get paid every month so that I can put food on the table for my family. I charge customers and companies to help them with curl. You too can get my help for a fee, which then indirectly helps making sure that curl continues to evolve, remain free and the kick-ass product it is.
  5. curl was my spare time project for twenty years before I started working with it full time. I've had great jobs and worked on awesome projects. I've been in a position of luxury where I could continue to work on curl on my spare time and keep shipping a quality product for free. My work on curl has given me friends, boosted my career and taken me to places I would not have been at otherwise.
  6. I would not do it differently if I could back and do it again.

Am I proud of what we've done?

Yes. So insanely much.

But I'm not satisfied with this and I'm not just leaning back, happy with what we've done. I keep working on curl every single day, to improve, to fix bugs, to add features and to make sure curl keeps being the number one file transfer solution for the world even going forward.

We do mistakes along the way. We make the wrong decisions and sometimes we implement things in crazy ways. But to win in the end and to conquer the world is about patience and endurance and constantly going back and reconsidering previous decisions and correcting previous mistakes. To continuously iterate, polish off rough edges and gradually improve over time.

Never give in. Never stop. Fix bugs. Add features. Iterate. To the end of time.

For real?

Yeah. For real.

Do I ever get tired? Is it ever done?

Sure I get tired at times. Working on something every day for over twenty years isn't a paved downhill road. Sometimes there are obstacles. During times things are rough. Occasionally people are just as ugly and annoying as people can be.

But curl is my life's project and I have patience. I have thick skin and I don't give up easily. The tough times pass and most days are awesome. I get to hang out with awesome people and the reward is knowing that my code helps driving the Internet revolution everywhere is an ego boost above normal.

curl will never be "done" and so far I think work on curl is pretty much the most fun I can imagine. Yes, I still think so even after twenty years in the driver's seat. And as long as I think it's fun I intend to keep at it.

Make text wrap in a cell with FPDF?

Text Wrap:

The MultiCell is used for print text with multiple lines. It has the same atributes of Cell except for ln and link.

$pdf->MultiCell( 200, 40, $reportSubtitle, 1);

Line Height:

What multiCell does is to spread the given text into multiple cells, this means that the second parameter defines the height of each line (individual cell) and not the height of all cells (collectively).

MultiCell(float w, float h, string txt [, mixed border [, string align [, boolean fill]]])

You can read the full documentation here.

Creating SVG graphics using Javascript?

You can use d3.js. It is easy to use and powerful.

D3.js is a JavaScript library for manipulating documents based on data. D3 helps you bring data to life using HTML, SVG and CSS.

Copy files from one directory into an existing directory

For inside some directory, this will be use full as it copy all contents from "folder1" to new directory "folder2" inside some directory.

$(pwd) will get path for current directory.

Notice the dot (.) after folder1 to get all contents inside folder1

cp -r $(pwd)/folder1/. $(pwd)/folder2

formatFloat : convert float number to string

Try this

package main

import "fmt"
import "strconv"

func FloatToString(input_num float64) string {
    // to convert a float number to a string
    return strconv.FormatFloat(input_num, 'f', 6, 64)
}

func main() {
    fmt.Println(FloatToString(21312421.213123))
}

If you just want as many digits precision as possible, then the special precision -1 uses the smallest number of digits necessary such that ParseFloat will return f exactly. Eg

strconv.FormatFloat(input_num, 'f', -1, 64)

Personally I find fmt easier to use. (Playground link)

fmt.Printf("x = %.6f\n", 21312421.213123)

Or if you just want to convert the string

fmt.Sprintf("%.6f", 21312421.213123)

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

I had this problem when I had navigated from root TVC to TVC A then to TVC B. After tapping the "load" button in TVC B I wanted to jump straight back to the root TVC (no need to revisit TVC A so why do it). I had:

//Pop child from the nav controller
[self.navigationController popViewControllerAnimated:YES];
//Pop self to return to root
[self.navigationController popViewControllerAnimated:YES];

...which gave the error "Unbalanced calls to begin/end etc". The following fixed the error, but no animation:

//Pop child from the nav controller
[self.navigationController popViewControllerAnimated:NO];
//Then pop self to return to root
[self.navigationController popViewControllerAnimated:NO];

This was my final solution, no error and still animated:

//Pop child from the nav controller
[self.navigationController popViewControllerAnimated:NO];
//Then pop self to return to root, only works if first pop above is *not* animated
[self.navigationController popViewControllerAnimated:YES];

Python one-line "for" expression

for item in array: array2.append (item)

Or, in this case:

array2 += array

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

I would recommend using rgba(255,255,255,0) because broken (newest) safari thinks that if you are using transparent or rgba(0,0,0,0) in linear-gradent you really mean gray, For more info please head to - What happens in Safari with the transparent color?

BeanFactory vs ApplicationContext

  1. ApplicationContext is more preferred way than BeanFactory

  2. In new Spring versions BeanFactory is replaced with ApplicationContext. But still BeanFactory exists for backward compatability

  3. ApplicationContext extends BeanFactory and has the following benefits
    • it supports internationalization for text messages
    • it supports event publication to the registered listeners
    • access to the resources such as URLs and files

EXC_BAD_ACCESS signal received

A major cause of EXC_BAD_ACCESS is from trying to access released objects.

To find out how to troubleshoot this, read this document: DebuggingAutoReleasePool

Even if you don't think you are "releasing auto-released objects", this will apply to you.

This method works extremely well. I use it all the time with great success!!

In summary, this explains how to use Cocoa's NSZombie debugging class and the command line "malloc_history" tool to find exactly what released object has been accessed in your code.

Sidenote:

Running Instruments and checking for leaks will not help troubleshoot EXC_BAD_ACCESS. I'm pretty sure memory leaks have nothing to do with EXC_BAD_ACCESS. The definition of a leak is an object that you no longer have access to, and you therefore cannot call it.

UPDATE: I now use Instruments to debug Leaks. From Xcode 4.2, choose Product->Profile and when Instruments launches, choose "Zombies".

base 64 encode and decode a string in angular (2+)

Use the btoa() function to encode:

_x000D_
_x000D_
console.log(btoa("password")); // cGFzc3dvcmQ=
_x000D_
_x000D_
_x000D_

To decode, you can use the atob() function:

_x000D_
_x000D_
console.log(atob("cGFzc3dvcmQ=")); // password
_x000D_
_x000D_
_x000D_

Determine if an element has a CSS class with jQuery

In the interests of helping anyone who lands here but was actually looking for a jQuery free way of doing this:

element.classList.contains('your-class-name')

How can I iterate over files in a given directory?

You can try using glob module:

import glob

for filepath in glob.iglob('my_dir/*.asm'):
    print(filepath)

and since Python 3.5 you can search subdirectories as well:

glob.glob('**/*.txt', recursive=True) # => ['2.txt', 'sub/3.txt']

From the docs:

The glob module finds all the pathnames matching a specified pattern according to the rules used by the Unix shell, although results are returned in arbitrary order. No tilde expansion is done, but *, ?, and character ranges expressed with [] will be correctly matched.

SVG fill color transparency / alpha?

To make a fill completely transparent, fill="transparent" seems to work in modern browsers. But it didn't work in Microsoft Word (for Mac), I had to use fill-opacity="0".

Alternative to file_get_contents?

You should try something like this, I am doing this for my project, its a fallback system

//function to get the remote data
function url_get_contents ($url) {
    if (function_exists('curl_exec')){ 
        $conn = curl_init($url);
        curl_setopt($conn, CURLOPT_SSL_VERIFYPEER, true);
        curl_setopt($conn, CURLOPT_FRESH_CONNECT,  true);
        curl_setopt($conn, CURLOPT_RETURNTRANSFER, 1);
        $url_get_contents_data = (curl_exec($conn));
        curl_close($conn);
    }elseif(function_exists('file_get_contents')){
        $url_get_contents_data = file_get_contents($url);
    }elseif(function_exists('fopen') && function_exists('stream_get_contents')){
        $handle = fopen ($url, "r");
        $url_get_contents_data = stream_get_contents($handle);
    }else{
        $url_get_contents_data = false;
    }
return $url_get_contents_data;
} 

then later you can do like this

$data = url_get_contents("http://www.google.com");
if($data){
//Do Something....
}

No such keg: /usr/local/Cellar/git

Os X Mojave 10.14 has:

Error: The Command Line Tools header package must be installed on Mojave.

Solution. Go to

/Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg

location and install the package manually. And brew will start working and we can run:

brew uninstall --force git
brew cleanup --force -s git
brew prune
brew install git

How to use absolute path in twig functions

The following works for me:

<img src="{{ asset('bundle/myname/img/image.gif', null, true) }}" />

How do I get a value of a <span> using jQuery?

$('#id span').text() is the answer!

Meaning of - <?xml version="1.0" encoding="utf-8"?>

An XML declaration is not required in all XML documents; however XHTML document authors are strongly encouraged to use XML declarations in all their documents. Such a declaration is required when the character encoding of the document is other than the default UTF-8 or UTF-16 and no encoding was determined by a higher-level protocol. Here is an example of an XHTML document. In this example, the XML declaration is included.

<?xml version="1.0" encoding="UTF-8"?>
 <!DOCTYPE html 
 PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  <head>
    <title>Virtual Library</title>
  </head>
  <body>
    <p>Moved to <a href="http://example.org/">example.org</a>.</p>
 </body>
</html>

Please refer to the W3 standards for XML.

Android Bitmap to Base64 String

use following method to convert bitmap to byte array:

ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();  
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();

to encode base64 from byte array use following method

String encoded = Base64.encodeToString(byteArray, Base64.DEFAULT);

python list by value not by reference

I found that we can use extend() to implement the function of copy()

a=['help', 'copyright', 'credits', 'license']
b = []
b.extend(a)
b.append("XYZ") 

How to prevent vim from creating (and leaving) temporary files?

I have this setup in my Ubuntu .vimrc. I don't see any swap files in my project files.

set undofile
set undolevels=1000         " How many undos
set undoreload=10000        " number of lines to save for undo

set backup                        " enable backups
set swapfile                      " enable swaps
set undodir=$HOME/.vim/tmp/undo     " undo files
set backupdir=$HOME/.vim/tmp/backup " backups
set directory=$HOME/.vim/tmp/swap   " swap files

" Make those folders automatically if they don't already exist.
if !isdirectory(expand(&undodir))
    call mkdir(expand(&undodir), "p")
endif
if !isdirectory(expand(&backupdir))
    call mkdir(expand(&backupdir), "p")
endif
if !isdirectory(expand(&directory))
    call mkdir(expand(&directory), "p")
endif

Adding an image to a project in Visual Studio

You need to turn on Show All Files option on solution pane toolbar and include this file manually.

Use xml.etree.ElementTree to print nicely formatted xml files

You could use the library lxml (Note top level link is now spam) , which is a superset of ElementTree. Its tostring() method includes a parameter pretty_print - for example:

>>> print(etree.tostring(root, pretty_print=True))
<root>
  <child1/>
  <child2/>
  <child3/>
</root>

How to implement DrawerArrowToggle from Android appcompat v7 21 library

To answer the updated part of your question: to style the drawer icon/arrow, you have two options:

Style the arrow itself

To do this, override drawerArrowStyle in your theme like so:

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="drawerArrowStyle">@style/MyTheme.DrawerArrowToggle</item>
</style>
<style name="MyTheme.DrawerArrowToggle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="color">@android:color/holo_purple</item>
    <!-- ^ this will make the icon purple -->
</style>

This is probably not what you want, because the ActionBar itself should have consistent styling with the arrow, so, most probably, you want the option two:

Theme the ActionBar/Toolbar

Override the android:actionBarTheme (actionBarTheme for appcompat) attribute of the global application theme with your own theme (which you probably should derive from ThemeOverlay.Material.ActionBar/ThemeOverlay.AppCompat.ActionBar) like so:

<style name="AppBaseTheme" parent="Theme.AppCompat.Light">
    <item name="actionBarTheme">@style/MyTheme.ActionBar</item>
</style>
<style name="MyTheme.ActionBar" parent="ThemeOverlay.AppCompat.ActionBar">
    <item name="android:textColorPrimary">@android:color/white</item>
    <!-- ^ this will make text and arrow white -->
    <!-- you can also override drawerArrowStyle here -->
</style>

An important note here is that when using a custom layout with a Toolbar instead of stock ActionBar implementation (e.g. if you're using the DrawerLayout-NavigationView-Toolbar combo to achieve the Material-style drawer effect where it's visible under translucent statusbar), the actionBarTheme attribute is obviosly not picked up automatically (because it's meant to be taken care of by the AppCompatActivity for the default ActionBar), so for your custom Toolbar don't forget to apply your theme manually:

<!--inside your custom layout with DrawerLayout
and NavigationView or whatever -->
<android.support.v7.widget.Toolbar
        ...
        app:theme="?actionBarTheme">

-- this will resolve to either AppCompat's default ThemeOverlay.AppCompat.ActionBar or your override if you set the attribute in your derived theme.

PS a little comment about the drawerArrowStyle override and the spinBars attribute -- which a lot of sources suggest should be set to true to get the drawer/arrow animation. Thing is, spinBars it is true by default in AppCompat (check out the Base.Widget.AppCompat.DrawerArrowToggle.Common style), you don't have to override actionBarTheme at all to get the animation working. You get the animation even if you do override it and set the attribute to false, it's just a different, less twirly animation. The important thing here is to use ActionBarDrawerToggle, it's what pulls in the fancy animated drawable.

Playing m3u8 Files with HTML Video Tag

In normally html5 video player will support mp4, WebM, 3gp and OGV format directly.

    <video controls>
      <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
      <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
      <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
      <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
    </video>

We can add an external HLS js script in web application.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>Your title</title>
      
    
      <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
      <script src="https://unpkg.com/video.js/dist/video.js"></script>
      <script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
       
    </head>
    <body>
      <video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"
      data-setup='{}'>
        <source src="https://cdn3.wowza.com/1/ejBGVnFIOW9yNlZv/cithRSsv/hls/live/playlist.m3u8" type="application/x-mpegURL">
      </video>
      
    <script>
    var player = videojs('my_video_1');
    player.play();
    </script>
      
    </body>
    </html>

Is there a C++ gdb GUI for Linux?

Check out Nemiver C/C++ Debugger. It is easy to install in Ubuntu (Developer Tools/Debugging).

Update: New link.

How get an apostrophe in a string in javascript

This is plain Javascript and has nothing to do with the jQuery library.

You simply escape the apostrophe with a backslash:

theAnchorText = 'I\'m home';

Another alternative is to use quotation marks around the string, then you don't have to escape apostrophes:

theAnchorText = "I'm home";

Returning Month Name in SQL Server Query

Select SUBSTRING (convert(varchar,S0.OrderDateTime,100),1,3) from your Table Name

os.path.dirname(__file__) returns empty

import os.path

dirname = os.path.dirname(__file__) or '.'

Instagram how to get my user id from username?

Instead of using the API, one can examine the Instagram userpage to get the id. Example code in PHP:

$html = file_get_contents("http://instagram.com/<username>");
$doc = new DOMDocument();
$doc->loadHTML($html);

$xpath = new DOMXPath($doc);
$js = $xpath->query('//body/script[@type="text/javascript"]')->item(1)->nodeValue;

$start = strpos($js, '{');
$end = strrpos($js, ';');
$json = substr($js, $start, $end - $start);

$data = json_decode($json, true);
$data = $data["entry_data"]["UserProfile"][0];
# The "userMedia" entry of $data now has the same structure as the "data" field
# in Instagram API responses to user endpoints queries

echo $data["user"]["id"];

Of course, this code has to be adapted if Instagram changes its page format.

MySQL error 1449: The user specified as a definer does not exist

I have tried the above methods, but feels like repetitive action when creating the view. I got the same issue while updating the views of the imported database.

You can simply overcome the issue in LOCAL by simply creating the User with the create privilege.

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

How to hide the Google Invisible reCAPTCHA badge

I saw next comment about this

It's also helpful to place the badge inline if you want to apply your own CSS to it. But do remember that you agreed to show Google's Terms and conditions when you registered for an API key - so don't hide it, please. And while it is possible to make the badge disappear completely with CSS, we wouldn't recommend it.

Subtract days from a DateTime

Using AddDays(-1) worked for me until I tried to cross months. When I tried to subtract 2 days from 2017-01-01 the result was 2016-00-30. It could not handle the month change correctly (though the year seemed to be fine).

I used date = Convert.ToDateTime(date).Subtract(TimeSpan.FromDays(2)).ToString("yyyy-mm-dd"); and have no issues.

How can I use Helvetica Neue Condensed Bold in CSS?

I had the same problem and trouble getting it to work on all browsers.

So this is the best font stack for Helvetica Neue Condensed Bold I could find:

font-family: "HelveticaNeue-CondensedBold", "HelveticaNeueBoldCondensed", "HelveticaNeue-Bold-Condensed", "Helvetica Neue Bold Condensed", "HelveticaNeueBold", "HelveticaNeue-Bold", "Helvetica Neue Bold", "HelveticaNeue", "Helvetica Neue", 'TeXGyreHerosCnBold', "Helvetica", "Tahoma", "Geneva", "Arial Narrow", "Arial", sans-serif; font-weight:600; font-stretch:condensed;

Even more stacks to find at:

http://rachaelmoore.name/posts/design/css/web-safe-helvetica-font-stack/

How do I send an HTML email?

You can find a complete and very simple java class for sending emails using Google(gmail) account here, Send email message using java application

It uses following properties

Properties props = new Properties();
  props.put("mail.smtp.auth", "true");
  props.put("mail.smtp.starttls.enable", "true");
  props.put("mail.smtp.host", "smtp.gmail.com");
  props.put("mail.smtp.port", "587");

ASP.NET MVC: What is the purpose of @section?

It lets you define a @Section of code in your template that you can then include in other files. For example, a sidebar defined in the template, could be referenced in another included view.

//This could be used to render a @Section defined as @Section SideBar { ...
@RenderSection("SideBar", required: false);

Hope this helps.

Sorting HashMap by values

In Java 8:

Map<Integer, String> sortedMap = 
     unsortedMap.entrySet().stream()
    .sorted(Entry.comparingByValue())
    .collect(Collectors.toMap(Entry::getKey, Entry::getValue,
                              (e1, e2) -> e1, LinkedHashMap::new));

ImportError: No module named 'pygame'

I was getting the same error. It is because your version of Pygame is not compatible with your version of Python or Pydev. Go to this link and get the proper version of Pygame for your current version of Python. Ctrl F to find it faster or click on the word python in blue. up at the top. While you instal Pygame it should find the Python path by itself. At least mind did any ways. I run Pygame through Eclipse with Python 3.4.

http://www.lfd.uci.edu/~gohlke/pythonlibs/

Create a global variable in TypeScript

im using only this

import {globalVar} from "./globals";
declare let window:any;
window.globalVar = globalVar;

Generic Property in C#

Okay, I'll bite. You want something like this: If you declare a "property" like this:

Update: I'm now pretty sure that Fredrik Mörk answered your question and gave a solution. I'm not really happy with the idea, but it seems to answer exactly what I understood from your question.

public class PropertyFoo {
  public MyProp<String> Name;
}

this ends up as

public class PropertyFoo {
  public string Name {
    get { /* do predefined stuff here */ }
    set { /*other predefined stuff here */ }
  }
}

No. Not possible and not a property, really. Look for template/snippet support in your IDE.

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

It's a C trigraph. ??! is |, so ??!??! is the operator ||

csv.Error: iterator should return strings, not bytes

Your problem is you have the b in the open flag. The flag rt (read, text) is the default, so, using the context manager, simply do this:

with open('sample.csv') as ifile:
    read = csv.reader(ifile) 
    for row in read:
        print (row)  

The context manager means you don't need generic error handling (without which you may get stuck with the file open, especially in an interpreter), because it will automatically close the file on an error, or on exiting the context.

The above is the same as:

with open('sample.csv', 'r') as ifile:
    ...

or

with open('sample.csv', 'rt') as ifile:
    ...

How to set URL query params in Vue with Vue-Router

Actually you can just push query like this: this.$router.push({query: {plan: 'private'}})

Based on: https://github.com/vuejs/vue-router/issues/1631

What is Mocking?

Prologue: If you look up the noun mock in the dictionary you will find that one of the definitions of the word is something made as an imitation.

Mocking is primarily used in unit testing. An object under test may have dependencies on other (complex) objects. To isolate the behavior of the object you want to replace the other objects by mocks that simulate the behavior of the real objects. This is useful if the real objects are impractical to incorporate into the unit test.

In short, mocking is creating objects that simulate the behavior of real objects.

At times you may want to distinguish between mocking as opposed to stubbing. There may be some disagreement about this subject but my definition of a stub is a "minimal" simulated object. The stub implements just enough behavior to allow the object under test to execute the test.

A mock is like a stub but the test will also verify that the object under test calls the mock as expected. Part of the test is verifying that the mock was used correctly.

To give an example: You can stub a database by implementing a simple in-memory structure for storing records. The object under test can then read and write records to the database stub to allow it to execute the test. This could test some behavior of the object not related to the database and the database stub would be included just to let the test run.

If you instead want to verify that the object under test writes some specific data to the database you will have to mock the database. Your test would then incorporate assertions about what was written to the database mock.

What are the differences between JSON and JSONP?

JSONP is a simple way to overcome browser restrictions when sending JSON responses from different domains from the client.

But the practical implementation of the approach involves subtle differences that are often not explained clearly.

Here is a simple tutorial that shows JSON and JSONP side by side.

All the code is freely available at Github and a live version can be found at http://json-jsonp-tutorial.craic.com

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

How to pass a function as a parameter in Java?

Thanks to Java 8 you don't need to do the steps below to pass a function to a method, that's what lambdas are for, see Oracle's Lambda Expression tutorial. The rest of this post describes what we used to have to do in the bad old days in order to implement this functionality.

Typically you declare your method as taking some interface with a single method, then you pass in an object that implements that interface. An example is in commons-collections, where you have interfaces for Closure, Transformer, and Predicate, and methods that you pass implementations of those into. Guava is the new improved commons-collections, you can find equivalent interfaces there.

So for instance, commons-collections has org.apache.commons.collections.CollectionUtils, which has lots of static methods that take objects passed in, to pick one at random, there's one called exists with this signature:

static boolean exists(java.util.Collection collection, Predicate predicate) 

It takes an object that implements the interface Predicate, which means it has to have a method on it that takes some Object and returns a boolean.

So I can call it like this:

CollectionUtils.exists(someCollection, new Predicate() {
    public boolean evaluate(Object object) { 
        return ("a".equals(object.toString());
    }
});

and it returns true or false depending on whether someCollection contains an object that the predicate returns true for.

Anyway, this is just an example, and commons-collections is outdated. I just forget the equivalent in Guava.

Eclipse internal error while initializing Java tooling

Just close the Eclipse or STS and restart it again. This may fix this error.

Get spinner selected items text?

One line version:

String text = ((Spinner)findViewById(R.id.spinner)).getSelectedItem().toString();

UPDATE: You can remove casting if you use SDK 26 (or newer) to compile your project.

String text = findViewById(R.id.spinner).getSelectedItem().toString();

_DEBUG vs NDEBUG

Is NDEBUG standard?

Yes it is a standard macro with the semantic "Not Debug" for C89, C99, C++98, C++2003, C++2011, C++2014 standards. There are no _DEBUG macros in the standards.

C++2003 standard send the reader at "page 326" at "17.4.2.1 Headers" to standard C.

That NDEBUG is similar as This is the same as the Standard C library.

In C89 (C programmers called this standard as standard C) in "4.2 DIAGNOSTICS" section it was said

http://port70.net/~nsz/c/c89/c89-draft.html

If NDEBUG is defined as a macro name at the point in the source file where is included, the assert macro is defined simply as

     #define assert(ignore) ((void)0)

If look at the meaning of _DEBUG macros in Visual Studio https://msdn.microsoft.com/en-us/library/b0084kay.aspx then it will be seen, that this macro is automatically defined by your ?hoice of language runtime library version.

How to print strings with line breaks in java

I think you are making it too complex. AttributedString is used when you want to store attributes - in Printing Context. But You are storing data inside that. AttributedString

Simply, store your data into Document object and pass properties like Font, Bold, Italic everything in AttributedString.

Hope this will be helpful A quick tutorial And In depth tutorial

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

Could this exception be thrown during an unfinished transaction, where your application is attempting to create an entity with a duplicate field to the identifier you are using to try find a single entity?

In this case the new (duplicate) entity will not be visible in the database as the transaction won't have, and will never be committed to the db. The exception will still be thrown however.

How to semantically add heading to a list

According to w3.org (note that this link is in the long-expired draft HTML 3.0 spec):

An unordered list typically is a bulleted list of items. HTML 3.0 gives you the ability to customise the bullets, to do without bullets and to wrap list items horizontally or vertically for multicolumn lists.

The opening list tag must be <UL>. It is followed by an optional list header (<LH>caption</LH>) and then by the first list item (<LI>). For example:

<UL>
  <LH>Table Fruit</LH>
  <LI>apples
  <LI>oranges
  <LI>bananas
</UL>

which could be rendered as:

Table Fruit

  • apples
  • oranges
  • bananas

Note: Some legacy documents may include headers or plain text before the first LI element. Implementors of HTML 3.0 user agents are advised to cater for this possibility in order to handle badly formed legacy documents.

How to close jQuery Dialog within the dialog?

Using $(this).dialog('close'); only works inside the click function of a button within the modal. If your button is not within the dialog box, as in this example, specify a selector:

$('#form-dialog').dialog('close');

For more information, see the documentation

Is there a minlength validation attribute in HTML5?

Here is HTML5-only solution (if you want minlength 5, maxlength 10 character validation)

http://jsfiddle.net/xhqsB/102/

<form>
  <input pattern=".{5,10}">
  <input type="submit" value="Check"></input>
</form>

How do I use the JAVA_OPTS environment variable?

JAVA_OPTS is not restricted to Tomcat’s Java process, but passed to all JVM processes running on the same machine.

Use CATALINA_OPTS if you specifically want to pass JVM arguments to Tomcat's servlet engine.

Angular 2 filter/search list

Slight modification to @Mosche answer, for handling if there exist no filter element.

TS:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
    name: 'filterFromList'
})
export class FilterPipe implements PipeTransform {
    public transform(value, keys: string, term: string) {

        if (!term) {
            return value
        }
        let res = (value || []).filter((item) => keys.split(',').some(key => item.hasOwnProperty(key) && new RegExp(term, 'gi').test(item[key])));
        return res.length ? res : [-1];

    }
}

Now, in your HTML you can check via '-1' value, for no results.

HTML:

<div *ngFor="let item of list | filterFromList: 'attribute': inputVariableModel">
            <mat-list-item *ngIf="item !== -1">
                <h4 mat-line class="inline-block">
                 {{item}}
                </h4>
            </mat-list-item>
            <mat-list-item *ngIf="item === -1">
                No Matches
            </mat-list-item>
        </div>

Makefiles with source files in different directories

The VPATH option might come in handy, which tells make what directories to look in for source code. You'd still need a -I option for each include path, though. An example:

CXXFLAGS=-Ipart1/inc -Ipart2/inc -Ipart3/inc
VPATH=part1/src:part2/src:part3/src

OutputExecutable: part1api.o part2api.o part3api.o

This will automatically find the matching partXapi.cpp files in any of the VPATH specified directories and compile them. However, this is more useful when your src directory is broken into subdirectories. For what you describe, as others have said, you are probably better off with a makefile for each part, especially if each part can stand alone.

How to install sklearn?

You didn't provide us which operating system are you on? If it is a Linux, make sure you have scipy installed as well, after that just do

pip install -U scikit-learn

If you are on windows you might want to check out these pages.

How to install Laravel's Artisan?

in laravel, artisan is a file under root/protected page

for example,

c:\xampp\htdocs\my_project\protected\artisan

you can view the content of "artisan" file with any text editor, it's a php command syntax

so when we type

php artisan

we tell php to run php script in "artisan" file

for example:

php artisan change

will show the change of current laravel version

to see the other option, just type

php artisan

How to break lines at a specific character in Notepad++?

If you are looking to get a comma separated string into a column with CR LF you wont be able to do that in Notepad++, assuming you didn't want to write code, you could manipulate it in Microsoft Excel.

If you copy your string to location B1:

A2 =LEFT(B1,FIND(",",B1)-1)
B2 =MID(B1,FIND(",",B1)+1,10000)

Select A2 and B2, copy the code to successive cells (by dragging):

A3 =LEFT(B2,FIND(",",B2)-1)
B3 =MID(B2,FIND(",",B2)+1,10000)

When you get #VALUE! in the last cell of column A replace it with the previous rows B value.

In the end your A column will contain the desired text. Copy and past it anywhere you wish.

Pure CSS collapse/expand div

Or a super simple version with barely any css :)

<style>   
.faq ul li {
    display:block;
    float:left;
    padding:5px;
}

.faq ul li div {
    display:none;
}

.faq ul li div:target {
    display:block;
}


</style>


<div class="faq">
   <ul>
   <li><a href="#question1">Question 1</a>   
   <div id="question1">Answer 1 </div>
   </li>


   <li><a href="#question2">Question 2</a>
   <div id="question2">Answer 2 </div>
   </li>
   <li><a href="#question3">Question 3</a>
   <div id="question3">Answer 3 </div>
   </li>
   <li><a href="#question4">Question 4</a>
   <div id="question4">Answer 4 </div>
   </li>
   <li><a href="#question5">Question 5</a>
   <div id="question5">Answer 5 </div>
   </li>
   <li><a href="#question6">Question 6</a>
   <div id="question6">Answer 6 </div>
   </li>
   </ul>  
</div>

http://jsfiddle.net/ionko22/4sKD3/

python variable NameError

This should do it:

#!/usr/local/cpython-2.7/bin/python  # offer users choice for how large of a song list they want to create # in order to determine (roughly) how many songs to copy print "\nHow much space should the random song list occupy?\n" print "1. 100Mb" print "2. 250Mb\n"  tSizeAns = int(raw_input())  if tSizeAns == 1:     tSize = "100Mb" elif tSizeAns == 2:     tSize = "250Mb" else:     tSize = "100Mb"    # in case user fails to enter either a 1 or 2  print "\nYou  want to create a random song list that is {}.".format(tSize) 

BTW, in case you're open to moving to Python 3.x, the differences are slight:

#!/usr/local/cpython-3.3/bin/python  # offer users choice for how large of a song list they want to create # in order to determine (roughly) how many songs to copy print("\nHow much space should the random song list occupy?\n") print("1. 100Mb") print("2. 250Mb\n")  tSizeAns = int(input())  if tSizeAns == 1:     tSize = "100Mb" elif tSizeAns == 2:     tSize = "250Mb" else:     tSize = "100Mb"    # in case user fails to enter either a 1 or 2  print("\nYou want to create a random song list that is {}.".format(tSize)) 

HTH

Visual Studio Community 2015 expiration date

In my case, even after sign up to Visual Studio account, I cant sign in and the license still expired.

Solution from across the internet: Download iso version of the installer. Then run installer, select repair. That would solve the problem for most case.

In my case, I got an iso version of ms Visual Studio 2013. Installed it and I can successfully sign in and its forever free.

What is the difference between vmalloc and kmalloc?

Short answer: download Linux Device Drivers and read the chapter on memory management.

Seriously, there are a lot of subtle issues related to kernel memory management that you need to understand - I spend a lot of my time debugging problems with it.

vmalloc() is very rarely used, because the kernel rarely uses virtual memory. kmalloc() is what is typically used, but you have to know what the consequences of the different flags are and you need a strategy for dealing with what happens when it fails - particularly if you're in an interrupt handler, like you suggested.

Set equal width of columns in table layout in Android

Change android:stretchColumns value to *.

Value 0 means stretch the first column. Value 1 means stretch the second column and so on.

Value * means stretch all the columns.

Using .htaccess to make all .html pages to run as .php files?

Using @Marc-François approach Firefox prompted me to download the html file

Finally the following is working for me (using both):

AddType application/x-httpd-php .htm .html AddHandler x-httpd-php .htm .html

Getting the client's time zone (and offset) in JavaScript

A one-liner that gives both the offset and the time zone is to simply call toTimeString() on a new Date object. From MDN:

The toTimeString() method returns the time portion of a Date object in human readable form in American English.

The catch is that the timezone is not in the standard IANA format; it's somewhat more user-friendly, than the "continent/city" IANA format. Try it out:

_x000D_
_x000D_
console.log(new Date().toTimeString().slice(9));
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);
console.log(new Date().getTimezoneOffset() / -60);
_x000D_
_x000D_
_x000D_

In California right now, toTimeString() returns Pacific Daylight Time while the Intl API returns America/Los_Angeles. In Colombia, you'd get Colombia Standard Time, vs. America/Bogota.

Note that many other answers to this question attempt to obtain the same information by calling Date.toString(). That approach is not that reliable, as MDN explains:

Date instances refer to a specific point in time. Calling toString() will return the date formatted in a human readable form in American English. [...] Sometimes it is desirable to obtain a string of the time portion; such a thing can be accomplished with the toTimeString() method.

The toTimeString() method is especially useful because compliant engines implementing ECMA-262 may differ in the string obtained from toString() for Date objects, as the format is implementation-dependent; simple string slicing approaches may not produce consistent results across multiple engines.

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

In datasets having large number of columns its even better to see how many columns contain null values and how many don't.

print("No. of columns containing null values")
print(len(df.columns[df.isna().any()]))

print("No. of columns not containing null values")
print(len(df.columns[df.notna().all()]))

print("Total no. of columns in the dataframe")
print(len(df.columns))

For example in my dataframe it contained 82 columns, of which 19 contained at least one null value.

Further you can also automatically remove cols and rows depending on which has more null values
Here is the code which does this intelligently:

df = df.drop(df.columns[df.isna().sum()>len(df.columns)],axis = 1)
df = df.dropna(axis = 0).reset_index(drop=True)

Note: Above code removes all of your null values. If you want null values, process them before.

Java ArrayList - Check if list is empty

You should use method listName.isEmpty()

How do I set the classpath in NetBeans?

Maven

The Answer by Bhesh Gurung is correct… unless your NetBeans project is Maven based.

Dependency

Under Maven, you add a "dependency". A dependency is a description of a library (its name & version number) you want to use from your code.

Or a dependency could be a description of a library which another library needs ("depends on"). Maven automatically handles this chain, libraries that need other libraries that then need other libraries and so on. For the mathematical-minded, perhaps the phrase "Maven resolves the transitive dependencies" makes sense.

Repository

Maven gets this related-ness information, and the libraries themselves from a Maven repository. A repository is basically an online database and collection of download files (the dependency library).

Easy to Use

Adding a dependency to a Maven-based project is really quite easy. That is the whole point to Maven, to make managing dependent libraries easy and to make building them into your project easy. To get started with adding a dependency, see this Question, Adding dependencies in Maven Netbeans and my Answer with screenshot.

enter image description here

How to uninstall Apache with command line

If Apache was installed using NSIS installer it should have left an uninstaller. You should search inside Apache installation directory for executable named unistaller.exe or something like that. NSIS uninstallers support /S flag by default for silent uninstall. So you can run something like "C:\Program Files\<Apache installation dir here>\uninstaller.exe" /S

From NSIS documentation:

3.2.1 Common Options

/NCRC disables the CRC check, unless CRCCheck force was used in the script. /S runs the installer or uninstaller silently. See section 4.12 for more information. /D sets the default installation directory ($INSTDIR), overriding InstallDir and InstallDirRegKey. It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. Only absolute paths are supported.

Adding Google Translate to a web site

<div id="google_translate_element"></div><script type="text/javascript">
function googleTranslateElementInit() {
  new google.translate.TranslateElement({pageLanguage: 'en', includedLanguages: 'ar', layout: google.translate.TranslateElement.InlineLayout.SIMPLE}, 'google_translate_element');
}
</script><script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

php mail setup in xampp

Unless you have a mail server set up on your local computer, setting SMTP = localhost won't have any effect.

In days gone by (long ago), it was sufficient to set the value of SMTP to the address of your ISP's SMTP server. This now rarely works because most ISPs insist on authentication with a username and password. However, the PHP mail() function doesn't support SMTP authentication. It's designed to work directly with the mail transport agent of the local server.

You either need to set up a local mail server or to use a PHP classs that supports SMTP authentication, such as Zend_Mail or PHPMailer. The simplest solution, however, is to upload your mail processing script to your remote server.

Escape quote in web.config connection string

Odeds answer is almost complete. Just one thing to add.

  1. Escape xml special chars like Emanuele Greco said.
  2. Put the password in single quotes like Oded said
  3. (this one is new) Escape single ticks with another single tick (ref)

having this password="'; this sould be a valid connection string:

connectionString='Server=dbsrv;User ID=myDbUser;Password='&quot;&amp;&amp;;'

PHP returning JSON to JQUERY AJAX CALL

You can return json in PHP this way:

header('Content-Type: application/json');
echo json_encode(array('foo' => 'bar'));
exit;

Stretch image to fit full container width bootstrap

In bootstrap 4.1, the w-100 class is required along with img-fluid for images smaller than the page to be stretched:

<div class="container">
  <div class="row">
    <img class='img-fluid w-100' src="#" alt="" />
  </div>
</div>

see closed issue: https://github.com/twbs/bootstrap/issues/20830

(As of 2018-04-20, the documentation is wrong: https://getbootstrap.com/docs/4.1/content/images/ says that img-fluid applies max-width: 100%; height: auto;" but img-fluid does not resolve the issue, and neither does manually adding those style attributes with or without bootstrap classes on the img tag.)

Export MySQL database using PHP only

This tool might be useful, it's a pure PHP based export utility: https://github.com/2createStudio/shuttle-export

How to get the last element of a slice?

Bit less elegant but can also do:

sl[len(sl)-1: len(sl)]

Generate SHA hash in C++ using OpenSSL library

OpenSSL has a horrible documentation with no code examples, but here you are:

#include <openssl/sha.h>

bool simpleSHA256(void* input, unsigned long length, unsigned char* md)
{
    SHA256_CTX context;
    if(!SHA256_Init(&context))
        return false;

    if(!SHA256_Update(&context, (unsigned char*)input, length))
        return false;

    if(!SHA256_Final(md, &context))
        return false;

    return true;
}

Usage:

unsigned char md[SHA256_DIGEST_LENGTH]; // 32 bytes
if(!simpleSHA256(<data buffer>, <data length>, md))
{
    // handle error
}

Afterwards, md will contain the binary SHA-256 message digest. Similar code can be used for the other SHA family members, just replace "256" in the code.

If you have larger data, you of course should feed data chunks as they arrive (multiple SHA256_Update calls).

How to make a UILabel clickable?

Good and convenient solution:

In your ViewController:

@IBOutlet weak var label: LabelButton!

override func viewDidLoad() {
    super.viewDidLoad()

    self.label.onClick = {
        // TODO
    }
}

You can place this in your ViewController or in another .swift file(e.g. CustomView.swift):

@IBDesignable class LabelButton: UILabel {
    var onClick: () -> Void = {}
    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
        onClick()
    }
}

In Storyboard select Label and on right pane in "Identity Inspector" in field class select LabelButton.

Don't forget to enable in Label Attribute Inspector "User Interaction Enabled"

Find row in datatable with specific id

I could use the following code. Thanks everyone.

int intID = 5;
DataTable Dt = MyFuctions.GetData();
Dt.PrimaryKey = new DataColumn[] { Dt.Columns["ID"] };
DataRow Drw = Dt.Rows.Find(intID);
if (Drw != null) Dt.Rows.Remove(Drw);

How do I replace a character in a string in Java?

Try using String.replace() or String.replaceAll() instead.

String my_new_str = my_str.replace("&", "&amp;");

(Both replace all occurrences; replaceAll allows use of regex.)

Where Sticky Notes are saved in Windows 10 1607

It worked for me when HDD with win8.1 crashed and my new HDD has win10. Important to know - Create Legacy folder mentioned in this link. - Remember to rename the StickyNotes.snt to ThresholdNotes.snt. - Restart the app

Find details here https://www.reddit.com/r/Windows10/comments/4wxfds/transfermigrate_sticky_notes_to_new_anniversary/

Convert NVARCHAR to DATETIME in SQL Server 2008

what about this

--// Convert NVARCHAR to DATETIME
DECLARE @date DATETIME = (SELECT convert(DATETIME, '2013-08-29 13:55:48', 120))
--// Convert DATETIME to custom NVARCHAR FORMAT
SELECT 
RIGHT('00'+ CAST(DAY(@date) AS NVARCHAR),2) + '-' +
RIGHT('00'+ CAST(MONTH(@date) AS NVARCHAR),2) + '-' + 
CAST(YEAR(@date) AS NVARCHAR) + ' ' + 
CAST(CONVERT(TIME,@date) AS NVARCHAR)

result: '29-08-2013 13:55:48.0000000'

Uninstall all installed gems, in OSX?

The only command helped me to cleanup all gems and ignores default gems, which can't be uninstalled

for x in `gem list --no-versions`; do gem uninstall $x -a -x -I; done

How to do what head, tail, more, less, sed do in Powershell?

Here are the built-in ways to do head and tail. Don't use pipes because if you have a large file, it will be extremely slow. Using these built-in options will be extremely fast even for huge files.

gc log.txt -head 10 
gc log.txt -tail 10
gc log.txt -tail 10 -wait # equivalent to tail -f

MongoDb shuts down with Code 100

Aravind.

It happened with me too because I stopped the MongoDB by the Task Manager.

Creating the C:\data\db folder and starting the MongoDB at C:\Program Files\MongoDB\Server\3.4\bin\mongod.exe worked for me, as cespon suggested, but the MongoDB didn't show any of my Databases previously created.

Then, removing the C:\data\db folder and repairing the installation with the MongoDB installer, I recovered my data and started normally the MongoDB.

(I'm very new with MongoDB, but it helped me solve this problem and recover may previews data).

How can I get an object's absolute position on the page in Javascript?

var cumulativeOffset = function(element) {
    var top = 0, left = 0;
    do {
        top += element.offsetTop  || 0;
        left += element.offsetLeft || 0;
        element = element.offsetParent;
    } while(element);

    return {
        top: top,
        left: left
    };
};

(Method shamelessly stolen from PrototypeJS; code style, variable names and return value changed to protect the innocent)

How to rename a component in Angular CLI?

Here is a checklist I use to rename a component:

1.Rename the component class (VSCode Rename Symbool will update all the references)

<Old Name>Component => <New Name>Component

2.Rename @Component selector along with references (use VSCode's Replace in Files):

app-<old-name> => app-<new-name>

Result:
@Component({
  selector: 'app-<old-name>' => 'app-<new-name>',
  ...
})

<app-{old-name}></app-{old-name}> => <app-{new-name}></app-{new-name}>

3.Rename component folder (when renaming folder in VSCode, it will update references in module and other components)

src\app\<module>\<old-name> => src\app\<module>\<new-name>

4.Rename component files (renaming manually will be the fastest, but you can also use a terminal to rename all at once)

<old-name>.compoonent.* => <new-name>.compoonent.*

Bash:
find . -name "<old-name>.component.*" -exec rename 's/\/<old-name>\.component/\/<new-name>.component/' '{}' +

PowerShell: 
Get-Item <old-name>.component.* | % { Rename-Item $_ <new-name>.component.$($_.Extension) }

Cmd:
rename <old-name>.component.* <new-name>.component.*

5.Replace file references in @Component (use VSCode's Replace in Files):

<old-name>.component => <new-name>.component

Result:
@Component({
  ...
  templateUrl: './<old-name>.component.html' => './<old-name>.component.html',
  styleUrls: ['./<old-name>.component.scss'] => ['./<new-name>.component.scss']
})

That should be sufficient

Foreign Key Django Model

I would advise, it is slightly better practise to use string model references for ForeignKey relationships if utilising an app based approach to seperation of logical concerns .

So, expanding on Martijn Pieters' answer:

class Person(models.Model):
    name = models.CharField(max_length=50)
    birthday = models.DateField()
    anniversary = models.ForeignKey(
        'app_label.Anniversary', on_delete=models.CASCADE)
    address = models.ForeignKey(
        'app_label.Address', on_delete=models.CASCADE)

class Address(models.Model):
    line1 = models.CharField(max_length=150)
    line2 = models.CharField(max_length=150)
    postalcode = models.CharField(max_length=10)
    city = models.CharField(max_length=150)
    country = models.CharField(max_length=150)

class Anniversary(models.Model):
    date = models.DateField()

How to get the current time in YYYY-MM-DD HH:MI:Sec.Millisecond format in Java?

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

What does PHP keyword 'var' do?

So basically it is an old style and do not use it for newer version of PHP. Better to use Public keyword instead;if you are not in love with var keyword. So instead of using

class Test {
    var $name;
}

Use

class Test {
   public $name;
}

What is the closest thing Windows has to fork()?

If you only care about creating a subprocess and waiting for it, perhaps _spawn* API's in process.h are sufficient. Here's more information about that:

https://docs.microsoft.com/en-us/cpp/c-runtime-library/process-and-environment-control https://en.wikipedia.org/wiki/Process.h

Default value in an asp.net mvc view model

<div class="form-group">
                    <label asp-for="Password"></label>
                    <input asp-for="Password"  value="Pass@123" readonly class="form-control" />
                    <span asp-validation-for="Password" class="text-danger"></span>
                </div>

use : value="Pass@123" for default value in input in .net core

Bulk Insert Correctly Quoted CSV File in SQL Server

Make sure you have enabled TextQualified option and set it to be ".

Get selected key/value of a combo box using jQuery

This works:

<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<input type="button" id="button" value="Button" />

$('#button').click(function() {
    alert($('#foo option:selected').text());
    alert($('#foo option:selected').val());
});

Do you have to put Task.Run in a method to make it async?

One of the most important thing to remember when decorating a method with async is that at least there is one await operator inside the method. In your example, I would translate it as shown below using TaskCompletionSource.

private Task<int> DoWorkAsync()
{
    //create a task completion source
    //the type of the result value must be the same
    //as the type in the returning Task
    TaskCompletionSource<int> tcs = new TaskCompletionSource<int>();
    Task.Run(() =>
    {
        int result = 1 + 2;
        //set the result to TaskCompletionSource
        tcs.SetResult(result);
    });
    //return the Task
    return tcs.Task;
}

private async void DoWork()
{
    int result = await DoWorkAsync();
}

How to execute a raw update sql with dynamic binding in rails

Why use raw SQL for this?

If you have a model for it use where:

f1 = 'foo'
f2 = 'bar'
f3 = 'buzz'
YourModel.where('f1 = ? and f2 = ?', f1, f2).each do |ym|
  # or where(f1: f1, f2: f2).each do (...)
  ym.update(f3: f3) 
end

If you don't have a model for it (just the table), you can create a file and model that will inherit from ActiveRecord::Base

class YourTable < ActiveRecord::Base
  self.table_name = 'your_table' # specify explicitly if needed
end

and again use where the same as above:

How do I insert datetime value into a SQLite database?

This may not be the most popular or efficient method, but I tend to forgo strong datatypes in SQLite since they are all essentially dumped in as strings anyway.

I've written a thin C# wrapper around the SQLite library before (when using SQLite with C#, of course) to handle insertions and extractions to and from SQLite as if I were dealing with DateTime objects.

How to define custom sort function in javascript?

function msort(arr){
    for(var i =0;i<arr.length;i++){
        for(var j= i+1;j<arr.length;j++){
            if(arr[i]>arr[j]){
                var swap = arr[i];
                arr[i] = arr[j];
                arr[j] = swap;
            }
        }
    }
return arr;
}

Where can I find a list of Mac virtual key codes?

Below is a list of the common key codes for quick reference, taken from Events.h.

If you need to use these keycodes in an application, you should include the Carbon framework:

Objective-C:
#include <Carbon/Carbon.h>

Swift:
import Carbon.HIToolbox

You can then use the kVK_ANSI_A constants directly.


WARNING

The key constants reference physical keys on the keyboard. Their output changes if the typist is using a different keyboard layout. The letters in the constants correspond only to the U.S. QWERTY keyboard layout.

For example, the left ring-finger key on the homerow:

QWERTY keyboard layout > s > kVK_ANSI_S > "s"
Dvorak keyboard layout > o > kVK_ANSI_S > "o"

Strategies for layout-agnostic conversion of keycode to string, and vice versa, are discussed here:

How to convert ASCII character to CGKeyCode?


From Events.h:

/*
 *  Summary:
 *    Virtual keycodes
 *  
 *  Discussion:
 *    These constants are the virtual keycodes defined originally in
 *    Inside Mac Volume V, pg. V-191. They identify physical keys on a
 *    keyboard. Those constants with "ANSI" in the name are labeled
 *    according to the key position on an ANSI-standard US keyboard.
 *    For example, kVK_ANSI_A indicates the virtual keycode for the key
 *    with the letter 'A' in the US keyboard layout. Other keyboard
 *    layouts may have the 'A' key label on a different physical key;
 *    in this case, pressing 'A' will generate a different virtual
 *    keycode.
 */
enum {
  kVK_ANSI_A                    = 0x00,
  kVK_ANSI_S                    = 0x01,
  kVK_ANSI_D                    = 0x02,
  kVK_ANSI_F                    = 0x03,
  kVK_ANSI_H                    = 0x04,
  kVK_ANSI_G                    = 0x05,
  kVK_ANSI_Z                    = 0x06,
  kVK_ANSI_X                    = 0x07,
  kVK_ANSI_C                    = 0x08,
  kVK_ANSI_V                    = 0x09,
  kVK_ANSI_B                    = 0x0B,
  kVK_ANSI_Q                    = 0x0C,
  kVK_ANSI_W                    = 0x0D,
  kVK_ANSI_E                    = 0x0E,
  kVK_ANSI_R                    = 0x0F,
  kVK_ANSI_Y                    = 0x10,
  kVK_ANSI_T                    = 0x11,
  kVK_ANSI_1                    = 0x12,
  kVK_ANSI_2                    = 0x13,
  kVK_ANSI_3                    = 0x14,
  kVK_ANSI_4                    = 0x15,
  kVK_ANSI_6                    = 0x16,
  kVK_ANSI_5                    = 0x17,
  kVK_ANSI_Equal                = 0x18,
  kVK_ANSI_9                    = 0x19,
  kVK_ANSI_7                    = 0x1A,
  kVK_ANSI_Minus                = 0x1B,
  kVK_ANSI_8                    = 0x1C,
  kVK_ANSI_0                    = 0x1D,
  kVK_ANSI_RightBracket         = 0x1E,
  kVK_ANSI_O                    = 0x1F,
  kVK_ANSI_U                    = 0x20,
  kVK_ANSI_LeftBracket          = 0x21,
  kVK_ANSI_I                    = 0x22,
  kVK_ANSI_P                    = 0x23,
  kVK_ANSI_L                    = 0x25,
  kVK_ANSI_J                    = 0x26,
  kVK_ANSI_Quote                = 0x27,
  kVK_ANSI_K                    = 0x28,
  kVK_ANSI_Semicolon            = 0x29,
  kVK_ANSI_Backslash            = 0x2A,
  kVK_ANSI_Comma                = 0x2B,
  kVK_ANSI_Slash                = 0x2C,
  kVK_ANSI_N                    = 0x2D,
  kVK_ANSI_M                    = 0x2E,
  kVK_ANSI_Period               = 0x2F,
  kVK_ANSI_Grave                = 0x32,
  kVK_ANSI_KeypadDecimal        = 0x41,
  kVK_ANSI_KeypadMultiply       = 0x43,
  kVK_ANSI_KeypadPlus           = 0x45,
  kVK_ANSI_KeypadClear          = 0x47,
  kVK_ANSI_KeypadDivide         = 0x4B,
  kVK_ANSI_KeypadEnter          = 0x4C,
  kVK_ANSI_KeypadMinus          = 0x4E,
  kVK_ANSI_KeypadEquals         = 0x51,
  kVK_ANSI_Keypad0              = 0x52,
  kVK_ANSI_Keypad1              = 0x53,
  kVK_ANSI_Keypad2              = 0x54,
  kVK_ANSI_Keypad3              = 0x55,
  kVK_ANSI_Keypad4              = 0x56,
  kVK_ANSI_Keypad5              = 0x57,
  kVK_ANSI_Keypad6              = 0x58,
  kVK_ANSI_Keypad7              = 0x59,
  kVK_ANSI_Keypad8              = 0x5B,
  kVK_ANSI_Keypad9              = 0x5C
};

/* keycodes for keys that are independent of keyboard layout*/
enum {
  kVK_Return                    = 0x24,
  kVK_Tab                       = 0x30,
  kVK_Space                     = 0x31,
  kVK_Delete                    = 0x33,
  kVK_Escape                    = 0x35,
  kVK_Command                   = 0x37,
  kVK_Shift                     = 0x38,
  kVK_CapsLock                  = 0x39,
  kVK_Option                    = 0x3A,
  kVK_Control                   = 0x3B,
  kVK_RightShift                = 0x3C,
  kVK_RightOption               = 0x3D,
  kVK_RightControl              = 0x3E,
  kVK_Function                  = 0x3F,
  kVK_F17                       = 0x40,
  kVK_VolumeUp                  = 0x48,
  kVK_VolumeDown                = 0x49,
  kVK_Mute                      = 0x4A,
  kVK_F18                       = 0x4F,
  kVK_F19                       = 0x50,
  kVK_F20                       = 0x5A,
  kVK_F5                        = 0x60,
  kVK_F6                        = 0x61,
  kVK_F7                        = 0x62,
  kVK_F3                        = 0x63,
  kVK_F8                        = 0x64,
  kVK_F9                        = 0x65,
  kVK_F11                       = 0x67,
  kVK_F13                       = 0x69,
  kVK_F16                       = 0x6A,
  kVK_F14                       = 0x6B,
  kVK_F10                       = 0x6D,
  kVK_F12                       = 0x6F,
  kVK_F15                       = 0x71,
  kVK_Help                      = 0x72,
  kVK_Home                      = 0x73,
  kVK_PageUp                    = 0x74,
  kVK_ForwardDelete             = 0x75,
  kVK_F4                        = 0x76,
  kVK_End                       = 0x77,
  kVK_F2                        = 0x78,
  kVK_PageDown                  = 0x79,
  kVK_F1                        = 0x7A,
  kVK_LeftArrow                 = 0x7B,
  kVK_RightArrow                = 0x7C,
  kVK_DownArrow                 = 0x7D,
  kVK_UpArrow                   = 0x7E
};

Macintosh Toolbox Essentials illustrates the physical locations of these virtual key codes for the Apple Extended Keyboard II in Figure 2-10:

Virtual key codes for the Apple Extended Keyboard II

What should I do when 'svn cleanup' fails?

Whenever I have similar problems I use rsync (NB: I use Linux or Mac OS X) to help out like so:

# Go to the parent directory
cd dir_above_borked

# Rename corrupted directory
mv borked_dir borked_dir.bak

# Checkout a fresh copy
svn checkout svn://... borked_dir

# Copy the modified files to the fresh checkout
# - test rsync
#   (possibly use -c to verify all content and show only actually changed files)
rsync -nav --exclude=.svn borked_dir.bak/ borked_dir/

# - If all ok, run rsync for real
#   (possibly using -c again, possibly not using -v)
rsync -av --exclude=.svn borked_dir.bak/ borked_dir/

That way you have a fresh checkout, but with the same working files. For me this always works like a charm.

Which is the correct C# infinite loop, for (;;) or while (true)?

It should be while(true) not while(1), so while(1) is incorrect in C#, yes ;)

How do I define and use an ENUM in Objective-C?

With current projects you may want to use the NS_ENUM() or NS_OPTIONS() macros.

typedef NS_ENUM(NSUInteger, PlayerState) {
        PLAYER_OFF,
        PLAYER_PLAYING,
        PLAYER_PAUSED
    };

iptables block access to port 8000 except from IP address

You can always use iptables to delete the rules. If you have a lot of rules, just output them using the following command.

iptables-save > myfile

vi to edit them from the commend line. Just use the "dd" to delete the lines you no longer want.

iptables-restore < myfile and you're good to go.  

REMEMBER THAT IF YOU DON'T CONFIGURE YOUR OS TO SAVE THE RULES TO A FILE AND THEN LOAD THE FILE DURING THE BOOT THAT YOUR RULES WILL BE LOST.

Convert .class to .java

I used the http://www.javadecompilers.com but in some classes it gives you the message "could not load this classes..."

INSTEAD download Android Studio, navigate to the folder containing the java class file and double click it. The code will show in the right pane and I guess you can copy it an save it as a java file from there

How to use UTF-8 in resource properties with ResourceBundle

Speaking for current (2021-2) Java versions there is still the old ISO-8859-1 function utils.Properties#load.

Allow me to quote from the official doc.

PropertyResourceBundle

PropertyResourceBundle can be constructed either from an InputStream or a Reader, which represents a property file. Constructing a PropertyResourceBundle instance from an InputStream requires that the input stream be encoded in UTF-8. By default, if a MalformedInputException or an UnmappableCharacterException occurs on reading the input stream, then the PropertyResourceBundle instance resets to the state before the exception, re-reads the input stream in ISO-8859-1, and continues reading. If the system property java.util.PropertyResourceBundle.encoding is set to either "ISO-8859-1" or "UTF-8", the input stream is solely read in that encoding, and throws the exception if it encounters an invalid sequence. If "ISO-8859-1" is specified, characters that cannot be represented in ISO-8859-1 encoding must be represented by Unicode Escapes as defined in section 3.3 of The Java™ Language Specification whereas the other constructor which takes a Reader does not have that limitation. Other encoding values are ignored for this system property. The system property is read and evaluated when initializing this class. Changing or removing the property has no effect after the initialization.

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/PropertyResourceBundle.html

Properties#load

Reads a property list (key and element pairs) from the input byte stream. The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification.

https://docs.oracle.com/en/java/javase/14/docs/api/java.base/java/util/Properties.html#load(java.io.InputStream)

How to Create a circular progressbar in Android which rotates on it?

Change

android:useLevel="false"

to

android:useLevel="true"

for second sahpe with id="@android:id/progress

hope it works

How to copy files from 'assets' folder to sdcard?

Copy all files and directories from assets to your folder!

for copying better use apache commons io

public void doCopyAssets() throws IOException {
    File externalFilesDir = context.getExternalFilesDir(null);

    doCopy("", externalFilesDir.getPath());

}

//THIS IS MAIN METHOD FOR COPY

private void doCopy(String dirName, String outPath) throws IOException {

    String[] srcFiles = assets.list(dirName);//for directory
    for (String srcFileName : srcFiles) {
        String outFileName = outPath + File.separator + srcFileName;
        String inFileName = dirName + File.separator + srcFileName;
        if (dirName.equals("")) {// for first time
            inFileName = srcFileName;
        }
        try {
            InputStream inputStream = assets.open(inFileName);
            copyAndClose(inputStream, new FileOutputStream(outFileName));
        } catch (IOException e) {//if directory fails exception
            new File(outFileName).mkdir();
            doCopy(inFileName, outFileName);
        }

    }
}

public static void closeQuietly(AutoCloseable autoCloseable) {
    try {
        if(autoCloseable != null) {
            autoCloseable.close();
        }
    } catch(IOException ioe) {
        //skip
    }
}

public static void copyAndClose(InputStream input, OutputStream output) throws IOException {
    copy(input, output);
    closeQuietly(input);
    closeQuietly(output);
}

public static void copy(InputStream input, OutputStream output) throws IOException {
    byte[] buffer = new byte[1024];
    int n = 0;
    while(-1 != (n = input.read(buffer))) {
        output.write(buffer, 0, n);
    }
}

How to conclude your merge of a file?

If you encounter this error in SourceTree, go to Actions>Resolve Conflicts>Restart Merge.

SourceTree version used is 1.6.14.0

How to set an iframe src attribute from a variable in AngularJS

this way i follow and its work for me fine, may it will works for you,

<iframe class="img-responsive" src="{{pdfLoc| trustThisUrl }}" ng-style="{
                height: iframeHeight * 0.75 + 'px'
            }" style="width:100%"></iframe>

here trustThisUrl is just filter,

angular.module("app").filter('trustThisUrl', ["$sce", function ($sce) {
        return function (val) {
            return $sce.trustAsResourceUrl(val);
        };
    }]);

install beautiful soup using pip

If you have more than one version of python installed, run the respective pip command.

For example for python3.6 run the following

pip3.6 install beautifulsoup4

To check the available command/version of pip and python on Mac run

ls /usr/local/bin

How to calculate distance between two locations using their longitude and latitude value

Why are you writing the code for calculating the distance by yourself?

Check the api's in Location class

Signed to unsigned conversion in C - is it always safe?

When converting from signed to unsigned there are two possibilities. Numbers that were originally positive remain (or are interpreted as) the same value. Number that were originally negative will now be interpreted as larger positive numbers.

List<String> to ArrayList<String> conversion issue

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

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

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

How do I create a view controller file after creating a new view controller?

To add new ViewController once you have have an existing ViewController, follow below step:

  1. Click on background of Main.storyboard.

  2. Search and select ViewController from object library at the utility window.

  3. Drag and drop it in background to create a new ViewController.

Rails: FATAL - Peer authentication failed for user (PG::Error)

I was facing same problem on Ubuntu machine so I removed this error by following some steps. Switch to postgres user

$ sudo su - postgres

it will ask for password and by default password is postgres

After switch the user to postgres, open psql console

$ psql

so check the version of postgres if multiple versions are available

psql=# select VERSION();

PostgreSQL 9.1.13 on x86_64-unk....         # so version is 9.1

Now Open postgres user

vim /etc/postgresql/9.1/main/pg_hba.conf

9.1 is version return form upper command

and replace

local   all             postgres                                peer

to

local   all             postgres                                md5

Restart the service

sudo service postgresql restart

I write steps on my blog also

http://tarungarg402.blogspot.in/2014/10/set-up-postgresql-on-ubuntu.html

How can I get href links from HTML using Python?

Using requests with BeautifulSoup and Python 3:

import requests 
from bs4 import BeautifulSoup


page = requests.get('http://www.website.com')
bs = BeautifulSoup(page.content, features='lxml')
for link in bs.findAll('a'):
    print(link.get('href'))

How to check if a stored procedure exists before creating it

In Sql server 2008 onwards, you can use "INFORMATION_SCHEMA.ROUTINES"

IF EXISTS (SELECT 1 FROM INFORMATION_SCHEMA.ROUTINES 
  WHERE ROUTINE_NAME = 'MySP'
        AND ROUTINE_TYPE = 'PROCEDURE') 

How to implement 2D vector array?

I'm not exactly sure what the problem is, as your example code has several errors and doesn't really make it clear what you're trying to do. But here's how you add to a specific row of a 2D vector:

// declare 2D vector
vector< vector<int> > myVector;
// make new row (arbitrary example)
vector<int> myRow(1,5);
myVector.push_back(myRow);
// add element to row
myVector[0].push_back(1);

Does this answer your question? If not, could you try to be more specific as to what you are having trouble with?

Two's Complement in Python

you could convert the integer to bytes and then use struct.unpack to convert:

from struct import unpack

x = unpack("b", 0b11111111.to_bytes(length=1, byteorder="little"))
print(x)  # (-1,)

Count number of times a date occurs and make a graph out of it

The simplest is to do a PivotChart. Select your array of dates (with a header) and create a new Pivot Chart (Insert / PivotChart / Ok) Then on the field list window, drag and drop the date column in the Axis list first and then in the value list first.

Step 1:

Step1

Step 2:

Step2

Multiline TextBox multiple newline

textBox1.Text = "Line1\r\r\Line2";
Solved the problem.

Excel 2007: How to display mm:ss format not as a DateTime (e.g. 73:07)?

5.In the Format Cells box, click Custom in the Category list. 6.In the Type box, at the top of the list of formats, type [h]:mm;@ and then click OK. (That’s a colon after [h], and a semicolon after mm.) YOu can then add hours. The format will be in the Type list the next time you need it.

From MS, works well.

http://office.microsoft.com/en-us/excel-help/add-or-subtract-time-HA102809662.aspx

How to prevent favicon.ico requests?

You can't. All you can do is to make that image as small as possible and set some cache invalidation headers (Expires, Cache-Control) far in the future. Here's what Yahoo! has to say about favicon.ico requests.

PHP Parse HTML code

Use PHP Document Object Model:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   $DOM = new DOMDocument;
   $DOM->loadHTML($str);

   //get all H1
   $items = $DOM->getElementsByTagName('h1');

   //display all H1 text
   for ($i = 0; $i < $items->length; $i++)
        echo $items->item($i)->nodeValue . "<br/>";
?>

This outputs as:

 T1
 T2
 T3

[EDIT]: After OP Clarification:

If you want the content like Lorem ipsum. etc, you can directly use this regex:

<?php
   $str = '<h1>T1</h1>Lorem ipsum.<h1>T2</h1>The quick red fox...<h1>T3</h1>... jumps over the lazy brown FROG';
   echo preg_replace("#<h1.*?>.*?</h1>#", "", $str);
?>

this outputs:

Lorem ipsum.The quick red fox...... jumps over the lazy brown FROG

Update a table using JOIN in SQL Server?

    UPDATE mytable
         SET myfield = CASE other_field
             WHEN 1 THEN 'value'
             WHEN 2 THEN 'value'
             WHEN 3 THEN 'value'
         END
    From mytable
    Join otherTable on otherTable.id = mytable.id
    Where othertable.somecolumn = '1234'

More alternatives here.

How do I hide the bullets on my list for the sidebar?

its on you ul in the file http://ratest4.com/wp-content/themes/HarnettArts-BP-2010/style.css on line 252

add this to your css

ul{
     list-style:none;
}

How Can I Set the Default Value of a Timestamp Column to the Current Timestamp with Laravel Migrations?

I use the following customization in Laravel to:

  1. Default created_at to the current timestamp
  2. Update the timestamp when the record is updated

First, I'll create a file, helpers.php, in the root of Laravel and insert the following:

<?php

if (!function_exists('database_driver')) {
    function database_driver(): string
    {
        $connection = config('database.default');
        return config('database.connections.' . $connection . '.driver');
    }
}

if (!function_exists('is_database_driver')) {
    function is_database_driver(string $driver): bool
    {
        return $driver === database_driver();
    }
}

In composer.json, I'll insert the following into autoload. This allows composer to auto-discover helpers.php.

    "autoload": {
        "files": [
            "app/Services/Uploads/Processors/processor_functions.php",
            "app/helpers.php"
        ]
    },

I use the following in my Laravel models.

        if (is_database_driver('sqlite')) {
            $table->timestamps();
        } else {
            $table->timestamp('created_at')->default(\DB::raw('CURRENT_TIMESTAMP'));
            $table->timestamp('updated_at')
                ->default(DB::raw('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'));
        }

This allows my team to continue using sqlite for unit tests. ON UPDATE CURRENT_TIMESTAMP is a MySQL shortcut and is not available in sqlite.

Window.open as modal popup?

That solution will open up a new browser window without the normal features such as address bar and similar.

To implement a modal popup, I suggest you to take a look at jQuery and SimpleModal, which is really slick.

(Here are some simple demos using SimpleModal: http://www.ericmmartin.com/projects/simplemodal-demos/)

What's the difference between ngOnInit and ngAfterViewInit of Angular2?

Content is what is passed as children. View is the template of the current component.

The view is initialized before the content and ngAfterViewInit() is therefore called before ngAfterContentInit().

** ngAfterViewInit() is called when the bindings of the children directives (or components) have been checked for the first time. Hence its perfect for accessing and manipulating DOM with Angular 2 components. As @Günter Zöchbauer mentioned before is correct @ViewChild() hence runs fine inside it.

Example:

@Component({
    selector: 'widget-three',
    template: `<input #input1 type="text">`
})
export class WidgetThree{
    @ViewChild('input1') input1;

    constructor(private renderer:Renderer){}

    ngAfterViewInit(){
        this.renderer.invokeElementMethod(
            this.input1.nativeElement,
            'focus',
            []
        )
    }
}

The name 'controlname' does not exist in the current context

I ran into this same error, except it was a WPF error. I was rearranging projects and had a control defined in like this:

<local:CustomControl Name="Custom" /> 

In my code behind I tried using Custom.Blah, but I got the error:

The name 'Custom' does not exist in the current context

What did the trick for me was changing my control in Xaml to this:

<local:CustomControl x:Name="Custom" />

Hope this helps someone out there!

Android Relative Layout Align Center

This will definately work for you.

<RelativeLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@drawable/top_bg" >

    <Button
        android:id="@+id/btn_report_lbAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true"
        android:layout_marginLeft="@dimen/btn_back_margin_left"
        android:background="@drawable/btn_edit" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_centerVertical="true"
        android:text="FlitsLimburg"
        android:textColor="@color/white"
        android:textSize="@dimen/tv_header_text"
        android:textStyle="bold" />

    <Button
        android:id="@+id/btn_refresh_lbAlert"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:layout_marginRight="@dimen/btn_back_margin_right"
        android:background="@drawable/btn_refresh" />
</RelativeLayout>

How to program a delay in Swift 3

I like one-line notation for GCD, it's more elegant:

    DispatchQueue.main.asyncAfter(deadline: .now() + 42.0) {
        // do stuff 42 seconds later
    }

Also, in iOS 10 we have new Timer methods, e.g. block initializer:

(so delayed action may be canceled)

    let timer = Timer.scheduledTimer(withTimeInterval: 42.0, repeats: false) { (timer) in
        // do stuff 42 seconds later
    }

Btw, keep in mind: by default, timer is added to the default run loop mode. It means timer may be frozen when the user is interacting with the UI of your app (for example, when scrolling a UIScrollView) You can solve this issue by adding the timer to the specific run loop mode:

RunLoop.current.add(timer, forMode: .common)

At this blog post you can find more details.

How to convert existing non-empty directory into a Git working directory and push files to a remote repository

In case the remote repository is not empty (this is the case if you are using IBM DevOps on hub.jazz.net) then you need to use the following sequence:

cd <localDir>
git init
git add -A .
git pull <url> master
git commit -m "message"
git remote add origin <url>
git push

EDIT 30th Jan 17: Please see comments below, make sure you are on the correct repo!

Suppress command line output

mysqldump doesn't work with: >nul 2>&1
Instead use: 2> nul
This suppress the stderr message: "Warning: Using a password on the command line interface can be insecure"

npm install hangs

You can try deleting package-lock.json and running npm install afterwards. This worked for me.

How do I install Python libraries in wheel format?

For windows, there are automatic installer packages available at this site

It includes most of the python packages.

But the best way for it is of course using pip.

Download TS files from video stream

I needed to download HLS video and audio streams from a e-learning portal with session-protected content with application/mp2t MIME content type.

Manually copying all authentication headers into the downloading scripts would be too cumbersome.

But the task got much easier with help of Video DownloadHelper Firefox extension and it's Companion App. It allowed to download both m3u8 playlists with TS chunks lists and actual video and audio streams into mp4 files via a click of button while correctly preserving authentication headers.

The resulting separate video and audio files can be merged with ffmpeg:

ffmpeg -i video.mp4 -i audio.mp4 -acodec copy -vcodec copy video-and-audio.mp4 

or with mp4box:

mp4box -add audio.mp4#audio video.mp4 -out video-and-audio.mp4

Tried Video DownloadHelper Chrome extension too, but it didn't work for me.

How to represent e^(-t^2) in MATLAB?

All the 3 first ways are identical. You have make sure that if t is a matrix you add . before using multiplication or the power.

for matrix:

t= [1 2 3;2 3 4;3 4 5];
tp=t.*t;
x=exp(-(t.^2));
y=exp(-(t.*t));
z=exp(-(tp));

gives the results:

x =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

y =

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

z=

0.3679    0.0183    0.0001
0.0183    0.0001    0.0000
0.0001    0.0000    0.0000

And using a scalar:

p=3;
pp=p^2;
x=exp(-(p^2));
y=exp(-(p*p));
z=exp(-pp);

gives the results:

x =

1.2341e-004

y =

1.2341e-004

z =

1.2341e-004

OpenSSL: unable to verify the first certificate for Experian URL

Here is what you can do:-

Exim SSL certificates

By default, the /etc/exim.conf will use the cert/key files:

/etc/exim.cert
/etc/exim.key

so if you're wondering where to set your files, that's where.

They're controlled by the exim.conf's options:

tls_certificate = /etc/exim.cert
tls_privatekey = /etc/exim.key

Intermediate Certificates

If you have a CA Root certificate (ca bundle, chain, etc.) you'll add the contents of your CA into the exim.cert, after your actual certificate.

Probably a good idea to make sure you have a copy of everything elsewhere in case you make an error.

Dovecot and ProFtpd should also read it correctly, so dovecot no longer needs the ssl_ca option. So for both cases, there is no need to make any changes to either the exim.conf or dovecot.conf(/etc/dovecot/conf/ssl.conf)

Read environment variables in Node.js

process.env.ENV_VARIABLE

Where ENV_VARIABLE is the name of the variable you wish to access.

See Node.js docs for process.env.

GSON - Date format

Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ").create();

Above format seems better to me as it has precision up to millis.

Eclipse : Maven search dependencies doesn't work

I have the same problem. None of the options suggested above worked for me. However I find, that if I lets say manually add groupid/artifact/version for org.springframework.spring-core version 4.3.4.RELEASE and save the pom.xml, the dependencies download automatically and the search works for the jars already present in the repository. However if I now search for org.springframework.spring-context , which isnt in the current dependencies, this search still doesn't work.

How do you loop in a Windows batch file?

FOR will give you any information you'll ever need to know about FOR loops, including examples on proper usage.

How to search in commit messages using command line?

git log --grep=<pattern>
    Limit the commits output to ones with log message that matches the 
    specified pattern (regular expression).

--git help log

How to find count of Null and Nan values for each column in a PySpark dataframe efficiently?

An alternative to the already provided ways is to simply filter on the column like so

df = df.where(F.col('columnNameHere').isNull())

This has the added benefit that you don't have to add another column to do the filtering and it's quick on larger data sets.

Nested JSON objects - do I have to use arrays for everything?

You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.

use each() wrap within another each() until the last array.

for result.data[0].stuff[0].onetype[0] in jQuery you could do the following:

`

$.each(data.result.data, function(index0, v) {
    $.each(v, function (index1, w) {
        $.each(w, function (index2, x) {
            alert(x.id);
        });
    });

});

`

How can I recursively find all files in current and subfolders based on wildcard matching?

Default way to search for recursive file, and available in most cases is

find . -name "filepattern"

It starts recursive traversing for filename or pattern from within current directory where you are positioned. With find command, you can use wildcards, and various switches, to see full list of options, type

man find

or if man pages aren't available at your system

find --help

However, there are more modern and faster tools then find, which are traversing your whole filesystem and indexing your files, one such common tool is locate or slocate/mlocate, you should check manual of your OS on how to install it, and once it's installed it needs to initiate database, if install script don't do it for you, it can be done manually by typing

sudo updatedb

And, to use it to look for some particular file type

locate filename

Or, to look for filename or patter from within current directory, you can type:

 pwd | xargs -n 1 -I {} locate "filepattern"

It will look through its database of files and quickly print out path names that match pattern that you have typed. To see full list of locate's options, type: locate --help or man locate

Additionally you can configure locate to update it's database on scheduled times via cron job, so sample cron which updates db at 1AM would look like:

0 1 * * * updatedb

These cron jobs need to be configured by root, since updatedb needs root privilege to traverse whole filesystem.

React.js: Wrapping one component into another

Using children

const Wrapper = ({children}) => (
  <div>
    <div>header</div>
    <div>{children}</div>
    <div>footer</div>
  </div>
);

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = ({name}) => (
  <Wrapper>
    <App name={name}/>
  </Wrapper>
);

render(<WrappedApp name="toto"/>,node);

This is also known as transclusion in Angular.

children is a special prop in React and will contain what is inside your component's tags (here <App name={name}/> is inside Wrapper, so it is the children

Note that you don't necessarily need to use children, which is unique for a component, and you can use normal props too if you want, or mix props and children:

const AppLayout = ({header,footer,children}) => (
  <div className="app">
    <div className="header">{header}</div>
    <div className="body">{children}</div>
    <div className="footer">{footer}</div>
  </div>
);

const appElement = (
  <AppLayout 
    header={<div>header</div>}
    footer={<div>footer</div>}
  >
    <div>body</div>
  </AppLayout>
);

render(appElement,node);

This is simple and fine for many usecases, and I'd recommend this for most consumer apps.


render props

It is possible to pass render functions to a component, this pattern is generally called render prop, and the children prop is often used to provide that callback.

This pattern is not really meant for layout. The wrapper component is generally used to hold and manage some state and inject it in its render functions.

Counter example:

const Counter = () => (
  <State initial={0}>
    {(val, set) => (
      <div onClick={() => set(val + 1)}>  
        clicked {val} times
      </div>
    )}
  </State>
); 

You can get even more fancy and even provide an object

<Promise promise={somePromise}>
  {{
    loading: () => <div>...</div>,
    success: (data) => <div>{data.something}</div>,
    error: (e) => <div>{e.message}</div>,
  }}
</Promise>

Note you don't necessarily need to use children, it is a matter of taste/API.

<Promise 
  promise={somePromise}
  renderLoading={() => <div>...</div>}
  renderSuccess={(data) => <div>{data.something}</div>}
  renderError={(e) => <div>{e.message}</div>}
/>

As of today, many libraries are using render props (React context, React-motion, Apollo...) because people tend to find this API more easy than HOC's. react-powerplug is a collection of simple render-prop components. react-adopt helps you do composition.


Higher-Order Components (HOC).

const wrapHOC = (WrappedComponent) => {
  class Wrapper extends React.PureComponent {
    render() {
      return (
        <div>
          <div>header</div>
          <div><WrappedComponent {...this.props}/></div>
          <div>footer</div>
        </div>
      );
    }  
  }
  return Wrapper;
}

const App = ({name}) => <div>Hello {name}</div>;

const WrappedApp = wrapHOC(App);

render(<WrappedApp name="toto"/>,node);

An Higher-Order Component / HOC is generally a function that takes a component and returns a new component.

Using an Higher-Order Component can be more performant than using children or render props, because the wrapper can have the ability to short-circuit the rendering one step ahead with shouldComponentUpdate.

Here we are using PureComponent. When re-rendering the app, if the WrappedApp name prop does not change over time, the wrapper has the ability to say "I don't need to render because props (actually, the name) are the same as before". With the children based solution above, even if the wrapper is PureComponent, it is not the case because the children element is recreated everytime the parent renders, which means the wrapper will likely always re-render, even if the wrapped component is pure. There is a babel plugin that can help mitigate this and ensure a constant children element over time.


Conclusion

Higher-Order Components can give you better performance. It's not so complicated but it certainly looks unfriendly at first.

Don't migrate your whole codebase to HOC after reading this. Just remember that on critical paths of your app you might want to use HOCs instead of runtime wrappers for performance reasons, particularly if the same wrapper is used a lot of times it's worth considering making it an HOC.

Redux used at first a runtime wrapper <Connect> and switched later to an HOC connect(options)(Comp) for performance reasons (by default, the wrapper is pure and use shouldComponentUpdate). This is the perfect illustration of what I wanted to highlight in this answer.

Note if a component has a render-prop API, it is generally easy to create a HOC on top of it, so if you are a lib author, you should write a render prop API first, and eventually offer an HOC version. This is what Apollo does with <Query> render-prop component, and the graphql HOC using it.

Personally, I use both, but when in doubt I prefer HOCs because:

  • It's more idiomatic to compose them (compose(hoc1,hoc2)(Comp)) compared to render props
  • It can give me better performances
  • I'm familiar with this style of programming

I don't hesitate to use/create HOC versions of my favorite tools:

  • React's Context.Consumer comp
  • Unstated's Subscribe
  • using graphql HOC of Apollo instead of Query render prop

In my opinion, sometimes render props make the code more readable, sometimes less... I try to use the most pragmatic solution according to the constraints I have. Sometimes readability is more important than performances, sometimes not. Choose wisely and don't bindly follow the 2018 trend of converting everything to render-props.

Safely remove migration In Laravel

DO NOT run php artisan migrate:fresh that's gonna drop all the tables

Parsing JSON objects for HTML table

Loop over each object, appending a table row with the relevant data each iteration.

$(document).ready(function () {
    $.getJSON(url,
    function (json) {
        var tr;
        for (var i = 0; i < json.length; i++) {
            tr = $('<tr/>');
            tr.append("<td>" + json[i].User_Name + "</td>");
            tr.append("<td>" + json[i].score + "</td>");
            tr.append("<td>" + json[i].team + "</td>");
            $('table').append(tr);
        }
    });
});

JSFiddle

changing textbox border colour using javascript

document.getElementById("fName").style.border="1px solid black";

C# Double - ToString() formatting with two decimal places but no rounding

I know this is a old thread but I've just had to do this. While the other approaches here work, I wanted an easy way to be able to affect a lot of calls to string.format. So adding the Math.Truncate to all the calls to wasn't really a good option. Also as some of the formatting is stored in a database, it made it even worse.

Thus, I made a custom format provider which would allow me to add truncation to the formatting string, eg:

string.format(new FormatProvider(), "{0:T}", 1.1299); // 1.12
string.format(new FormatProvider(), "{0:T(3)", 1.12399); // 1.123
string.format(new FormatProvider(), "{0:T(1)0,000.0", 1000.9999); // 1,000.9

The implementation is pretty simple and is easily extendible to other requirements.

public class FormatProvider : IFormatProvider, ICustomFormatter
{
    public object GetFormat(Type formatType)
    {
        if (formatType == typeof (ICustomFormatter))
        {
            return this;
        }
        return null;
    }

    public string Format(string format, object arg, IFormatProvider formatProvider)
    {
        if (arg == null || arg.GetType() != typeof (double))
        {
            try
            {
                return HandleOtherFormats(format, arg);
            }
            catch (FormatException e)
            {
                throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
            }
        }

        if (format.StartsWith("T"))
        {
            int dp = 2;
            int idx = 1;
            if (format.Length > 1)
            {
                if (format[1] == '(')
                {
                    int closeIdx = format.IndexOf(')');
                    if (closeIdx > 0)
                    {
                        if (int.TryParse(format.Substring(2, closeIdx - 2), out dp))
                        {
                            idx = closeIdx + 1;
                        }
                    }
                    else
                    {
                        throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
                    }
                }
            }
            double mult = Math.Pow(10, dp);
            arg = Math.Truncate((double)arg * mult) / mult;
            format = format.Substring(idx);
        }

        try
        {
            return HandleOtherFormats(format, arg);
        }
        catch (FormatException e)
        {
            throw new FormatException(string.Format("The format of '{0}' is invalid.", format));
        }
    }

    private string HandleOtherFormats(string format, object arg)
    {
        if (arg is IFormattable)
        {
            return ((IFormattable) arg).ToString(format, CultureInfo.CurrentCulture);
        }
        return arg != null ? arg.ToString() : String.Empty;
    }
}

invalid new-expression of abstract class type

Another possible cause for future Googlers

I had this issue because a method I was trying to implement required a std::unique_ptr<Queue>(myQueue) as a parameter, but the Queue class is abstract. I solved that by using a QueuePtr(myQueue) constructor like so:

using QueuePtr = std::unique_ptr<Queue>;

and used that in the parameter list instead. This fixes it because the initializer tries to create a copy of Queue when you make a std::unique_ptr of its type, which can't happen.

Multiple dex files define Landroid/support/v4/accessibilityservice/AccessibilityServiceInfoCompat

I had the same problem when adding react-native-palette to my project, here is my dependencies tree:

./gradlew app:dependencies
+--- project :react-native-palette
|    +--- com.facebook.react:react-native:0.20.+ -> 0.44.2
|    |    +--- javax.inject:javax.inject:1
|    |    +--- com.android.support:appcompat-v7:23.0.1
|    |    |    \--- com.android.support:support-v4:23.0.1
|    |    |         \--- com.android.support:support-annotations:23.0.1 -> 24.2.1
...
|    \--- com.android.support:palette-v7:24.+ -> 24.2.1
|         +--- com.android.support:support-compat:24.2.1
|         |    \--- com.android.support:support-annotations:24.2.1
|         \--- com.android.support:support-core-utils:24.2.1
|              \--- com.android.support:support-compat:24.2.1 (*)
+--- com.android.support:appcompat-v7:23.0.1 (*)
\--- com.facebook.react:react-native:+ -> 0.44.2 (*)

I tried many solutons and could not fix it, until changing the com.android.support:appcompat version in android/app/build.gradle, I wish this can help:

dependencies {
    compile project(':react-native-palette')
    compile project(':react-native-image-picker')
    compile project(':react-native-camera')
    compile fileTree(dir: "libs", include: ["*.jar"])
    // compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.android.support:appcompat-v7:24.2.1"
    compile "com.facebook.react:react-native:+"
}

it seems that multiple entries is not a big problem, version mismatch is

What is difference between XML Schema and DTD?

DTD can have only two types of data, the CDATA and the PCDATA. But in a schema you can use all the primitive data type that you use in the programming language and you have the flexibility of defining your own custom data types.

The developer building a schema can create custom data types based on the core data types and by using different operators and modifiers.

How to call Stored Procedure in Entity Framework 6 (Code-First)?

All you have to do is create an object that has the same property names as the results returned by the stored procedure. For the following stored procedure:

    CREATE PROCEDURE [dbo].[GetResultsForCampaign]  
    @ClientId int   
    AS
    BEGIN
    SET NOCOUNT ON;

    SELECT AgeGroup, Gender, Payout
    FROM IntegrationResult
    WHERE ClientId = @ClientId
    END

create a class that looks like:

    public class ResultForCampaign
    {
        public string AgeGroup { get; set; }

        public string Gender { get; set; }

        public decimal Payout { get; set; }
    }

and then call the procedure by doing the following:

    using(var context = new DatabaseContext())
    {
            var clientIdParameter = new SqlParameter("@ClientId", 4);

            var result = context.Database
                .SqlQuery<ResultForCampaign>("GetResultsForCampaign @ClientId", clientIdParameter)
                .ToList();
    }

The result will contain a list of ResultForCampaign objects. You can call SqlQuery using as many parameters as needed.

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

How can I ssh directly to a particular directory?

simply modify your home with the command: usermod -d /newhome username

View stored procedure/function definition in MySQL

An alternative quick and hacky solution if you want to get an overview of all the produres there are, or run into the issue of only getting the procedure header shown by SHOW CREATE PROCEDURE:

mysqldump --user=<user> -p --no-data --routines <database>

It will export the table descriptions as well, but no data. Works well for sniffing around unknown or forgotten schemas... ;)

What is the difference between synchronous and asynchronous programming (in node.js)

The main difference is with asynchronous programming, you don't stop execution otherwise. You can continue executing other code while the 'request' is being made.

time.sleep -- sleeps thread or process?

The thread will block, but the process is still alive.

In a single threaded application, this means everything is blocked while you sleep. In a multithreaded application, only the thread you explicitly 'sleep' will block and the other threads still run within the process.

Moving items around in an ArrayList

A simple swap is far better for "moving something up" in an ArrayList:

if(i > 0) {
    Item toMove = arrayList.get(i);
    arrayList.set(i, arrayList.get(i-1));
    arrayList.set(i-1, toMove);
}

Because an ArrayList uses an array, if you remove an item from an ArrayList, it has to "shift" all the elements after that item upward to fill in the gap in the array. If you insert an item, it has to shift all the elements after that item to make room to insert it. These shifts can get very expensive if your array is very big. Since you know that you want to end up with the same number of elements in the list, doing a swap like this allows you to "move" an element to another location in the list very efficiently.

As Chris Buckler and Michal Kreuzman point out, there is even a handy method in the Collections class to reduce these three lines of code to one:

Collections.swap(arrayList, i, i-1);

What is the difference between hg forget and hg remove?

From the documentation, you can apparently use either command to keep the file in the project history. Looks like you want remove, since it also deletes the file from the working directory.

From the Mercurial book at http://hgbook.red-bean.com/read/:

Removing a file does not affect its history. It is important to understand that removing a file has only two effects. It removes the current version of the file from the working directory. It stops Mercurial from tracking changes to the file, from the time of the next commit. Removing a file does not in any way alter the history of the file.

The man page hg(1) says this about forget:

Mark the specified files so they will no longer be tracked after the next commit. This only removes files from the current branch, not from the entire project history, and it does not delete them from the working directory.

And this about remove:

Schedule the indicated files for removal from the repository. This only removes files from the current branch, not from the entire project history.

git: can't push (unpacker error) related to permission issues

It is a permission error. The way that was most appropriate and secure for me was adding users to a supplementary group that the repo. is owned by (or vice versa):

groupadd git
chgrp -R git .git
chgrp -R git ./
usermod -G -a git $(whoami)

batch file Copy files with certain extensions from multiple directories into one directory

Just use the XCOPY command with recursive option

xcopy c:\*.doc k:\mybackup /sy

/s will make it "recursive"

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

For Mac OSX: There is a way to install Visual Studio Code through Brew-Cask.

  1. First, install 'Homebrew' from here.
  2. Now run following command and it will install latest Visual Studio Code on your Mac.

    $> brew cask install visual-studio-code

Above command should install Visual Studio Code and also set up the command-line calling of Visual Studio Code.

If above steps don't work then you can do it manually. By following Microsoft Visual Studio Code documentation given here.

Change image size with JavaScript

Once you have a reference to your image, you can set its height and width like so:

var yourImg = document.getElementById('yourImgId');
if(yourImg && yourImg.style) {
    yourImg.style.height = '100px';
    yourImg.style.width = '200px';
}

In the html, it would look like this:

<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>

Why do I need to do `--set-upstream` all the time?

You can also do git push -u origin $(current_branch)

Update style of a component onScroll in React.js

to help out anyone here who noticed the laggy behavior / performance issues when using Austins answer, and wants an example using the refs mentioned in the comments, here is an example I was using for toggling a class for a scroll up / down icon:

In the render method:

<i ref={(ref) => this.scrollIcon = ref} className="fa fa-2x fa-chevron-down"></i>

In the handler method:

if (this.scrollIcon !== null) {
  if(($(document).scrollTop() + $(window).height() / 2) > ($('body').height() / 2)){
    $(this.scrollIcon).attr('class', 'fa fa-2x fa-chevron-up');
  }else{
    $(this.scrollIcon).attr('class', 'fa fa-2x fa-chevron-down');
  }
}

And add / remove your handlers the same way as Austin mentioned:

componentDidMount(){
  window.addEventListener('scroll', this.handleScroll);
},
componentWillUnmount(){
  window.removeEventListener('scroll', this.handleScroll);
},

docs on the refs.

MySQL error code: 1175 during UPDATE in MySQL Workbench

just type SET SQL_SAFE_UPDATES = 0; before the delete or update and set to 1 again SET SQL_SAFE_UPDATES = 1

Excel VBA function to print an array to the workbook

On the same theme as other answers, keeping it simple

Sub PrintArray(Data As Variant, Cl As Range)
    Cl.Resize(UBound(Data, 1), UBound(Data, 2)) = Data
End Sub


Sub Test()
    Dim MyArray() As Variant

    ReDim MyArray(1 To 3, 1 To 3) ' make it flexible

    ' Fill array
    '  ...

    PrintArray MyArray, ActiveWorkbook.Worksheets("Sheet1").[A1]
End Sub

Check if textbox has empty value

var inp = $("#txt").val();
if(jQuery.trim(inp).length > 0)
{
   //do something
}

Removes white space before checking. If the user entered only spaces then this will still work.