Programs & Examples On #Javax.swing.text

How can I get href links from HTML using Python?

This answer is similar to others with requests and BeautifulSoup, but using list comprehension.

Because find_all() is the most popular method in the Beautiful Soup search API, you can use soup("a") as a shortcut of soup.findAll("a") and using list comprehension:

import requests
from bs4 import BeautifulSoup

URL = "http://www.yourwebsite.com"
page = requests.get(URL)
soup = BeautifulSoup(page.content, features='lxml')
# Find links
all_links = [link.get("href") for link in soup("a")]
# Only external links
ext_links = [link.get("href") for link in soup("a") if "http" in link.get("href")]

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#calling-a-tag-is-like-calling-find-all

Insert php variable in a href

echo '<a href="' . $folder_path . '">Link text</a>';

Please note that you must use the path relative to your domain and, if the folder path is outside the public htdocs directory, it will not work.

EDIT: maybe i misreaded the question; you have a file on your pc and want to insert the path on the html page, and then send it to the server?

JavaScript string newline character?

printAccountSummary: function()
        {return "Welcome!" + "\n" + "Your balance is currently $1000 and your interest rate is 1%."}
};
console.log(savingsAccount.printAccountSummary()); // method

Prints:

Welcome!
Your balance is currently $1000 and your interest rate is 1%.

When is null or undefined used in JavaScript?

I might be missing something, but afaik, you get undefined only

Update: Ok, I missed a lot, trying to complete:

You get undefined...

... when you try to access properties of an object that don't exist:

var a = {}
a.foo // undefined

... when you have declared a variable but not initialized it:

var a;
// a is undefined

... when you access a parameter for which no value was passed:

function foo (a, b) {
    // something
}

foo(42); // b inside foo is undefined

... when a function does not return a value:

function foo() {};
var a = foo(); // a is undefined

It might be that some built-in functions return null on some error, but if so, then it is documented. null is a concrete value in JavaScript, undefined is not.


Normally you don't need to distinguish between those. Depending on the possible values of a variable, it is sufficient to use if(variable) to test whether a value is set or not (both, null and undefined evaluate to false).

Also different browsers seem to be returning these differently.

Please give a concrete example.

Convert char* to string C++

std::string str(buffer, buffer + length);

Or, if the string already exists:

str.assign(buffer, buffer + length);

Edit: I'm still not completely sure I understand the question. But if it's something like what JoshG is suggesting, that you want up to length characters, or until a null terminator, whichever comes first, then you can use this:

std::string str(buffer, std::find(buffer, buffer + length, '\0'));

How do you fade in/out a background color using jquery?

Using jQuery only (no UI library/plugin). Even jQuery can be easily eliminated

//Color row background in HSL space (easier to manipulate fading)
$('tr').eq(1).css('backgroundColor','hsl(0,100%,50%');

var d = 1000;
for(var i=50; i<=100; i=i+0.1){ //i represents the lightness
    d  += 10;
    (function(ii,dd){
        setTimeout(function(){
            $('tr').eq(1).css('backgroundColor','hsl(0,100%,'+ii+'%)'); 
        }, dd);    
    })(i,d);
}

Demo : http://jsfiddle.net/5NB3s/2/

  • SetTimeout increases the lightness from 50% to 100%, essentially making the background white (you can choose any value depending on your color).
  • SetTimeout is wrapped in an anonymous function for it to work properly in a loop ( reason )

WinSCP: Permission denied. Error code: 3 Error message from server: Permission denied

You possibly do not have create permissions to the folder. So WinSCP fails to create a temporary file for the transfer.

You have two options:

Removing whitespace between HTML elements when using line breaks

Sorry if this is old but I just found a solution.

Try setting the font-size to 0. Thus the white-spaces in between the images will be 0 in width, and the images won't be affected.

Don't know if this works in all browsers, but I tried it with Chromium and some <li> elements with display: inline-block;.

What's the equivalent of Java's Thread.sleep() in JavaScript?

The simple answer is that there is no such function.

The closest thing you have is:

var millisecondsToWait = 500;
setTimeout(function() {
    // Whatever you want to do after the wait
}, millisecondsToWait);

Note that you especially don't want to busy-wait (e.g. in a spin loop), since your browser is almost certainly executing your JavaScript in a single-threaded environment.

Here are a couple of other SO questions that deal with threads in JavaScript:

And this question may also be helpful:

indexOf method in an object array?

While, most other answers here are valid. Sometimes, it's best to just make a short simple function near where you will use it.

// indexOf wrapper for the list of objects
function indexOfbyKey(obj_list, key, value) {
    for (index in obj_list) {
        if (obj_list[index][key] === value) return index;
    }
    return -1;
}
// Find the string in the list (default -1)
var test1 = indexOfbyKey(object_list, 'name', 'Stevie');
var test2 = indexOfbyKey(object_list, 'last_name', 'some other name');

It depends on what is important to you. It might save lines of code and be very clever to use a one-liner, or to put a generic solution somewhere that covers various edge cases. But sometimes it's better to just say: "here I did it like this" rather than leave future developers to have extra reverse engineering work. Especially if you consider yourself "a newbie" like in your question.

No 'Access-Control-Allow-Origin' header is present on the requested resource - Resteasy

After facing a similar issue, below is what I did :

  • Created a class extending javax.ws.rs.core.Application and added a Cors Filter to it.

To the CORS filter, I added corsFilter.getAllowedOrigins().add("http://localhost:4200");.

Basically, you should add the URL which you want to allow Cross-Origin Resource Sharing. Ans you can also use "*" instead of any specific URL to allow any URL.

public class RestApplication
    extends Application
{
    private Set<Object> singletons = new HashSet<Object>();

    public MessageApplication()
    {
        singletons.add(new CalculatorService()); //CalculatorService is your specific service you want to add/use.
        CorsFilter corsFilter = new CorsFilter();
        // To allow all origins for CORS add following, otherwise add only specific urls.
        // corsFilter.getAllowedOrigins().add("*");
        System.out.println("To only allow restrcited urls ");
        corsFilter.getAllowedOrigins().add("http://localhost:4200");
        singletons = new LinkedHashSet<Object>();
        singletons.add(corsFilter);
    }

    @Override
    public Set<Object> getSingletons()
    {
        return singletons;
    }
}
  • And here is my web.xml:
<web-app id="WebApp_ID" version="2.4"
    xmlns="http://java.sun.com/xml/ns/j2ee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <display-name>Restful Web Application</display-name>

    <!-- Auto scan rest service -->
    <context-param>
        <param-name>resteasy.scan</param-name>
        <param-value>true</param-value>
    </context-param>

    <context-param>
        <param-name>resteasy.servlet.mapping.prefix</param-name>
        <param-value>/rest</param-value>
    </context-param>

    <listener>
        <listener-class>
            org.jboss.resteasy.plugins.server.servlet.ResteasyBootstrap
        </listener-class>
    </listener>

    <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>
            org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
        </servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.app.RestApplication</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/rest/*</url-pattern>
    </servlet-mapping>

</web-app>

The most important code which I was missing when I was getting this issue was, I was not adding my class extending javax.ws.rs.Application i.e RestApplication to the init-param of <servlet-name>resteasy-servlet</servlet-name>

   <init-param>
        <param-name>javax.ws.rs.Application</param-name>
        <param-value>com.app.RestApplication</param-value>
    </init-param>

And therefore my Filter was not able to execute and thus the application was not allowing CORS from the URL specified.

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

I face similar issue while importing TensorFlow. If you are using Tensorflow which uses Pandas library, I suggest restarting your kernel of Anaconda. This works for me.

How does the FetchMode work in Spring Data JPA

I think that Spring Data ignores the FetchMode. I always use the @NamedEntityGraph and @EntityGraph annotations when working with Spring Data

@Entity
@NamedEntityGraph(name = "GroupInfo.detail",
  attributeNodes = @NamedAttributeNode("members"))
public class GroupInfo {

  // default fetch mode is lazy.
  @ManyToMany
  List<GroupMember> members = new ArrayList<GroupMember>();

  …
}

@Repository
public interface GroupRepository extends CrudRepository<GroupInfo, String> {

  @EntityGraph(value = "GroupInfo.detail", type = EntityGraphType.LOAD)
  GroupInfo getByGroupName(String name);

}

Check the documentation here

Can you hide the controls of a YouTube embed without enabling autoplay?

To continue using the iframe YouTube, you should only have to change ?autoplay=1 to ?autoplay=0.

Another way to accomplish this would be by using the YouTube JavaScript Player API. (https://developers.google.com/youtube/js_api_reference)

Edit: the YouTube JavaScript Player API is no longer supported.

<div id="howToVideo"></div>

<script type="application/javascript">

    var ga = document.createElement('script');
    ga.type = 'text/javascript';
    ga.async = false;
    ga.src = 'http://www.youtube.com/player_api';
    var s = document.getElementsByTagName('script')[0];
    s.parentNode.insertBefore(ga, s);

    var done = false;
    var player;

    function onYouTubePlayerAPIReady() {
        player = new YT.Player('howToVideo', {
            height: '390',
            width: '640',
            videoId: 'qUJYqhKZrwA',
        playerVars: {
            controls: 0,
            disablekb: 1
        },
          events: {
            'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange
          }
        });
    }
    function onPlayerReady(evt) {
        console.log('onPlayerReady', evt);
    }
    function onPlayerStateChange(evt) {
        console.log('onPlayerStateChange', evt);
        if (evt.data == YT.PlayerState.PLAYING && !done) {
            setTimeout(stopVideo, 6000);
            done = true;
        }
    }

    function stopVideo() {
        console.log('stopVideo');
        player.stopVideo();
    }

</script>

Here is a jsfiddle for the example: http://jsfiddle.net/fgkrj/

Note that player controls are disabled in the "playerVars" part of the player. The one sacrifice you make is that users are still able to pause the video by clicking on it. I would suggest writing a simple javascript function that subscribes to a stop event and calls player.playVideo().

Sleep function in Windows, using C

Include the following function at the start of your code, whenever you want to busy wait. This is distinct from sleep, because the process will be utilizing 100% cpu while this function is running.

void sleep(unsigned int mseconds)
{
    clock_t goal = mseconds + clock();
    while (goal > clock())
        ;
}

Note that the name sleep for this function is misleading, since the CPU will not be sleeping at all.

Linq to Sql: Multiple left outer joins

This may be cleaner (you dont need all the into statements):

var query = 
    from order in dc.Orders
    from vendor 
    in dc.Vendors
        .Where(v => v.Id == order.VendorId)
        .DefaultIfEmpty()
    from status 
    in dc.Status
        .Where(s => s.Id == order.StatusId)
        .DefaultIfEmpty()
    select new { Order = order, Vendor = vendor, Status = status } 
    //Vendor and Status properties will be null if the left join is null

Here is another left join example

var results = 
    from expense in expenseDataContext.ExpenseDtos
    where expense.Id == expenseId //some expense id that was passed in
    from category 
    // left join on categories table if exists
    in expenseDataContext.CategoryDtos
                         .Where(c => c.Id == expense.CategoryId)
                         .DefaultIfEmpty() 
    // left join on expense type table if exists
    from expenseType 
    in expenseDataContext.ExpenseTypeDtos
                         .Where(e => e.Id == expense.ExpenseTypeId)
                         .DefaultIfEmpty()
    // left join on currency table if exists
    from currency 
    in expenseDataContext.CurrencyDtos
                         .Where(c => c.CurrencyID == expense.FKCurrencyID)
                         .DefaultIfEmpty() 
    select new 
    { 
        Expense = expense,
        // category will be null if join doesn't exist
        Category = category,
        // expensetype will be null if join doesn't exist
        ExpenseType = expenseType,
        // currency will be null if join doesn't exist
        Currency = currency  
    }

How do I properly force a Git push?

Just do:

git push origin <your_branch_name> --force

or if you have a specific repo:

git push https://git.... --force

This will delete your previous commit(s) and push your current one.

It may not be proper, but if anyone stumbles upon this page, thought they might want a simple solution...

Short flag

Also note that -f is short for --force, so

git push origin <your_branch_name> -f

will also work.

Colspan all columns

For IE 6, you'll want to equal colspan to the number of columns in your table. If you have 5 columns, then you'll want: colspan="5".

The reason is that IE handles colspans differently, it uses the HTML 3.2 specification:

IE implements the HTML 3.2 definition, it sets colspan=0 as colspan=1.

The bug is well documented.

Create random list of integers in Python

Firstly, you should use randrange(0,1000) or randint(0,999), not randint(0,1000). The upper limit of randint is inclusive.

For efficiently, randint is simply a wrapper of randrange which calls random, so you should just use random. Also, use xrange as the argument to sample, not range.

You could use

[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]

to generate 10,000 numbers in the range using sample 10 times.

(Of course this won't beat NumPy.)

$ python2.7 -m timeit -s 'from random import randrange' '[randrange(1000) for _ in xrange(10000)]'
10 loops, best of 3: 26.1 msec per loop

$ python2.7 -m timeit -s 'from random import sample' '[a%1000 for a in sample(xrange(10000),10000)]'
100 loops, best of 3: 18.4 msec per loop

$ python2.7 -m timeit -s 'from random import random' '[int(1000*random()) for _ in xrange(10000)]' 
100 loops, best of 3: 9.24 msec per loop

$ python2.7 -m timeit -s 'from random import sample' '[a for a in sample(xrange(1000),1000) for _ in range(10000/1000)]'
100 loops, best of 3: 3.79 msec per loop

$ python2.7 -m timeit -s 'from random import shuffle
> def samplefull(x):
>   a = range(x)
>   shuffle(a)
>   return a' '[a for a in samplefull(1000) for _ in xrange(10000/1000)]'
100 loops, best of 3: 3.16 msec per loop

$ python2.7 -m timeit -s 'from numpy.random import randint' 'randint(1000, size=10000)'
1000 loops, best of 3: 363 usec per loop

But since you don't care about the distribution of numbers, why not just use:

range(1000)*(10000/1000)

?

How to generate unique ID with node.js

used https://www.npmjs.com/package/uniqid in npm

npm i uniqid

It will always create unique id's based on the current time, process and machine name.

  • With the current time the ID's are always unique in a single process.
  • With the Process ID the ID's are unique even if called at the same time from multiple processes.
  • With the MAC Address the ID's are unique even if called at the same time from multiple machines and processes.

Features:-

  • Very fast
  • Generates unique id's on multiple processes and machines even if called at the same time.
  • Shorter 8 and 12 byte versions with less uniqueness.

Disable back button in android

Just using this code: If you want backpressed disable, you dont use super.OnBackPressed();

@Override
public void onBackPressed() {

}

Virtualbox shared folder permissions

In my case the following was necessary:

sudo chgrp vboxsf /media/sf_sharedFolder

How to perform Join between multiple tables in LINQ lambda

take look at this sample code from my project

public static IList<Letter> GetDepartmentLettersLinq(int departmentId)
{
    IEnumerable<Letter> allDepartmentLetters =
        from allLetter in LetterService.GetAllLetters()
        join allUser in UserService.GetAllUsers() on allLetter.EmployeeID equals allUser.ID into usersGroup
        from user in usersGroup.DefaultIfEmpty()// here is the tricky part
        join allDepartment in DepartmentService.GetAllDepartments() on user.DepartmentID equals allDepartment.ID
        where allDepartment.ID == departmentId
        select allLetter;

    return allDepartmentLetters.ToArray();
}

in this code I joined 3 tables and I spited join condition from where clause

note: the Services classes are just warped(encapsulate) the database operations

Configure Flask dev server to be visible across the network

While this is possible, you should not use the Flask dev server in production. The Flask dev server is not designed to be particularly secure, stable, or efficient. See the docs on deploying for correct solutions.


Add a parameter to your app.run(). By default it runs on localhost, change it to app.run(host= '0.0.0.0') to run on all your machine's IP addresses. 0.0.0.0 is a special value, you'll need to navigate to the actual IP address.

Documented on the Flask site under "Externally Visible Server" on the Quickstart page:

Externally Visible Server

If you run the server you will notice that the server is only available from your own computer, not from any other in the network. This is the default because in debugging mode a user of the application can execute arbitrary Python code on your computer. If you have debug disabled or trust the users on your network, you can make the server publicly available.

Just change the call of the run() method to look like this:

app.run(host='0.0.0.0')

This tells your operating system to listen on a public IP.

How to move or copy files listed by 'find' command in unix?

Actually, you can process the find command output in a copy command in two ways:

  1. If the find command's output doesn't contain any space, i.e if the filename doesn't contain a space in it, then you can use:

    Syntax:
        find <Path> <Conditions> | xargs cp -t <copy file path>
    Example:
        find -mtime -1 -type f | xargs cp -t inner/
    
  2. But our production data files might contain spaces, so most of time this command is effective:

    Syntax:
       find <path> <condition> -exec cp '{}' <copy path> \;
    
    Example 
       find -mtime -1 -type f -exec cp '{}' inner/ \;
    

In the second example, the last part, the semi-colon is also considered as part of the find command, and should be escaped before pressing Enter. Otherwise you will get an error something like:

find: missing argument to `-exec'

Install python 2.6 in CentOS

If you want to make it easier on yourself, there are CentOS RPMs for new Python versions floating around the net. E.g. see:

http://www.geekymedia.com/python_26_centos.html

How to send POST in angularjs with multiple params?

If you're using ASP.NET MVC and Web API chances are you have the Newtonsoft.Json NuGet package installed.This library has a class called JObject which allows you to pass through multiple parameters:

Api Controller:

public class ProductController : ApiController
{
    [HttpPost]
    public void Post(Newtonsoft.Json.Linq.JObject data)
    {
        System.Diagnostics.Debugger.Break();

        Product product = data["product"].ToObject<Product>();
        Product product2 = data["product2"].ToObject<Product>();

        int someRandomNumber = data["randomNumber"].ToObject<int>();
        string productName = product.ProductName;
        string product2Name = product2.ProductName;
    }
}

public class Product
{
    public int ProductID { get; set; }
    public string ProductName { get; set; }
}

View:

<script src="~/Scripts/angular.js"></script>
<script type="text/javascript">
    var myApp = angular.module("app", []);
    myApp.controller('controller', function ($scope, $http) {

        $scope.AddProducts = function () {
            var product = {
                ProductID: 0,
                ProductName: "Orange",
            }

            var product2 = {
                ProductID: 1,
                ProductName: "Mango",
            }

            var data = {
                product: product,
                product2: product2,
                randomNumber:12345
            };

            $http.post("/api/Product", data).
            success(function (data, status, headers, config) {
            }).
            error(function (data, status, headers, config) {
                alert("An error occurred during the AJAX request");
            });
        }
    });
</script>
<div ng-app="app" ng-controller="controller">
    <input type="button" ng-click="AddProducts()" value="Get Full Name" />
</div>

Is it possible to use jQuery .on and hover?

jQuery hover function gives mouseover and mouseout functionality.

$(selector).hover(inFunction,outFunction);

$(".item-image").hover(function () {
    // mouseover event codes...
}, function () {
    // mouseout event codes...
});

Source: http://www.w3schools.com/jquery/event_hover.asp

Linux configure/make, --prefix?

Do configure --help and see what other options are available.

It is very common to provide different options to override different locations. By standard, --prefix overrides all of them, so you need to override config location after specifying the prefix. This course of actions usually works for every automake-based project.

The worse case scenario is when you need to modify the configure script, or even worse, generated makefiles and config.h headers. But yeah, for Xfce you can try something like this:

./configure --prefix=/home/me/somefolder/mybuild/output/target --sysconfdir=/etc 

I believe that should do it.

Getting the name of a variable as a string

Using the python-varname package, you can easily retrieve the name of the variables

https://github.com/pwwang/python-varname

As of v0.6.0, in your case, you can do:

from varname.helpers import Wrapper

foo = Wrapper(dict())

# foo.name == 'foo'
# foo.value == {}
foo.value['bar'] = 2

For list comprehension part, you can do:

n_jobs = Wrapper(<original_value>) 
users = Wrapper(<original_value>) 
queues = Wrapper(<original_value>) 
priorities = Wrapper(<original_value>) 

list_of_dicts = [n_jobs, users, queues, priorities]
columns = [d.name for d in list_of_dicts]
# ['n_jobs', 'users', 'queues', 'priorities']
# REMEMBER that you have to access the <original_value> by d.value

You can also try to retrieve the variable name DIRECTLY:

from varname import nameof

foo = dict()

fooname = nameof(foo)
# fooname == 'foo'

Note that this is working in this case as you expected:

n_jobs = <original_value>
d = n_jobs

nameof(d) # will return d, instead of n_jobs
# nameof only works directly with the variable

I am the author of this package. Please let me know if you have any questions or you can submit issues on Github.

Ruby Hash to array of values

hash  = { :a => ["a", "b", "c"], :b => ["b", "c"] }
hash.values #=> [["a","b","c"],["b","c"]]

Convert blob URL to normal URL

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

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

How to open local file on Jupyter?

simple way is to move your files to be read under the same folder of your python file, then you just need to use the name of the file, without calling another path.

jquery live hover

This code works:

    $(".ui-button-text").live(
        'hover',
        function (ev) {
            if (ev.type == 'mouseover') {
                $(this).addClass("ui-state-hover");
            }

            if (ev.type == 'mouseout') {
                $(this).removeClass("ui-state-hover");
            }
        });

Stack Memory vs Heap Memory

Stack memory is specifically the range of memory that is accessible via the Stack register of the CPU. The Stack was used as a way to implement the "Jump-Subroutine"-"Return" code pattern in assembly language, and also as a means to implement hardware-level interrupt handling. For instance, during an interrupt, the Stack was used to store various CPU registers, including Status (which indicates the results of an operation) and Program Counter (where was the CPU in the program when the interrupt occurred).

Stack memory is very much the consequence of usual CPU design. The speed of its allocation/deallocation is fast because it is strictly a last-in/first-out design. It is a simple matter of a move operation and a decrement/increment operation on the Stack register.

Heap memory was simply the memory that was left over after the program was loaded and the Stack memory was allocated. It may (or may not) include global variable space (it's a matter of convention).

Modern pre-emptive multitasking OS's with virtual memory and memory-mapped devices make the actual situation more complicated, but that's Stack vs Heap in a nutshell.

jQuery: If this HREF contains

Try this:

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

NULL or BLANK fields (ORACLE)

You can not count nulls (at least not in Oracle). Instead try this

SELECT count(1) FROM TABLE WHERE COL_NAME IS NULL

Generate a Hash from string in Javascript

This is a refined and better performing variant:

String.prototype.hashCode = function() {
    var hash = 0, i = 0, len = this.length;
    while ( i < len ) {
        hash  = ((hash << 5) - hash + this.charCodeAt(i++)) << 0;
    }
    return hash;
};

This matches Java's implementation of the standard object.hashCode()

Here is also one that returns only positive hashcodes:

String.prototype.hashcode = function() {
    return (this.hashCode() + 2147483647) + 1;
};

And here is a matching one for Java that only returns positive hashcodes:

public static long hashcode(Object obj) {
    return ((long) obj.hashCode()) + Integer.MAX_VALUE + 1l;
}

Enjoy!

Without prototype:

function hashCode(str) {
    var hash = 0, i = 0, len = str.length;
    while ( i < len ) {
        hash  = ((hash << 5) - hash + str.charCodeAt(i++)) << 0;
    }
    return hash;
}

Better way to check variable for null or empty string?

// Function for basic field validation (present and neither empty nor only white space
function IsNullOrEmptyString($str){
    return (!isset($str) || trim($str) === '');
}

PHP pass variable to include

Do this:

$checksum = "my value"; 
header("Location: recordupdated.php?checksum=$checksum");

Using wire or reg with input or output in Verilog

seeing it in digital circuit domain

  1. A Wire will create a wire output which can only be assigned any input by using assign statement as assign statement creates a port/pin connection and wire can be joined to the port/pin
  2. A reg will create a register(D FLIP FLOP ) which gets or recieve inputs on basis of sensitivity list either it can be clock (rising or falling ) or combinational edge .

so it completely depends on your use whether you need to create a register and tick it according to sensitivity list or you want to create a port/pin assignment

What is the difference between a web API and a web service?

In the context of ASP.Net a Web API is a Controller whose base class is ApiController and does not use Views. A Web Service is a class derived from WebService and has automatic WSDL generation. By default it is a SOAP api, but you can also use JSON by adding a ScriptServiceAttribute.

CMD: Export all the screen content to a text file

From command prompt Run as Administrator. Example below is to print a list of Services running on your PC run the command below:

net start > c:\netstart.txt

You should see a copy of the text file you just exported with a listing all the PC services running at the root of your C:\ drive.

How can I read a text file from the SD card in Android?

BufferedReader br = null;
try {
        String fpath = Environment.getExternalStorageDirectory() + <your file name>;
        try {
            br = new BufferedReader(new FileReader(fpath));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        String line = "";
        while ((line = br.readLine()) != null) {
         //Do something here 
        }

How to convert a column of DataTable to a List

1.Very Simple Code to iterate datatable and get columns in list.

2.code ==>>>

 foreach (DataColumn dataColumn in dataTable.Columns)
 {
    var list = dataTable.Rows.OfType<DataRow>()
     .Select(dataRow => dataRow.Field<string> 
       (dataColumn.ToString())).ToList();
 }

Sqlite or MySql? How to decide?

Their feature sets are not at all the same. Sqlite is an embedded database which has no network capabilities (unless you add them). So you can't use it on a network.

If you need

  • Network access - for example accessing from another machine;
  • Any real degree of concurrency - for example, if you think you are likely to want to run several queries at once, or run a workload that has lots of selects and a few updates, and want them to go smoothly etc.
  • a lot of memory usage, for example, to buffer parts of your 1Tb database in your 32G of memory.

You need to use mysql or some other server-based RDBMS.

Note that MySQL is not the only choice and there are plenty of others which might be better for new applications (for example pgSQL).

Sqlite is a very, very nice piece of software, but it has never made claims to do any of these things that RDBMS servers do. It's a small library which runs SQL on local files (using locking to ensure that multiple processes don't screw the file up). It's really well tested and I like it a lot.

Also, if you aren't able to choose this correctly by yourself, you probably need to hire someone on your team who can.

How do I convert NSInteger to NSString datatype?

The answer is given but think that for some situation this will be also interesting way to get string from NSInteger

NSInteger value = 12;
NSString * string = [NSString stringWithFormat:@"%0.0f", (float)value];

Get all validation errors from Angular 2 FormGroup

Or you can just use this library to get all errors, even from deep and dynamic forms.

npm i @naologic/forms

If you want to use the static function on your own forms

import {NaoFormStatic} from '@naologic/forms';
...
const errorsFlat = NaoFormStatic.getAllErrorsFlat(fg); 
console.log(errorsFlat);

If you want to use NaoFromGroup you can import and use it

import {NaoFormGroup, NaoFormControl, NaoValidators} from '@naologic/forms';
...
    this.naoFormGroup = new NaoFormGroup({
      firstName: new NaoFormControl('John'),
      lastName: new NaoFormControl('Doe'),
      ssn: new NaoFormControl('000 00 0000', NaoValidators.isSSN()),
    });

   const getFormErrors = this.naoFormGroup.getAllErrors();
   console.log(getFormErrors);
   // --> {first: {ok: false, isSSN: false, actualValue: "000 00 0000"}}

Read the full documentation

Coerce multiple columns to factors at once

Here is an option using dplyr. The %<>% operator from magrittr update the lhs object with the resulting value.

library(magrittr)
library(dplyr)
cols <- c("A", "C", "D", "H")

data %<>%
       mutate_each_(funs(factor(.)),cols)
str(data)
#'data.frame':  4 obs. of  10 variables:
# $ A: Factor w/ 4 levels "23","24","26",..: 1 2 3 4
# $ B: int  15 13 39 16
# $ C: Factor w/ 4 levels "3","5","18","37": 2 1 3 4
# $ D: Factor w/ 4 levels "2","6","28","38": 3 1 4 2
# $ E: int  14 4 22 20
# $ F: int  7 19 36 27
# $ G: int  35 40 21 10
# $ H: Factor w/ 4 levels "11","29","32",..: 1 4 3 2
# $ I: int  17 1 9 25
# $ J: int  12 30 8 33

Or if we are using data.table, either use a for loop with set

setDT(data)
for(j in cols){
  set(data, i=NULL, j=j, value=factor(data[[j]]))
}

Or we can specify the 'cols' in .SDcols and assign (:=) the rhs to 'cols'

setDT(data)[, (cols):= lapply(.SD, factor), .SDcols=cols]

MySQL VARCHAR size?

Actually, it will takes 101 bytes.

MySQL Reference

How can I preview a merge in git?

Most answers here either require a clean working directory and multiple interactive steps (bad for scripting), or don't work for all cases, e.g. past merges which already bring some of the outstanding changes into your target branch, or cherry-picks doing the same.

To truly see what would change in the master branch if you merged develop into it, right now:

git merge-tree $(git merge-base master develop) master develop

As it's a plumbing command, it does not guess what you mean, you have to be explicit. It also doesn't colorize the output or use your pager, so the full command would be:

git merge-tree $(git merge-base master develop) master develop | colordiff | less -R

https://git.seveas.net/previewing-a-merge-result.html

(thanks to David Normington for the link)

P.S.:

If you would get merge conflicts, they will show up with the usual conflict markers in the output, e.g.:

$ git merge-tree $(git merge-base a b ) a b 
added in both
  our    100644 78981922613b2afb6025042ff6bd878ac1994e85 a
  their  100644 61780798228d17af2d34fce4cfbdf35556832472 a
@@ -1 +1,5 @@
+<<<<<<< .our
 a
+=======
+b
+>>>>>>> .their

User @dreftymac makes a good point: this makes it unsuitable for scripting, because you can't easily catch that from the status code. The conflict markers can be quite different depending on circumstance (deleted vs modified, etc), which makes it hard to grep, too. Beware.

c++ boost split string

The problem is somewhere else in your code, because this works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;    
for (size_t i = 0; i < strs.size(); i++)
    cout << strs[i] << endl;

and testing your approach, which uses a vector iterator also works:

string line("test\ttest2\ttest3");
vector<string> strs;
boost::split(strs,line,boost::is_any_of("\t"));

cout << "* size of the vector: " << strs.size() << endl;
for (vector<string>::iterator it = strs.begin(); it != strs.end(); ++it)
{
    cout << *it << endl;
}

Again, your problem is somewhere else. Maybe what you think is a \t character on the string, isn't. I would fill the code with debugs, starting by monitoring the insertions on the vector to make sure everything is being inserted the way its supposed to be.

Output:

* size of the vector: 3
test
test2
test3

C# Creating an array of arrays

The problem is that you are attempting to define the elements in lists to multiple lists (not multiple ints as is defined). You should be defining lists like this.

int[,] list = new int[4,4] {
 {1,2,3,4},
 {5,6,7,8},
 {1,3,2,1},
 {5,4,3,2}};

You could also do

int[] list1 = new int[4] { 1, 2, 3, 4};
int[] list2 = new int[4] { 5, 6, 7, 8};
int[] list3 = new int[4] { 1, 3, 2, 1 };
int[] list4 = new int[4] { 5, 4, 3, 2 };

int[,] lists = new int[4,4] {
 {list1[0],list1[1],list1[2],list1[3]},
 {list2[0],list2[1],list2[2],list2[3]},
 etc...};

Calling a class function inside of __init__

How about:

class MyClass(object):
    def __init__(self, filename):
        self.filename = filename 
        self.stats = parse_file(filename)

def parse_file(filename):
    #do some parsing
    return results_from_parse

By the way, if you have variables named stat1, stat2, etc., the situation is begging for a tuple: stats = (...).

So let parse_file return a tuple, and store the tuple in self.stats.

Then, for example, you can access what used to be called stat3 with self.stats[2].

Best tool for inspecting PDF files?

I use iText RUPS(Reading and Updating PDF Syntax) in Linux. Since it's written in Java, it works on Windows, too. You can browse all the objects in PDF file in a tree structure. It can also decode Flate encoded streams on-the-fly to make inspecting easier.

Here is a screenshot:

iText RUPS screenshot

How to increment a number by 2 in a PHP For Loop

You should use other variable:

 $m=0; 
 for($n=1; $n<=8; $n++): 
  $n = $n + $m;
  $m++;
  echo '<p>'. $n .'</p>';
 endfor;

Java HashMap performance optimization / alternative

As pointed out, your hashcode implementation has too many collisions, and fixing it should result in decent performance. Moreover, caching hashCodes and implementing equals efficiently will help.

If you need to optimize even further:

By your description, there are only (52 * 51 / 2) * (52 * 51 * 50 / 6) = 29304600 different keys (of which 26000000, i.e. about 90%, will be present). Therefore, you can design a hash function without any collisions, and use a simple array rather than a hashmap to hold your data, reducing memory consumption and increasing lookup speed:

T[] array = new T[Key.maxHashCode];

void put(Key k, T value) {
    array[k.hashCode()] = value;

T get(Key k) {
    return array[k.hashCode()];
}

(Generally, it is impossible to design an efficient, collision-free hash function that clusters well, which is why a HashMap will tolerate collisions, which incurs some overhead)

Assuming a and b are sorted, you might use the following hash function:

public int hashCode() {
    assert a[0] < a[1]; 
    int ahash = a[1] * a[1] / 2 
              + a[0];

    assert b[0] < b[1] && b[1] < b[2];

    int bhash = b[2] * b[2] * b[2] / 6
              + b[1] * b[1] / 2
              + b[0];
    return bhash * 52 * 52 / 2 + ahash;
}

static final int maxHashCode = 52 * 52 / 2 * 52 * 52 * 52 / 6;  

I think this is collision-free. Proving this is left as an exercise for the mathematically inclined reader.

Create folder with batch but only if it doesn't already exist

if exist C:\VTS\NUL echo "Folder already exists"

if not exist C:\VTS\NUL echo "Folder does not exist"

See also https://support.microsoft.com/en-us/kb/65994

(Update March 7, 2018; Microsoft article is down, archive on https://web.archive.org/web/20150609092521/https://support.microsoft.com/en-us/kb/65994 )

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

The sample DataAnnotations model binder will fill model state with validation errors taken from the DataAnnotations attributes on your model.

How do I navigate to a parent route from a child route?

To navigate to the parent component regardless of the number of parameters in the current route or the parent route: Angular 6 update 1/21/19

   let routerLink = this._aRoute.parent.snapshot.pathFromRoot
        .map((s) => s.url)
        .reduce((a, e) => {
            //Do NOT add last path!
            if (a.length + e.length !== this._aRoute.parent.snapshot.pathFromRoot.length) {
                return a.concat(e);
            }
            return a;
        })
        .map((s) => s.path);
    this._router.navigate(routerLink);

This has the added bonus of being an absolute route you can use with the singleton Router.

(Angular 4+ for sure, probably Angular 2 too.)

Collection was modified; enumeration operation may not execute in ArrayList

I agree with several of the points I've read in this post and I've incorporated them into my solution to solve the exact same issue as the original posting.

That said, the comments I appreciated are:

  • "unless you are using .NET 1.0 or 1.1, use List<T> instead of ArrayList. "

  • "Also, add the item(s) to be deleted to a new list. Then go through and delete those items." .. in my case I just created a new List and the populated it with the valid data values.

e.g.

private List<string> managedLocationIDList = new List<string>();
string managedLocationIDs = ";1321;1235;;" // user input, should be semicolon seperated list of values

managedLocationIDList.AddRange(managedLocationIDs.Split(new char[] { ';' }));
List<string> checkLocationIDs = new List<string>();

// Remove any duplicate ID's and cleanup the string holding the list if ID's
Functions helper = new Functions();
checkLocationIDs = helper.ParseList(managedLocationIDList);

...
public List<string> ParseList(List<string> checkList)
{
    List<string> verifiedList = new List<string>();

    foreach (string listItem in checkList)
    if (!verifiedList.Contains(listItem.Trim()) && listItem != string.Empty)
        verifiedList.Add(listItem.Trim());

    verifiedList.Sort();
    return verifiedList;
}        

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

According to HTML living standard specification, the load event is

Fired at the Window when the document has finished loading; fired at an element containing a resource (e.g. img, embed) when its resource has finished loading

I.e. load event is not fired on document object.

Credit: Why does document.addEventListener(‘load’, handler) not work?

Is it possible to preview stash contents in git?

I'm a fan of gitk's graphical UI to visualize git repos. You can view the last item stashed with:

gitk stash

You can also use view any of your stashed changes (as listed by git stash list). For example:

gitk stash@{2}

In the below screenshot, you can see the stash as a commit in the upper-left, when and where it came from in commit history, the list of files modified on the bottom right, and the line-by-line diff in the lower-left. All while the stash is still tucked away.

gitk viewing a stash

How can I create download link in HTML?

i know i am late but this is what i got after 1 hour of search

 <?php 
      $file = 'file.pdf';

    if (! file) {
        die('file not found'); //Or do something 
    } else {
       if(isset($_GET['file'])){  
        // Set headers
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
        header("Content-Disposition: attachment; filename=$file");
        header("Content-Type: application/zip");
        header("Content-Transfer-Encoding: binary");
        // Read the file from disk
        readfile($file); }
    }

    ?>

and for downloadable link i did this

<a href="index.php?file=file.pdf">Download PDF</a>

How to download Visual Studio 2017 Community Edition for offline installation?

I have used the exact steps from here and it worked flawlessly : https://docs.microsoft.com/en-us/visualstudio/install/install-vs-inconsistent-quality-network

In 3 simple steps:

Step 1 : Download the respective Visual Studio 2017 version from the download page (https://www.visualstudio.com/downloads/)

Step 2: Open your command prompt as Administarator, point to where your Visual studio download exe is and execute the following command (this command is specifically for Web & Desktop development) :

vs_community.exe --layout c:\vs2017layout --add Microsoft.VisualStudio.Workload.ManagedDesktop --add Microsoft.VisualStudio.Workload.NetWeb --add Component.GitHub.VisualStudio --includeOptional --lang en-US

Step 3 : Traverse to the path c:\vs2017layout in your command prompt and then run the following command (this command is specifically for Web & Desktop development)

vs_community.exe --add Microsoft.VisualStudio.Workload.ManagedDesktop --add Microsoft.VisualStudio.Workload.NetWeb --add Component.GitHub.VisualStudio --includeOptional

What does if __name__ == "__main__": do?

Create a file, a.py:

print(__name__) # It will print out __main__

__name__ is always equal to __main__ whenever that file is run directly showing that this is the main file.

Create another file, b.py, in the same directory:

import a  # Prints a

Run it. It will print a, i.e., the name of the file which is imported.

So, to show two different behavior of the same file, this is a commonly used trick:

# Code to be run when imported into another python file

if __name__ == '__main__':
    # Code to be run only when run directly

Setting Android Theme background color

Open res -> values -> styles.xml and to your <style> add this line replacing with your image path <item name="android:windowBackground">@drawable/background</item>. Example:

<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
        <item name="android:windowBackground">@drawable/background</item>
    </style>

</resources>

There is a <item name ="android:colorBackground">@color/black</item> also, that will affect not only your main window background but all the component in your app. Read about customize theme here.

If you want version specific styles:

If a new version of Android adds theme attributes that you want to use, you can add them to your theme while still being compatible with old versions. All you need is another styles.xml file saved in a values directory that includes the resource version qualifier. For example:

res/values/styles.xml        # themes for all versions
res/values-v21/styles.xml    # themes for API level 21+ only

Because the styles in the values/styles.xml file are available for all versions, your themes in values-v21/styles.xml can inherit them. As such, you can avoid duplicating styles by beginning with a "base" theme and then extending it in your version-specific styles.

Read more here(doc in theme).

How to select rows in a DataFrame between two values, in Python Pandas?

If one has to call pd.Series.between(l,r) repeatedly (for different bounds l and r), a lot of work is repeated unnecessarily. In this case, it's beneficial to sort the frame/series once and then use pd.Series.searchsorted(). I measured a speedup of up to 25x, see below.

def between_indices(x, lower, upper, inclusive=True):
    """
    Returns smallest and largest index i for which holds 
    lower <= x[i] <= upper, under the assumption that x is sorted.
    """
    i = x.searchsorted(lower, side="left" if inclusive else "right")
    j = x.searchsorted(upper, side="right" if inclusive else "left")
    return i, j

# Sort x once before repeated calls of between()
x = x.sort_values().reset_index(drop=True)
# x = x.sort_values(ignore_index=True) # for pandas>=1.0
ret1 = between_indices(x, lower=0.1, upper=0.9)
ret2 = between_indices(x, lower=0.2, upper=0.8)
ret3 = ...

Benchmark

Measure repeated evaluations (n_reps=100) of pd.Series.between() as well as the method based on pd.Series.searchsorted(), for different arguments lower and upper. On my MacBook Pro 2015 with Python v3.8.0 and Pandas v1.0.3, the below code results in the following outpu

# pd.Series.searchsorted()
# 5.87 ms ± 321 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
# pd.Series.between(lower, upper)
# 155 ms ± 6.08 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
# Logical expressions: (x>=lower) & (x<=upper)
# 153 ms ± 3.52 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)
import numpy as np
import pandas as pd

def between_indices(x, lower, upper, inclusive=True):
    # Assumption: x is sorted.
    i = x.searchsorted(lower, side="left" if inclusive else "right")
    j = x.searchsorted(upper, side="right" if inclusive else "left")
    return i, j

def between_fast(x, lower, upper, inclusive=True):
    """
    Equivalent to pd.Series.between() under the assumption that x is sorted.
    """
    i, j = between_indices(x, lower, upper, inclusive)
    if True:
        return x.iloc[i:j]
    else:
        # Mask creation is slow.
        mask = np.zeros_like(x, dtype=bool)
        mask[i:j] = True
        mask = pd.Series(mask, index=x.index)
        return x[mask]

def between(x, lower, upper, inclusive=True):
    mask = x.between(lower, upper, inclusive=inclusive)
    return x[mask]

def between_expr(x, lower, upper, inclusive=True):
    if inclusive:
        mask = (x>=lower) & (x<=upper)
    else:
        mask = (x>lower) & (x<upper)
    return x[mask]

def benchmark(func, x, lowers, uppers):
    for l,u in zip(lowers, uppers):
        func(x,lower=l,upper=u)

n_samples = 1000
n_reps = 100
x = pd.Series(np.random.randn(n_samples))
# Sort the Series.
# For pandas>=1.0:
# x = x.sort_values(ignore_index=True)
x = x.sort_values().reset_index(drop=True)

# Assert equivalence of different methods.
assert(between_fast(x, 0, 1, True ).equals(between(x, 0, 1, True)))
assert(between_expr(x, 0, 1, True ).equals(between(x, 0, 1, True)))
assert(between_fast(x, 0, 1, False).equals(between(x, 0, 1, False)))
assert(between_expr(x, 0, 1, False).equals(between(x, 0, 1, False)))

# Benchmark repeated evaluations of between().
uppers = np.linspace(0, 3, n_reps)
lowers = -uppers
%timeit benchmark(between_fast, x, lowers, uppers)
%timeit benchmark(between, x, lowers, uppers)
%timeit benchmark(between_expr, x, lowers, uppers)

XML Schema Validation : Cannot find the declaration of element

cvc-elt.1: Cannot find the declaration of element 'Root'. [7]

Your schemaLocation attribute on the root element should be xsi:schemaLocation, and you need to fix it to use the right namespace.

You should probably change the targetNamespace of the schema and the xmlns of the document to http://myNameSpace.com (since namespaces are supposed to be valid URIs, which Test.Namespace isn't, though urn:Test.Namespace would be ok). Once you do that it should find the schema. The point is that all three of the schema's target namespace, the document's namespace, and the namespace for which you're giving the schema location must be the same.

(though it still won't validate as your <element2> contains an <element3> in the document where the schema expects item)

Angular JS update input field after change

You can add ng-change directive to input fields. Have a look at the docs example.

Reference alias (calculated in SELECT) in WHERE clause

As a workaround to force the evaluation of the SELECT clause before the WHERE clause, you could put the former in a sub-query while the latter remains in the main query:

SELECT * FROM (
  SELECT (InvoiceTotal - PaymentTotal - CreditTotal) AS BalanceDue
  FROM Invoices) AS temp
WHERE BalanceDue > 0
  

Unable to add window -- token null is not valid; is your activity running?

If you're using getApplicationContext() as Context in Activity for the dialog like this

Dialog dialog = new Dialog(getApplicationContext());

then use YourActivityName.this

Dialog dialog = new Dialog(YourActivityName.this);

Convert DataTable to CSV stream

BFree's answer worked for me. I needed to post the stream right to the browser. Which I'd imagine is a common alternative. I added the following to BFree's Main() code to do this:

//StreamReader reader = new StreamReader(stream);
//Console.WriteLine(reader.ReadToEnd());

string fileName = "fileName.csv";
HttpContext.Current.Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
HttpContext.Current.Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", fileName));
stream.Position = 0;
stream.WriteTo(HttpContext.Current.Response.OutputStream);

Rotate camera in Three.js with mouse

OrbitControls and TrackballControls seems to be good for this purpose.

controls = new THREE.TrackballControls( camera );
controls.rotateSpeed = 1.0;
controls.zoomSpeed = 1.2;
controls.panSpeed = 0.8;
controls.noZoom = false;
controls.noPan = false;
controls.staticMoving = true;
controls.dynamicDampingFactor = 0.3;

update in render

controls.update();

How do I pass parameters to a jar file at the time of execution?

To pass arguments to the jar:

java -jar myjar.jar one two

You can access them in the main() method of "Main-Class" (mentioned in the manifest.mf file of a JAR).

String one = args[0];  
String two = args[1];  

Can I get the name of the current controller in the view?

controller_name holds the name of the controller used to serve the current view.

NuGet Package Restore Not Working

Automatic Package Restore will fail for any of the following reasons:

  1. You did not remove the NuGet.exe and NuGet.targets files from the solution's .nuget folder (which can be found in your solution root folder)
  2. You did not enable automatic package restore from the Tools >> Options >> Nuget Package Manager >> General settings.
  3. You forgot to manually remove references in all your projects to the Nuget.targets file
  4. You need to restart Visual Studio (make sure the process is killed from your task manager before starting up again).

The following article outlines in more detail how to go about points 1-3: https://docs.nuget.org/consume/package-restore/migrating-to-automatic-package-restore

Can HTML checkboxes be set to readonly?

@(Model.IsEnabled) Use this condition for dynamically check and uncheck and set readonly if check box is already checked.

 <input id="abc" name="abc"  type="checkbox" @(Model.IsEnabled ? "checked=checked onclick=this.checked=!this.checked;" : string.Empty) >

How can I convert my Java program to an .exe file?

Launch4j

Launch4j is a cross-platform tool for wrapping Java applications distributed as jars in lightweight Windows native executables. The executable can be configured to search for a certain JRE version or use a bundled one, and it's possible to set runtime options, like the initial/max heap size. The wrapper also provides better user experience through an application icon, a native pre-JRE splash screen, a custom process name, and a Java download page in case the appropriate JRE cannot be found.

– Launch4j's website

I cannot start SQL Server browser

right click on SQL Server browser and properties, then Connection tab and chose open session with system account and not this account. then apply and chose automatic and finally run the server.

Android Gradle 5.0 Update:Cause: org.jetbrains.plugins.gradle.tooling.util

I upgraded my IntelliJ Version from 2018.1 to 2018.3.6. It works !

jQuery function to get all unique elements from an array?

    // for numbers
    a = [1,3,2,4,5,6,7,8, 1,1,4,5,6]
    $.unique(a)
    [7, 6, 1, 8, 3, 2, 5, 4]

    // for string
    a = ["a", "a", "b"]
    $.unique(a)
    ["b", "a"]

And for dom elements there is no example is needed here I guess because you already know that!

Here is the jsfiddle link of live example: http://jsfiddle.net/3BtMc/4/

Need to get a string after a "word" in a string in c#

add this code to your project

  public static class Extension {
        public static string TextAfter(this string value ,string search) {
            return  value.Substring(value.IndexOf(search) + search.Length);
        }
  }

then use

"code : string text ".TextAfter(":")

Package name does not correspond to the file path - IntelliJ

I've seen this error a few times too, and I've always been able to solve it by correctly identifying the project's module settings. In IntelliJ, right-click on the top level project -> "Open Module Settings". This should open up a window with the entire project structure and content identified as "Source Folders", "Test Source Folders", etc. Make sure these are correctly set. For the "Source Folders", ensure that the folder is your src/ or src/java (or whatever your source language is), as the case may be

What is the use of join() in Python threading?

There are a few reasons for the main thread (or any other thread) to join other threads

  1. A thread may have created or holding (locking) some resources. The join-calling thread may be able to clear the resources on its behalf

  2. join() is a natural blocking call for the join-calling thread to continue after the called thread has terminated.

If a python program does not join other threads, the python interpreter will still join non-daemon threads on its behalf.

mongoError: Topology was destroyed

In my case, this error was caused by an identical server instance already running background.

The weird thing is when I started my server without notice there's one running already, the console didn't show anything like 'something is using port xxx'. I could even upload something to the server. So, it took me quite long to locate this problem.

What's more, after closing all the applications I can imagine, I still could not find the process which is using this port in my Mac's activity monitor. I have to use lsof to trace. The culprit was not surprising - it's a node process. However, with the PID shown in the terminal, I found the port number in the monitor is different from the one used by my server.

All in all, kill all the node processes may solve this problem directly.

Difference between Pig and Hive? Why have both?

From the link: http://www.aptibook.com/discuss-technical?uid=tech-hive4&question=What-kind-of-datawarehouse-application-is-suitable-for-Hive?

Hive is not a full database. The design constraints and limitations of Hadoop and HDFS impose limits on what Hive can do.

Hive is most suited for data warehouse applications, where

1) Relatively static data is analyzed,

2) Fast response times are not required, and

3) When the data is not changing rapidly.

Hive doesn’t provide crucial features required for OLTP, Online Transaction Processing. It’s closer to being an OLAP tool, Online Analytic Processing. So, Hive is best suited for data warehouse applications, where a large data set is maintained and mined for insights, reports, etc.

Short IF - ELSE statement

As others have indicated, something of the form

x ? y : z

is an expression, not a (complete) statement. It is an rvalue which needs to get used someplace - like on the right side of an assignment, or a parameter to a function etc.

Perhaps you could look at this: http://download.oracle.com/javase/tutorial/java/nutsandbolts/expressions.html

How to center a table of the screen (vertically and horizontally)

For horizontal alignment (No CSS)

Just insert an align attribute inside the table tag

<table align="center"></table

How to install plugins to Sublime Text 2 editor?

According to John Day's answer

You should have a Data/Packages folder in your Sublime Text 2 install directory. All you need to do is download the plugin and put the plugin folder in the Packages folder.

In case if you are searching for Data/Packages folder you can find it here

Windows: %APPDATA%\Sublime Text 2

OS X: ~/Library/Application Support/Sublime Text 2

Linux: ~/.Sublime Text 2

Portable Installation: Sublime Text 2/Data

How to express a NOT IN query with ActiveRecord/Rails?

Using Arel:

topics=Topic.arel_table
Topic.where(topics[:forum_id].not_in(@forum_ids))

or, if preferred:

topics=Topic.arel_table
Topic.where(topics[:forum_id].in(@forum_ids).not)

and since rails 4 on:

topics=Topic.arel_table
Topic.where.not(topics[:forum_id].in(@forum_ids))

Please notice that eventually you do not want the forum_ids to be the ids list, but rather a subquery, if so then you should do something like this before getting the topics:

@forum_ids = Forum.where(/*whatever conditions are desirable*/).select(:id)

in this way you get everything in a single query: something like:

select * from topic 
where forum_id in (select id 
                   from forum 
                   where /*whatever conditions are desirable*/)

Also notice that eventually you do not want to do this, but rather a join - what might be more efficient.

How to increase icons size on Android Home Screen?

Unless you write your own Homescreen launcher or use an existing one from Goolge Play, there's "no way" to resize icons.

Well, "no way" does not mean its impossible:

  • As said, you can write your own launcher as discussed in Stackoverflow.
  • You can resize elements on the home screen, but these elements are AppWidgets. Since API level 14 they can be resized and user can - in limits - change the size. But that are Widgets not Shortcuts for launching icons.

What is the reason for having '//' in Python?

In Python 3, they made the / operator do a floating-point division, and added the // operator to do integer division (i.e., quotient without remainder); whereas in Python 2, the / operator was simply integer division, unless one of the operands was already a floating point number.

In Python 2.X:

>>> 10/3
3
>>> # To get a floating point number from integer division:
>>> 10.0/3
3.3333333333333335
>>> float(10)/3
3.3333333333333335

In Python 3:

>>> 10/3
3.3333333333333335
>>> 10//3
3

For further reference, see PEP238.

When saving, how can you check if a field has changed?

as an extension of SmileyChris' answer, you can add a datetime field to the model for last_updated, and set some sort of limit for the max age you'll let it get to before checking for a change

How can strip whitespaces in PHP's variable?

You can use trim function from php to trim both sides (left and right)

 trim($yourinputdata," ");

Or

trim($yourinputdata);

You can also use

ltrim() - Removes whitespace or other predefined characters from the left side of a string
rtrim() - Removes whitespace or other predefined characters from the right side of a string

System: PHP 4,5,7
Docs: http://php.net/manual/en/function.trim.php

How to position a table at the center of div horizontally & vertically

Centering is one of the biggest issues in CSS. However, some tricks exist:

To center your table horizontally, you can set left and right margin to auto:

<style>
  #test {
    width:100%;
    height:100%;
  }
  table {
    margin: 0 auto; /* or margin: 0 auto 0 auto */
  }
</style>

To center it vertically, the only way is to use javascript:

var tableMarginTop = Math.round( (testHeight - tableHeight) / 2 );
$('table').css('margin-top', tableMarginTop) # with jQuery
$$('table')[0].setStyle('margin-top', tableMarginTop) # with Mootools

No vertical-align:middle is possible as a table is a block and not an inline element.

Edit

Here is a website that sums up CSS centering solutions: http://howtocenterincss.com/

Overcoming "Display forbidden by X-Frame-Options"

Try this thing, i dont think anyone suggested this in the Topic, this will resolve like 70% of your issue, for some other pages, you have to scrap, i have the full solution but not for public,

ADD below to your iframe

sandbox="allow-same-origin allow-scripts allow-popups allow-forms"

D3 Appending Text to a SVG Rectangle

Have you tried the SVG text element?

.append("text").text(function(d, i) { return d[whichevernode];})

rect element doesn't permit text element inside of it. It only allows descriptive elements (<desc>, <metadata>, <title>) and animation elements (<animate>, <animatecolor>, <animatemotion>, <animatetransform>, <mpath>, <set>)

Append the text element as a sibling and work on positioning.

UPDATE

Using g grouping, how about something like this? fiddle

You can certainly move the logic to a CSS class you can append to, remove from the group (this.parentNode)

What's the best visual merge tool for Git?

Beyond Compare 3, my favorite, has a merge functionality in the Pro edition. The good thing with its merge is that it let you see all 4 views: base, left, right, and merged result. It's somewhat less visual than P4V but way more than WinDiff. It integrates with many source control and works on Windows/Linux. It has many features like advanced rules, editions, manual alignment...

The Perforce Visual Client (P4V) is a free tool that provides one of the most explicit interface for merging (see some screenshots). Works on all major platforms. My main disappointement with that tool is its kind of "read-only" interface. You cannot edit manually the files and you cannot manually align.

PS: P4Merge is included in P4V. Perforce tries to make it a bit hard to get their tool without their client.

SourceGear Diff/Merge may be my second free tool choice. Check that merge screens-shot and you'll see it's has the 3 views at least.


Meld is a newer free tool that I'd prefer to SourceGear Diff/Merge: Now it's also working on most platforms (Windows/Linux/Mac) with the distinct advantage of natively supporting some source control like Git. So you can have some history diff on all files much simpler. The merge view (see screenshot) has only 3 panes, just like SourceGear Diff/Merge. This makes merging somewhat harder in complex cases.

PS: If one tool one day supports 5 views merging, this would really be awesome, because if you cherry-pick commits in Git you really have not one base but two. Two base, two changes, and one resulting merge.

How to add a line to a multiline TextBox?

Just put a line break into your text.

You don't add lines as a method. Multiline just supports the use of line breaks.

How does one set up the Visual Studio Code compiler/debugger to GCC?

You need to install C compiler, C/C++ extension, configure launch.json and tasks.json to be able to debug C code.

This article would guide you how to do it: https://medium.com/@jerrygoyal/run-debug-intellisense-c-c-in-vscode-within-5-minutes-3ed956e059d6

Django -- Template tag in {% if %} block

Sorry for comment in an old post but if you want to use an else if statement this will help you

{% if title == source %}
    Do This
{% elif title == value %}
    Do This
{% else %}
    Do This
{% endif %}

For more info see Django Documentation

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

This should give you a list of all the tables in your database

SELECT Distinct TABLE_NAME FROM information_schema.TABLES

So you can use it similar to your database check.

If NOT EXISTS(SELECT Distinct TABLE_NAME FROM information_schema.TABLES Where TABLE_NAME = 'Your_Table')
BEGIN
    --CREATE TABLE Your_Table
END
GO

What is base 64 encoding used for?

When you have some binary data that you want to ship across a network, you generally don't do it by just streaming the bits and bytes over the wire in a raw format. Why? because some media are made for streaming text. You never know -- some protocols may interpret your binary data as control characters (like a modem), or your binary data could be screwed up because the underlying protocol might think that you've entered a special character combination (like how FTP translates line endings).

So to get around this, people encode the binary data into characters. Base64 is one of these types of encodings.

Why 64?
Because you can generally rely on the same 64 characters being present in many character sets, and you can be reasonably confident that your data's going to end up on the other side of the wire uncorrupted.

When to use <span> instead <p>?

A practical explanation: By default, <p> </p> will add line breaks before and after the enclosed text (so it creates a paragraph). <span> does not do this, that is why it is called inline.

How to generate .env file for laravel?

in console (cmd), go to app root path and execute:

type .env.example > .env

Changing the page title with Jquery

There's no need to use jQuery to change the title. Try:

document.title = "blarg";

See this question for more details.

To dynamically change on button click:

$(selectorForMyButton).click(function(){
    document.title = "blarg";
});

To dynamically change in loop, try:

var counter = 0;

var titleTimerId = setInterval(function(){
    document.title = document.title + '>';
    counter++;
    if(counter == 5){
        clearInterval(titleTimerId);
    }
}, 100);

To string the two together so that it dynamically changes on button click, in a loop:

var counter = 0;

$(selectorForMyButton).click(function(){
  titleTimerId = setInterval(function(){
    document.title = document.title + '>';
    counter++;
    if(counter == 5){
        clearInterval(titleTimerId);
    }
  }, 100);
});

Skip over a value in the range function in python

In addition to the Python 2 approach here are the equivalents for Python 3:

# Create a range that does not contain 50
for i in [x for x in range(100) if x != 50]:
    print(i)

# Create 2 ranges [0,49] and [51, 100]
from itertools import chain
concatenated = chain(range(50), range(51, 100))
for i in concatenated:
    print(i)

# Create a iterator and skip 50
xr = iter(range(100))
for i in xr:
    print(i)
    if i == 49:
        next(xr)

# Simply continue in the loop if the number is 50
for i in range(100):
    if i == 50:
        continue
    print(i)

Ranges are lists in Python 2 and iterators in Python 3.

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

For AAPT2 error: check logs for details or error: failed linking file resources. errors:

Check your .xml files that contains android:background="" and remove this empty attribute can solve your problem.

Android scale animation on view

try this code to create Scale animation without using xml

ScaleAnimation animation = new ScaleAnimation(fromXscale, toXscale, fromYscale, toYscale, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);

Changing specific text's color using NSMutableAttributedString in Swift

You need to change textview parameters, not parameters of attributed string

textView.linkTextAttributes = [
        NSAttributedString.Key.foregroundColor: UIColor.red,
        NSAttributedString.Key.underlineColor: UIColor.red,
        NSAttributedString.Key.underlineStyle: NSUnderlineStyle.single.rawValue
    ]

Way to insert text having ' (apostrophe) into a SQL table

INSERT INTO exampleTbl VALUES('he doesn''t work for me')

If you're adding a record through ASP.NET, you can use the SqlParameter object to pass in values so you don't have to worry about the apostrophe's that users enter in.

CSS - Overflow: Scroll; - Always show vertical scroll bar?

Please note on iPad Safari, NoviceCoding's solution won't work if you have -webkit-overflow-scrolling: touch; somewhere in your CSS. The solution is either removing all the occurrences of -webkit-overflow-scrolling: touch; or putting -webkit-overflow-scrolling: auto; with NoviceCoding's solution.

VBA error 1004 - select method of range class failed

You can't select a range without having first selected the sheet it is in. Try to select the sheet first and see if you still get the problem:

sourceSheetSum.Select
sourceSheetSum.Range("C3").Select

When to use If-else if-else over switch statements and vice versa

I personally prefer to see switch statements over too many nested if-elses because they can be much easier to read. Switches are also better in readability terms for showing a state.

See also the comment in this post regarding pacman ifs.

How to change the version of the 'default gradle wrapper' in IntelliJ IDEA?

In build.gradle add wrapper { gradleVersion = '6.0' }

Pretty-print an entire Pandas Series / DataFrame

After importing pandas, as an alternative to using the context manager, set such options for displaying entire dataframes:

pd.set_option('display.max_columns', None)  # or 1000
pd.set_option('display.max_rows', None)  # or 1000
pd.set_option('display.max_colwidth', -1)  # or 199

For full list of useful options, see:

pd.describe_option('display')

Which command in VBA can count the number of characters in a string variable?

Len(word)

Although that's not what your question title asks =)

How do I use reflection to invoke a private method?

Microsoft recently modified the reflection API rendering most of these answers obsolete. The following should work on modern platforms (including Xamarin.Forms and UWP):

obj.GetType().GetTypeInfo().GetDeclaredMethod("MethodName").Invoke(obj, yourArgsHere);

Or as an extension method:

public static object InvokeMethod<T>(this T obj, string methodName, params object[] args)
{
    var type = typeof(T);
    var method = type.GetTypeInfo().GetDeclaredMethod(methodName);
    return method.Invoke(obj, args);
}

Note:

  • If the desired method is in a superclass of obj the T generic must be explicitly set to the type of the superclass.

  • If the method is asynchronous you can use await (Task) obj.InvokeMethod(…).

"401 Unauthorized" on a directory

You need to check the folder permissions on your server and check that the account that you are using to run your application has access to that folder.

How to take input in an array + PYTHON?

raw_input is your helper here. From documentation -

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

So your code will basically look like this.

num_array = list()
num = raw_input("Enter how many elements you want:")
print 'Enter numbers in array: '
for i in range(int(num)):
    n = raw_input("num :")
    num_array.append(int(n))
print 'ARRAY: ',num_array

P.S: I have typed all this free hand. Syntax might be wrong but the methodology is correct. Also one thing to note is that, raw_input does not do any type checking, so you need to be careful...

Palindrome check in Javascript

This worked for me.

var number = 8008
number = number + "";
numberreverse = number.split("").reverse().join('');
console.log ("The number if reversed is: " +numberreverse);
if (number == numberreverse)
    console.log("Yes, this is a palindrome");
else
    console.log("Nope! It isnt a palindrome");

How to set base url for rest in spring boot?

For spring boot framework version 2.0.4.RELEASE+. Add this line to application.properties

server.servlet.context-path=/api

How to find the maximum value in an array?

Iterate over the Array. First initialize the maximum value to the first element of the array and then for each element optimize it if the element under consideration is greater.

Strip out HTML and Special Characters

to allow periods and any other character just add them like so:

change: '#[^a-zA-Z ]#' to:'#[^a-zA-Z .()!]#'

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

public void Each<T>(IEnumerable<T> items, Action<T> action)
{
    foreach (var item in items)
        action(item);
}

... and call it thusly:

Each(myList, i => Console.WriteLine(i));

UL or DIV vertical scrollbar

You need to set a height on the DIV. Otherwise it will keep expanding indefinitely.

php mysqli_connect: authentication method unknown to the client [caching_sha2_password]

I solve this by SQL command:

ALTER USER 'mysqlUsername'@'localhost' IDENTIFIED WITH mysql_native_password BY 'mysqlUsernamePassword';

which is referenced by https://dev.mysql.com/doc/refman/8.0/en/alter-user.html

if you are creating new user

 CREATE USER 'jeffrey'@'localhost' IDENTIFIED WITH mysql_native_password BY 'password';

which is referenced by https://dev.mysql.com/doc/refman/8.0/en/create-user.html

this works for me

Regular expression containing one word or another

You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:

([0-9]+)\s+((\bseconds\b)|(\bminutes\b))

Without those you were either matching a number followed by seconds OR just the word minutes

How to enable LogCat/Console in Eclipse for Android?

Go to your desired perspective. Go to 'Window->show view' menu.

If you see logcat there, click it and you are done.

Else, click on 'other' (at the bottom), chose 'Android'->logcat.

Hope that helps :-)

How to Specify Eclipse Proxy Authentication Credentials?

This sometime works, sometime no.

I have installed 1 Eclipse - works.

Installed second - doesn't work.

And I cann't figure why!

After some time may be found a solution.

Need delete all setting for proxy (included credentials). And re-insert for new.

After this for me getting work.

How to convert int to float in C?

This can give you the correct Answer

#include <stdio.h>
int main()
{
    float total=100, number=50;
    float percentage;
    percentage=(number/total)*100;
    printf("%0.2f",percentage);
    return 0;
}

How to link html pages in same or different folders?

If you'd like to link to the root directory you can use

/, or /index.html

If you'd like to link to a file in the same directory, simply put the file name

<a href="/employees.html">Employees Click Here</a>

To move back a folder, you can use

../

To link to the index page in the employees directory from the root directory, you'd do this

<a href="../employees/index.html">Employees Directory Index Page</a>

How to retrieve value from elements in array using jQuery?

Use: http://jsfiddle.net/xH79d/

var n = $("input[name^='card']").length;
var array = $("input[name^='card']");

for(i=0; i < n; i++) {

   // use .eq() within a jQuery object to navigate it by Index

   card_value = array.eq(i).attr('name'); // I'm assuming you wanted -name-
   // otherwise it'd be .eq(i).val(); (if you wanted the text value)
   alert(card_value);
}

?

How to group an array of objects by key

There is absolutely no reason to download a 3rd party library to achieve this simple problem, like the above solutions suggest.

The one line version to group a list of objects by a certain key in es6:

const groupByKey = (list, key) => list.reduce((hash, obj) => ({...hash, [obj[key]]:( hash[obj[key]] || [] ).concat(obj)}), {})

The longer version that filters out the objects without the key:

_x000D_
_x000D_
function groupByKey(array, key) {
   return array
     .reduce((hash, obj) => {
       if(obj[key] === undefined) return hash; 
       return Object.assign(hash, { [obj[key]]:( hash[obj[key]] || [] ).concat(obj)})
     }, {})
}


var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];

console.log(groupByKey(cars, 'make'))
_x000D_
_x000D_
_x000D_

NOTE: It appear the original question asks how to group cars by make, but omit the make in each group. So the short answer, without 3rd party libraries, would look like this:

_x000D_
_x000D_
const groupByKey = (list, key, {omitKey=false}) => list.reduce((hash, {[key]:value, ...rest}) => ({...hash, [value]:( hash[value] || [] ).concat(omitKey ? {...rest} : {[key]:value, ...rest})} ), {})

var cars = [{'make':'audi','model':'r8','year':'2012'},{'make':'audi','model':'rs5','year':'2013'},{'make':'ford','model':'mustang','year':'2012'},{'make':'ford','model':'fusion','year':'2015'},{'make':'kia','model':'optima','year':'2012'}];

console.log(groupByKey(cars, 'make', {omitKey:true}))
_x000D_
_x000D_
_x000D_

Multiple file-extensions searchPattern for System.IO.Directory.GetFiles

c# version of @qfactor77's answer. This is the best way without LINQ .

string[] wildcards= {"*.mp4", "*.jpg"};
ReadOnlyCollection<string> filePathCollection = FileSystem.GetFiles(dirPath, Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories, wildcards);
string[] filePath=new string[filePathCollection.Count];
filePathCollection.CopyTo(filePath,0);

now return filePath string array. In the beginning you need

using Microsoft.VisualBasic.FileIO;
using System.Collections.ObjectModel;

also you need to add reference to Microsoft.VisualBasic

Sorting rows in a data table

Did you try using the Select(filterExpression, sortOrder) method on DataTable? See here for an example. Note this method will not sort the data table in place, if that is what you are looking for, but it will return a sorted array of rows without using a data view.

How do I select child elements of any depth using XPath?

//form/descendant::input[@type='submit']

Force flushing of output to a file while bash script is still running

You can use tee to write to the file without the need for flushing.

/homedir/MyScript 2>&1 | tee some_log.log > /dev/null

jQuery Mobile Page refresh mechanism

function refreshPage()
{
    jQuery.mobile.changePage(window.location.href, {
        allowSamePageTransition: true,
        transition: 'none',
        reloadPage: true
    });
}

Taken from here http://scottwb.com/blog/2012/06/29/reload-the-same-page-without-blinking-on-jquery-mobile/ also tested on jQuery Mobile 1.2.0

Change UITextField and UITextView Cursor / Caret Color

Swift 4

In viewDidLoad() just call below code:

CODE SAMPLE

//txtVComplaint is a textView

txtVComplaint.tintColor = UIColor.white

txtVComplaint.tintColorDidChange()

Manually Triggering Form Validation using jQuery

_x000D_
_x000D_
var field = $("#field")_x000D_
field.keyup(function(ev){_x000D_
    if(field[0].value.length < 10) {_x000D_
        field[0].setCustomValidity("characters less than 10")_x000D_
        _x000D_
    }else if (field[0].value.length === 10) {_x000D_
        field[0].setCustomValidity("characters equal to 10")_x000D_
        _x000D_
    }else if (field[0].value.length > 10 && field[0].value.length < 20) {_x000D_
        field[0].setCustomValidity("characters greater than 10 and less than 20")_x000D_
        _x000D_
    }else if(field[0].validity.typeMismatch) {_x000D_
     field[0].setCustomValidity("wrong email message")_x000D_
        _x000D_
    }else {_x000D_
     field[0].setCustomValidity("") // no more errors_x000D_
        _x000D_
    }_x000D_
    field[0].reportValidity()_x000D_
    _x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<input type="email" id="field">
_x000D_
_x000D_
_x000D_

Using bootstrap with bower

assuming you have npm installed and bower installed globally

  1. navigate to your project
  2. bower init (this will generate the bower.json file in your directory)
  3. (then keep clicking yes)...
  4. to set the path where bootstrap will be installed:
    manually create a .bowerrc file next to the bower.json file and add the following to it:

    { "directory" : "public/components" }

  5. bower install bootstrap --save

Note: to install other components:

 bower search {component-name-here}

How to draw a filled triangle in android canvas?

Don't moveTo() after each lineTo()

In other words, remove every moveTo() except the first one.

Seriously, if I just copy-paste OP's code and remove the unnecessary moveTo() calls, it works.

Nothing else needs to be done.


EDIT: I know the OP already posted his "final working solution", but he didn't state why it works. The actual reason was quite surprising to me, so I felt the need to add an answer.

How can I convert ArrayList<Object> to ArrayList<String>?

You can use wildcard to do this as following

ArrayList<String> strList = (ArrayList<String>)(ArrayList<?>)(list);

If Radio Button is selected, perform validation on Checkboxes

function validateDays() {
    if (document.getElementById("option1").checked == true) {
        alert("You have selected Option 1");
    }
    else if (document.getElementById("option2").checked == true) {
        alert("You have selected Option 2");
    }
    else if (document.getElementById("option3").checked == true) {
        alert("You have selected Option 3");
    }
    else {
        // DO NOTHING
        }
    }

String Concatenation using '+' operator

It doesn't - the C# compiler does :)

So this code:

string x = "hello";
string y = "there";
string z = "chaps";
string all = x + y + z;

actually gets compiled as:

string x = "hello";
string y = "there";
string z = "chaps";
string all = string.Concat(x, y, z);

(Gah - intervening edit removed other bits accidentally.)

The benefit of the C# compiler noticing that there are multiple string concatenations here is that you don't end up creating an intermediate string of x + y which then needs to be copied again as part of the concatenation of (x + y) and z. Instead, we get it all done in one go.

EDIT: Note that the compiler can't do anything if you concatenate in a loop. For example, this code:

string x = "";
foreach (string y in strings)
{
    x += y;
}

just ends up as equivalent to:

string x = "";
foreach (string y in strings)
{
    x = string.Concat(x, y);
}

... so this does generate a lot of garbage, and it's why you should use a StringBuilder for such cases. I have an article going into more details about the two which will hopefully answer further questions.

How can I test a change made to Jenkinsfile locally?

I have a solution that works well for me. It consists of a local jenkins running in docker and a git web hook to trigger the pipeline in the local jenkins on every commit. You no longer need to push to your github or bitbucket repository to test the pipeline.

This has only been tested in a linux environment.

It is fairly simple to make this work although this instruction is a tad long. Most steps are there.

This is what you need

  • Docker installed and working. This is not part of this instruction.
  • A Jenkins running in docker locally. Explained how below.
    • The proper rights (ssh access key) for your local Jenkins docker user to pull from your local git repo. Explained how below.
    • A Jenkins pipeline project that pulls from your local git repository. Explained below.
    • A git user in your local Jenkins with minimal rights. Explained below.
  • A git project with a post-commit web hook that triggers the pipeline project. Explained below.

This is how you do it

Jenkins Docker

Create a file called Dockerfile in place of your choosing. I'm placing it in /opt/docker/jenkins/Dockerfile fill it with this:

FROM jenkins/jenkins:lts
USER root
RUN apt-get -y update && apt-get -y upgrade
# Your needed installations goes here
USER jenkins

Build the local_jenkins image

This you will need to do only once or after you have added something to the Dockerfile.

$ docker build -t local_jenkins /opt/docker/jenkins/

Start and restart local_jenkins

From time to time you want to start and restart jenkins easily. E.g. after a reboot of your machine. For this I made an alias that I put in .bash_aliases in my home folder.

$ echo "alias localjenkinsrestart='docker stop jenkins;docker rm jenkins;docker run --name jenkins -i -d -p 8787:8080 -p 50000:50000 -v /opt/docker/jenkins/jenkins_home:/var/jenkins_home:rw local_jenkins'" >> ~/.bash_aliases
$ source .bash_aliases  # To make it work

Make sure the /opt/docker/jenkins/jenkins_home folder exists and that you have user read and write rights to it.

To start or restart your jenkins just type:

$ localjenkinsrestart

Everything you do in your local jenkins will be stored in the folder /opt/docker/jenkins/jenkins_home and preserved between restarts.

Create a ssh access key in your docker jenkins

This is a very important part for this to work. First we start the docker container and create a bash shell to it:

$ localjenkinsrestart
$ docker exec -it jenkins /bin/bash

You have now entered into the docker container, this you can see by something like jenkins@e7b23bad10aa:/$ in your terminal. The hash after the @ will for sure differ.

Create the key

jenkins@e7b23bad10aa:/$ ssh-keygen

Press enter on all questions until you get the prompt back

Copy the key to your computer. From within the docker container your computer is 172.17.0.1 should you wonder.

jenkins@e7b23bad10aa:/$ ssh-copy-id [email protected]

user = your username and 172.17.0.1 is the ip address to your computer from within the docker container.

You will have to type your password at this point.

Now lets try to complete the loop by ssh-ing to your computer from within the docker container.

jenkins@e7b23bad10aa:/$ ssh [email protected]

This time you should not need to enter you password. If you do, something went wrong and you have to try again.

You will now be in your computers home folder. Try ls and have a look.

Do not stop here since we have a chain of ssh shells that we need to get out of.

$ exit
jenkins@e7b23bad10aa:/$ exit

Right! Now we are back and ready to continue.

Install your Jenkins

You will find your local Jenkins in your browser at http://localhost:8787.

First time you point your browser to your local Jenkins your will be greated with a Installation Wizard. Defaults are fine, do make sure you install the pipeline plugin during the setup though.

Setup your jenkins

It is very important that you activate matrix based security on http://localhost:8787/configureSecurity and give yourself all rights by adding yourself to the matrix and tick all the boxes. (There is a tick-all-boxes icon on the far right)

  • Select Jenkins’ own user database as the Security Realm
  • Select Matrix-based security in the Authorization section
  • Write your username in the field User/group to add: and click on the [ Add ] button
  • In the table above your username should pop up with a people icon next to it. If it is crossed over you typed your username incorrectly.
  • Go to the far right of the table and click on the tick-all-button or manually tick all the boxes in your row.
  • Please verify that the checkbox Prevent Cross Site Request Forgery exploits is unchecked. (Since this Jenkins is only reachable from your computer this isn't such a big deal)
  • Click on [ Save ] and log out of Jenkins and in again just to make sure it works. If it doesn't you have to start over from the beginning and emptying the /opt/docker/jenkins/jenkins_home folder before restarting

Add the git user

We need to allow our git hook to login to our local Jenkins with minimal rights. Just to see and build jobs is sufficient. Therefore we create a user called git with password login.

Direct your browser to http://localhost:8787/securityRealm/addUser and add git as username and login as password. Click on [ Create User ].

Add the rights to the git user

Go to the http://localhost:8787/configureSecurity page in your browser. Add the git user to the matrix:

  • Write git in the field User/group to add: and click on [ Add ]

Now it is time to check the boxes for minimal rights to the git user. Only these are needed:

  • overall:read
  • job:build
  • job:discover
  • job:read

Make sure that the Prevent Cross Site Request Forgery exploits checkbox is unchecked and click on [ Save ]

Create the pipeline project

We assume we have the username user and our git enabled project with the Jenkinsfile in it is called project and is located at /home/user/projects/project

In your http://localhost:8787 Jenkins add a new pipeline project. I named it hookpipeline for reference.

  • Click on New Item in the Jenkins menu
  • Name the project hookpipeline
  • Click on Pipeline
  • Click [ OK ]
  • Tick the checkbox Poll SCM in the Build Triggers section. Leave the Schedule empty.
  • In the Pipeline section:
    • select Pipeline script from SCM
    • in the Repository URL field enter [email protected]:projects/project/.git
    • in the Script Path field enter Jenkinsfile
  • Save the hookpipeline project
  • Build the hookpipeline manually once, this is needed for the Poll SCM to start working.

Create the git hook

Go to the /home/user/projects/project/.git/hooks folder and create a file called post-commit that contains this:

#!/bin/sh
BRANCHNAME=$(git rev-parse --abbrev-ref HEAD)
MASTERBRANCH='master'

curl -XPOST -u git:login http://localhost:8787/job/hookpipeline/build
echo "Build triggered successfully on branch: $BRANCHNAME"

Make this file executable:

$ chmod +x /home/user/projects/project/.git/hooks/post-commit

Test the post-commit hook:

$ /home/user/projects/project/.git/hooks/post-commit

Check in Jenkins if your hookpipeline project was triggered.

Finally make some arbitrary change to your project, add the changes and do a commit. This will now trigger the pipeline in your local Jenkins.

Happy Days!

Show ImageView programmatically

int id = getResources().getIdentifier("gameover", "drawable", getPackageName());
ImageView imageView = new ImageView(this);
LinearLayout.LayoutParams vp = 
    new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, 
                    LayoutParams.WRAP_CONTENT);
imageView.setLayoutParams(vp);        
imageView.setImageResource(id);        
someLinearLayout.addView(imageView); 

Android: Changing Background-Color of the Activity (Main View)

I just want to add my 2 cents. I had the same goal (to change the background color from the .java class). But none of the above methods worked for me.

Issue was, that I set the background color inside the layout .xml file with android:background="@color/colorGray":

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/colorGray">

So I just deleted particular line:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

Now I (you) can set the color from the code with:

getWindow().getDecorView().setBackgroundColor(Color.GRAY);

Adding image inside table cell in HTML

There are some syntax errors on your HTML.

First, the URL of the image needs to point to an address on the public Internet. The users viewing your page won't have your hard drive, so pointing to a file on your local hard drive cannot work. Replace C:\Pics with the actual URL of the image, not a path on development machine filesystem. If you want to be absolutely sure, use a different computer and paste the img tag src attribute value to the address bar of the browser. If it works there, then you're good. Do not that the path can be relative and still valid, but then it needs to be relative to the public URL of the web page it's embedded in.

Second, the <title> tag. You need to add this tag if you need a title on the browser, and you can't format it.

The third error, if about the <th> tag, you have to add this header inside a <tr> tag, because <th> needs a row (create by <tr>).

Another thing is, you don't need all colspan you did.

I tried to do a valid html as you need. Take a look:

<!DOCTYPE html> 
<html>
<head>
    <title>CAR APPLICATION</title>
</head>
<body>
    <center>
        <h1>CAR APPLICATION</h1>
    </center>

    <table border="5" bordercolor="red" align="center">
        <tr>
            <th colspan="3">SONAKSHI RAINA 10B ROLL No:-32</th> 
        </tr>
        <tr>
            <th>Name</th>
            <th>Origin</th>
            <th>Photo</th>
        </tr>
        <tr>
            <td>Bugatti Veyron Super Sport</td>
            <td>Molsheim, Alsace, France</td>
                    <!-- considering it is on the same folder that .html file -->
            <td><img src="H.gif" alt="" border=3 height=100 width=100></img></td>
        </tr>
        <tr>
            <td>SSC Ultimate Aero TT  TopSpeed</td>
            <td>United States</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td>Koenigsegg CCX</td>
            <td>Ängelholm, Sweden</td>
            <td border=4 height=100 width=300>Photo1</td>
        </tr>
        <tr>
            <td>Saleen S7</td>
            <td>Irvine, California, United States</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td> McLaren F1</td>
            <td>Surrey, England</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td>Ferrari Enzo</td>
            <td>Maranello, Italy</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
        <tr>
            <td> Pagani Zonda F Clubsport</td>
            <td>Modena, Italy</td>
            <td border=3 height=100 width=100>Photo1</td>
        </tr>
    </table>
</body>
<html>

Where is Maven Installed on Ubuntu

$ mvn --version

and look for Maven home: in the output , mine is: Maven home: /usr/share/maven

Table overflowing outside of div

I tried all the solutions mentioned above, then did not work. I have 3 tables one below the other. The last one over flowed. I fixed it using:

/* Grid Definition */
table {
    word-break: break-word;
}

For IE11 in edge mode, you need to set this to word-break:break-all

querying WHERE condition to character length?

Sorry, I wasn't sure which SQL platform you're talking about:

In MySQL:

$query = ("SELECT * FROM $db WHERE conditions AND LENGTH(col_name) = 3");

in MSSQL

$query = ("SELECT * FROM $db WHERE conditions AND LEN(col_name) = 3");

The LENGTH() (MySQL) or LEN() (MSSQL) function will return the length of a string in a column that you can use as a condition in your WHERE clause.

Edit

I know this is really old but thought I'd expand my answer because, as Paulo Bueno rightly pointed out, you're most likely wanting the number of characters as opposed to the number of bytes. Thanks Paulo.

So, for MySQL there's the CHAR_LENGTH(). The following example highlights the difference between LENGTH() an CHAR_LENGTH():

CREATE TABLE words (
    word VARCHAR(100)
) ENGINE INNODB DEFAULT CHARSET utf8mb4 COLLATE utf8mb4_unicode_ci;

INSERT INTO words(word) VALUES('??'), ('happy'), ('hayir');

SELECT word, LENGTH(word) as num_bytes, CHAR_LENGTH(word) AS num_characters FROM words;

+--------+-----------+----------------+
| word   | num_bytes | num_characters |
+--------+-----------+----------------+
| ??    |         6 |              2 |
| happy  |         5 |              5 |
| hayir  |         6 |              5 |
+--------+-----------+----------------+

Be careful if you're dealing with multi-byte characters.

Why does visual studio 2012 not find my tests?

In My case it was something else. I had installed a package and then uninstall it and reinstall an earlier version. That left a residual configuration/runtime/asssemblyBinding/dependencyIdentity redirecting in my app.config. I had to correct it. I figured it out by looking at the Output window and selecting "Tests" in the drop down. The error message was there. This was a pain... I hope it helps someone else.

Does return stop a loop?

The return statement stops a loop only if it's inside the function (i.e. it terminates both the loop and the function). Otherwise, you will get this error:

Uncaught SyntaxError: Illegal return statement(…)

To terminate a loop you should use break.

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

I had this issue and it was due to the .Net framework version. I had upgraded the build to framework 4.0 but this seemed to affect some comms dlls the application was using. I rolled back to framework 3.5 and it worked fine.

How to close <img> tag properly?

Unfortunately the above solutions did not work in my case - maybe because a put the button inside a form-tag. This code ...

<input class="button" type="submit" value=" ">
    <img src="../assets/logo.png" alt="test" />
</input>

... always leads to error (with or without the closing slash of the img tag):

error  Parsing error: x-invalid-end-tag  vue/no-parsing-error

? 1 problem (1 error, 0 warnings)

A kind of workaround that did work was to define the image as background-image by means of css.

The html snippet describes the button only. The value attribute contains a single blank in order to suppress some browsers presenting unwanted default text.

<input class="button" type="submit" value=" " />

the CSS defines the button's background image:

.button {
  display: block;
  width: 6em;
  height: 6em;
  color: white;
  background-color: #639f59;
  padding: 0.4em 1.2em;
  box-shadow: inset 0 -0.6em 1em -0.35em rgba(5, 122, 11, 0.30),
    inset 0 0.6em 2em -0.3em rgba(255, 255, 255, 0.30),
    inset 0 0 0em 0.05em rgba(255, 255, 255, 0.30);
  cursor: pointer;
  background: url("../assets/logo.png") ;
  background-repeat: no-repeat;
  background-size: 6em;
  background-position: center;
  border: 0;
  border-radius: 3em;
}

Can not deserialize instance of java.lang.String out of START_OBJECT token

If you do not want to define a separate class for nested json , Defining nested json object as JsonNode should work ,for example :

{"id":2,"socket":"0c317829-69bf-43d6-b598-7c0c550635bb","type":"getDashboard","data":{"workstationUuid":"ddec1caa-a97f-4922-833f-632da07ffc11"},"reply":true}

@JsonProperty("data")
    private JsonNode data;

putting datepicker() on dynamically created elements - JQuery/JQueryUI

The new method for dynamic elements is MutationsObserver .. The following example uses underscore.js to use ( _.each ) function.

MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;    

var observerjQueryPlugins = new MutationObserver(function (repeaterWrapper) {

    _.each(repeaterWrapper, function (repeaterItem, index) {

        var jq_nodes = $(repeaterItem.addedNodes);

        jq_nodes.each(function () {

            // Date Picker
            $(this).parents('.current-repeateritem-container').find('.element-datepicker').datepicker({
                dateFormat: "dd MM, yy",
                showAnim: "slideDown",
                changeMonth: true,
                numberOfMonths: 1
            });

        });

    });

});

observerjQueryPlugins.observe(document, {
    childList: true,
    subtree: true,
    attributes: false,
    characterData: false
});

How to detect escape key press with pure JS or jQuery?

Best way is to make function for this

FUNCTION:

$.fn.escape = function (callback) {
    return this.each(function () {
        $(document).on("keydown", this, function (e) {
            var keycode = ((typeof e.keyCode !='undefined' && e.keyCode) ? e.keyCode : e.which);
            if (keycode === 27) {
                callback.call(this, e);
            };
        });
    });
};

EXAMPLE:

$("#my-div").escape(function () {
    alert('Escape!');
})

Split and join C# string

You can split and join the string, but why not use substrings? Then you only end up with one split instead of splitting the string into 5 parts and re-joining it. The end result is the same, but the substring is probably a bit faster.

string lcStart = "Some Very Large String Here";
int lnSpace = lcStart.IndexOf(' ');

if (lnSpace > -1)
{
    string lcFirst = lcStart.Substring(0, lnSpace);
    string lcRest = lcStart.Substring(lnSpace + 1);
}

Function to calculate distance between two coordinates

I have written the function to find distance between two coordinates. It will return distance in meter.

 function findDistance() {
   var R = 6371e3; // R is earth’s radius
   var lat1 = 23.18489670753479; // starting point lat
   var lat2 = 32.726601;         // ending point lat
   var lon1 = 72.62524545192719; // starting point lon
   var lon2 = 74.857025;         // ending point lon
   var lat1radians = toRadians(lat1);
   var lat2radians = toRadians(lat2);

   var latRadians = toRadians(lat2-lat1);
   var lonRadians = toRadians(lon2-lon1);

   var a = Math.sin(latRadians/2) * Math.sin(latRadians/2) +
        Math.cos(lat1radians) * Math.cos(lat2radians) *
        Math.sin(lonRadians/2) * Math.sin(lonRadians/2);
   var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

   var d = R * c;

   console.log(d)
}

function toRadians(val){
    var PI = 3.1415926535;
    return val / 180.0 * PI;
}

Where does Anaconda Python install on Windows?

Update May 2020, installed Anaconda 3 Individual Edition from https://www.anaconda.com/products/individual, chose 32-bit installer for Python 3.7, and installed with Default options.

enter image description here

Here is the directory where Anaconda was installed (C:\ProgramData\Anaconda3). Note ProgramData is a hidden folder not visible via Windows File Explorer. enter image description here

And launching Anaconda command prompt from Start Menu>>Anaconda3 gives below command shell

enter image description here

"where anaconda" command gives below output C:\ProgramData\Anaconda3\Scripts\anaconda.exe and versions for anaconda, conda, python enter image description here

Updated original question which was asked 3 years ago, and is relevant today as well in May 2020 as I had similar question/doubt when installing Anaconda recently.

PostgreSQL naming conventions

Regarding tables names, case, etc, the prevalent convention is:

  • SQL keywords: UPPER CASE
  • names (identifiers): lower_case_with_underscores

For example:

UPDATE my_table SET name = 5;

This is not written in stone, but the bit about identifiers in lower case is highly recommended, IMO. Postgresql treats identifiers case insensitively when not quoted (it actually folds them to lowercase internally), and case sensitively when quoted; many people are not aware of this idiosyncrasy. Using always lowercase you are safe. Anyway, it's acceptable to use camelCase or PascalCase (or UPPER_CASE), as long as you are consistent: either quote identifiers always or never (and this includes the schema creation!).

I am not aware of many more conventions or style guides. Surrogate keys are normally made from a sequence (usually with the serial macro), it would be convenient to stick to that naming for those sequences if you create them by hand (tablename_colname_seq).

See also some discussion here, here and (for general SQL) here, all with several related links.

Note: Postgresql 10 introduced identity columns as an SQL-compliant replacement for serial.

Get WooCommerce product categories from WordPress

You could also use wp_list_categories();

wp_list_categories( array('taxonomy' => 'product_cat', 'title_li'  => '') );

Couldn't process file resx due to its being in the Internet or Restricted zone or having the mark of the web on the file

If, like me, you have diligently followed all the above solutions and the error is still there, try closing and reopening Visual Studio.

Obvious, I know, but perhaps I'm not the only one who's become fuzzy-brained after staring at a computer screen all day.

Moment.js - how do I get the number of years since a date, not rounded up?

If you dont want to use any module for age calculation

var age = Math.floor((new Date() - new Date(date_of_birth)) / 1000 / 60 / 60 / 24 / 365.25)

error C2039: 'string' : is not a member of 'std', header file problem

You need to have

#include <string>

in the header file too.The forward declaration on it's own doesn't do enough.

Also strongly consider header guards for your header files to avoid possible future problems as your project grows. So at the top do something like:

#ifndef THE_FILE_NAME_H
#define THE_FILE_NAME_H

/* header goes in here */

#endif

This will prevent the header file from being #included multiple times, if you don't have such a guard then you can have issues with multiple declarations.

How to set the text color of TextView in code?

You can use

holder.text.setTextColor(Color.rgb(200,0,0));

You can also specify what color you want with Transparency.

holder.text.setTextColor(Color.argb(0,200,0,0));

a for Alpha (Transparent) value r-red g-green b-blue

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

How to check if div element is empty

Using plain javascript

 var isEmpty = document.getElementById('cartContent').innerHTML === "";

And if you are using jquery it can be done like

 var isEmpty = $("#cartContent").html() === "";

What does "Changes not staged for commit" mean

Try following int git bash

1.git add -u :/

2.git commit -m "your commit message"

  1. git push -u origin master

Note:if you have not initialized your repo.

First of all

git init 

and follow above mentioned steps in order. This worked for me

Upload file to SFTP using PowerShell

There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.

Here is an example using Posh-SSH:

# Set the credentials
$Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)

# Set local file path, SFTP path, and the backup location path which I assume is an SMB path
$FilePath = "C:\FileDump\test.txt"
$SftpPath = '/Outbox'
$SmbPath = '\\filer01\Backup'

# Set the IP of the SFTP server
$SftpIp = '10.209.26.105'

# Load the Posh-SSH module
Import-Module C:\Temp\Posh-SSH

# Establish the SFTP connection
$ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential

# Upload the file to the SFTP path
Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath

#Disconnect all SFTP Sessions
Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }

# Copy the file to the SMB location
Copy-Item -Path $FilePath -Destination $SmbPath

Some additional notes:

  • You'll have to download the Posh-SSH module which you can install to your user module directory (e.g. C:\Users\jon_dechiro\Documents\WindowsPowerShell\Modules) and just load using the name or put it anywhere and load it like I have in the code above.
  • If having the credentials in the script is not acceptable you'll have to use a credential file. If you need help with that I can update with some details or point you to some links.
  • Change the paths, IPs, etc. as needed.

That should give you a decent starting point.

Convert integer to binary in C#

Very Simple with no extra code, just input, conversion and output.

using System;

namespace _01.Decimal_to_Binary
{
    class DecimalToBinary
    {
        static void Main(string[] args)
        {
            Console.Write("Decimal: ");
            int decimalNumber = int.Parse(Console.ReadLine());

            int remainder;
            string result = string.Empty;
            while (decimalNumber > 0)
            {
                remainder = decimalNumber % 2;
                decimalNumber /= 2;
                result = remainder.ToString() + result;
            }
            Console.WriteLine("Binary:  {0}",result);
        }
    }
}

How can I make a HTML a href hyperlink open a new window?

<a href="#" onClick="window.open('http://www.yahoo.com', '_blank')">test</a>

Easy as that.

Or without JS

<a href="http://yahoo.com" target="_blank">test</a>

unix diff side-to-side results?

diff -y --suppress-common-lines file1 file2

How to format string to money

It works!

decimal moneyvalue = 1921.39m; 
string html = String.Format("Order Total: {0:C}", moneyvalue); 
Console.WriteLine(html);

Output

Order Total: $1,921.39

Delete all SYSTEM V shared memory and semaphores on UNIX-like systems

Since you mentioned that you're working on a NFS system, do you have access to those semaphores and shared memory? I think you misunderstood what they are, they are an API code that enables processes to communicate with each other, semaphores are a solution for preventing race conditions and for threads to communicate with each other, in simple answer, they do not leave any residue on any filesystem.

Unless you are using an socket or a pipe? Do you have the necessary permissions to remove them, why are they on an NFS system?

Hope this helps, Best regards, Tom.

How to run python script with elevated privilege on windows

Here is a solution which needed ctypes module only. Support pyinstaller wrapped program.

#!python
# coding: utf-8
import sys
import ctypes

def run_as_admin(argv=None, debug=False):
    shell32 = ctypes.windll.shell32
    if argv is None and shell32.IsUserAnAdmin():
        return True

    if argv is None:
        argv = sys.argv
    if hasattr(sys, '_MEIPASS'):
        # Support pyinstaller wrapped program.
        arguments = map(unicode, argv[1:])
    else:
        arguments = map(unicode, argv)
    argument_line = u' '.join(arguments)
    executable = unicode(sys.executable)
    if debug:
        print 'Command line: ', executable, argument_line
    ret = shell32.ShellExecuteW(None, u"runas", executable, argument_line, None, 1)
    if int(ret) <= 32:
        return False
    return None


if __name__ == '__main__':
    ret = run_as_admin()
    if ret is True:
        print 'I have admin privilege.'
        raw_input('Press ENTER to exit.')
    elif ret is None:
        print 'I am elevating to admin privilege.'
        raw_input('Press ENTER to exit.')
    else:
        print 'Error(ret=%d): cannot elevate privilege.' % (ret, )

Force Intellij IDEA to reread all maven dependencies

If you work in IntelliJ, there are four independent ways to refresh maven repositories. Each of them refreshes another local repository on your computer or refreshes them differently.

1. mvn -U clean install
2. Ctrl+Shift+A - Reimport
3. Round arrows in the Maven window

4. Ctrl+Alt+S , go to Build, Execution, Deployment | Build Tools | Maven | Repositories -choose rep - update

What is interesting, it is often said, that the last refresh is equal to the round arrows in the Maven window. But, according to my experience, they are absolutely different! The proof: Our large project fails the last refresh, but exists and runs happily without it. And double round arrows run OK on it.

Each of these four can help you with your problems or/and find problems of its own. For example, for running our real-life project only the first is necessary, but for testing in IntelliJ we also need 2 and 3. Surely, somebody needs 4, too. (Why else IntelliJ has it?)

Remove icon/logo from action bar on android

Qiqi Abaziz's answer is ok, but I still struggled for a long time getting it to work with the compatibility pack and to apply the style to the correct elements. Also, the transparency-hack is unneccessary. So here is a complete example working for v8 and up:

values\styles.xml

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="MyActivityTheme" parent="@style/Theme.AppCompat">
        <item name="actionBarStyle">@style/NoLogoActionBar</item> <!-- pre-v11-compatibility -->
        <item name="android:actionBarStyle">@style/NoLogoActionBar</item>
    </style>
    <style name="NoLogoActionBar" parent="@style/Widget.AppCompat.ActionBar">
        <item name="displayOptions">showHome</item> <!-- pre-v11-compatibility -->
        <item name="android:displayOptions">showHome</item>
    </style>
</resources>

AndroidManifest.xml (shell)

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">   
    <uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19"/>
    <application android:theme="@android:style/Theme.Light.NoTitleBar">
        <activity android:theme="@style/PentActivityTheme"/>
    </application>
</manifest>

:: (double colon) operator in Java 8

In older Java versions, instead of "::" or lambd, you can use:

public interface Action {
    void execute();
}

public class ActionImpl implements Action {

    @Override
    public void execute() {
        System.out.println("execute with ActionImpl");
    }

}

public static void main(String[] args) {
    Action action = new Action() {
        @Override
        public void execute() {
            System.out.println("execute with anonymous class");
        }
    };
    action.execute();

    //or

    Action actionImpl = new ActionImpl();
    actionImpl.execute();
}

Or passing to the method:

public static void doSomething(Action action) {
    action.execute();
}

Storing an object in state of a React component?

this.setState({abc: {xyz: 'new value'}}); will NOT work, as state.abc will be entirely overwritten, not merged.

This works for me:

this.setState((previousState) => {
  previousState.abc.xyz = 'blurg';
  return previousState;
});

Unless I'm reading the docs wrong, Facebook recommends the above format. https://facebook.github.io/react/docs/component-api.html

Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:

const newState = { ...this.state.abc }; // deconstruct state.abc into a new object-- effectively making a copy
newState.xyz = 'blurg';
this.setState(newState);

Adding images or videos to iPhone Simulator

If you need to import more than just one or two photos then take a look at this article that I wrote. It describes an easy way to perform a bulk import of photos and works for iOS 4.x.

Can a table row expand and close?

It depends on your mark-up, but it can certainly be made to work, I used the following:

jQuery

$(document).ready(
  function() {
  $('td p').slideUp();
    $('td h2').click(
      function(){
       $(this).siblings('p').slideToggle();
      }
      );
  }
  );

html

  <table>
  <thead>
    <tr>
      <th>Actor</th>
      <th>Which Doctor</th>
      <th>Significant companion</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td><h2>William Hartnell</h2></td>
      <td><h2>First</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
      <td><h2>Susan Foreman</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
    </tr>
    <tr>
      <td><h2>Patrick Troughton</h2></td>
      <td><h2>Second</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
      <td><h2>Jamie MacCrimmon</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
    </tr>
    <tr>
      <td><h2>Jon Pertwee</h2></td>
      <td><h2>Third</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas.</p></td>
      <td><h2>Jo Grant</h2><p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p></td>
    </tr>
  </tbody>
</table>

The way I approached it is to collapse specific elements within the cells of the row, so that, in my case, the row would slideUp() as the paragraphs were hidden, and still leave an element, h2 to click on in order to re-show the content. If the row collapsed entirely there'd be no easily obvious way to bring it back.

Demo at JS Bin


As @Peter Ajtai noted, in the comments, the above approach focuses on only one cell (though deliberately). To expand all the child p elements this would work:

$(document).ready(
  function() {
  $('td p').slideUp();
    $('td h2').click(
      function(){
       $(this).closest('tr').find('p').slideToggle();
      }
      );
  }
  );

Demo at JS Bin

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

At the very core, the file extension you use makes no difference as to how perl interprets those files.

However, putting modules in .pm files following a certain directory structure that follows the package name provides a convenience. So, if you have a module Example::Plot::FourD and you put it in a directory Example/Plot/FourD.pm in a path in your @INC, then use and require will do the right thing when given the package name as in use Example::Plot::FourD.

The file must return true as the last statement to indicate successful execution of any initialization code, so it's customary to end such a file with 1; unless you're sure it'll return true otherwise. But it's better just to put the 1;, in case you add more statements.

If EXPR is a bareword, the require assumes a ".pm" extension and replaces "::" with "/" in the filename for you, to make it easy to load standard modules. This form of loading of modules does not risk altering your namespace.

All use does is to figure out the filename from the package name provided, require it in a BEGIN block and invoke import on the package. There is nothing preventing you from not using use but taking those steps manually.

For example, below I put the Example::Plot::FourD package in a file called t.pl, loaded it in a script in file s.pl.

C:\Temp> cat t.pl
package Example::Plot::FourD;

use strict; use warnings;

sub new { bless {} => shift }

sub something { print "something\n" }

"Example::Plot::FourD"

C:\Temp> cat s.pl
#!/usr/bin/perl
use strict; use warnings;

BEGIN {
    require 't.pl';
}

my $p = Example::Plot::FourD->new;
$p->something;


C:\Temp> s
something

This example shows that module files do not have to end in 1, any true value will do.

.includes() not working in Internet Explorer

Problem:

Try running below(without solution) from Internet Explorer and see the result.

_x000D_
_x000D_
console.log("abcde".includes("cd"));
_x000D_
_x000D_
_x000D_

Solution:

Now run below solution and check the result

_x000D_
_x000D_
if (!String.prototype.includes) {//To check browser supports or not_x000D_
  String.prototype.includes = function (str) {//If not supported, then define the method_x000D_
    return this.indexOf(str) !== -1;_x000D_
  }_x000D_
}_x000D_
console.log("abcde".includes("cd"));
_x000D_
_x000D_
_x000D_

Check if value already exists within list of dictionaries?

Following works out for me.

    #!/usr/bin/env python
    a = [{ 'main_color': 'red', 'second_color':'blue'},
    { 'main_color': 'yellow', 'second_color':'green'},
    { 'main_color': 'yellow', 'second_color':'blue'}]

    found_event = next(
            filter(
                lambda x: x['main_color'] == 'red',
                a
            ),
      #return this dict when not found
            dict(
                name='red',
                value='{}'
            )
        )

    if found_event:
        print(found_event)

    $python  /tmp/x
    {'main_color': 'red', 'second_color': 'blue'}

Is it possible to have placeholders in strings.xml for runtime values?

Formatting and Styling

Yes, see the following from String Resources: Formatting and Styling

If you need to format your strings using String.format(String, Object...), then you can do so by putting your format arguments in the string resource. For example, with the following resource:

<string name="welcome_messages">Hello, %1$s! You have %2$d new messages.</string>

In this example, the format string has two arguments: %1$s is a string and %2$d is a decimal number. You can format the string with arguments from your application like this:

Resources res = getResources();
String text = String.format(res.getString(R.string.welcome_messages), username, mailCount);

Basic Usage

Note that getString has an overload that uses the string as a format string:

String text = res.getString(R.string.welcome_messages, username, mailCount);

Plurals

If you need to handle plurals, use this:

<plurals name="welcome_messages">
    <item quantity="one">Hello, %1$s! You have a new message.</item>
    <item quantity="other">Hello, %1$s! You have %2$d new messages.</item>
</plurals>

The first mailCount param is used to decide which format to use (single or plural), the other params are your substitutions:

Resources res = getResources();
String text = res.getQuantityString(R.plurals.welcome_messages, mailCount, username, mailCount);

See String Resources: Plurals for more details.

What is "pom" packaging in maven?

Packaging of pom is used in projects that aggregate other projects, and in projects whose only useful output is an attached artifact from some plugin. In your case, I'd guess that your top-level pom includes <modules>...</modules> to aggregate other directories, and the actual output is the result of one of the other (probably sub-) directories. It will, if coded sensibly for this purpose, have a packaging of war.

How to use MapView in android using google map V2?

I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX

You can find complete project here: github-link

MainActivity.kt

class MainActivity : AppCompatActivity() {

val position = LatLng(-33.920455, 18.466941)

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    with(mapView) {
        // Initialise the MapView
        onCreate(null)
        // Set the map ready callback to receive the GoogleMap object
        getMapAsync{
            MapsInitializer.initialize(applicationContext)
            setMapLocation(it)
        }
    }
}

private fun setMapLocation(map : GoogleMap) {
    with(map) {
        moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
        addMarker(MarkerOptions().position(position))
        mapType = GoogleMap.MAP_TYPE_NORMAL
        setOnMapClickListener {
            Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()
        }
    }
}

override fun onResume() {
    super.onResume()
    mapView.onResume()
}

override fun onPause() {
    super.onPause()
    mapView.onPause()
}

override fun onDestroy() {
    super.onDestroy()
    mapView.onDestroy()
}

override fun onLowMemory() {
    super.onLowMemory()
    mapView.onLowMemory()
 }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      xmlns:tools="http://schemas.android.com/tools" package="com.murgupluoglu.googlemap">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

<application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:ignore="GoogleAppIndexingWarning">
    <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="API_KEY_HERE" />
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
</application>

</manifest>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

<com.google.android.gms.maps.MapView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:id="@+id/mapView"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"/>

</androidx.constraintlayout.widget.ConstraintLayout>

Remove characters from a String in Java

Can't you use

id = id.substring(0, id.length()-4);

And what Eric said, ofcourse.