Programs & Examples On #Scmbug

scmbug is a tool for software change management that insists on tying commits to a particular bug number. Use this tag if you have issues integrating scmbug with other tools.

Android: Flush DNS

Perform a hard reboot of your phone. The easiest way to do this is to remove the phone's battery. Wait for at least 30 seconds, then replace the battery. The phone will reboot, and upon completing its restart will have an empty DNS cache.

Read more: How to Flush the DNS on an Android Phone | eHow.com http://www.ehow.com/how_10021288_flush-dns-android-phone.html#ixzz1gRJnmiJb

How to give spacing between buttons using bootstrap

Adding margins to a button makes it wider so that les buttons fit in the grid system. If only a visual effect is important, then give the button a white border with [style="margin:0px; border:solid white;"] This leaves the button width unaffected.

invalid command code ., despite escaping periods, using sed

On OS X nothing helps poor builtin sed to become adequate. The solution is:

brew install gnu-sed

And then use gsed instead of sed, which will just work as expected.

jQuery - Click event on <tr> elements with in a table and getting <td> element values

Try jQuery's delegate() function, like so:

$(document).ready(function(){
    $("div.custList table").delegate('tr', 'click', function() {
        alert("You clicked my <tr>!");
        //get <td> element values here!!??
    });
});

A delegate works in the same way as live() except that live() cannot be applied to chained items, whereas delegate() allows you to specify an element within an element to act on.

How do include paths work in Visual Studio?

To resume the working solutions in VisualStudio 2013 and 2015 too:

Add an include-path to the current project only

In Solution Explorer (a palette-window of the VisualStudio-mainwindow), open the shortcut menu for the project and choose Properties, and then in the left pane of the Property Pages dialog box, expand Configuration Properties and select VC++ Directories. Additional include- or lib-paths are specifyable there.

Its the what Stackunderflow and user1741137 say in the answers above. Its the what Microsoft explains in MSDN too.

Add an include-path to every new project automatically

Its the question, what Jay Elston is asking in a comment above and what is a very obvious and burning question in my eyes, what seems to be nonanswered here yet.

There exist regular ways to do it in VisualStudio (see CurlyBrace.com), what in my experience are not working properly. In the sense, that it works only once, and thereafter, it is no more expandable and nomore removable. The approach of Steve Wilkinson in another close related thread of StackOverflow, editing the Microsoft-Factory-XML-file in the ‘program files’ - directory is probably a risky hack, as it isnt expected by Microsoft to meet there something foreign. The effect is potentally unpredictable. Well, I like rather to judge it risky not much, but anyway the best way to make VisualStudio work incomprehensible at least for someone else.

The what is working fine compared to, is the editing the corresponding User-XML-file:

C:\Users\UserName\AppData\Local\Microsoft\MSBuild\v4.0\Microsoft.Cpp.Win32.user.props

or/and

C:\Users\UserName\AppData\Local\Microsoft\MSBuild\v4.0\Microsoft.Cpp.x64.user.props

For example:

<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  <ImportGroup Label="PropertySheets">
  </ImportGroup>
  <PropertyGroup Label="UserMacros" />
  <PropertyGroup>
    <IncludePath>C:\any-name\include;$(IncludePath)</IncludePath>
    <LibraryPath>C:\any-name\lib;$(LibraryPath)</LibraryPath>
  </PropertyGroup>
  <ItemDefinitionGroup />
  <ItemGroup />
</Project>

Where the directory ‘C:\any-name\include’ will get prepended to the present include-path and the directory ‘C:\any-name\lib’ to the library-path. Here, we can edit it ago in an extending and removing sense and remove it all, removing thewhole content of the tag .

Its the what makes VisualStudio itself, doing it in the regular way what CurlyBrace describes. As said, it isnt editable in the CurlyBrace-way thereafter nomore, but in the XML-editing-way it is.

For more insight, see Brian Tyler@MSDN-Blog 2009, what is admittedly not very fresh, but always the what Microsoft is linking to.

Refresh Page and Keep Scroll Position

document.location.reload() stores the position, see in the docs.

Add additional true parameter to force reload, but without restoring the position.

document.location.reload(true)

MDN docs:

The forcedReload flag changes how some browsers handle the user's scroll position. Usually reload() restores the scroll position afterward, but forced mode can scroll back to the top of the page, as if window.scrollY === 0.

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

To track down the correct parameters you need to go first to ?plot.default, which refers you to ?par and ?axis:

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=1.5,    #  for the xlab and ylab
           col="green")                   #  for the points

How to detect the physical connected state of a network cable/connector?

Use 'ip monitor' to get REAL TIME link state changes.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

How to make FileFilter in java?

Here is a little utility class that I created:

import java.io.File;
import java.io.FilenameFilter;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

/**
 * Convenience utility to create a FilenameFilter, based on a list of extensions
 */
public class FileExtensionFilter implements FilenameFilter {
    private Set<String> exts = new HashSet<String>();

    /**
     * @param extensions
     *            a list of allowed extensions, without the dot, e.g.
     *            <code>"xml","html","rss"</code>
     */
    public FileExtensionFilter(String... extensions) {
        for (String ext : extensions) {
            exts.add("." + ext.toLowerCase().trim());
        }
    }

    public boolean accept(File dir, String name) {
        final Iterator<String> extList = exts.iterator();
        while (extList.hasNext()) {
            if (name.toLowerCase().endsWith(extList.next())) {
                return true;
            }
        }
        return false;
    }
}

Usage:

       String[] files = new File("myfile").list(new FileExtensionFilter("pdf", "zip"));

Combine two OR-queries with AND in Mongoose

It's probably easiest to create your query object directly as:

  Test.find({
      $and: [
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ]
  }, function (err, results) {
      ...
  }

But you can also use the Query#and helper that's available in recent 3.x Mongoose releases:

  Test.find()
      .and([
          { $or: [{a: 1}, {b: 1}] },
          { $or: [{c: 1}, {d: 1}] }
      ])
      .exec(function (err, results) {
          ...
      });

How to align an image dead center with bootstrap

Assuming there is nothing else alongside the image, the best way is to use text-align: center in the img parent:

.row .span4 {
    text-align: center;
}

Edit

As mentioned in the other answers, you can add the bootstrap CSS class .text-center to the parent element. This does exactly the same thing and is available in both v2.3.3 and v3

Reading CSV file and storing values into an array

The open-source Angara.Table library allows to load CSV into typed columns, so you can get the arrays from the columns. Each column can be indexed both by name or index. See http://predictionmachines.github.io/Angara.Table/saveload.html.

The library follows RFC4180 for CSV; it enables type inference and multiline strings.

Example:

using System.Collections.Immutable;
using Angara.Data;
using Angara.Data.DelimitedFile;

...

ReadSettings settings = new ReadSettings(Delimiter.Semicolon, false, true, null, null);
Table table = Table.Load("data.csv", settings);
ImmutableArray<double> a = table["double-column-name"].Rows.AsReal;

for(int i = 0; i < a.Length; i++)
{
    Console.WriteLine("{0}: {1}", i, a[i]);
}

You can see a column type using the type Column, e.g.

Column c = table["double-column-name"];
Console.WriteLine("Column {0} is double: {1}", c.Name, c.Rows.IsRealColumn);

Since the library is focused on F#, you might need to add a reference to the FSharp.Core 4.4 assembly; click 'Add Reference' on the project and choose FSharp.Core 4.4 under "Assemblies" -> "Extensions".

Spring Boot java.lang.NoClassDefFoundError: javax/servlet/Filter

For Jar

Add pom.xml

<dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

Is there a command to refresh environment variables from the command prompt in Windows?

On Windows 7/8/10, you can install Chocolatey, which has a script for this built-in.

After installing Chocolatey, just type refreshenv.

Flexbox not working in Internet Explorer 11

See "Can I Use" for the full list of IE11 Flexbox bugs and more

There are numerous Flexbox bugs in IE11 and other browsers - see flexbox on Can I Use -> Known Issues, where the following are listed under IE11:

  • IE 11 requires a unit to be added to the third argument, the flex-basis property
  • In IE10 and IE11, containers with display: flex and flex-direction: column will not properly calculate their flexed childrens' sizes if the container has min-height but no explicit height property
  • IE 11 does not vertically align items correctly when min-height is used

Also see Philip Walton's Flexbugs list of issues and workarounds.

How to write DataFrame to postgres table?

Starting from pandas 0.14 (released end of May 2014), postgresql is supported. The sql module now uses sqlalchemy to support different database flavors. You can pass a sqlalchemy engine for a postgresql database (see docs). E.g.:

from sqlalchemy import create_engine
engine = create_engine('postgresql://username:password@localhost:5432/mydatabase')
df.to_sql('table_name', engine)

You are correct that in pandas up to version 0.13.1 postgresql was not supported. If you need to use an older version of pandas, here is a patched version of pandas.io.sql: https://gist.github.com/jorisvandenbossche/10841234.
I wrote this a time ago, so cannot fully guarantee that it always works, buth the basis should be there). If you put that file in your working directory and import it, then you should be able to do (where con is a postgresql connection):

import sql  # the patched version (file is named sql.py)
sql.write_frame(df, 'table_name', con, flavor='postgresql')

How to find path of active app.config file?

If you mean you are only getting a null return when you use NUnit, then you probably need to copy the ConnectionString value the your app.config of your application to the app.config of your test library.

When it is run by the test loader, the test assembly is loaded at runtime and will look in its own app.config (renamed to testAssembly.dll.config at compile time) rather then your applications config file.

To get the location of the assembly you're running, try

System.Reflection.Assembly.GetExecutingAssembly().Location

Replace text in HTML page with jQuery

...I have a string "-9o0-9909" and I want to replace it with another string.

The code below will do that.

var str = '-9o0-9909';

str = 'new string';

Jokes aside, replacing text nodes is not trivial with JavaScript.

I've written a post about this: Replacing text with JavaScript.

Difference between __getattr__ vs __getattribute__

I find that no one mentions this difference:

__getattribute__ has a default implementation, but __getattr__ does not.

class A:
    pass
a = A()
a.__getattr__ # error
a.__getattribute__ # return a method-wrapper

This has a clear meaning: since __getattribute__ has a default implementation, while __getattr__ not, clearly python encourages users to implement __getattr__.

String "true" and "false" to boolean

You could consider only appending internal to your url if it is true, then if the checkbox isn't checked and you don't append it params[:internal] would be nil, which evaluates to false in Ruby.

I'm not that familiar with the specific jQuery you're using, but is there a cleaner way to call what you want than manually building a URL string? Have you had a look at $get and $ajax?

An item with the same key has already been added

I had the same problem and this is how I solved it. I had a duplicate property with the same name in my ViewModel. One Property was in BaseViewModel and another is in derived Model.

public class BaseviewModel{
  public int UserId { get; set; }
}


 public class Model : BaseViewModel
 {
     public int UserId { get; set; }
 }

I changed that to

public class BaseviewModel{
   public int UserId { get; set; }
}


public class Model : BaseViewModel
{
    public int User_Id { get; set; }
}

Now it is working fine.

CSS Printing: Avoiding cut-in-half DIVs between pages?

Using break-inside should work:

@media print {
  div {
    break-inside: avoid;
  }
}

It works on all major browsers:

  • Chrome 50+
  • Edge 12+
  • Firefox 65+
  • Opera 37+
  • Safari 10+

Using page-break-inside: avoid; instead should work too, but has been exactly deprecated by break-inside: avoid.

Detect whether Office is 32bit or 64bit via the registry

This Wikipedia article states:

On 64-bit versions of Windows, there are two folders for application files; the "Program Files" folder contains 64-bit programs, and the "Program Files (x86)" folder contains 32-bit programs.

So if the program is installed under C:\Program Files it is a 64-bit version. If it is installed under C:\Program Files (x86) it is a 32-bit installation.

numpy division with RuntimeWarning: invalid value encountered in double_scalars

You can use np.logaddexp (which implements the idea in @gg349's answer):

In [33]: d = np.array([[1089, 1093]])

In [34]: e = np.array([[1000, 4443]])

In [35]: log_res = np.logaddexp(-3*d[0,0], -3*d[0,1]) - np.logaddexp(-3*e[0,0], -3*e[0,1])

In [36]: log_res
Out[36]: -266.99999385580668

In [37]: res = exp(log_res)

In [38]: res
Out[38]: 1.1050349147204485e-116

Or you can use scipy.special.logsumexp:

In [52]: from scipy.special import logsumexp

In [53]: res = np.exp(logsumexp(-3*d) - logsumexp(-3*e))

In [54]: res
Out[54]: 1.1050349147204485e-116

json_encode(): Invalid UTF-8 sequence in argument

Seems like the symbol was Å, but since data consists of surnames that shouldn't be public, only first letter was shown and it was done by just $lastname[0], which is wrong for multibyte strings and caused the whole hassle. Changed it to mb_substr($lastname, 0, 1) - works like a charm.

Div table-cell vertical align not working

Set the height for the parent element.

.htaccess not working on localhost with XAMPP

for xampp vm on MacOS capitan, high sierra, MacOS Mojave (10.12+), you can follow these

1. mount /opt/lampp
2. explore the folder
3. open terminal from the folder
4. cd to `htdocs`>yourapp (ex: techaz.co)
5. vim .htaccess
6. paste your .htaccess content (that is suggested on options-permalink.php)

enter image description here

How to place object files in separate subdirectory

Since you're using GNUmake, use a pattern rule for compiling object files:

$(OBJDIR)/%.o: %.c
    $(CC) $(CFLAGS) $(CPPFLAGS) -c -o $@ $<

Which browser has the best support for HTML 5 currently?

Seems that new browsers support most of the tags: <header>, <section> etc. For older browsers (IE, Fx2, Camino etc) then you can use this to allow styling of these tags:

document.createElement('header');

Would make these older browsers allow CSS styling of a header tag, instead of just ignoring it.

This means that you can now use the new tags without any loss of functionality, which is a good start!

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

Check key exist in python dict

Use the in keyword.

if 'apples' in d:
    if d['apples'] == 20:
        print('20 apples')
    else:
        print('Not 20 apples')

If you want to get the value only if the key exists (and avoid an exception trying to get it if it doesn't), then you can use the get function from a dictionary, passing an optional default value as the second argument (if you don't pass it it returns None instead):

if d.get('apples', 0) == 20:
    print('20 apples.')
else:
    print('Not 20 apples.')

How to get a jqGrid cell value when editing

Try this, it will give you particular column's value

onSelectRow: function(id) {
    var rowData = jQuery(this).getRowData(id); 
    var temp= rowData['name'];//replace name with you column
    alert(temp);
}

Measuring code execution time

If you use the Stopwatch class, you can use the .StartNew() method to reset the watch to 0. So you don't have to call .Reset() followed by .Start(). Might come in handy.

Can I embed a .png image into an html page?

There are a few base64 encoders online to help you with this, this is probably the best I've seen:

http://www.greywyvern.com/code/php/binary2base64

As that page shows your main options for this are CSS:

div.image {
  width:100px;
  height:100px;
  background-image:url(data:image/png;base64,iVBORwA<MoreBase64SringHere>); 
}

Or the <img> tag itself, like this:

<img alt="My Image" src="data:image/png;base64,iVBORwA<MoreBase64SringHere>" />

Is it possible to save HTML page as PDF using JavaScript or jquery?

This might be a late answer but this is the best around: https://github.com/eKoopmans/html2pdf

Pure javascript implementation. Allows you to specify just a single element by ID and convert it.

TypeScript: correct way to do string equality?

The === is not for checking string equalit , to do so you can use the Regxp functions for example

if (x.match(y) === null) {
// x and y are not equal 
}

there is also the test function

convert nan value to zero

You can use lambda function, an example for 1D array:

import numpy as np
a = [np.nan, 2, 3]
map(lambda v:0 if np.isnan(v) == True else v, a)

This will give you the result:

[0, 2, 3]

Passing arrays as url parameter

There is a very simple solution: http_build_query(). It takes your query parameters as an associative array:

$data = array(
    1,
    4,
    'a' => 'b',
    'c' => 'd'
);
$query = http_build_query(array('aParam' => $data));

will return

string(63) "aParam%5B0%5D=1&aParam%5B1%5D=4&aParam%5Ba%5D=b&aParam%5Bc%5D=d"

http_build_query() handles all the necessary escaping for you (%5B => [ and %5D => ]), so this string is equal to aParam[0]=1&aParam[1]=4&aParam[a]=b&aParam[c]=d.

How to convert strings into integers in Python?

You can do this with a list comprehension:

T2 = [[int(column) for column in row] for row in T1]

The inner list comprehension ([int(column) for column in row]) builds a list of ints from a sequence of int-able objects, like decimal strings, in row. The outer list comprehension ([... for row in T1])) builds a list of the results of the inner list comprehension applied to each item in T1.

The code snippet will fail if any of the rows contain objects that can't be converted by int. You'll need a smarter function if you want to process rows containing non-decimal strings.

If you know the structure of the rows, you can replace the inner list comprehension with a call to a function of the row. Eg.

T2 = [parse_a_row_of_T1(row) for row in T1]

u'\ufeff' in Python string

That character is the BOM or "Byte Order Mark". It is usually received as the first few bytes of a file, telling you how to interpret the encoding of the rest of the data. You can simply remove the character to continue. Although, since the error says you were trying to convert to 'ascii', you should probably pick another encoding for whatever you were trying to do.

Java division by zero doesnt throw an ArithmeticException - why?

Why can't you just check it yourself and throw an exception if that is what you want.

    try {
        for (int i = 0; i < tab.length; i++) {
            tab[i] = 1.0 / tab[i];

            if (tab[i] == Double.POSITIVE_INFINITY ||
                    tab[i] == Double.NEGATIVE_INFINITY)
                throw new ArithmeticException();
        }
    } catch (ArithmeticException ae) {
        System.out.println("ArithmeticException occured!");
    }

How to change the status bar background color and text color on iOS 7?

Goto your app info.plist

1) Set View controller-based status bar appearance to NO
2) Set Status bar style to UIStatusBarStyleLightContent

Then Goto your app delegate and paste the following code where you set your Windows's RootViewController.

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"7.0"))
{
    UIView *view=[[UIView alloc] initWithFrame:CGRectMake(0, 0,[UIScreen mainScreen].bounds.size.width, 20)];
    view.backgroundColor=[UIColor blackColor];
    [self.window.rootViewController.view addSubview:view];
}

Hope it helps.

__init__() missing 1 required positional argument

You need to pass some data into it. An empty dictionary, for example.

if __name__ == '__main__': DHT('a').showData()

However, in your example a parameter is not even needed. You can declare it by just:

def __init__(self):

Maybe you mean to set it from the data?

class DHT:
    def __init__(self, data):
        self.data['one'] = data['one']
        self.data['two'] = data['two']
        self.data['three'] = data['three']
    def showData(self):
        print(self.data)

if __name__ == '__main__': DHT({'one':2, 'two':4, 'three':5}).showData()

showData will print the data you just entered.

How to append elements at the end of ArrayList in Java?

Here is the syntax, along with some other methods you might find useful:

    //add to the end of the list
    stringList.add(random);

    //add to the beginning of the list
    stringList.add(0,  random);

    //replace the element at index 4 with random
    stringList.set(4, random);

    //remove the element at index 5
    stringList.remove(5);

    //remove all elements from the list
    stringList.clear();

how much memory can be accessed by a 32 bit machine?

No your concepts are not right. And to set it right you need the answer to the question that you incorrectly answered:

What is meant by 32bit or 64 bit machine?

The answer to the question is "something significant in the CPU is 32bit or 64 bit". So the question is what is that something significant? Lot of people say the width of data bus that determine whether the machine is 32bit or 64 bit. But none of the latest 32 bit processors have 32 bit or 64 bit wide data buses. most 32 bit systems will have 36 bit at least to support more RAM. Most 64 bit processors have no more than 48bit wide data bus because that is hell lot of memory already.

So according to me a 32 bit or 64 bit machine is determined by the size of its general purpose registers used in computation or "the natural word size" used by the computer.

Note that a 32 bit OS is a different thing. You can have a 32 bit OS running on 64 bit computer. Additionally, you can have 32 bit application running on 64 bit OS. If you do not understand the difference, post another question.

So the maximum amount of RAM a processor can address is 2^(width of data bus in bits), given that the proper addressing mode is switched on in the processor.

Further note, there is nothing stopping someone to introduce a multiplex between data Bus and memory banks, that will select a bank and then address the RAM (in two steps). This way you can address even more RAM. But that is impractical, and highly inefficient.

is there a function in lodash to replace matched item

Not bad variant too)

var arr = [{id: 1, name: "Person 1"}, {id: 2, name: "Person 2"}];

var id = 1; //id to find

arr[_.find(arr, {id: id})].name = 'New Person';

Ternary operator (?:) in Bash

The let command supports most of the basic operators one would need:

let a=b==5?c:d;

Naturally, this works only for assigning variables; it cannot execute other commands.

How do I get Month and Date of JavaScript in 2 digit format?

if u want getDate() function to return the date as 01 instead of 1, here is the code for it.... Lets assume Today's date is 01-11-2018

var today = new Date();
today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + today.getDate();      
console.log(today);       //Output: 2018-11-1


today = today.getFullYear()+ "-" + (today.getMonth() + 1) + "-" + ((today.getDate() < 10 ? '0' : '') + today.getDate());
console.log(today);        //Output: 2018-11-01

How to include external Python code to use in other files?

You will need to import the other file as a module like this:

import Math

If you don't want to prefix your Calculate function with the module name then do this:

from Math import Calculate

If you want to import all members of a module then do this:

from Math import *

Edit: Here is a good chapter from Dive Into Python that goes a bit more in depth on this topic.

How can I stop float left?

You could modify .adm and add

.adm{
 clear:both;
}

That should make it move to a new line

Remove numbers from string sql server

One more approach using Recursive CTE..

declare @string varchar(100)
set @string ='te165st1230004616161616'

;With cte
as
(
select @string as string,0  as n
union all
select cast(replace(string,n,'') as varchar(100)),n+1
from cte
where n<9
)
select top 1 string from cte
order by n desc


**Output:**   
  test

How do you UrlEncode without using System.Web?

To UrlEncode without using System.Web:

String s = System.Net.WebUtility.UrlEncode(str);
//fix some different between WebUtility.UrlEncode and HttpUtility.UrlEncode
s = Regex.Replace(s, "(%[0-9A-F]{2})", c => c.Value.ToLowerInvariant());

more details: https://www.samnoble.co.uk/2014/05/21/beware-webutility-urlencode-vs-httputility-urlencode/

How to get http headers in flask?

Let's see how we get the params, headers and body in Flask. I'm gonna explain with the help of postman.

enter image description here

The params keys and values are reflected in the API endpoint. for example key1 and key2 in the endpoint : https://127.0.0.1/upload?key1=value1&key2=value2

from flask import Flask, request
app = Flask(__name__)

@app.route('/upload')
def upload():

  key_1 = request.args.get('key1')
  key_2 = request.args.get('key2')
  print(key_1)
  #--> value1
  print(key_2)
  #--> value2

After params, let's now see how to get the headers:

enter image description here

  header_1 = request.headers.get('header1')
  header_2 = request.headers.get('header2')
  print(header_1)
  #--> header_value1
  print(header_2)
  #--> header_value2

Now let's see how to get the body

enter image description here

  file_name = request.files['file'].filename
  ref_id = request.form['referenceId']
  print(ref_id)
  #--> WWB9838yb3r47484

so we fetch the uploaded files with request.files and text with request.form

Update Fragment from ViewPager

Because none of the above answers did the trick for me, here is my solution:

I combined the POSITION_NONE with loading on setUserVisibleHint(boolean isVisibleToUser) instead of onStart()

As seen here: https://stackoverflow.com/a/25676323/497366

In the Fragment:

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
    super.setUserVisibleHint(isVisibleToUser);
    if (isVisibleToUser) {
        // load data here
    }else{
       // fragment is no longer visible
    }
}

and in the FragmentStatePagerAdapter as seen in the top answer here from Simon Dorociak https://stackoverflow.com/a/18088509/497366:

@Override
public int getItemPosition(@NonNull Object object) {
    return POSITION_NONE;
}

Now the fragments reload the data into their views everytime they are shown to the user.

How to convert xml into array in php?

easy!

$xml = simplexml_load_string($xmlstring, "SimpleXMLElement", LIBXML_NOCDATA);
$json = json_encode($xml);
$array = json_decode($json,TRUE);

Converting from byte to int in java

byte b = (byte)0xC8;
int v1 = b;       // v1 is -56 (0xFFFFFFC8)
int v2 = b & 0xFF // v2 is 200 (0x000000C8)

Most of the time v2 is the way you really need.

What does Visual Studio mean by normalize inconsistent line endings?

Line endings also called newline, end of line (EOL) or line break is a control character or sequence of control characters in a character encoding specification (e.g. ASCII or EBCDIC) that is used to signify the end of a line of text and the start of a new one. Some text editors set/implement this special character when you press the Enter key.

The Carriage Return, Line Feed characters are ASCII representations for the end of a line (EOL). They will end the current line of a string, and start a new one.

However, at the operating system level, they are treated differently:

  • The Carriage Return ("CR") character (ASCII 13\0x0D, \r): Moves the cursor to the beginning of the line without advancing to the next line. This character is used as the new line character in Commodore and Early Macintosh operating systems (Mac OS 9 and earlier).

  • The Line Feed ("LF") character (ASCII 10\0x0A, \n): Moves the cursor down to the next line without returning to the beginning of the line. This character is used as the new line character in Unix based systems (Linux, macOS X, Android, etc).

  • The Carriage Return Line Feed ("CRLF") character (0x0D0A, \r\n): This is actually two ASCII characters and is a combination of the CR and LF characters. It moves the cursor both down to the next line and to the beginning of that line. This character is used as the new line character in most other non-Unix operating systems, including Microsoft Windows and Symbian OS.

Normalizing inconsistent line endings in Visual Studio means selecting one character type to be used for all your files. It could be:

  • The Carriage Return Line Feed ("CRLF") character
  • The Line Feed ("LF") character
  • The Carriage Return ("CR") character

However, you can set this in a better way using .gitattributes file in your root directory to avoid conflicts when you move your files from one Operating system to the other.

Simply create a new file called .gitattributes in the root directory of your application:

touch .gitattributes

And add the following in it:

# Enforce Unix newlines
* text=auto eol=lf

This enforces the Unix line feed line ending character.

Note: If this is an already existing project, simply run this command to update the files for the application using the newly defined line ending as specified in the .gitattributes.

git rm --cached -r .
git reset --hard

That's all.

I hope this helps

Change the spacing of tick marks on the axis of a plot?

I have a data set with Time as the x-axis, and Intensity as y-axis. I'd need to first delete all the default axes except the axes' labels with:

plot(Time,Intensity,axes=F)

Then I rebuild the plot's elements with:

box() # create a wrap around the points plotted
axis(labels=NA,side=1,tck=-0.015,at=c(seq(from=0,to=1000,by=100))) # labels = NA prevents the creation of the numbers and tick marks, tck is how long the tick mark is.
axis(labels=NA,side=2,tck=-0.015)
axis(lwd=0,side=1,line=-0.4,at=c(seq(from=0,to=1000,by=100))) # lwd option sets the tick mark to 0 length because tck already takes care of the mark
axis(lwd=0,line=-0.4,side=2,las=1) # las changes the direction of the number labels to horizontal instead of vertical.

So, at = c(...) specifies the collection of positions to put the tick marks. Here I'd like to put the marks at 0, 100, 200,..., 1000. seq(from =...,to =...,by =...) gives me the choice of limits and the increments.

How to get a list of all files in Cloud Storage in a Firebase app?

For Android the best pratice is to use FirebaseUI and Glide.

You need to add that on your gradle/app in order to get the library. Note that it already has Glide on it!

implementation 'com.firebaseui:firebase-ui-storage:4.1.0'

And then in your code use

// Reference to an image file in Cloud Storage
StorageReference storageReference = FirebaseStorage.getInstance().getReference();

// ImageView in your Activity
ImageView imageView = findViewById(R.id.imageView);

// Download directly from StorageReference using Glide
// (See MyAppGlideModule for Loader registration)
GlideApp.with(this /* context */)
        .load(storageReference)
        .into(imageView);

Iterate through a C array

You can store the size somewhere, or you can have a struct with a special value set that you use as a sentinel, the same way that '\0' indicates the end of a string.

How to compare 2 files fast using .NET?

Honestly, I think you need to prune your search tree down as much as possible.

Things to check before going byte-by-byte:

  1. Are sizes the same?
  2. Is the last byte in file A different than file B

Also, reading large blocks at a time will be more efficient since drives read sequential bytes more quickly. Going byte-by-byte causes not only far more system calls, but it causes the read head of a traditional hard drive to seek back and forth more often if both files are on the same drive.

Read chunk A and chunk B into a byte buffer, and compare them (do NOT use Array.Equals, see comments). Tune the size of the blocks until you hit what you feel is a good trade off between memory and performance. You could also multi-thread the comparison, but don't multi-thread the disk reads.

reading text file with utf-8 encoding using java

You need to specify the encoding of the InputStreamReader using the Charset parameter.

Charset inputCharset = Charset.forName("ISO-8859-1");
InputStreamReader isr = new InputStreamReader(fis, inputCharset));

This is work for me. i hope to help you.

XPath query to get nth instance of an element

This is a FAQ:

//somexpression[$N]

means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:

(//input[@id="search_query"])[2]

Remember: The [] operator has higher precedence (priority) than the // abbreviation.

How to get character for a given ascii value

This works in my code.

string asciichar = (Convert.ToChar(65)).ToString();

Return: asciichar = 'A';

#ifdef replacement in the Swift language

There are some processors that take an argument and I listed them below. you can change the argument as you like:

#if os(macOS) /* Checks the target operating system */

#if canImport(UIKit) /* Check if a module presents */

#if swift(<5) /* Check the Swift version */

#if targetEnvironment(simulator) /* Check envrionments like Simulator or Catalyst */

#if compiler(<7) /* Check compiler version */

Also, You can use any custom flags like DEBUG or any other flags you defined

#if DEBUG
print("Debug mode")
#endif

how to view the contents of a .pem certificate

An alternative to using keytool, you can use the command

openssl x509 -in certificate.pem -text

This should work for any x509 .pem file provided you have openssl installed.

Sorting a vector in descending order

bool comp(int i, int j) { return i > j; }
sort(numbers.begin(), numbers.end(), comp);

What's the fastest algorithm for sorting a linked list?

You can copy it into an array and then sort it.

  • Copying into array O(n),

  • sorting O(nlgn) (if you use a fast algorithm like merge sort ),

  • copying back to linked list O(n) if necessary,

so it is gonna be O(nlgn).

note that if you do not know the number of elements in the linked list you won't know the size of array. If you are coding in java you can use an Arraylist for example.

Batch file: Find if substring is in string (not in a file)

Better answer was here:

set "i=hello " world"
set i|find """" >nul && echo contains || echo not_contains

ES6 Class Multiple inheritance

https://www.npmjs.com/package/ts-mixer

With the best TS support and many other useful features!

MySQL LEFT JOIN 3 tables

Select 
    p.Name,
    p.SS,
    f.fear
From
    Persons p
left join
        Person_Fear pf
    inner join
        Fears f
    on
        pf.fearID = f.fearID
 on
    p.personID = pf.PersonID

How to pretty print XML from the command line?

libxml2-utils

This utility comes with libxml2-utils:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    xmllint --format -

Perl's XML::Twig

This command comes with XML::Twig module, sometimes xml-twig-tools package:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    xml_pp

xmlstarlet

This command comes with xmlstarlet:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    xmlstarlet format --indent-tab

tidy

Check the tidy package:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    tidy -xml -i -

Python

Python's xml.dom.minidom can format XML (both python2 and python3):

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    python -c 'import sys;import xml.dom.minidom;s=sys.stdin.read();print(xml.dom.minidom.parseString(s).toprettyxml())'

saxon-lint

You need saxon-lint:

echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    saxon-lint --indent --xpath '/' -

saxon-HE

You need saxon-HE:

 echo '<root><foo a="b">lorem</foo><bar value="ipsum" /></root>' |
    java -cp /usr/share/java/saxon/saxon9he.jar net.sf.saxon.Query \
    -s:- -qs:/ '!indent=yes'

What does the "at" (@) symbol do in Python?

Python decorator is like a wrapper of a function or a class. It’s still too conceptual.

def function_decorator(func):
    def wrapped_func():
        # Do something before the function is executed
        func()
        # Do something after the function has been executed
    return wrapped_func

The above code is a definition of a decorator that decorates a function. function_decorator is the name of the decorator.

wrapped_func is the name of the inner function, which is actually only used in this decorator definition. func is the function that is being decorated. In the inner function wrapped_func, we can do whatever before and after the func is called. After the decorator is defined, we simply use it as follows.

@function_decorator
def func():
    pass

Then, whenever we call the function func, the behaviours we’ve defined in the decorator will also be executed.

EXAMPLE :

from functools import wraps

def mydecorator(f):
    @wraps(f)
    def wrapped(*args, **kwargs):
        print "Before decorated function"
        r = f(*args, **kwargs)
        print "After decorated function"
        return r
    return wrapped

@mydecorator
def myfunc(myarg):
    print "my function", myarg
    return "return value"

r = myfunc('asdf')
print r

Output :

    Before decorated function
    my function asdf
    After decorated function
    return value

Regular cast vs. static_cast vs. dynamic_cast

dynamic_cast only supports pointer and reference types. It returns NULL if the cast is impossible if the type is a pointer or throws an exception if the type is a reference type. Hence, dynamic_cast can be used to check if an object is of a given type, static_cast cannot (you will simply end up with an invalid value).

C-style (and other) casts have been covered in the other answers.

Div vertical scrollbar show

Always : If you always want vertical scrollbar, use overflow-y: scroll;

jsFiddle:

<div style="overflow-y: scroll;">
......
</div>

When needed: If you only want vertical scrollbar when needed, use overflow-y: auto; (You need to specify a height in this case)

jsFiddle:

<div style="overflow-y: auto; height:150px; ">
....
</div>

Text file in VBA: Open/Find Replace/SaveAs/Close File

This code will open and read lines of complete text file That variable "ReadedData" Holds the text line in memory

Open "C:\satheesh\myfile\Hello.txt" For Input As #1

do until EOF(1)   

       Input #1, ReadedData
loop**

How do I build an import library (.lib) AND a DLL in Visual C++?

Does your DLL project have any actual exports? If there are no exports, the linker will not generate an import library .lib file.

In the non-Express version of VS, the import libray name is specfied in the project settings here:

Configuration Properties/Linker/Advanced/Import Library

I assume it's the same in Express (if it even provides the ability to configure the name).

Set Background cell color in PHPExcel

You can easily apply colours on cell and rows.

$sheet->cell(1, function($row) 
{ 
  $row->setBackground('#CCCCCC'); 
});

$sheet->row(1, ['Col 1', 'Col 2', 'Col 3']); 
$sheet->row(1, function($row) 
{ 
  $row->setBackground('#CCCCCC'); 
});

Javascript - get array of dates between 2 dates

Function:

  var dates = [],
      currentDate = startDate,
      addDays = function(days) {
        var date = new Date(this.valueOf());
        date.setDate(date.getDate() + days);
        return date;
      };
  while (currentDate <= endDate) {
    dates.push(currentDate);
    currentDate = addDays.call(currentDate, 1);
  }
  return dates;
};

Usage:

var dates = getDatesRange(new Date(2019,01,01), new Date(2019,01,25));                                                                                                           
dates.forEach(function(date) {
  console.log(date);
});

Hope it helps you

Can't concatenate 2 arrays in PHP

Try array_merge.

$array1 = array('Item 1');

$array2 = array('Item 2');

$array3 = array_merge($array1, $array2);

I think its because you are not assigning a key to either, so they both have key of 0, and the + does not re-index, so its trying to over write it.

Gradle - Move a folder from ABC to XYZ

Your task declaration is incorrectly combining the Copy task type and project.copy method, resulting in a task that has nothing to copy and thus never runs. Besides, Copy isn't the right choice for renaming a directory. There is no Gradle API for renaming, but a bit of Groovy code (leveraging Java's File API) will do. Assuming Project1 is the project directory:

task renABCToXYZ {     doLast {         file("ABC").renameTo(file("XYZ"))     } } 

Looking at the bigger picture, it's probably better to add the renaming logic (i.e. the doLast task action) to the task that produces ABC.

Why I can't access remote Jupyter Notebook server?

Try doing below step:

Following command fixes the read/write

    sudo chmod -R a+rw /home/ubuntu/certs/mycert.pem

How to set a session variable when clicking a <a> link

Is your link to another web page? If so, perhaps you could put the variable in the query string and set the session variable when the page being linked to is loaded.

So the link looks like this:

<a href="home.php?variable=value" name="home">home</a>

And the homge page would parse the query string and set the session variable.

How to execute python file in linux

yes there is. add

#!/usr/bin/env python

to the beginning of the file and do

chmod u+rx <file>

assuming your user owns the file, otherwise maybe adjust the group or world permissions.

.py files under windows are associated with python as the program to run when opening them just like MS word is run when opening a .docx for example.

sublime text2 python error message /usr/bin/python: can't find '__main__' module in ''

You get that error because you haven't saved your file, save it for example "holamundo.py" then run it Ctrl + B

Minimum rights required to run a windows service as a domain account

Two ways:

  1. Edit the properties of the service and set the Log On user. The appropriate right will be automatically assigned.

  2. Set it manually: Go to Administrative Tools -> Local Security Policy -> Local Policies -> User Rights Assignment. Edit the item "Log on as a service" and add your domain user there.

CSS transition shorthand with multiple properties?

This helped me understand / streamline, only what I needed to animate:

// SCSS - Multiple Animation: Properties | durations | etc.
// on hover, animate div (width/opacity) - from: {0px, 0} to: {100vw, 1}

.base {
  max-width: 0vw;
  opacity: 0;

  transition-property: max-width, opacity; // relative order
  transition-duration: 2s, 4s; // effects relatively ordered animation properties
  transition-delay: 6s; // effects delay of all animation properties
  animation-timing-function: ease;

  &:hover {
    max-width: 100vw;
    opacity: 1;

    transition-duration: 5s; // effects duration of all aniomation properties
    transition-delay: 2s, 7s; // effects relatively ordered animation properties
  }
}

~ This applies for all transition properties (duration, transition-timing-function, etc.) within the '.base' class

How to open an Excel file in C#?

Is this a commercial application or some hobbyist / open source software?

I'm asking this because in my experience, all free .NET Excel handling alternatives have serious problems, for different reasons. For hobbyist things, I usually end up porting jExcelApi from Java to C# and using it.

But if this is a commercial application, you would be better off by purchasing a third party library, like Aspose.Cells. Believe me, it totally worths it as it saves a lot of time and time ain't free.

macro for Hide rows in excel 2010

Well, you're on the right path, Benno!

There are some tips regarding VBA programming that might help you out.

  1. Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.

  2. As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.

  3. Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.

Now, let's have a draft code...

Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.

Hope it helps!

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim oSheet As Excel.Worksheet

    'We only want to do something if the changed cell is B6, right?
    If Target.Address = "$B$6" Then

        'Checks if it's a number...
        If IsNumeric(Target.Value) Then

            'Let's avoid values out of your bonds, correct?
            If Target.Value > 0 And Target.Value < 51 Then

                'Let's assign the worksheet we'll show / hide rows to one variable and then
                '   use only the reference to the variable itself instead of the sheet name.
                '   It's safer.

                'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
                '   the sheet index within the workbook
                Set oSheet = ActiveWorkbook.Sheets("Sheet 2")

                'We'll unhide before hide, to ensure we hide the correct ones
                oSheet.Range("A7:A56").EntireRow.Hidden = False

                oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True

            End If

        End If

    End If

End Sub

How do I suspend painting for a control and its children?

This is even simpler, and perhaps hacky - as I can see a lot of GDI muscle on this thread, and is obviously only a good fit for certain scenarios. YMMV

In my scenario, I use what I'll refer to as a "Parent" UserControl - and during the Load event, I simply remove the control-to-be-manipulated from the Parent's .Controls collection, and the Parent's OnPaint takes care of completely painting the child control in whatever special way.. fully taking the child's paint capabilities offline.

Now, I hand off my child paint routine to an extension method based off this concept from Mike Gold for printing windows forms.

Here I'm needing a sub-set of labels to render perpendicular to the layout:

simple diagram of your Visual Studio IDE

Then, I exempt the child control from being painted, with this code in the ParentUserControl.Load event handler:

Private Sub ParentUserControl_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    SetStyle(ControlStyles.UserPaint, True)
    SetStyle(ControlStyles.AllPaintingInWmPaint, True)

    'exempt this control from standard painting: 
    Me.Controls.Remove(Me.HostedControlToBeRotated) 
End Sub

Then, in the same ParentUserControl, we paint the control-to-be-manipulated from the ground up:

Protected Overrides Sub OnPaint(e As PaintEventArgs)
    'here, we will custom paint the HostedControlToBeRotated instance...

    'twist rendering mode 90 counter clockwise, and shift rendering over to right-most end 
    e.Graphics.SmoothingMode = Drawing2D.SmoothingMode.AntiAlias
    e.Graphics.TranslateTransform(Me.Width - Me.HostedControlToBeRotated.Height, Me.Height)
    e.Graphics.RotateTransform(-90)
    MyCompany.Forms.CustomGDI.DrawControlAndChildren(Me.HostedControlToBeRotated, e.Graphics)

    e.Graphics.ResetTransform()
    e.Graphics.Dispose()

    GC.Collect()
End Sub

Once you host the ParentUserControl somewhere, e.g. a Windows Form - I'm finding that my Visual Studio 2015 renders the form correctly at Design Time as well as runtime: ParentUserControl hosted in a Windows Form or perhaps other user control

Now, since my particular manipulation rotates the child control 90 degrees, I'm sure all the hot spots and interactivity has been destroyed in that region - but, the problem I was solving was all for a package label that needed to preview and print, which worked out fine for me.

If there are ways to reintroduce the hot spots and control-ness to my purposely orphaned control - I'd love to learn about that someday (not for this scenario, of course, but.. just to learn). Of course, WPF supports such craziness OOTB.. but.. hey.. WinForms is so much fun still, amiright?

Online code beautifier and formatter

It depends of the language, and of the architecture you are using.

alt text alt text

For example, in a php platform, you can format almost language with GeSHi

As bluish comments, GeSHi is a generic syntax highlighter, with no beautification feature. It is more used on the server side, and combine it with a beautification tool can be tricky, as illustrated with this GeSHi drupal ticket.

How can I add a class attribute to an HTML element generated by MVC's HTML Helpers?

In order to create an anonymous type (or any type) with a property that has a reserved keyword as its name in C#, you can prepend the property name with an at sign, @:

Html.BeginForm("Foo", "Bar", FormMethod.Post, new { @class = "myclass"})

For VB.NET this syntax would be accomplished using the dot, ., which in that language is default syntax for all anonymous types:

Html.BeginForm("Foo", "Bar", FormMethod.Post, new with { .class = "myclass" })

Short form for Java if statement

Simple & clear:

String manType = hasMoney() ? "rich" : "poor";

long version:

      String manType;
    if (hasMoney()) {
        manType = "rich";
    } else {
        manType = "poor";
    }

or how I'm using it to be clear for other code readers:

 String manType = "poor";
    if (hasMoney())
        manType = "rich";

What is IllegalStateException?

Usually, IllegalStateException is used to indicate that "a method has been invoked at an illegal or inappropriate time." However, this doesn't look like a particularly typical use of it.

The code you've linked to shows that it can be thrown within that code at line 259 - but only after dumping a SQLException to standard output.

We can't tell what's wrong just from that exception - and better code would have used the original SQLException as a "cause" exception (or just let the original exception propagate up the stack) - but you should be able to see more details on standard output. Look at that information, and you should be able to see what caused the exception, and fix it.

How to Call a Function inside a Render in React/Jsx

The fix was at the accepted answer. Yet if someone wants to know why it worked and why the implementation in the SO question didn't work,

First, functions are first class objects in JavaScript. That means they are treated like any other variable. Function can be passed as an argument to other functions, can be returned by another function and can be assigned as a value to a variable. Read more here.

So we use that variable to invoke the function by adding parentheses () at the end.

One thing, If you have a function that returns a funtion and you just need to call that returned function, you can just have double paranthesis when you call the outer function ()().

Contains method for a slice

I created the following Contains function using reflect package. This function can be used for various types like int32 or struct etc.

// Contains returns true if an element is present in a slice
func Contains(list interface{}, elem interface{}) bool {
    listV := reflect.ValueOf(list)

    if listV.Kind() == reflect.Slice {
        for i := 0; i < listV.Len(); i++ {
            item := listV.Index(i).Interface()

            target := reflect.ValueOf(elem).Convert(reflect.TypeOf(item)).Interface()
            if ok := reflect.DeepEqual(item, target); ok {
                return true
            }
        }
    }
    return false
}

Usage of contains function is below

// slice of int32
containsInt32 := Contains([]int32{1, 2, 3, 4, 5}, 3)
fmt.Println("contains int32:", containsInt32)

// slice of float64
containsFloat64 := Contains([]float64{1.1, 2.2, 3.3, 4.4, 5.5}, 4.4)
fmt.Println("contains float64:", containsFloat64)


// slice of struct
type item struct {
    ID   string
    Name string
}
list := []item{
    item{
        ID:   "1",
        Name: "test1",
    },
    item{
        ID:   "2",
        Name: "test2",
    },
    item{
        ID:   "3",
        Name: "test3",
    },
}
target := item{
    ID:   "2",
    Name: "test2",
}
containsStruct := Contains(list, target)
fmt.Println("contains struct:", containsStruct)

// Output:
// contains int32: true
// contains float64: true
// contains struct: true

Please see here for more details: https://github.com/glassonion1/xgo/blob/main/contains.go

How can you run a command in bash over and over until success?

If anyone looking to have retry limit:

max_retry=5
counter=0
until $command
do
   sleep 1
   [[ counter -eq $max_retry ]] && echo "Failed!" && exit 1
   echo "Trying again. Try #$counter"
   ((counter++))
done

Why compile Python code?

It's compiled to bytecode which can be used much, much, much faster.

The reason some files aren't compiled is that the main script, which you invoke with python main.py is recompiled every time you run the script. All imported scripts will be compiled and stored on the disk.

Important addition by Ben Blank:

It's worth noting that while running a compiled script has a faster startup time (as it doesn't need to be compiled), it doesn't run any faster.

How do you connect to multiple MySQL databases on a single webpage?

<?php
    // Sapan Mohanty
    // Skype:sapan.mohannty
    //***********************************
    $oldData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    $NewData = mysql_connect('localhost', 'DBUSER', 'DBPASS');
    echo mysql_error();
    mysql_select_db('OLDDBNAME', $oldData );
    mysql_select_db('NEWDBNAME', $NewData );
    $getAllTablesName    = "SELECT table_name FROM information_schema.tables WHERE table_type = 'base table'";
    $getAllTablesNameExe = mysql_query($getAllTablesName);
    //echo mysql_error();
    while ($dataTableName = mysql_fetch_object($getAllTablesNameExe)) {

        $oldDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $oldData);
        $oldDataCountResult = mysql_fetch_object($oldDataCount);


        $newDataCount       = mysql_query('select count(*) as noOfRecord from ' . $dataTableName->table_name, $NewData);
        $newDataCountResult = mysql_fetch_object($newDataCount);

        if ( $oldDataCountResult->noOfRecord != $newDataCountResult->noOfRecord ) {
            echo "<br/><b>" . $dataTableName->table_name . "</b>";
            echo " | Old: " . $oldDataCountResult->noOfRecord;
            echo " | New: " . $newDataCountResult->noOfRecord;

            if ($oldDataCountResult->noOfRecord < $newDataCountResult->noOfRecord) {
                echo " | <font color='green'>*</font>";

            } else {
                echo " | <font color='red'>*</font>";
            }

            echo "<br/>----------------------------------------";

        }     

    }
    ?>

What is the use of the @Temporal annotation in Hibernate?

Temporal types are the set of time-based types that can be used in persistent state mappings.

The list of supported temporal types includes the three java.sql types java.sql.Date, java.sql.Time, and java.sql.Timestamp, and it includes the two java.util types java.util.Date and java.util.Calendar.

The java.sql types are completely hassle-free. They act just like any other simple mapping type and do not need any special consideration.

The two java.util types need additional metadata, however, to indicate which of the JDBC java.sql types to use when communicating with the JDBC driver. This is done by annotating them with the @Temporal annotation and specifying the JDBC type as a value of the TemporalType enumerated type.

There are three enumerated values of DATE, TIME, and TIMESTAMP to represent each of the java.sql types.

How to connect to a remote MySQL database with Java?

Just supply the IP / hostname of the remote machine in your database connection string, instead of localhost. For example:

jdbc:mysql://192.168.15.25:3306/yourdatabase

Make sure there is no firewall blocking the access to port 3306

Also, make sure the user you are connecting with is allowed to connect from this particular hostname. For development environments it is safe to do this by 'username'@'%'. Check the user creation manual and the GRANT manual.

how to clear JTable

You must remove the data from the TableModel used for the table.

If using the DefaultTableModel, just set the row count to zero. This will delete the rows and fire the TableModelEvent to update the GUI.

JTable table;
…
DefaultTableModel model = (DefaultTableModel) table.getModel();
model.setRowCount(0);

If you are using other TableModel, please check the documentation.

How to update Ruby to 1.9.x on Mac?

This command actually works

\curl -L https://get.rvm.io | bash -s stable --ruby

Get the cartesian product of a series of lists?

I would use list comprehension :

somelists = [
   [1, 2, 3],
   ['a', 'b'],
   [4, 5]
]

cart_prod = [(a,b,c) for a in somelists[0] for b in somelists[1] for c in somelists[2]]

How do I convert a org.w3c.dom.Document object to a String?

This worked for me, as documented on this page:

TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
StringWriter sw = new StringWriter();
trans.transform(new DOMSource(document), new StreamResult(sw));
return sw.toString();

What is an application binary interface (ABI)?

Summary

There are various interpretation and strong opinions of the exact layer that define an ABI (application binary interface).

In my view an ABI is a subjective convention of what is considered a given/platform for a specific API. The ABI is the "rest" of conventions that "will not change" for a specific API or that will be addressed by the runtime environment: executors, tools, linkers, compilers, jvm, and OS.

Defining an Interface: ABI, API

If you want to use a library like joda-time you must declare a dependency on joda-time-<major>.<minor>.<patch>.jar. The library follows best practices and use Semantic Versioning. This defines the API compatibility at three levels:

  1. Patch - You don't need to change at all your code. The library just fixes some bugs.
  2. Minor - You don't need to change your code since the additions
  3. Major - The interface (API) is changed and you might need to change your code.

In order for you to use a new major release of the same library a lot of other conventions are still to be respected:

  • The binary language used for the libraries (in Java cases the JVM target version that defines the Java bytecode)
  • Calling conventions
  • JVM conventions
  • Linking conventions
  • Runtime conventions All these are defined and managed by the tools we use.

Examples

Java case study

For example, Java standardized all these conventions, not in a tool, but in a formal JVM specification. The specification allowed other vendors to provide a different set of tools that can output compatible libraries.

Java provides two other interesting case studies for ABI: Scala versions and Dalvik virtual machine.

Dalvik virtual machine broke the ABI

The Dalvik VM needs a different type of bytecode than the Java bytecode. The Dalvik libraries are obtained by converting the Java bytecode (with same API) for Dalvik. In this way you can get two versions of the same API: defined by the original joda-time-1.7.2.jar. We could call it joda-time-1.7.2.jar and joda-time-1.7.2-dalvik.jar. They use a different ABI one is for the stack-oriented standard Java vms: Oracle's one, IBM's one, open Java or any other; and the second ABI is the one around Dalvik.

Scala successive releases are incompatible

Scala doesn't have binary compatibility between minor Scala versions: 2.X . For this reason the same API "io.reactivex" %% "rxscala" % "0.26.5" has three versions (in the future more): for Scala 2.10, 2.11 and 2.12. What is changed? I don't know for now, but the binaries are not compatible. Probably the latest versions adds things that make the libraries unusable on the old virtual machines, probably things related to linking/naming/parameter conventions.

Java successive releases are incompatible

Java has problems with the major releases of the JVM too: 4,5,6,7,8,9. They offer only backward compatibility. Jvm9 knows how to run code compiled/targeted (javac's -target option) for all other versions, while JVM 4 doesn't know how to run code targeted for JVM 5. All these while you have one joda-library. This incompatibility flies bellow the radar thanks to different solutions:

  1. Semantic versioning: when libraries target higher JVM they usually change the major version.
  2. Use JVM 4 as the ABI, and you're safe.
  3. Java 9 adds a specification on how you can include bytecode for specific targeted JVM in the same library.

Why did I start with the API definition?

API and ABI are just conventions on how you define compatibility. The lower layers are generic in respect of a plethora of high level semantics. That's why it's easy to make some conventions. The first kind of conventions are about memory alignment, byte encoding, calling conventions, big and little endian encodings, etc. On top of them you get the executable conventions like others described, linking conventions, intermediate byte code like the one used by Java or LLVM IR used by GCC. Third you get conventions on how to find libraries, how to load them (see Java classloaders). As you go higher and higher in concepts you have new conventions that you consider as a given. That's why they didn't made it to the semantic versioning. They are implicit or collapsed in the major version. We could amend semantic versioning with <major>-<minor>-<patch>-<platform/ABI>. This is what is actually happening already: platform is already a rpm, dll, jar (JVM bytecode), war(jvm+web server), apk, 2.11 (specific Scala version) and so on. When you say APK you already talk about a specific ABI part of your API.

API can be ported to different ABI

The top level of an abstraction (the sources written against the highest API can be recompiled/ported to any other lower level abstraction.

Let's say I have some sources for rxscala. If the Scala tools are changed I can recompile them to that. If the JVM changes I could have automatic conversions from the old machine to the new one without bothering with the high level concepts. While porting might be difficult will help any other client. If a new operating system is created using a totally different assembler code a translator can be created.

APIs ported across languages

There are APIs that are ported in multiple languages like reactive streams. In general they define mappings to specific languages/platforms. I would argue that the API is the master specification formally defined in human language or even a specific programming language. All the other "mappings" are ABI in a sense, else more API than the usual ABI. The same is happening with the REST interfaces.

Create a SQL query to retrieve most recent records

Add an auto incrementing Primary Key to each record, for example, UserStatusId.

Then your query could look like this:

select * from UserStatus where UserStatusId in
(
    select max(UserStatusId) from UserStatus group by User
)

Date User Status Notes

React - changing an uncontrolled input

An update for this. For React Hooks use const [name, setName] = useState(" ")

How to change bower's default components folder?

Hi i am same problem and resolve this ways.

windows user and vs cant'create .bowerrc file.

in cmd go any folder

install any packages which is contains .bowerrc file forexample

bower install angular-local-storage

this plugin contains .bowerrc file. copy that and go to your project and paste this file.

and in visual studio - solution explorer - show all files and include project seen .bowerrc file

i resolve this ways :)

Why use prefixes on member variables in C++ classes

I prefer postfix underscores, like such:

class Foo
{
   private:
      int bar_;

   public:
      int bar() { return bar_; }
};

Execute JavaScript using Selenium WebDriver in C#

public static class Webdriver
{        
    public static void ExecuteJavaScript(string scripts)
    {
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
        js.ExecuteScript(scripts);
    }

    public static T ExecuteJavaScript<T>(string scripts)
    {
        IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
        return (T)js.ExecuteScript(scripts);
    }
}

In your code you can then do

string test = Webdriver.ExecuteJavaScript<string>(" return 'hello World'; ");
int test = Webdriver.ExecuteJavaScript<int>(" return 3; ");

How do I pass multiple parameters into a function in PowerShell?

If you try:

PS > Test("ABC", "GHI") ("DEF")

you get:

$arg1 value: ABC GHI
$arg2 value: DEF

So you see that the parentheses separates the parameters


If you try:

PS > $var = "C"
PS > Test ("AB" + $var) "DEF"

you get:

$arg1 value: ABC
$arg2 value: DEF

Now you could find some immediate usefulness of the parentheses - a space will not become a separator for the next parameter - instead you have an eval function.

Change the Theme in Jupyter Notebook?

My complete solution:

1) Get Dark Reader on chrome which will not only get you a great Dark Theme for Jupyter but also for every single website you'd like (you can play with the different filters. I use Dynamic).

2) Paste those lines of code in your notebook so the legends and axes become visible:

from jupyterthemes import jtplot
jtplot.style(theme='monokai', context='notebook', ticks=True, grid=False)

You're all set for a disco coding night !

Pretty-Print JSON in Java

Using org json. Reference link

JSONObject jsonObject = new JSONObject(obj);
String prettyJson = jsonObject.toString(4);

Using Gson. Reference link

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String json = gson.toJson(obj);

Using Jackson. Reference link

ObjectMapper mapper = new ObjectMapper();
mapper.enable(SerializationFeature.INDENT_OUTPUT);
String json = mapper.writeValueAsString(obj);

Using Genson. Reference link.

Genson prettyGenson = new GensonBuilder().useIndentation(true).create();
String prettyJson = prettyGenson.serialize(obj);

Static Vs. Dynamic Binding in Java

There are three major differences between static and dynamic binding while designing the compilers and how variables and procedures are transferred to the runtime environment. These differences are as follows:

Static Binding: In static binding three following problems are discussed:

  • Definition of a procedure

  • Declaration of a name(variable, etc.)

  • Scope of the declaration

Dynamic Binding: Three problems that come across in the dynamic binding are as following:

  • Activation of a procedure

  • Binding of a name

  • Lifetime of a binding

Alter column, add default constraint

Actually you have to Do Like below Example, which will help to Solve the Issue...

drop table ABC_table

create table ABC_table
(
    names varchar(20),
    age int
)

ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names

insert into ABC(age) values(10)

select * from ABC

How do I go about adding an image into a java project with eclipse?

It is very simple to adding an image into project and view the image. First create a folder into in your project which can contain any type of images.

Then Right click on Project ->>Go to Build Path ->> configure Build Path ->> add Class folder ->> choose your folder (which you just created for store the images) under the project name.

class Surface extends JPanel {

    private BufferedImage slate;
    private BufferedImage java;
    private BufferedImage pane;
    private TexturePaint slatetp;
    private TexturePaint javatp;
    private TexturePaint panetp;

    public Surface() {

        loadImages();
    }

    private void loadImages() {

        try {

            slate = ImageIO.read(new File("images\\slate.png"));
            java = ImageIO.read(new File("images\\java.png"));
            pane = ImageIO.read(new File("images\\pane.png"));

        } catch (IOException ex) {

            Logger.`enter code here`getLogger(Surface.class.getName()).log(
                    Level.SEVERE, null, ex);
        }
    }

    private void doDrawing(Graphics g) {

        Graphics2D g2d = (Graphics2D) g.create();

        slatetp = new TexturePaint(slate, new Rectangle(0, 0, 90, 60));
        javatp = new TexturePaint(java, new Rectangle(0, 0, 90, 60));
        panetp = new TexturePaint(pane, new Rectangle(0, 0, 90, 60));

        g2d.setPaint(slatetp);
        g2d.fillRect(10, 15, 90, 60);

        g2d.setPaint(javatp);
        g2d.fillRect(130, 15, 90, 60);

        g2d.setPaint(panetp);
        g2d.fillRect(250, 15, 90, 60);

        g2d.dispose();
    }

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);
        doDrawing(g);
    }
}

public class TexturesEx extends JFrame {

    public TexturesEx() {

        initUI();
    }

    private void initUI() {

        add(new Surface());

        setTitle("Textures");
        setSize(360, 120);
        setLocationRelativeTo(null);        
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                TexturesEx ex = new TexturesEx();
                ex.setVisible(true);
            }
        });
    }
}

set height of imageview as matchparent programmatically

imageView.setLayoutParams
    (new ViewGroup.MarginLayoutParams
        (width, ViewGroup.LayoutParams.MATCH_PARENT));

The Type of layout params depends on the parent view group. If you put the wrong one it will cause exception.

Difference between git pull and git pull --rebase

git pull = git fetch + git merge against tracking upstream branch

git pull --rebase = git fetch + git rebase against tracking upstream branch

If you want to know how git merge and git rebase differ, read this.

How to show/hide an element on checkbox checked/unchecked states using jQuery?

Try

$(document).ready(function(){
    //Register click events to all checkboxes inside question element
    $(document).on('click', '.question input:checkbox', function() {
        //Find the next answer element to the question and based on the checked status call either show or hide method
        $(this).closest('.question').next('.answer')[this.checked? 'show' : 'hide']()
    });

});

Demo: Fiddle

Or

$(document).ready(function(){
    //Register click events to all checkboxes inside question element
    $(document).on('click', '.question input:checkbox', function() {
        //Find the next answer element to the question and based on the checked status call either show or hide method
        var answer = $(this).closest('.question').next('.answer');

        if(this.checked){
            answer.show(300);
        } else {
            answer.hide(300);
        }
    });

});

How to add lines to end of file on Linux

The easiest way is to redirect the output of the echo by >>:

echo 'VNCSERVERS="1:root"' >> /etc/sysconfig/configfile
echo 'VNCSERVERARGS[1]="-geometry 1600x1200"' >> /etc/sysconfig/configfile

Javascript/Jquery to change class onclick?

I would think this: http://jsfiddle.net/Skooljester/S3y5p/1/ should do it. If I don't have the class names 100% correct you can just change them to whatever you need them to be.

Adding <script> to WordPress in <head> element

For anyone else who comes here looking, I'm afraid I'm with @usama sulaiman here.

Using the enqueue function provides a safe way to load style sheets and scripts according to the script dependencies and is WordPress' recommended method of achieving what the original poster was trying to achieve. Just think of all the plugins trying to load their own copy of jQuery for instance; you better hope they're using enqueue :D.

Also, wherever possible create a plugin; as adding custom code to your functions file can be pita if you don't have a back-up and you upgrade your theme and overwrite your functions file in the process.

Having a plugin handle this and other custom functions also means you can switch them off if you think their code is clashing with some other plugin or functionality.

Something along the following in a plugin file is what you are looking for:

<?php
/*
Plugin Name: Your plugin name
Description: Your description
Version: 1.0
Author: Your name
Author URI: 
Plugin URI: 
*/

function $yourJS() {
    wp_enqueue_script(
        'custom_script',
        plugins_url( '/js/your-script.js', __FILE__ ),
        array( 'jquery' )
    );
}
 add_action( 'wp_enqueue_scripts',  '$yourJS' );
 add_action( 'wp_enqueue_scripts', 'prefix_add_my_stylesheet' );

 function prefix_add_my_stylesheet() {
    wp_register_style( 'prefix-style', plugins_url( '/css/your-stylesheet.css', __FILE__ ) );
    wp_enqueue_style( 'prefix-style' );
  }

?>

Structure your folders as follows:

Plugin Folder
  |_ css folder
  |_ js folder
  |_ plugin.php ...contains the above code - modified of course ;D

Then zip it up and upload it to your WordPress installation using your add plugins interface, activate it and Bob's your uncle.

How can I add an ampersand for a value in a ASP.net/C# app config file value

Although the accepted answer here is technically correct, there seems to be some confusion amongst users based on the comments. When working with a ViewBag in a .cshtml file, you must use @Html.Raw otherwise your data, after being unescaped by the ConfigurationManager, will become re-escaped once again. Use Html.Raw() to prevent this from occurring.

Prefer composition over inheritance?

What do you want to force yourself (or another programmer) to adhere to and when do you want to allow yourself (or another programmer) more freedom. It has been argued that inheritance is helpful when you want to force someone into a way of dealing with/solving a particular problem so they can't head off in the wrong direction.

Is-a and Has-a is a helpful rule of thumb.

What are queues in jQuery?

Multiple objects animation in a queue

Here is a simple example of multiple objects animation in a queue.

Jquery alow us to make queue over only one object. But within animation function we can access other objects. In this example we build our queue over #q object while animating #box1 and #box2 objects.

Think of queue as a array of functions. So you can manipulate queue as a array. You can use push, pop, unshift, shift to manipulate the queue. In this example we remove the last function from the animation queue and insert it at the beginning.

When we are done, we start animation queue by dequeue() function.

See at jsFiddle

html:

  <button id="show">Start Animation Queue</button>
  <p></p>
  <div id="box1"></div>
  <div id="box2"></div>
  <div id="q"></div>

js:

$(function(){

 $('#q').queue('chain',function(next){  
      $("#box2").show("slow", next);
  });


  $('#q').queue('chain',function(next){  
      $('#box1').animate(
          {left: 60}, {duration:1000, queue:false, complete: next}
      )
  });    


  $('#q').queue('chain',function(next){  
      $("#box1").animate({top:'200'},1500, next);
  });


  $('#q').queue('chain',function(next){  
      $("#box2").animate({top:'200'},1500, next);
  });


  $('#q').queue('chain',function(next){  
      $("#box2").animate({left:'200'},1500, next);
  });

  //notice that show effect comes last
  $('#q').queue('chain',function(next){  
      $("#box1").show("slow", next);
  });

});

$("#show").click(function () {
    $("p").text("Queue length is: " + $('#q').queue("chain").length);

    // remove the last function from the animation queue.
    var lastFunc = $('#q').queue("chain").pop();
    // insert it at the beginning:    
    $('#q').queue("chain").unshift(lastFunc);

    //start animation queue
    $('#q').dequeue('chain');
});

css:

        #box1 { margin:3px; width:40px; height:40px;
                position:absolute; left:10px; top:60px; 
                background:green; display: none; }
        #box2 { margin:3px; width:40px; height:40px;
                position:absolute; left:100px; top:60px; 
                background:red; display: none; }
        p { color:red; }  

How to get row count in sqlite using Android?

Sooo simple to get row count:

cursor = dbObj.rawQuery("select count(*) from TABLE where COLUMN_NAME = '1' ", null);
cursor.moveToFirst();
String count = cursor.getString(cursor.getColumnIndex(cursor.getColumnName(0)));

How to disable Compatibility View in IE

All you need is to force disable C.M. in IE - Just paste This code (in IE9 and under c.m. will be disabled):

<meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />

Source: http://twigstechtips.blogspot.com/2010/03/css-ie8-meta-tag-to-disable.html

Check if string contains only letters in javascript

You need

/^[a-zA-Z]+$/

Currently, you are matching a single character at the start of the input. If your goal is to match letter characters (one or more) from start to finish, then you need to repeat the a-z character match (using +) and specify that you want to match all the way to the end (via $)

How do I get PHP errors to display?

This code on top should work:

error_reporting(E_ALL);

However, try to edit the code on the phone in the file:

error_reporting =on

How to get client IP address in Laravel 5+

  $ip = $_SERVER['REMOTE_ADDR'];

ldconfig error: is not a symbolic link

Solved, at least at the point of the question.

I searched in the web before asking, an there were no conclusive solution, the reason why this error is: lib1.so and lib2.so are not OK, very probably where not compiled for a 64 PC, but for a 32 bits machine otherwise lib3.so is a 64 bits lib. At least that is my hipothesis.

VERY unfortunately ldconfig doesn't give a clean error message informing that it could not load the library, it only pumps:

ldconfig: /folder_where_the_wicked_lib_is/ is not a symbolic link

I solved this when I removed the libs not found by ldd over the binary. Now it's easier that I know where lies the problem.

My ld version: GNU ld version 2.20.51, and I don't know if a most recent version has a better message for its users.

Thanks.

jQuery DataTables Getting selected row values

You can iterate over the row data

$('#button').click(function () {
    var ids = $.map(table.rows('.selected').data(), function (item) {
        return item[0]
    });
    console.log(ids)
    alert(table.rows('.selected').data().length + ' row(s) selected');
});

Demo: Fiddle

xsd:boolean element type accept "true" but not "True". How can I make it accept it?

You cannot.

According to the XML Schema specification, a boolean is true or false. True is not valid:


  3.2.2.1 Lexical representation
  An instance of a datatype that is defined as ·boolean· can have the 
  following legal literals {true, false, 1, 0}. 

  3.2.2.2 Canonical representation
  The canonical representation for boolean is the set of 
  literals {true, false}. 

If the tool you are using truly validates against the XML Schema standard, then you cannot convince it to accept True for a boolean.

How to unpackage and repackage a WAR file

Adapting from the above answers, this works for Tomcat, but can be adapted for JBoss as well or any container:

sudo -u tomcat /opt/tomcat/bin/shutdown.sh
cd /opt/tomcat/webapps
sudo mkdir tmp; cd tmp
sudo jar -xvf ../myapp.war
#make edits...
sudo vi WEB-INF/classes/templates/fragments/header.html
sudo vi WEB-INF/classes/application.properties
#end of making edits
sudo jar -cvf myapp0.0.1.war *
sudo cp myapp0.0.1.war ..
cd ..
sudo chown tomcat:tomcat myapp0.0.1.war
sudo rm -rf tmp
sudo -u tomcat /opt/tomcat/bin/startup.sh

Clear and reset form input fields

_x000D_
_x000D_
import React, { Component } from 'react'

export default class Form extends Component {
  constructor(props) {
    super(props)
    this.formRef = React.createRef()
    this.state = {
      email: '',
      loading: false,
      eror: null
    }
  }

  reset = () => {
    this.formRef.current.reset()
  }

  render() {
    return (
      <div>
        <form>
          <input type="email" name="" id=""/>
          <button type="submit">Submit</button>
          <button onClick={()=>this.reset()}>Reset</button>
        </form>
      </div>
    )
  }
}
_x000D_
_x000D_
_x000D_

How to call getResources() from a class which has no context?

This always works for me:

import android.app.Activity;
import android.content.Context;

public class yourClass {

 Context ctx;

 public yourClass (Handler handler, Context context) {
 super(handler);
    ctx = context;
 }

 //Use context (ctx) in your code like this:
 block1 = new Droid(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.birdpic), 100, 10);
 //OR
 builder.setLargeIcon(BitmapFactory.decodeResource(ctx.getResources(), R.drawable.birdpic));
 //OR
 final Intent intent = new Intent(ctx, MainActivity.class);
 //OR
 NotificationManager notificationManager = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
 //ETC...

}

Not related to this question but example using a Fragment to access system resources/activity like this:

public boolean onQueryTextChange(String newText) {
 Activity activity = getActivity();
 Context context = activity.getApplicationContext();
 returnSomething(newText);
 return false;
}

View customerInfo = getActivity().getLayoutInflater().inflate(R.layout.main_layout_items, itemsLayout, false);
 itemsLayout.addView(customerInfo);

How to center absolute div horizontally using CSS?

You can't use margin:auto; on position:absolute; elements, just remove it if you don't need it, however, if you do, you could use left:30%; ((100%-40%)/2) and media queries for the max and min values:

.container {
    position: absolute;
    top: 15px;
    left: 30%;
    z-index: 2;
    width:40%;
    height: 60px;
    overflow: hidden;
    background: #fff;
}

@media all and (min-width:960px) {

    .container {
        left: 50%;
        margin-left:-480px;
        width: 960px;
    }

}

@media all and (max-width:600px) {

    .container {
        left: 50%;
        margin-left:-300px;
        width: 600px;
    }

}

What are the differences between if, else, and else if?

There's no "else if". You have the following:

if (condition)
    statement or block

Or:

if (condition)
    statement or block
else
    statement or block

In the first case, the statement or block is executed if the condition is true (different than 0). In the second case, if the condition is true, the first statement or block is executed, otherwise the second statement or block is executed.

So, when you write "else if", that's an "else statement", where the second statement is an if statement. You might have problems if you try to do this:

if (condition)
    if (condition)
        statement or block
else
    statement or block

The problem here being you want the "else" to refer to the first "if", but you are actually referring to the second one. You fix this by doing:

if (condition)
{
    if (condition)
        statement or block
} else
    statement or block

NOT IN vs NOT EXISTS

Actually, I believe this would be the fastest:

SELECT ProductID, ProductName 
    FROM Northwind..Products p  
          outer join Northwind..[Order Details] od on p.ProductId = od.ProductId)
WHERE od.ProductId is null

Difference between using bean id and name in Spring configuration file

Either one would work. It depends on your needs:
If your bean identifier contains special character(s) for example (/viewSummary.html), it wont be allowed as the bean id, because it's not a valid XML ID. In such cases you could skip defining the bean id and supply the bean name instead.
The name attribute also helps in defining aliases for your bean, since it allows specifying multiple identifiers for a given bean.

Mailto on submit button

Just include "a" tag in "button" tag.

<button><a href="mailto:..."></a></button>

Ruby on Rails: Clear a cached page

I was able to resolve this problem by cleaning my assets cache:

$ rake assets:clean

Fatal error: Class 'SoapClient' not found

For PHP 8:

sudo apt update
sudo apt-get install php8.0-soap

What does the ELIFECYCLE Node.js error mean?

While working on a WordPress theme, I got the same ELIFECYCLE error with slightly different output:

npm ERR! Darwin 14.5.0
npm ERR! argv "/usr/local/Cellar/node/7.6.0/bin/node" "/usr/local/bin/npm" "install"
npm ERR! node v7.6.0
npm ERR! npm  v3.7.3
npm ERR! code ELIFECYCLE
npm ERR! [email protected] postinstall: `bower install && gulp build`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the [email protected] postinstall script 'bower install && gulp build'.
npm ERR! Make sure you have the latest version of node.js and npm installed.
npm ERR! If you do, this is most likely a problem with the foundationsix package,
npm ERR! not with npm itself.
npm ERR! Tell the author that this fails on your system:
npm ERR!     bower install && gulp build

After trying npm install one more time with the same result, I tried bower install. When that was successful I tried gulp build and that also worked.

Everything is working just fine now. No idea why running each command separately worked when && failed but maybe someone else will find this answer useful.

Free Barcode API for .NET

I do recommend BarcodeLibrary

Here is a small piece of code of how to use it.

        BarcodeLib.Barcode barcode = new BarcodeLib.Barcode()
        {
            IncludeLabel = true,
            Alignment = AlignmentPositions.CENTER,
            Width = 300,
            Height = 100,
            RotateFlipType = RotateFlipType.RotateNoneFlipNone,
            BackColor = Color.White,
            ForeColor = Color.Black,
        };

        Image img = barcode.Encode(TYPE.CODE128B, "123456789");

How to select rows for a specific date, ignoring time in SQL Server

Something like this:

select 
  * 
from sales 
where salesDate >= '11/11/2010' 
  AND salesDate < (Convert(datetime, '11/11/2010') + 1)

Import Certificate to Trusted Root but not to Personal [Command Line]

To print the content of Root store:

certutil -store Root

To output content to a file:

certutil -store Root > root_content.txt

To add certificate to Root store:

certutil -addstore -enterprise Root file.cer

Ping all addresses in network, windows

Open the Command Prompt and type in the following:

FOR /L %i IN (1,1,254) DO ping -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txt

Change 192.168.10 to match you own network.

By using -n 1 you are asking for only 1 packet to be sent to each computer instead of the usual 4 packets.

The above command will ping all IP Addresses on the 192.168.10.0 network and create a text document in the C:\ drive called ipaddresses.txt. This text document should only contain IP Addresses that replied to the ping request.

Although it will take quite a bit longer to complete, you can also resolve the IP Addresses to HOST names by simply adding -a to the ping command.

FOR /L %i IN (1,1,254) DO ping -a -n 1 192.168.10.%i | FIND /i "Reply">>c:\ipaddresses.txt

This is from Here

Hope this helps

failed to find target with hash string android-23

This poblem is solved for me after Run as administrator the Andorid Studio

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

Culprit: False Data Dependency (and the compiler isn't even aware of it)

On Sandy/Ivy Bridge and Haswell processors, the instruction:

popcnt  src, dest

appears to have a false dependency on the destination register dest. Even though the instruction only writes to it, the instruction will wait until dest is ready before executing. This false dependency is (now) documented by Intel as erratum HSD146 (Haswell) and SKL029 (Skylake)

Skylake fixed this for lzcnt and tzcnt.
Cannon Lake (and Ice Lake) fixed this for popcnt.
bsf/bsr have a true output dependency: output unmodified for input=0. (But no way to take advantage of that with intrinsics - only AMD documents it and compilers don't expose it.)

(Yes, these instructions all run on the same execution unit).


This dependency doesn't just hold up the 4 popcnts from a single loop iteration. It can carry across loop iterations making it impossible for the processor to parallelize different loop iterations.

The unsigned vs. uint64_t and other tweaks don't directly affect the problem. But they influence the register allocator which assigns the registers to the variables.

In your case, the speeds are a direct result of what is stuck to the (false) dependency chain depending on what the register allocator decided to do.

  • 13 GB/s has a chain: popcnt-add-popcnt-popcnt → next iteration
  • 15 GB/s has a chain: popcnt-add-popcnt-add → next iteration
  • 20 GB/s has a chain: popcnt-popcnt → next iteration
  • 26 GB/s has a chain: popcnt-popcnt → next iteration

The difference between 20 GB/s and 26 GB/s seems to be a minor artifact of the indirect addressing. Either way, the processor starts to hit other bottlenecks once you reach this speed.


To test this, I used inline assembly to bypass the compiler and get exactly the assembly I want. I also split up the count variable to break all other dependencies that might mess with the benchmarks.

Here are the results:

Sandy Bridge Xeon @ 3.5 GHz: (full test code can be found at the bottom)

  • GCC 4.6.3: g++ popcnt.cpp -std=c++0x -O3 -save-temps -march=native
  • Ubuntu 12

Different Registers: 18.6195 GB/s

.L4:
    movq    (%rbx,%rax,8), %r8
    movq    8(%rbx,%rax,8), %r9
    movq    16(%rbx,%rax,8), %r10
    movq    24(%rbx,%rax,8), %r11
    addq    $4, %rax

    popcnt %r8, %r8
    add    %r8, %rdx
    popcnt %r9, %r9
    add    %r9, %rcx
    popcnt %r10, %r10
    add    %r10, %rdi
    popcnt %r11, %r11
    add    %r11, %rsi

    cmpq    $131072, %rax
    jne .L4

Same Register: 8.49272 GB/s

.L9:
    movq    (%rbx,%rdx,8), %r9
    movq    8(%rbx,%rdx,8), %r10
    movq    16(%rbx,%rdx,8), %r11
    movq    24(%rbx,%rdx,8), %rbp
    addq    $4, %rdx

    # This time reuse "rax" for all the popcnts.
    popcnt %r9, %rax
    add    %rax, %rcx
    popcnt %r10, %rax
    add    %rax, %rsi
    popcnt %r11, %rax
    add    %rax, %r8
    popcnt %rbp, %rax
    add    %rax, %rdi

    cmpq    $131072, %rdx
    jne .L9

Same Register with broken chain: 17.8869 GB/s

.L14:
    movq    (%rbx,%rdx,8), %r9
    movq    8(%rbx,%rdx,8), %r10
    movq    16(%rbx,%rdx,8), %r11
    movq    24(%rbx,%rdx,8), %rbp
    addq    $4, %rdx

    # Reuse "rax" for all the popcnts.
    xor    %rax, %rax    # Break the cross-iteration dependency by zeroing "rax".
    popcnt %r9, %rax
    add    %rax, %rcx
    popcnt %r10, %rax
    add    %rax, %rsi
    popcnt %r11, %rax
    add    %rax, %r8
    popcnt %rbp, %rax
    add    %rax, %rdi

    cmpq    $131072, %rdx
    jne .L14

So what went wrong with the compiler?

It seems that neither GCC nor Visual Studio are aware that popcnt has such a false dependency. Nevertheless, these false dependencies aren't uncommon. It's just a matter of whether the compiler is aware of it.

popcnt isn't exactly the most used instruction. So it's not really a surprise that a major compiler could miss something like this. There also appears to be no documentation anywhere that mentions this problem. If Intel doesn't disclose it, then nobody outside will know until someone runs into it by chance.

(Update: As of version 4.9.2, GCC is aware of this false-dependency and generates code to compensate it when optimizations are enabled. Major compilers from other vendors, including Clang, MSVC, and even Intel's own ICC are not yet aware of this microarchitectural erratum and will not emit code that compensates for it.)

Why does the CPU have such a false dependency?

We can speculate: it runs on the same execution unit as bsf / bsr which do have an output dependency. (How is POPCNT implemented in hardware?). For those instructions, Intel documents the integer result for input=0 as "undefined" (with ZF=1), but Intel hardware actually gives a stronger guarantee to avoid breaking old software: output unmodified. AMD documents this behaviour.

Presumably it was somehow inconvenient to make some uops for this execution unit dependent on the output but others not.

AMD processors do not appear to have this false dependency.


The full test code is below for reference:

#include <iostream>
#include <chrono>
#include <x86intrin.h>

int main(int argc, char* argv[]) {

   using namespace std;
   uint64_t size=1<<20;

   uint64_t* buffer = new uint64_t[size/8];
   char* charbuffer=reinterpret_cast<char*>(buffer);
   for (unsigned i=0;i<size;++i) charbuffer[i]=rand()%256;

   uint64_t count,duration;
   chrono::time_point<chrono::system_clock> startP,endP;
   {
      uint64_t c0 = 0;
      uint64_t c1 = 0;
      uint64_t c2 = 0;
      uint64_t c3 = 0;
      startP = chrono::system_clock::now();
      for( unsigned k = 0; k < 10000; k++){
         for (uint64_t i=0;i<size/8;i+=4) {
            uint64_t r0 = buffer[i + 0];
            uint64_t r1 = buffer[i + 1];
            uint64_t r2 = buffer[i + 2];
            uint64_t r3 = buffer[i + 3];
            __asm__(
                "popcnt %4, %4  \n\t"
                "add %4, %0     \n\t"
                "popcnt %5, %5  \n\t"
                "add %5, %1     \n\t"
                "popcnt %6, %6  \n\t"
                "add %6, %2     \n\t"
                "popcnt %7, %7  \n\t"
                "add %7, %3     \n\t"
                : "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
                : "r"  (r0), "r"  (r1), "r"  (r2), "r"  (r3)
            );
         }
      }
      count = c0 + c1 + c2 + c3;
      endP = chrono::system_clock::now();
      duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
      cout << "No Chain\t" << count << '\t' << (duration/1.0E9) << " sec \t"
            << (10000.0*size)/(duration) << " GB/s" << endl;
   }
   {
      uint64_t c0 = 0;
      uint64_t c1 = 0;
      uint64_t c2 = 0;
      uint64_t c3 = 0;
      startP = chrono::system_clock::now();
      for( unsigned k = 0; k < 10000; k++){
         for (uint64_t i=0;i<size/8;i+=4) {
            uint64_t r0 = buffer[i + 0];
            uint64_t r1 = buffer[i + 1];
            uint64_t r2 = buffer[i + 2];
            uint64_t r3 = buffer[i + 3];
            __asm__(
                "popcnt %4, %%rax   \n\t"
                "add %%rax, %0      \n\t"
                "popcnt %5, %%rax   \n\t"
                "add %%rax, %1      \n\t"
                "popcnt %6, %%rax   \n\t"
                "add %%rax, %2      \n\t"
                "popcnt %7, %%rax   \n\t"
                "add %%rax, %3      \n\t"
                : "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
                : "r"  (r0), "r"  (r1), "r"  (r2), "r"  (r3)
                : "rax"
            );
         }
      }
      count = c0 + c1 + c2 + c3;
      endP = chrono::system_clock::now();
      duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
      cout << "Chain 4   \t"  << count << '\t' << (duration/1.0E9) << " sec \t"
            << (10000.0*size)/(duration) << " GB/s" << endl;
   }
   {
      uint64_t c0 = 0;
      uint64_t c1 = 0;
      uint64_t c2 = 0;
      uint64_t c3 = 0;
      startP = chrono::system_clock::now();
      for( unsigned k = 0; k < 10000; k++){
         for (uint64_t i=0;i<size/8;i+=4) {
            uint64_t r0 = buffer[i + 0];
            uint64_t r1 = buffer[i + 1];
            uint64_t r2 = buffer[i + 2];
            uint64_t r3 = buffer[i + 3];
            __asm__(
                "xor %%rax, %%rax   \n\t"   // <--- Break the chain.
                "popcnt %4, %%rax   \n\t"
                "add %%rax, %0      \n\t"
                "popcnt %5, %%rax   \n\t"
                "add %%rax, %1      \n\t"
                "popcnt %6, %%rax   \n\t"
                "add %%rax, %2      \n\t"
                "popcnt %7, %%rax   \n\t"
                "add %%rax, %3      \n\t"
                : "+r" (c0), "+r" (c1), "+r" (c2), "+r" (c3)
                : "r"  (r0), "r"  (r1), "r"  (r2), "r"  (r3)
                : "rax"
            );
         }
      }
      count = c0 + c1 + c2 + c3;
      endP = chrono::system_clock::now();
      duration=chrono::duration_cast<std::chrono::nanoseconds>(endP-startP).count();
      cout << "Broken Chain\t"  << count << '\t' << (duration/1.0E9) << " sec \t"
            << (10000.0*size)/(duration) << " GB/s" << endl;
   }

   free(charbuffer);
}

An equally interesting benchmark can be found here: http://pastebin.com/kbzgL8si
This benchmark varies the number of popcnts that are in the (false) dependency chain.

False Chain 0:  41959360000 0.57748 sec     18.1578 GB/s
False Chain 1:  41959360000 0.585398 sec    17.9122 GB/s
False Chain 2:  41959360000 0.645483 sec    16.2448 GB/s
False Chain 3:  41959360000 0.929718 sec    11.2784 GB/s
False Chain 4:  41959360000 1.23572 sec     8.48557 GB/s

Pandas conditional creation of a series/dataframe column

Here's yet another way to skin this cat, using a dictionary to map new values onto the keys in the list:

def map_values(row, values_dict):
    return values_dict[row]

values_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4}

df = pd.DataFrame({'INDICATOR': ['A', 'B', 'C', 'D'], 'VALUE': [10, 9, 8, 7]})

df['NEW_VALUE'] = df['INDICATOR'].apply(map_values, args = (values_dict,))

What's it look like:

df
Out[2]: 
  INDICATOR  VALUE  NEW_VALUE
0         A     10          1
1         B      9          2
2         C      8          3
3         D      7          4

This approach can be very powerful when you have many ifelse-type statements to make (i.e. many unique values to replace).

And of course you could always do this:

df['NEW_VALUE'] = df['INDICATOR'].map(values_dict)

But that approach is more than three times as slow as the apply approach from above, on my machine.

And you could also do this, using dict.get:

df['NEW_VALUE'] = [values_dict.get(v, None) for v in df['INDICATOR']]

Connect multiple devices to one device via Bluetooth

Yes you can do so and I have created a library for the same.
This allows you to connect up-to four devices to the main server device creating different channels for each client and running interactions on different threads.
To use this library simple add compile com.mdg.androble:library:0.1.2 in dependency section of your build.gradle .

How to get today's Date?

Code To Get Today's date in any specific Format

You can define the desired format in SimpleDateFormat instance to get the date in that specific formate

 DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        String todaysdate = dateFormat.format(date);
         System.out.println("Today's date : " + todaysdate);

Follow below links to see the valid date format combination.

https://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html

CODE : To get x days ahead or Previous from Today's date, To get the past date or Future date.

For Example :

Today date : 11/27/2018

xdayFromTodaysDate = 2 to get date as 11/29/2018

xdayFromTodaysDate = -2 to get date as 11/25/2018

  public String getAniversaryDate(int xdayFromTodaysDate ){

        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        Calendar cal = Calendar.getInstance();
        Date date = cal.getTime();
        cal.setTime(date);
        cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
        date = cal.getTime();
        String aniversaryDate = dateFormat.format(date);
        LOGGER.info("Today's date : " + todaysdate);
          return aniversaryDate;

    }

CODE : To get x days ahead or Previous from a Given date

  public String getAniversaryDate(String givendate, int xdayFromTodaysDate ){


        Calendar cal = Calendar.getInstance();
        DateFormat dateFormat = new SimpleDateFormat("MM/dd/yyyy");
        try {
            Date date = dateFormat.parse(givendate);
            cal.setTime(date);
            cal.add(Calendar.DAY_OF_MONTH,xdayFromTodaysDate);
            date = cal.getTime();
            String aniversaryDate = dateFormat.format(date);
            LOGGER.info("aniversaryDate : " + aniversaryDate);
            return aniversaryDate;
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }

    }

DevTools failed to load SourceMap: Could not load content for chrome-extension

That's because Chrome added support for source maps.

Go to the developer tools (F12 in the browser), then select the three dots in the upper right corner, and go to Settings.

Then, look for Sources, and disable the options: "Enable javascript source maps" "Enable CSS source maps"

If you do that, that would get rid of the warnings. It has nothing to do with your code. Check the developer tools in other pages and you will see the same warning.

How to determine the number of days in a month in SQL Server?

select add_months(trunc(sysdate,'MM'),1) -  trunc(sysdate,'MM') from dual;

How to get the selected date of a MonthCalendar control in C#

I just noticed that if you do:

monthCalendar1.SelectionRange.Start.ToShortDateString() 

you will get only the date (e.g. 1/25/2014) from a MonthCalendar control.

It's opposite to:

monthCalendar1.SelectionRange.Start.ToString()

//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)

Because these MonthCalendar properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.

Loop and get key/value pair for JSON array using jQuery

var obj = $.parseJSON(result);
for (var prop in obj) {
    alert(prop + " is " + obj[prop]);
}

how can I enable scrollbars on the WPF Datagrid?

Put the DataGrid in a Grid, DockPanel, ContentControl or directly in the Window. A vertically-oriented StackPanel will give its children whatever vertical space they ask for - even if that means it is rendered out of view.

flutter run: No connected devices

This was my solution. Hope my confusion can help someone else too:

My "Developer Options" was ON,

but the "USB Debbugging" was OFF.

So I turned ON the USB Debbugging and the problem was solved.

Equivalent of .bat in mac os

The common convention would be to put it in a .sh file that looks like this -

#!/bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;... etc

Note that '\' become '/'.

You could execute as

sh myfile.sh

or set the x bit on the file

chmod +x myfile.sh

and then just call

myfile.sh

How to implement a queue using two stacks?

You'll have to pop everything off the first stack to get the bottom element. Then put them all back onto the second stack for every "dequeue" operation.

Check if XML Element exists

additionally to sangam code

if (chNode["innerNode"]["innermostNode"]==null)
            return true; //node    *parentNode*/innerNode/innermostNode exists

How do I load an HTML page in a <div> using JavaScript?

I saw this and thought it looked quite nice so I ran some tests on it.

It may seem like a clean approach, but in terms of performance it is lagging by 50% compared by the time it took to load a page with jQuery load function or using the vanilla javascript approach of XMLHttpRequest which were roughly similar to each other.

I imagine this is because under the hood it gets the page in the exact same fashion but it also has to deal with constructing a whole new HTMLElement object as well.

In summary I suggest using jQuery. The syntax is about as easy to use as it can be and it has a nicely structured call back for you to use. It is also relatively fast. The vanilla approach may be faster by an unnoticeable few milliseconds, but the syntax is confusing. I would only use this in an environment where I didn't have access to jQuery.

Here is the code I used to test - it is fairly rudimentary but the times came back very consistent across multiple tries so I would say precise to around +- 5ms in each case. Tests were run in Chrome from my own home server:

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
    <div id="content"></div>
    <script>
        /**
        * Test harness to find out the best method for dynamically loading a
        * html page into your app.
        */
        var test_times  = {};
        var test_page   = 'testpage.htm';
        var content_div = document.getElementById('content');

        // TEST 1 = use jQuery to load in testpage.htm and time it.
        /*
        function test_()
        {
            var start = new Date().getTime();
            $(content_div).load(test_page, function() {
                alert(new Date().getTime() - start);
            });
        }

        // 1044
        */

        // TEST 2 = use <object> to load in testpage.htm and time it.
        /*
        function test_()
        {
            start = new Date().getTime();
            content_div.innerHTML = '<object type="text/html" data="' + test_page +
            '" onload="alert(new Date().getTime() - start)"></object>'
        }

        //1579
        */

        // TEST 3 = use httpObject to load in testpage.htm and time it.
       function test_()
       {
           var xmlHttp = new XMLHttpRequest();

           xmlHttp.onreadystatechange = function() {
                if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                {
                   content_div.innerHTML = xmlHttp.responseText;
                   alert(new Date().getTime() - start);
                }
            };

            start = new Date().getTime();

            xmlHttp.open("GET", test_page, true); // true for asynchronous
            xmlHttp.send(null);

            // 1039
        }

        // Main - run tests
        test_();
    </script>
</body>
</html>

How do I get the picture size with PIL?

This is a complete example loading image from URL, creating with PIL, printing the size and resizing...

import requests
h = { 'User-Agent': 'Neo'}
r = requests.get("https://images.freeimages.com/images/large-previews/85c/football-1442407.jpg", headers=h)

from PIL import Image
from io import BytesIO
# create image from binary content
i = Image.open(BytesIO(r.content))


width, height = i.size
print(width, height)
i = i.resize((100,100))
display(i)

Bash Shell Script - Check for a flag and grab its value

Try shFlags -- Advanced command-line flag library for Unix shell scripts.

http://code.google.com/p/shflags/

It is very good and very flexible.

FLAG TYPES: This is a list of the DEFINE_*'s that you can do. All flags take a name, default value, help-string, and optional 'short' name (one-letter name). Some flags have other arguments, which are described with the flag.

DEFINE_string: takes any input, and intreprets it as a string.

DEFINE_boolean: typically does not take any argument: say --myflag to set FLAGS_myflag to true, or --nomyflag to set FLAGS_myflag to false. Alternately, you can say --myflag=true or --myflag=t or --myflag=0 or --myflag=false or --myflag=f or --myflag=1 Passing an option has the same affect as passing the option once.

DEFINE_float: takes an input and intreprets it as a floating point number. As shell does not support floats per-se, the input is merely validated as being a valid floating point value.

DEFINE_integer: takes an input and intreprets it as an integer.

SPECIAL FLAGS: There are a few flags that have special meaning: --help (or -?) prints a list of all the flags in a human-readable fashion --flagfile=foo read flags from foo. (not implemented yet) -- as in getopt(), terminates flag-processing

EXAMPLE USAGE:

-- begin hello.sh --
 ! /bin/sh
. ./shflags
DEFINE_string name 'world' "somebody's name" n
FLAGS "$@" || exit $?
eval set -- "${FLAGS_ARGV}"
echo "Hello, ${FLAGS_name}."
-- end hello.sh --

$ ./hello.sh -n Kate
Hello, Kate.

Note: I took this text from shflags documentation

Getting the closest string match

To query a large set of text in efficient manner you can use the concept of Edit Distance/ Prefix Edit Distance.

Edit Distance ED(x,y): minimal number of transfroms to get from term x to term y

But computing ED between each term and query text is resource and time intensive. Therefore instead of calculating ED for each term first we can extract possible matching terms using a technique called Qgram Index. and then apply ED calculation on those selected terms.

An advantage of Qgram index technique is it supports for Fuzzy Search.

One possible approach to adapt QGram index is build an Inverted Index using Qgrams. In there we store all the words which consists with particular Qgram, under that Qgram.(Instead of storing full string you can use unique ID for each string). You can use Tree Map data structure in Java for this. Following is a small example on storing of terms

col : colmbia, colombo, gancola, tacolama

Then when querying, we calculate the number of common Qgrams between query text and available terms.

Example: x = HILLARY, y = HILARI(query term)
Qgrams
$$HILLARY$$ -> $$H, $HI, HIL, ILL, LLA, LAR, ARY, RY$, Y$$
$$HILARI$$ -> $$H, $HI, HIL, ILA, LAR, ARI, RI$, I$$
number of q-grams in common = 4

number of q-grams in common = 4.

For the terms with high number of common Qgrams, we calculate the ED/PED against the query term and then suggest the term to the end user.

you can find an implementation of this theory in following project(See "QGramIndex.java"). Feel free to ask any questions. https://github.com/Bhashitha-Gamage/City_Search

To study more about Edit Distance, Prefix Edit Distance Qgram index please watch the following video of Prof. Dr Hannah Bast https://www.youtube.com/embed/6pUg2wmGJRo (Lesson starts from 20:06)

Laravel Password & Password_Confirmation Validation

I have used in this way.. Working fine!

 $inputs = request()->validate([
        'name' => 'required | min:6 | max: 20',
        'email' => 'required',
        'password' => 'required| min:4| max:7 |confirmed',
        'password_confirmation' => 'required| min:4'
  ]);

How to trigger button click in MVC 4

yo can try this code

@using (Html.BeginForm("SignUp", "Account", FormMethod.Post)){<fieldset>
    <legend>Sign Up</legend>
    <table>
        <tr>
            <td>
                @Html.Label("User Name")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Username)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Email")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Email)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Password")
            </td>
            <td>
                @Html.TextBoxFor(account => account.Password)
            </td>
        </tr>
        <tr>
            <td>
                @Html.Label("Confirm Password")
            </td>
            <td>
                @Html.Password("txtPassword")
            </td>
        </tr>
        <tr>
            <td>
                <input type="submit" name="btnSubmit" value="Sign Up" />
            </td>
        </tr>
    </table>
</fieldset>}

How do I make a MySQL database run completely in memory?

In place of the Memory storage engine, one can consider MySQL Cluster. It is said to give similar performance but to support disk-backed operation for durability. I've not tried it, but it looks promising (and been in development for a number of years).

You can find the official MySQL Cluster documentation here.

Difference between `npm start` & `node app.js`, when starting app?

From the man page, npm start:

runs a package's "start" script, if one was provided. If no version is specified, then it starts the "active" version.

Admittedly, that description is completely unhelpful, and that's all it says. At least it's more documented than socket.io.

Anyhow, what really happens is that npm looks in your package.json file, and if you have something like

"scripts": { "start": "coffee server.coffee" }

then it will do that. If npm can't find your start script, it defaults to:

node server.js

 

Size of character ('a') in C/C++

In C, the type of a character constant like 'a' is actually an int, with size of 4 (or some other implementation-dependent value). In C++, the type is char, with size of 1. This is one of many small differences between the two languages.

Android: checkbox listener

Translation of the accepted answer by Chris into Kotlin:

val checkBox: CheckBox = findViewById(R.id.chk)
checkBox.setOnCheckedChangeListener { buttonView, isChecked ->
    // Code here 
}

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

You will have to annotate your service with @Service since you have said I am using annotations for mapping

The type or namespace name does not exist in the namespace 'System.Web.Mvc'

I had the same problem, none of the solutions worked for me, Finally I removed the System.Web.MVC and added again Then everything was back to normal and my problem solved.

How to loop in excel without VBA or macros?

The way to get the results of your formula would be to start in a new sheet.

In cell A1 put the formula

=IF('testsheet'!C1 <= 99,'testsheet'!A1,"") 

Copy that cell down to row 40 In cell B1 put the formula

=A1

In cell B2 put the formula

=B1 & A2

Copy that cell down to row 40.

The value you want is now in that column in row 40.

Not really the answer you want, but that is the fastest way to get things done excel wise without creating a custom formula that takes in a range and makes the calculation (which would be more fun to do).

Remove blue border from css custom-styled button in Chrome

Simply write outline:none;. No need to use pseudo element focus

PHP: How can I determine if a variable has a value that is between two distinct constant values?

returns true if subject is between low and high (inclusive)

$between = function( $low, $high, $subject ) {
    if( $subject < $low ) return false;
    if( $subject > $high ) return false;
    return true;
};

if( $between( 0, 100, $givenNumber )) {
   // do whatever...
}

looks cleaner to me

How can I convert string to datetime with format specification in JavaScript?

I think this can help you: http://www.mattkruse.com/javascript/date/

There's a getDateFromFormat() function that you can tweak a little to solve your problem.

Update: there's an updated version of the samples available at javascripttoolbox.com

"rm -rf" equivalent for Windows?

Here is what you need to do...

Create a batch file with the following line

RMDIR /S %1

Save your batch file as Remove.bat and put it in C:\windows

Create the following registry key

HKEY_CLASSES_ROOT\Directory\shell\Remove Directory (RMDIR)

Launch regedit and update the default value HKEY_CLASSES_ROOT\Directory\shell\Remove Directory (RMDIR)\default with the following value

"c:\windows\REMOVE.bat" "%1"

Thats it! Now you can right click any directory and use the RMDIR function

How does Access-Control-Allow-Origin header work?

In Python I have been using the Flask-CORS library with great success. It makes dealing with CORS super easy and painless. I added some code from the library's documentation below.

Installing:

$ pip install -U flask-cors

Simple example that allows CORS for all domains on all routes:

from flask import Flask
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

@app.route("/")
def helloWorld():
  return "Hello, cross-origin-world!"

For more specific examples see the documentation. I have used the simple example above to get around the CORS issue in an ionic application I am building that has to access a separate flask server.

Process with an ID #### is not running in visual studio professional 2013 update 3

Resolution I found;

Head to the following directory

%userprofile%\documents\IISExpress\Config directory

Delete all files within that folder. Restart visual studio and works like a charm.

Java JSON serialization - best practice

As others have hinted, you should consider dumping org.json's library. It's pretty much obsolete these days, and trying to work around its problems is waste of time.

But to specific question; type variable T just does not have any information to help you, as it is little more than compile-time information. Instead you need to pass actual class (as 'Class cls' argument), and you can then create an instance with 'cls.newInstance()'.

android edittext onchange listener

The Watcher method fires on every character input. So, I built this code based on onFocusChange method:

public static boolean comS(String s1,String s2){
    if (s1.length()==s2.length()){
        int l=s1.length();
        for (int i=0;i<l;i++){
            if (s1.charAt(i)!=s2.charAt(i))return false;
        }
        return true;
    }
    return false;
}

public void onChange(final EditText EdTe, final Runnable FRun){
    class finalS{String s="";}
    final finalS dat=new finalS();  
    EdTe.setOnFocusChangeListener(new OnFocusChangeListener() {          
        @Override
        public void onFocusChange(View v, boolean hasFocus) {
            if (hasFocus) {dat.s=""+EdTe.getText();}
            else if (!comS(dat.s,""+EdTe.getText())){(new Handler()).post(FRun);}       
        }
    });
}

To using it, just call like this:

onChange(YourEditText, new Runnable(){public void run(){
    // V  V    YOUR WORK HERE

    }}
);

You can ignore the comS function by replace the !comS(dat.s,""+EdTe.getText()) with !equal function. However the equal function itself some time work not correctly in run time.

The onChange listener will remember old data of EditText when user focus typing, and then compare the new data when user lose focus or jump to other input. If comparing old String not same new String, it fires the work.

If you only have 1 EditText, then u will need to make a ClearFocus function by making an Ultimate Secret Transparent Micro EditText outside the windows and request focus to it, then hide the keyboard via Import Method Manager.

Nginx serves .php files as downloads, instead of executing them

check your nginx config file extension is *.conf.
for example: /etc/nginx/conf.d/myfoo.conf

I got the same situation. After I rename the my config file from myfoo to myfoo.conf, it fixed. Do not forget to restart nginx after rename it.

Using PHP with Socket.io

I haven't tried it yet, but you should be able to do this with ReactPHP and this socket component. Looks just like Node, but in PHP.

How to run script as another user without password?

Call visudo and add this:

user1 ALL=(user2) NOPASSWD: /home/user2/bin/test.sh

The command paths must be absolute! Then call sudo -u user2 /home/user2/bin/test.sh from a user1 shell. Done.

how to draw directed graphs using networkx in python?

I only put this in for completeness. I've learned plenty from marius and mdml. Here are the edge weights. Sorry about the arrows. Looks like I'm not the only one saying it can't be helped. I couldn't render this with ipython notebook I had to go straight from python which was the problem with getting my edge weights in sooner.

import networkx as nx
import numpy as np
import matplotlib.pyplot as plt
import pylab

G = nx.DiGraph()

G.add_edges_from([('A', 'B'),('C','D'),('G','D')], weight=1)
G.add_edges_from([('D','A'),('D','E'),('B','D'),('D','E')], weight=2)
G.add_edges_from([('B','C'),('E','F')], weight=3)
G.add_edges_from([('C','F')], weight=4)


val_map = {'A': 1.0,
                   'D': 0.5714285714285714,
                              'H': 0.0}

values = [val_map.get(node, 0.45) for node in G.nodes()]
edge_labels=dict([((u,v,),d['weight'])
                 for u,v,d in G.edges(data=True)])
red_edges = [('C','D'),('D','A')]
edge_colors = ['black' if not edge in red_edges else 'red' for edge in G.edges()]

pos=nx.spring_layout(G)
nx.draw_networkx_edge_labels(G,pos,edge_labels=edge_labels)
nx.draw(G,pos, node_color = values, node_size=1500,edge_color=edge_colors,edge_cmap=plt.cm.Reds)
pylab.show()

enter image description here

Angular 2 - innerHTML styling

update 2 ::slotted

::slotted is now supported by all new browsers and can be used with ViewEncapsulation.ShadowDom

https://developer.mozilla.org/en-US/docs/Web/CSS/::slotted

update 1 ::ng-deep

/deep/ was deprecated and replaced by ::ng-deep.

::ng-deep is also already marked deprecated, but there is no replacement available yet.

When ViewEncapsulation.Native is properly supported by all browsers and supports styling accross shadow DOM boundaries, ::ng-deep will probably be discontinued.

original

Angular adds all kinds of CSS classes to the HTML it adds to the DOM to emulate shadow DOM CSS encapsulation to prevent styles of bleeding in and out of components. Angular also rewrites the CSS you add to match these added classes. For HTML added using [innerHTML] these classes are not added and the rewritten CSS doesn't match.

As a workaround try

  • for CSS added to the component
/* :host /deep/ mySelector { */
:host ::ng-deep mySelector { 
  background-color: blue;
}
  • for CSS added to index.html
/* body /deep/ mySelector { */
body ::ng-deep mySelector {
  background-color: green;
}

>>> (and the equivalent/deep/ but /deep/ works better with SASS) and ::shadow were added in 2.0.0-beta.10. They are similar to the shadow DOM CSS combinators (which are deprecated) and only work with encapsulation: ViewEncapsulation.Emulated which is the default in Angular2. They probably also work with ViewEncapsulation.None but are then only ignored because they are not necessary. These combinators are only an intermediate solution until more advanced features for cross-component styling is supported.

Another approach is to use

@Component({
  ...
  encapsulation: ViewEncapsulation.None,
})

for all components that block your CSS (depends on where you add the CSS and where the HTML is that you want to style - might be all components in your application)

Update

Example Plunker

What is the difference between square brackets and parentheses in a regex?

The first 2 examples act very differently if you are REPLACING them by something. If you match on this:

str = str.replace(/^(7|8|9)/ig,''); 

you would replace 7 or 8 or 9 by the empty string.

If you match on this

str = str.replace(/^[7|8|9]/ig,''); 

you will replace 7 or 8 or 9 OR THE VERTICAL BAR!!!! by the empty string.

I just found this out the hard way.

How to display both icon and title of action inside ActionBar?

Some of you guys have great answers, but I found some additional thing. If you want create a MenuItem with some SubMenu programmatically:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {

        SubMenu subMenu = menu.addSubMenu(0, Menu.NONE, 0, "Menu title");
        subMenu.getItem().setIcon(R.drawable.ic_action_child);
        subMenu.getItem().setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);

        subMenu.add(0, Menu.NONE, 0, "Subitem 1");
        subMenu.add(0, Menu.NONE, 1, "Subitem 2");
        subMenu.add(0, Menu.NONE, 2, "Subitem 3");

        return true;
    }

Copy directory contents into a directory with python

The python libs are obsolete with this function. I've done one that works correctly:

import os
import shutil

def copydirectorykut(src, dst):
    os.chdir(dst)
    list=os.listdir(src)
    nom= src+'.txt'
    fitx= open(nom, 'w')

    for item in list:
        fitx.write("%s\n" % item)

    fitx.close()

    f = open(nom,'r')
    for line in f.readlines():
        if "." in line:
            shutil.copy(src+'/'+line[:-1],dst+'/'+line[:-1])
        else:
            if not os.path.exists(dst+'/'+line[:-1]):
                os.makedirs(dst+'/'+line[:-1])
                copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
            copydirectorykut(src+'/'+line[:-1],dst+'/'+line[:-1])
    f.close()
    os.remove(nom)
    os.chdir('..')

In C#, how to check if a TCP port is available?

    public static bool TestOpenPort(int Port)
    {
        var tcpListener = default(TcpListener);

        try
        {
            var ipAddress = Dns.GetHostEntry("localhost").AddressList[0];

            tcpListener = new TcpListener(ipAddress, Port);
            tcpListener.Start();

            return true;
        }
        catch (SocketException)
        {
        }
        finally
        {
            if (tcpListener != null)
                tcpListener.Stop();
        }

        return false;
    }

open resource with relative path in Java

When you use 'getResource' on a Class, a relative path is resolved based on the package the Class is in. When you use 'getResource' on a ClassLoader, a relative path is resolved based on the root folder.

If you use an absolute path, both 'getResource' methods will start at the root folder.