Programs & Examples On #Anagram

A word, phrase, or name formed by rearranging the letters of another, such as cinema, formed from iceman.

How to check if two words are anagrams

If you sort either array, the solution becomes O(n log n). but if you use a hashmap, it's O(n). tested and working.

char[] word1 = "test".toCharArray();
char[] word2 = "tes".toCharArray();

Map<Character, Integer> lettersInWord1 = new HashMap<Character, Integer>();

for (char c : word1) {
    int count = 1;
    if (lettersInWord1.containsKey(c)) {
        count = lettersInWord1.get(c) + 1;
    }
    lettersInWord1.put(c, count);
}

for (char c : word2) {
    int count = -1;
    if (lettersInWord1.containsKey(c)) {
        count = lettersInWord1.get(c) - 1;
    }
    lettersInWord1.put(c, count);
}

for (char c : lettersInWord1.keySet()) {
    if (lettersInWord1.get(c) != 0) {
        return false;
    }
}

return true;

Using Python, find anagrams for a list of words

There are multiple solutions to this problem:

  1. Classic approach

    First, let's consider what defines an anagram: two words are anagrams of each other if they consist of the same set of letters and each letter appears exactly the same number or time in both words. This is basically a histogram of letters count of each word. This is a perfect use case for collections.Counter data structure (see docs). The algorithms is as follows:

    • Build a dictionary where keys would be histograms and values would be lists of words that have this histogram.
    • For each word build it's histogram and add it to the list that corresponds to this histogram.
    • Output list of dictionary values.

    Here is the code:

    from collections import Counter, defaultdict
    
    def anagram(words):
        anagrams = defaultdict(list)
        for word in words:
            histogram = tuple(Counter(word).items()) # build a hashable histogram
            anagrams[histogram].append(word)
        return list(anagrams.values())
    
    keywords = ("hi", "hello", "bye", "helol", "abc", "cab", 
                    "bac", "silenced", "licensed", "declines")
    
    print(anagram(keywords))
    

    Note that constructing Counter is O(l), while sorting each word is O(n*log(l)) where l is the length of the word.

  2. Solving anagrams using prime numbers

    This is a more advanced solution, that relies on the "multiplicative uniqueness" of prime numbers. You can refer to this SO post: Comparing anagrams using prime numbers, and here is a sample python implementation.

Java Code for calculating Leap Year

Pseudo code from Wikipedia translated into the most compact Java

(year % 400 == 0) || ((year % 4 == 0) && (year % 100 != 0))

How to remove old and unused Docker images

docker rm $(docker ps -faq)
docker rmi $(docker ps -faq)

-f force

-a all

-q in the mode

On duplicate key ignore?

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

Query OK, 0 rows affected (0.07 sec)

What exactly is nullptr?

Well, other languages have reserved words that are instances of types. Python, for instance:

>>> None = 5
  File "<stdin>", line 1
SyntaxError: assignment to None
>>> type(None)
<type 'NoneType'>

This is actually a fairly close comparison because None is typically used for something that hasn't been intialized, but at the same time comparisons such as None == 0 are false.

On the other hand, in plain C, NULL == 0 would return true IIRC because NULL is just a macro returning 0, which is always an invalid address (AFAIK).

Initialising mock objects - MockIto

MockitoAnnotations & the runner have been well discussed above, so I'm going to throw in my tuppence for the unloved:

XXX mockedXxx = mock(XXX.class);

I use this because I find it a little bit more descriptive and I prefer (not out right ban) unit tests not to use member variables as I like my tests to be (as much as they can be) self contained.

Stop a gif animation onload, on mouseover start the activation

For restarting the animation of a gif image, you can use the code:

$('#img_gif').attr('src','file.gif?' + Math.random());

ArrayBuffer to base64 encoded string

The OP did not specify the Running Enviroment but if you are using Node.JS there is a very simple way to do such thing.

Accordig with the official Node.JS docs https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings

// This step is only necessary if you don't already have a Buffer Object
const buffer = Buffer.from(yourArrayBuffer);

const base64String = buffer.toString('base64');

Also, If you are running under Angular for example, the Buffer Class will also be made available in a Browser Environment.

git-upload-pack: command not found, when cloning remote Git repo

I found and used (successfully) this fix:

# Fix it with symlinks in /usr/bin
$ cd /usr/bin/
$ sudo ln -s /[path/to/git]/bin/git* .

Thanks to Paul Johnston.

Why is C so fast, and why aren't other languages as fast or faster?

Back in the good ole days, there were just two types of languages: compiled and interpreted.

Compiled languages utilized a "compiler" to read the language syntax and convert it into identical assembly language code, which could than just directly on the CPU. Interpreted languages used a couple of different schemes, but essentially the language syntax was converted into an intermediate form, and then run in a "interpreter", an environment for executing the code.

Thus, in a sense, there was another "layer" -- the interpreter -- between the code and the machine. And, as always the case in a computer, more means more resources get used. Interpreters were slower, because they had to perform more operations.

More recently, we've seen more hybrid languages like Java, that employ both a compiler and an interpreter to make them work. It's complicated, but a JVM is faster, more sophisticated and way more optimized than the old interpreters, so it stands a much better change of performing (over time) closer to just straight compiled code. Of course, the newer compilers also have more fancy optimizing tricks so they tend to generate way better code than they used to as well. But most optimizations, most often (although not always) make some type of trade-off such that they are not always faster in all circumstances. Like everything else, nothing comes for free, so the optimizers must get their boast from somewhere (although often times it using compile-time CPU to save runtime CPU).

Getting back to C, it is a simple language, that can be compiled into fairly optimized assembly and then run directly on the target machine. In C, if you increment an integer, it's more than likely that it is only one assembler step in the CPU, in Java however, it could end up being a lot more than that (and could include a bit of garbage collection as well :-) C offers you an abstraction that is way closer to the machine (assembler is the closest), but you end up having to do way more work to get it going and it is not as protected, easy to use or error friendly. Most other languages give you a higher abstraction and take care of more of the underlying details for you, but in exchange for their advanced functionality they require more resources to run. As you generalize some solutions, you have to handle a broader range of computing, which often requires more resources.

Paul.

How to unstage large number of files without deleting the content

Warning: do not use the following command unless you want to lose uncommitted work!

Using git reset has been explained, but you asked for an explanation of the piped commands as well, so here goes:

git ls-files -z | xargs -0 rm -f
git diff --name-only --diff-filter=D -z | xargs -0 git rm --cached

The command git ls-files lists all files git knows about. The option -z imposes a specific format on them, the format expected by xargs -0, which then invokes rm -f on them, which means to remove them without checking for your approval.

In other words, "list all files git knows about and remove your local copy".

Then we get to git diff, which shows changes between different versions of items git knows about. Those can be changes between different trees, differences between local copies and remote copies, and so on.
As used here, it shows the unstaged changes; the files you have changed but haven't committed yet. The option --name-only means you want the (full) file names only and --diff-filter=D means you're interested in deleted files only. (Hey, didn't we just delete a bunch of stuff?) This then gets piped into the xargs -0 we saw before, which invokes git rm --cached on them, meaning that they get removed from the cache, while the working tree should be left alone — except that you've just removed all files from your working tree. Now they're removed from your index as well.

In other words, all changes, staged or unstaged, are gone, and your working tree is empty. Have a cry, checkout your files fresh from origin or remote, and redo your work. Curse the sadist who wrote these infernal lines; I have no clue whatsoever why anybody would want to do this.


TL;DR: you just hosed everything; start over and use git reset from now on.

How do I create HTML table using jQuery dynamically?

FOR EXAMPLE YOU HAVE RECIEVED JASON DATA FROM SERVER.

                var obj = JSON.parse(msg);
                var tableString ="<table id='tbla'>";
                tableString +="<th><td>Name<td>City<td>Birthday</th>";


                for (var i=0; i<obj.length; i++){
                    //alert(obj[i].name);
                    tableString +=gg_stringformat("<tr><td>{0}<td>{1}<td>{2}</tr>",obj[i].name, obj[i].age, obj[i].birthday);
                }
                tableString +="</table>";
                alert(tableString);
                $('#divb').html(tableString);

HERE IS THE CODE FOR gg_stringformat

function gg_stringformat() {
var argcount = arguments.length,
    string,
    i;

if (!argcount) {
    return "";
}
if (argcount === 1) {
    return arguments[0];
}
string = arguments[0];
for (i = 1; i < argcount; i++) {
    string = string.replace(new RegExp('\\{' + (i - 1) + '}', 'gi'), arguments[i]);
}
return string;

}

How do you implement a re-try-catch?

Simplifying @ach's previous solution into one file and using functional interfaces.

public class OperationHelper {

    public static void doWithRetry(int maxAttempts, Runnable operation, Consumer<Exception> handle) {
        for (int count = 0; count < maxAttempts; count++) {
            try {
                operation.run();
                count = maxAttempts; //don't retry
            } catch (Exception e) {
                handle.accept(e);
            }
        }
    }
}

PHP file_get_contents() returns "failed to open stream: HTTP request failed!"

I notice that your URL has spaces in it. I think that usually is a bad thing. Try encoding the URL with

$my_url = urlencode("my url");

and then calling

file_get_contents($my_url);

and see if you have better luck.

composer laravel create project

My few cents. The forward-slash in the package name (laravel*/*laravel) is matter. If you put back-slash you will get package not found stability error.

Eclipse projects not showing up after placing project files in workspace/projects

This problems comes while .metadata of current workspace has been corrupted due to shut down Eclipse Unexpectedly. So if you face this problem just do the following steps:

  • Create a new workspace. Import your existing projects to your new workspace.

you made it!

Improve INSERT-per-second performance of SQLite

I coudn't get any gain from transactions until I raised cache_size to a higher value i.e. PRAGMA cache_size=10000;

how to filter out a null value from spark dataframe

Another easy way to filter out null values from multiple columns in spark dataframe. Please pay attention there is AND between columns.

df.filter(" COALESCE(col1, col2, col3, col4, col5, col6) IS NOT NULL")

If you need to filter out rows that contain any null (OR connected) please use

df.na.drop()

How to iterate a table rows with JQuery and access some cell values?

do this:

$("tr.item").each(function(i, tr) {
    var value = $("span.value", tr).text();
    var quantity = $("input.quantity", tr).val();
});

how to display none through code behind

I believe this should work:

login_div.Attributes.Add("style","display:none");

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

From Hadley Wickham:

From Hadley Wickham

My (crappy looking) modification to show using tidyverse / purrr:

enter image description here

Faster alternative in Oracle to SELECT COUNT(*) FROM sometable

You can create a fast refresh materialized view to store the count.

Example:

create table sometable (
id number(10) not null primary key
, name varchar2(100) not null);

create materialized view log on sometable with rowid including new values;

create materialized view sometable_count
refresh on commit
as
select count(*) count
from   sometable;

insert into sometable values (1,'Raymond');
insert into sometable values (2,'Hans');

commit;

select count from sometable_count; 

It will slow mutations on table sometable a bit but the counting will become a lot faster.

Execute bash script from URL

Using wget, which is usually part of default system installation:

bash <(wget -qO- http://mywebsite.com/myscript.txt)

How to receive POST data in django

res = request.GET['paymentid'] will raise a KeyError if paymentid is not in the GET data.

Your sample php code checks to see if paymentid is in the POST data, and sets $payID to '' otherwise:

$payID = isset($_POST['paymentid']) ? $_POST['paymentid'] : ''

The equivalent in python is to use the get() method with a default argument:

payment_id = request.POST.get('payment_id', '')

while debugging, this is what I see in the response.GET: <QueryDict: {}>, request.POST: <QueryDict: {}>

It looks as if the problem is not accessing the POST data, but that there is no POST data. How are you are debugging? Are you using your browser, or is it the payment gateway accessing your page? It would be helpful if you shared your view.

Once you are managing to submit some post data to your page, it shouldn't be too tricky to convert the sample php to python.

Convert a double to a QString

You can use arg(), as follow:

double dbl = 0.25874601;
QString str = QString("%1").arg(dbl);

This overcomes the problem of: "Fixed precision" at the other functions like: setNum() and number(), which will generate random numbers to complete the defined precision

How to set level logging to DEBUG in Tomcat?

JULI logging levels for Tomcat

SEVERE - Serious failures

WARNING - Potential problems

INFO - Informational messages

CONFIG - Static configuration messages

FINE - Trace messages

FINER - Detailed trace messages

FINEST - Highly detailed trace messages

You can find here more https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/pasoe-admin/tomcat-logging.html

How can I increment a char?

Check this: USING FOR LOOP

for a in range(5):
    x='A'
    val=chr(ord(x) + a)
    print(val)

LOOP OUTPUT: A B C D E

Removing legend on charts with chart.js v2

You simply need to add that line legend: { display: false }

mysqldump with create database line

By default mysqldump always creates the CREATE DATABASE IF NOT EXISTS db_name; statement at the beginning of the dump file.

[EDIT] Few things about the mysqldump file and it's options:

--all-databases, -A

Dump all tables in all databases. This is the same as using the --databases option and naming all the databases on the command line.

--add-drop-database

Add a DROP DATABASE statement before each CREATE DATABASE statement. This option is typically used in conjunction with the --all-databases or --databases option because no CREATE DATABASE statements are written unless one of those options is specified.

--databases, -B

Dump several databases. Normally, mysqldump treats the first name argument on the command line as a database name and following names as table names. With this option, it treats all name arguments as database names. CREATE DATABASE and USE statements are included in the output before each new database.

--no-create-db, -n

This option suppresses the CREATE DATABASE statements that are otherwise included in the output if the --databases or --all-databases option is given.

Some time ago, there was similar question actually asking about not having such statement on the beginning of the file (for XML file). Link to that question is here.

So to answer your question:

  • if you have one database to dump, you should have the --add-drop-database option in your mysqldump statement.
  • if you have multiple databases to dump, you should use the option --databases or --all-databases and the CREATE DATABASE syntax will be added automatically

More information at MySQL Reference Manual

Java Scanner class reading strings

It's because the in.nextInt() doesn't change line. So you first "enter" (after you press 3 ) cause the endOfLine read by your in.nextLine() in your loop.

Here a small change that you can do:

int nnames;
    String names[];

    System.out.print("How many names are you going to save: ");
    Scanner in = new Scanner(System.in);
    nnames = Integer.parseInt(in.nextLine());
    names = new String[nnames];

    for (int i = 0; i < names.length; i++){
            System.out.print("Type a name: ");
            names[i] = in.nextLine();
    }

Check if string is neither empty nor space in shell script

In case you need to check against any amount of whitespace, not just single space, you can do this:

To strip string of extra white space (also condences whitespace in the middle to one space):

trimmed=`echo -- $original`

The -- ensures that if $original contains switches understood by echo, they'll still be considered as normal arguments to be echoed. Also it's important to not put "" around $original, or the spaces will not get removed.

After that you can just check if $trimmed is empty.

[ -z "$trimmed" ] && echo "empty!"

Sharing url link does not show thumbnail image on facebook

My site faces same issue too.

Using Facebook debug tool is no help at all. Fetch new data but not IMAGE CACHE.

I forced facebook to clear IMAGE CACHE by add www. into image url. In your case is remove www. and config web server redirect.

 add/remove www. in image url should solve the problem

mysql -> insert into tbl (select from another table) and some default values

If you want to insert all the columns then

insert into def select * from abc;

here the number of columns in def should be equal to abc.

if you want to insert the subsets of columns then

insert into def (col1,col2, col3 ) select scol1,scol2,scol3 from abc; 

if you want to insert some hardcorded values then

insert into def (col1, col2,col3) select 'hardcoded value',scol2, scol3 from abc;

How to revert a "git rm -r ."?

With Git 2.23+ (August 2019), the proper command to restore files (and the index) woud be to use... git restore (not reset --hard or the confusing git checkout command)

That is:

git restore -s=HEAD --staged --worktree -- .

Or its abbreviated form:

git restore -s@ -SW -- .

Display List in a View MVC

You are passing wrong mode to you view. Your view is looking for @model IEnumerable<Standings.Models.Teams> and you are passing var model = tm.Name.ToList(); name list. You have to pass list of Teams.

You have to pass following model

var model = new List<Teams>();

model.Add(new Teams { Name =  new List<string>(){"Sky","ABC"}});
model.Add(new Teams { Name =  new List<string>(){"John","XYZ"} });
return View(model);

What's the difference between "Request Payload" vs "Form Data" as seen in Chrome dev tools Network tab

In Chrome, request with 'Content-Type:application/json' shows as Request PayedLoad and sends data as json object.

But request with 'Content-Type:application/x-www-form-urlencoded' shows Form Data and sends data as Key:Value Pair, so if you have array of object in one key it flats that key's value:

{ Id: 1, 
name:'john', 
phones:[{title:'home',number:111111,...},
        {title:'office',number:22222,...}]
}

sends

{ Id: 1, 
name:'john', 
phones:[object object]
phones:[object object]
}

How to exit from the application and show the home screen?

If you want to end an activity you can simply call finish(). It is however bad practice to have an exit button on the screen.

How to post a file from a form with Axios

Sample application using Vue. Requires a backend server running on localhost to process the request:

var app = new Vue({
  el: "#app",
  data: {
    file: ''
  },
  methods: {
    submitFile() {
      let formData = new FormData();
      formData.append('file', this.file);
      console.log('>> formData >> ', formData);

      // You should have a server side REST API 
      axios.post('http://localhost:8080/restapi/fileupload',
          formData, {
            headers: {
              'Content-Type': 'multipart/form-data'
            }
          }
        ).then(function () {
          console.log('SUCCESS!!');
        })
        .catch(function () {
          console.log('FAILURE!!');
        });
    },
    handleFileUpload() {
      this.file = this.$refs.file.files[0];
      console.log('>>>> 1st element in files array >>>> ', this.file);
    }
  }
});

https://codepen.io/pmarimuthu/pen/MqqaOE

$(window).width() not the same as media query

What i do ;

<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
...

and call aWidth variable anywhere afterwards.

You need to put the getWidth() up in your document body to make sure that the scrollbar width is counted, else scrollbar width of the browser subtracted from getWidth().

PHP replacing special characters like à->a, è->e

The string $chain is in the same character encoding as the characters in the array - it's possible, even likely, that the $first_name string is in a different encoding, and so those characters don't match. You might want to try using the multibyte string functions instead.

Try mb_convert_encoding. You might also want to try using HTML_ENTITIES as the to_encoding parameter, then you don't need to worry about how the characters will get converted - it will be very predictable.

Assuming your input to this script is in UTF-8, probably not a bad place to start...

$first_name = mb_convert_encoding($first_name, "HTML-ENTITIES", "UTF-8"); 

Visual Studio keyboard shortcut to automatically add the needed 'using' statement

  • Context Menu key (one one with the menu on it, next to the right Windows key)
  • Then choose "Resolve" from the menu. That can be done by pressing "s".

Is it a good practice to use try-except-else in Python?

Whenever you see this:

try:
    y = 1 / x
except ZeroDivisionError:
    pass
else:
    return y

Or even this:

try:
    return 1 / x
except ZeroDivisionError:
    return None

Consider this instead:

import contextlib
with contextlib.suppress(ZeroDivisionError):
    return 1 / x

How to Solve Max Connection Pool Error

Before you begin to curse your application you need to check this:

  1. Is your application the only one using that instance of SQL Server. a. If the answer to that is NO then you need to investigate how the other applications are consuming resources on your SQl Server.run b. If the answer is yes then you must investigate your application.

  2. Run SQL Server Profiler and check what activity is happening in other applications (1a) using SQL Server and check your application as well (1b).

  3. If indeed your application is starved off of resources then you need to make farther investigations. For more read on this http://sqlserverplanet.com/troubleshooting/sql-server-slowness

NSURLSession/NSURLConnection HTTP load failed on iOS 9

Simply add the following fields in your .plist file

enter image description here

Syntax looks like this:

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

How to get equal width of input and select fields

Updated answer

Here is how to change the box model used by the input/textarea/select elements so that they all behave the same way. You need to use the box-sizing property which is implemented with a prefix for each browser

-ms-box-sizing:content-box;
-moz-box-sizing:content-box;
-webkit-box-sizing:content-box; 
box-sizing:content-box;

This means that the 2px difference we mentioned earlier does not exist..

example at http://www.jsfiddle.net/gaby/WaxTS/5/

note: On IE it works from version 8 and upwards..


Original

if you reset their borders then the select element will always be 2 pixels less than the input elements..

example: http://www.jsfiddle.net/gaby/WaxTS/2/

How do I add my bot to a channel?

This is how I've added a bot to my channel and set up notifications:

  1. Make sure the channel is public (you can set it private later)
  2. Add administrators > Type the bot username and make it administrator
  3. Your bot will join your channel
  4. set a channel id by setting the channel url like

telegram.me/whateverIWantAndAvailable

the channel id will be @whateverIWantAndAvailable

Now set up your bot to send notifications by pusshing the messages here:

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Test

the message which bot will notify is: Test

I strongly suggest an urlencode of the message like

https://api.telegram.org/botTOKENOFTHEBOT/sendMessage?chat_id=@whateverIWantAndAvailable&text=Testing%20if%20this%20works

in php you can use urlencode("Test if this works"); in js you can encodeURIComponent("Test if this works");

I hope it helps

MySQL Error #1133 - Can't find any matching row in the user table

To expound on Stephane's answer.

I got this error when I tried to grant remote connections privileges of a particular database to a root user on MySQL server by running the command:

USE database_name;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%';

This gave an error:

ERROR 1133 (42000): Can't find any matching row in the user table

Here's how I fixed it:

First, confirm that your MySQL server allows for remote connections. Use your preferred text editor to open the MySQL server configuration file:

sudo nano /etc/mysql/mysql.conf.d/mysqld.cnf

Scroll down to the bind-address line and ensure that is either commented out or replaced with 0.0.0.0 (to allow all remote connections) or replaced with Ip-Addresses that you want remote connections from.

Once you make the necessary changes, save and exit the configuration file. Apply the changes made to the MySQL config file by restarting the MySQL service:

sudo systemctl restart mysql

Next, log into the MySQL server console on the server it was installed:

mysql -u root -p

Enter your mysql user password

Check the hosts that the user you want has access to already. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| localhost |
+-----------+

Next, I ran the command below which is similar to the previous one that was throwing errors, but notice that I added a password to it this time:

USE database_name;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'my-password';

Note: % grants a user remote access from all hosts on a network. You can specify the Ip-Address of the individual hosts that you want to grant the user access from using the command - GRANT ALL PRIVILEGES ON *.* TO 'root'@'Ip-Address' IDENTIFIED BY 'my-password';

Afterwhich I checked the hosts that the user now has access to. In my case the user is root:

SELECT host FROM mysql.user WHERE user = "root";

This gave me this output:

+-----------+
| host      |
+-----------+
| %         |
| localhost |
+-----------+

Finally, you can try connecting to the MySQL server from another server using the command:

mysql -u username -h mysql-server-ip-address -p

Where u represents user, h represents mysql-server-ip-address and p represents password. So in my case it was:

mysql -u root -h 34.69.261.158 -p

Enter your mysql user password

You should get this output depending on your MySQL server version:

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.31 MySQL Community Server (GPL)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

Resources: How to Allow Remote Connections to MySQL

That's all.

I hope this helps

How do I debug a stand-alone VBScript script?

Click the mse7.exe installed along with Office typically at \Program Files\Microsoft Office\OFFICE11.

This will open up the debugger, open the file and then run the debugger in the GUI mode.

Why em instead of px?

It is wrong to say that one is a better choice than the other (or both wouldn't have been given their own purpose in the spec). It may even be worth noting that StackOverflow makes extensive use of px units. It is not the poor choice Spoike was told it was.

Definition of units

  • px is an absolute unit of measurement (like in, pt, or cm) that also happens to be 1/96 of an in unit (more on why later). Because it is an absolute measurement, it may be used any time you want to define something to be a particular size, rather than being proportional to something else like the size of the browser window or the font size.

    Like all the other absolute units, px units don't scale according to the width of the browser window. Thus, if your entire page design uses absolute units such as px rather than %, it won't adapt to the width of the browser. This is not inherently good or bad, just a choice that the designer needs to make between adhering to an exact size and being inflexible versus stretching but in the process not adhering to an exact size. It would be typical for a site to have a mix of fixed-size and flexible-sized objects.

    Fixed size elements often need to be incorporated into the page - such as advertising banners, logos or icons. This ensures you almost always need at least some px-based measurements in a design. Images, for example, will (by default) be scaled such that each pixel is 1*px* in size, so if you are designing around an image you'll need px units. It is also very useful for precise font sizing, and for border widths, where due to rounding it makes the most sense to use px units for the majority of screens.

    All absolute measurements are rigidly related to each other; that is, 1in is always 96px, just as 1in is always 72pt. (Note that 1in is almost never actually a physical inch when talking about screen-based media). All absolute measurements assume a nominal screen resolution of 96ppi and a nominal viewing distance of a desktop monitor, and on such a screen one px will be equal to one physical pixel on the screen and one in will be equal to 96 physical pixels. On screens that differ significantly in either pixel density or viewing distance, or if the user has zoomed the page using the browser's zoom function, px will no longer necessarily relate to physical pixels.

  • em is not an absolute unit - it is a unit that is relative to the currently chosen font size. Unless you have overridden font style by setting your font size with an absolute unit (such as px or pt), this will be affected by the choice of fonts in the user's browser or OS if they have made one, so it does not make sense to use em as a general unit of length except where you specifically want it to scale as the font size scales.

    Use em when you specifically want the size of something to depend on the current font size.

  • % is also a relative unit, in this case, relative to either the height or width of a parent element. They are a good alternative to px units for things like the total width of a design if your design does not rely on specific pixel sizes to set its size.

    Using % units in your design allows your design to adapt to the width of the screen/device, whereas using an absolute unit such as px does not.

Stop handler.postDelayed()

You can define a boolean and change it to false when you want to stop handler. Like this..

boolean stop = false;

handler.postDelayed(new Runnable() {
    @Override
    public void run() {

        //do your work here..

        if (!stop) {
            handler.postDelayed(this, delay);
        }
    }
}, delay);

Powershell equivalent of bash ampersand (&) for forking/running background processes

As long as the command is an executable or a file that has an associated executable, use Start-Process (available from v2):

Start-Process -NoNewWindow ping google.com

You can also add this as a function in your profile:

function bg() {Start-Process -NoNewWindow @args}

and then the invocation becomes:

bg ping google.com

In my opinion, Start-Job is an overkill for the simple use case of running a process in the background:

  1. Start-Job does not have access to your existing scope (because it runs in a separate session). You cannot do "Start-Job {notepad $myfile}"
  2. Start-Job does not preserve the current directory (because it runs in a separate session). You cannot do "Start-Job {notepad myfile.txt}" where myfile.txt is in the current directory.
  3. The output is not displayed automatically. You need to run Receive-Job with the ID of the job as parameter.

NOTE: Regarding your initial example, "bg sleep 30" would not work because sleep is a Powershell commandlet. Start-Process only works when you actually fork a process.

How to generate classes from wsdl using Maven and wsimport?

Even though this is bit late response, may be helpful for someone. Look like you have used pluginManagement. If you use pluginManagement , it will not pick the plug-in execution.

It should be under

<build>
<plugins>           
        <plugin> 

Can I style an image's ALT text with CSS?

You can use img[alt] {styles} to style only the alternative text.

When is "java.io.IOException:Connection reset by peer" thrown?

java.io.IOException in Netty means your game server tries to send data to a client, but that client has closed connection to your server.

And that exception is not the only one! There're several others. See BadClientSilencer in Xitrum. I had to add that to prevent those errors from messing my log file.

Convert String to double in Java

Used this to convert any String number to double when u need int just convert the data type from num and num2 to int ; took all the cases for any string double with Eng:"Bader Qandeel"

public static double str2doubel(String str) {
    double num = 0;
    double num2 = 0;
    int idForDot = str.indexOf('.');
    boolean isNeg = false;
    String st;
    int start = 0;
    int end = str.length();

    if (idForDot != -1) {
        st = str.substring(0, idForDot);
        for (int i = str.length() - 1; i >= idForDot + 1; i--) {
            num2 = (num2 + str.charAt(i) - '0') / 10;
        }
    } else {
        st = str;
    }

    if (st.charAt(0) == '-') {
        isNeg = true;
        start++;
    } else if (st.charAt(0) == '+') {
        start++;
    }

    for (int i = start; i < st.length(); i++) {
        if (st.charAt(i) == ',') {
            continue;
        }
        num *= 10;
        num += st.charAt(i) - '0';
    }

    num = num + num2;
    if (isNeg) {
        num = -1 * num;
    }
    return num;
}

How can I SELECT multiple columns within a CASE WHEN on SQL Server?

No, CASE is a function, and can only return a single value. I think you are going to have to duplicate your CASE logic.

The other option would be to wrap the whole query with an IF and have two separate queries to return results. Without seeing the rest of the query, it's hard to say if that would work for you.

PRINT statement in T-SQL

For the benefit of anyone else reading this question that really is missing print statements from their output, there actually are cases where the print executes but is not returned to the client. I can't tell you specifically what they are. I can tell you that if put a go statement immediately before and after any print statement, you will see it if it is executed.

proper way to logout from a session in PHP

From the session_destroy() page in the PHP manual:

<?php
// Initialize the session.
// If you are using session_name("something"), don't forget it now!
session_start();

// Unset all of the session variables.
$_SESSION = array();

// If it's desired to kill the session, also delete the session cookie.
// Note: This will destroy the session, and not just the session data!
if (ini_get("session.use_cookies")) {
    $params = session_get_cookie_params();
    setcookie(session_name(), '', time() - 42000,
        $params["path"], $params["domain"],
        $params["secure"], $params["httponly"]
    );
}

// Finally, destroy the session.
session_destroy();
?>

How to fix "unable to open stdio.h in Turbo C" error?

Since you did not mention which version of Turbo C this method below will cover both v2 and v3.

  • Click on 'Options', 'Directories', enter the proper location for the Include and Lib directories.

How to program a fractal?

The mandelbrot set is generated by repeatedly evaluating a function until it overflows (some defined limit), then checking how long it took you to overflow.

Pseudocode:

MAX_COUNT = 64 // if we haven't escaped to infinity after 64 iterations, 
               // then we're inside the mandelbrot set!!!

foreach (x-pixel)
  foreach (y-pixel)
    calculate x,y as mathematical coordinates from your pixel coordinates
    value = (x, y)
    count = 0
    while value.absolutevalue < 1 billion and count < MAX_COUNT
        value = value * value + (x, y)
        count = count + 1

    // the following should really be one statement, but I split it for clarity
    if count == MAX_COUNT 
        pixel_at (x-pixel, y-pixel) = BLACK
    else 
        pixel_at (x-pixel, y-pixel) = colors[count] // some color map. 

Notes:

value is a complex number. a complex number (a+bi) is squared to give (aa-b*b+2*abi). You'll have to use a complex type, or include that calculation in your loop.

Adding a column after another column within SQL

Assuming MySQL (EDIT: posted before the SQL variant was supplied):

ALTER TABLE myTable ADD myNewColumn VARCHAR(255) AFTER myOtherColumn

The AFTER keyword tells MySQL where to place the new column. You can also use FIRST to flag the new column as the first column in the table.

How to create a simple proxy in C#?

For what it's worth, here is a C# sample async implementation based on HttpListener and HttpClient (I use it to be able to connect Chrome in Android devices to IIS Express, that's the only way I found...).

And If you need HTTPS support, it shouldn't require more code, just certificate configuration: Httplistener with HTTPS support

// define http://localhost:5000 and http://127.0.0.1:5000/ to be proxies for http://localhost:53068
using (var server = new ProxyServer("http://localhost:53068", "http://localhost:5000/", "http://127.0.0.1:5000/"))
{
    server.Start();
    Console.WriteLine("Press ESC to stop server.");
    while (true)
    {
        var key = Console.ReadKey(true);
        if (key.Key == ConsoleKey.Escape)
            break;
    }
    server.Stop();
}

....

public class ProxyServer : IDisposable
{
    private readonly HttpListener _listener;
    private readonly int _targetPort;
    private readonly string _targetHost;
    private static readonly HttpClient _client = new HttpClient();

    public ProxyServer(string targetUrl, params string[] prefixes)
        : this(new Uri(targetUrl), prefixes)
    {
    }

    public ProxyServer(Uri targetUrl, params string[] prefixes)
    {
        if (targetUrl == null)
            throw new ArgumentNullException(nameof(targetUrl));

        if (prefixes == null)
            throw new ArgumentNullException(nameof(prefixes));

        if (prefixes.Length == 0)
            throw new ArgumentException(null, nameof(prefixes));

        RewriteTargetInText = true;
        RewriteHost = true;
        RewriteReferer = true;
        TargetUrl = targetUrl;
        _targetHost = targetUrl.Host;
        _targetPort = targetUrl.Port;
        Prefixes = prefixes;

        _listener = new HttpListener();
        foreach (var prefix in prefixes)
        {
            _listener.Prefixes.Add(prefix);
        }
    }

    public Uri TargetUrl { get; }
    public string[] Prefixes { get; }
    public bool RewriteTargetInText { get; set; }
    public bool RewriteHost { get; set; }
    public bool RewriteReferer { get; set; } // this can have performance impact...

    public void Start()
    {
        _listener.Start();
        _listener.BeginGetContext(ProcessRequest, null);
    }

    private async void ProcessRequest(IAsyncResult result)
    {
        if (!_listener.IsListening)
            return;

        var ctx = _listener.EndGetContext(result);
        _listener.BeginGetContext(ProcessRequest, null);
        await ProcessRequest(ctx).ConfigureAwait(false);
    }

    protected virtual async Task ProcessRequest(HttpListenerContext context)
    {
        if (context == null)
            throw new ArgumentNullException(nameof(context));

        var url = TargetUrl.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
        using (var msg = new HttpRequestMessage(new HttpMethod(context.Request.HttpMethod), url + context.Request.RawUrl))
        {
            msg.Version = context.Request.ProtocolVersion;

            if (context.Request.HasEntityBody)
            {
                msg.Content = new StreamContent(context.Request.InputStream); // disposed with msg
            }

            string host = null;
            foreach (string headerName in context.Request.Headers)
            {
                var headerValue = context.Request.Headers[headerName];
                if (headerName == "Content-Length" && headerValue == "0") // useless plus don't send if we have no entity body
                    continue;

                bool contentHeader = false;
                switch (headerName)
                {
                    // some headers go to content...
                    case "Allow":
                    case "Content-Disposition":
                    case "Content-Encoding":
                    case "Content-Language":
                    case "Content-Length":
                    case "Content-Location":
                    case "Content-MD5":
                    case "Content-Range":
                    case "Content-Type":
                    case "Expires":
                    case "Last-Modified":
                        contentHeader = true;
                        break;

                    case "Referer":
                        if (RewriteReferer && Uri.TryCreate(headerValue, UriKind.Absolute, out var referer)) // if relative, don't handle
                        {
                            var builder = new UriBuilder(referer);
                            builder.Host = TargetUrl.Host;
                            builder.Port = TargetUrl.Port;
                            headerValue = builder.ToString();
                        }
                        break;

                    case "Host":
                        host = headerValue;
                        if (RewriteHost)
                        {
                            headerValue = TargetUrl.Host + ":" + TargetUrl.Port;
                        }
                        break;
                }

                if (contentHeader)
                {
                    msg.Content.Headers.Add(headerName, headerValue);
                }
                else
                {
                    msg.Headers.Add(headerName, headerValue);
                }
            }

            using (var response = await _client.SendAsync(msg).ConfigureAwait(false))
            {
                using (var os = context.Response.OutputStream)
                {
                    context.Response.ProtocolVersion = response.Version;
                    context.Response.StatusCode = (int)response.StatusCode;
                    context.Response.StatusDescription = response.ReasonPhrase;

                    foreach (var header in response.Headers)
                    {
                        context.Response.Headers.Add(header.Key, string.Join(", ", header.Value));
                    }

                    foreach (var header in response.Content.Headers)
                    {
                        if (header.Key == "Content-Length") // this will be set automatically at dispose time
                            continue;

                        context.Response.Headers.Add(header.Key, string.Join(", ", header.Value));
                    }

                    var ct = context.Response.ContentType;
                    if (RewriteTargetInText && host != null && ct != null &&
                        (ct.IndexOf("text/html", StringComparison.OrdinalIgnoreCase) >= 0 ||
                        ct.IndexOf("application/json", StringComparison.OrdinalIgnoreCase) >= 0))
                    {
                        using (var ms = new MemoryStream())
                        {
                            using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                            {
                                await stream.CopyToAsync(ms).ConfigureAwait(false);
                                var enc = context.Response.ContentEncoding ?? Encoding.UTF8;
                                var html = enc.GetString(ms.ToArray());
                                if (TryReplace(html, "//" + _targetHost + ":" + _targetPort + "/", "//" + host + "/", out var replaced))
                                {
                                    var bytes = enc.GetBytes(replaced);
                                    using (var ms2 = new MemoryStream(bytes))
                                    {
                                        ms2.Position = 0;
                                        await ms2.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);
                                    }
                                }
                                else
                                {
                                    ms.Position = 0;
                                    await ms.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);
                                }
                            }
                        }
                    }
                    else
                    {
                        using (var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false))
                        {
                            await stream.CopyToAsync(context.Response.OutputStream).ConfigureAwait(false);
                        }
                    }
                }
            }
        }
    }

    public void Stop() => _listener.Stop();
    public override string ToString() => string.Join(", ", Prefixes) + " => " + TargetUrl;
    public void Dispose() => ((IDisposable)_listener)?.Dispose();

    // out-of-the-box replace doesn't tell if something *was* replaced or not
    private static bool TryReplace(string input, string oldValue, string newValue, out string result)
    {
        if (string.IsNullOrEmpty(input) || string.IsNullOrEmpty(oldValue))
        {
            result = input;
            return false;
        }

        var oldLen = oldValue.Length;
        var sb = new StringBuilder(input.Length);
        bool changed = false;
        var offset = 0;
        for (int i = 0; i < input.Length; i++)
        {
            var c = input[i];

            if (offset > 0)
            {
                if (c == oldValue[offset])
                {
                    offset++;
                    if (oldLen == offset)
                    {
                        changed = true;
                        sb.Append(newValue);
                        offset = 0;
                    }
                    continue;
                }

                for (int j = 0; j < offset; j++)
                {
                    sb.Append(input[i - offset + j]);
                }

                sb.Append(c);
                offset = 0;
            }
            else
            {
                if (c == oldValue[0])
                {
                    if (oldLen == 1)
                    {
                        changed = true;
                        sb.Append(newValue);
                    }
                    else
                    {
                        offset = 1;
                    }
                    continue;
                }

                sb.Append(c);
            }
        }

        if (changed)
        {
            result = sb.ToString();
            return true;
        }

        result = input;
        return false;
    }
}

@POST in RESTful web service

REST webservice: (http://localhost:8080/your-app/rest/data/post)

package com.yourorg.rest;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST; 
import javax.ws.rs.Path; 
import javax.ws.rs.Produces; 
import javax.ws.rs.core.MediaType; 
import javax.ws.rs.core.Response;

    @Path("/data")
public class JSONService {

    @POST
    @Path("/post")
    @Consumes(MediaType.APPLICATION_JSON)
    public Response createDataInJSON(String data) { 

        String result = "Data post: "+data;

        return Response.status(201).entity(result).build(); 
    }

Client send a post:

package com.yourorg.client;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;

public class JerseyClientPost {

  public static void main(String[] args) {

    try {

        Client client = Client.create();

        WebResource webResource = client.resource("http://localhost:8080/your-app/rest/data/post");

        String input = "{\"message\":\"Hello\"}";

        ClientResponse response = webResource.type("application/json")
           .post(ClientResponse.class, input);

        if (response.getStatus() != 201) {
            throw new RuntimeException("Failed : HTTP error code : "
                 + response.getStatus());
        }

        System.out.println("Output from Server .... \n");
        String output = response.getEntity(String.class);
        System.out.println(output);

      } catch (Exception e) {

        e.printStackTrace();

      }

    }
}

BeautifulSoup Grab Visible Webpage Text

I completely respect using Beautiful Soup to get rendered content, but it may not be the ideal package for acquiring the rendered content on a page.

I had a similar problem to get rendered content, or the visible content in a typical browser. In particular I had many perhaps atypical cases to work with such a simple example below. In this case the non displayable tag is nested in a style tag, and is not visible in many browsers that I have checked. Other variations exist such as defining a class tag setting display to none. Then using this class for the div.

<html>
  <title>  Title here</title>

  <body>

    lots of text here <p> <br>
    <h1> even headings </h1>

    <style type="text/css"> 
        <div > this will not be visible </div> 
    </style>


  </body>

</html>

One solution posted above is:

html = Utilities.ReadFile('simple.html')
soup = BeautifulSoup.BeautifulSoup(html)
texts = soup.findAll(text=True)
visible_texts = filter(visible, texts)
print(visible_texts)


[u'\n', u'\n', u'\n\n        lots of text here ', u' ', u'\n', u' even headings ', u'\n', u' this will not be visible ', u'\n', u'\n']

This solution certainly has applications in many cases and does the job quite well generally but in the html posted above it retains the text that is not rendered. After searching SO a couple solutions came up here BeautifulSoup get_text does not strip all tags and JavaScript and here Rendered HTML to plain text using Python

I tried both these solutions: html2text and nltk.clean_html and was surprised by the timing results so thought they warranted an answer for posterity. Of course, the speeds highly depend on the contents of the data...

One answer here from @Helge was about using nltk of all things.

import nltk

%timeit nltk.clean_html(html)
was returning 153 us per loop

It worked really well to return a string with rendered html. This nltk module was faster than even html2text, though perhaps html2text is more robust.

betterHTML = html.decode(errors='ignore')
%timeit html2text.html2text(betterHTML)
%3.09 ms per loop

How to convert String to DOM Document object in java?

you can try

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));

Document doc = db.parse(is);

refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

C# ASP.NET Send Email via TLS

I was almost using the same technology as you did, however I was using my app to connect an Exchange Server via Office 365 platform on WinForms. I too had the same issue as you did, but was able to accomplish by using code which has slight modification of what others have given above.

SmtpClient client = new SmtpClient(exchangeServer, 587);
client.Credentials = new System.Net.NetworkCredential(username, password);
client.EnableSsl = true;
client.Send(msg);

I had to use the Port 587, which is of course the default port over TSL and the did the authentication.

Hour from DateTime? in 24 hours format

Try this, if your input is string 
For example 

string input= "13:01";
string[] arry = input.Split(':');                  
string timeinput = arry[0] + arry[1];
private string Convert24To12HourInEnglish(string timeinput)

 {

DateTime startTime = new DateTime(2018, 1, 1, int.Parse(timeinput.Substring(0, 2)), 
int.Parse(timeinput.Substring(2, 2)), 0); 
return startTime.ToString("hh:mm tt");

}
out put: 01:01

How can I make an EXE file from a Python program?

Auto PY to EXE - A .py to .exe converter using a simple graphical interface built using Eel and PyInstaller in Python.


py2exe is probably what you want, but it only works on Windows.
PyInstaller works on Windows and Linux.
Py2app works on the Mac.

How to redirect siteA to siteB with A or CNAME records

I think several of the answers hit around the possible solution to your problem.

I agree the easiest (and best solution for SEO purposes) is the 301 redirect. In IIS this is fairly trivial, you'd create a site for subdomain.hostone.com, after creating the site, right-click on the site and go into properties. Click on the "Home Directory" tab of the site properties window that opens. Select the radio button "A redirection to a URL", enter the url for the new site (http://subdomain.hosttwo.com), and check the checkboxes for "The exact URL entered above", "A permanent redirection for this resource" (this second checkbox causes a 301 redirect, instead of a 302 redirect). Click OK, and you're done.

Or you could create a page on the site of http://subdomain.hostone.com, using one of the following methods (depending on what the hosting platform supports)

PHP Redirect:


<?
Header( "HTTP/1.1 301 Moved Permanently" ); 
Header( "Location: http://subdomain.hosttwo.com" ); 
?>

ASP Redirect:


<%@ Language=VBScript %>
<%
Response.Status="301 Moved Permanently"
Response.AddHeader "Location","http://subdomain.hosttwo.com"
%>

ASP .NET Redirect:


<script runat="server">
private void Page_Load(object sender, System.EventArgs e)
{
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location","http://subdomain.hosttwo.com");
}
</script>

Now assuming your CNAME record is correctly created, then the only problem you are experiencing is that the site created for http://subdomain.hosttwo.com is using a shared IP, and host headers to determine which site should be displayed. To resolve this issue under IIS, in IIS Manager on the web server, you'd right-click on the site for subdomain.hosttwo.com, and click "Properties". On the displayed "Web Site" tab, you should see an "Advanced" button next to the IP address that you'll need to click. On the "Advanced Web Site Identification" window that appears, click "Add". Select the same IP address that is already being used by subdomain.hosttwo.com, enter 80 as the TCP port, and then enter subdomain.hosttwo.com as the Host Header value. Click OK until you are back to the main IIS Manager window, and you should be good to go. Open a browser, and browse to http://subdomain.hostone.com, and you'll see the site at http://subdomain.hosttwo.com appear, even though your URL shows http://subdomain.hostone.com

Hope that helps...

What is the difference between DAO and Repository patterns?

Repository are nothing but well-designed DAO.

ORM are table centric but not DAO.

There's no need to use several DAO in repository since DAO itself can do exactly the same with ORM repositories/entities or any DAL provider, no matter where and how a car is persisted 1 table, 2 tables, n tables, half a table, a web service, a table and a web service etc. Services uses several DAO/repositories.

My own DAO, let's say CarDao only deal with Car DTO,I mean, only take Car DTO in input and only return car DTO or car DTO collections in output.

So just like Repository, DAO actually is an IoC, for the business logic, allowing persitence interfaces not be be intimidated by persitence strategies or legacies. DAO both encapsulates the persistence strategy and does provide the domaine-related persitence interface. Repository is just an another word for those who had not understood what a well-defined DAO actualy was.

Ubuntu, how do you remove all Python 3 but not 2

Removing Python 3 was the worst thing I did since I recently moved to the world of Linux. It removed Firefox, my launcher and, as I read while trying to fix my problem, it may also remove your desktop and terminal! Finally fixed after a long daytime nightmare. Just don't remove Python 3. Keep it there!

If that happens to you, here is the fix:

https://askubuntu.com/q/384033/402539

https://askubuntu.com/q/810854/402539

What is the difference between Jupyter Notebook and JupyterLab?

To answer your question directly:

The single most important difference between the two is that you should start using JupyterLab straight away, and that you should not worry about Jupyter Notebook at all. Because:

JupyterLab will eventually replace the classic Jupyter Notebook. Throughout this transition, the same notebook document format will be supported by both the classic Notebook and JupyterLab

But you would also like to also know this:

Other posts have suggested that Jupyter Notebook (JN) could potentially be easier to use than JupyterLab (JL) for beginners. But I would have to disagree.

A great advantage with JL, and arguably one of the most important differences between JL and JN, is that you can more easily run a single line and even highlighted text. I prefer using a keyboard shortcut for this, and assigning shortcuts is pretty straight-forward.

And the fact that you can execute code in a Python console makes JL much more fun to work with. Other answers have already mentioned this, but JL can in some ways be considered a tool to run Notebooks and more. So the way I use JupyterLab is by having it set up with an .ipynb file, a file browser and a python console like this:

enter image description here

And now you have these tools at your disposal:

  1. View Files, running kernels, Commands, Notebook Tools, Open Tabs or Extension manager
  2. Run cells using, among other options, Ctrl+Enter
  3. Run single expression, line or highlighted text using menu options or keyboard shortcuts
  4. Run code directly in a console using Shift+Enter
  5. Inspect variables, dataframes or plots quickly and easily in a console without cluttering your notebook output.

How to loop through array in jQuery?

  for(var key in substr)
{
     // do something with substr[key];

} 

json_encode sparse PHP array as JSON array, not JSON object

Array in JSON are indexed array only, so the structure you're trying to get is not valid Json/Javascript.

PHP Associatives array are objects in JSON, so unless you don't need the index, you can't do such conversions.

If you want to get such structure you can do:

$indexedOnly = array();

foreach ($associative as $row) {
    $indexedOnly[] = array_values($row);
}

json_encode($indexedOnly);

Will returns something like:

[
     [0, "name1", "n1"],
     [1, "name2", "n2"],
]

how to re-format datetime string in php?

If you want to use substr(), you can easily add the dashes or slashes like this..

$datetime = "20130409163705"; 
$yyyy = substr($datetime,0,4);
$mm = substr($datetime,4,6);
$dd = substr($datetime,6,8);
$hh = substr($datetime,8,10);
$MM = substr($datetime,10,12);
$ss = substr($datetime,12,14);
$dt_formatted = $mm."/".$dd."/".$yyyy." ".$hh.":".$MM.":".$ss;

You can figure out any further formatting from that point.

What exactly is LLVM?

LLVM (used to mean "Low Level Virtual Machine" but not anymore) is a compiler infrastructure, written in C++, which is designed for compile-time, link-time, run-time, and "idle-time" optimization of programs written in arbitrary programming languages. Originally implemented for C/C++, the language-independent design (and the success) of LLVM has since spawned a wide variety of front-ends, including Objective C, Fortran, Ada, Haskell, Java bytecode, Python, Ruby, ActionScript, GLSL, and others.

Read this for more explanation
Also check out Unladen Swallow

git rm - fatal: pathspec did not match any files

In your case, use git filter-branch instead of git rm.

git rm will delete the files in the sense that they will not be tracked by git anymore, but that does not remove the old commit objects corresponding to those images, and so you will still be stuck with pushing the earlier commits which correspond to 12GB of images.

The git filter-branch, on the other hand, can remove those files from all the previous commits as well, thus doing away with the need to push any of them.

  1. Use the command

    git filter-branch --force --index-filter \
      'git rm -r --cached --ignore-unmatch public/photos' \
      --prune-empty --tag-name-filter cat -- --all
    
  2. After the filter branch is complete, verify that no unintended file was lost.

  3. Now add a .gitignore rule

    echo public/photos >> .gitignore
    git add .gitignore && git commit -m "ignore rule for photos"
    
  4. Now do a push

    git push -f origin branch
    

Check this, this and this for further help. Just to be on the safer side, I would suggest you create a backup copy of the repo on your system before going ahead with these instructions.

As for your orignial error message, it is happening because you already untracked them using git rm, and hence git is complaining because it can't remove a file it isn't tracking. Read more about this here.

Passing parameters to JavaScript files

Check out this URL. It is working perfectly for the requirement.

http://feather.elektrum.org/book/src.html

Thanks a lot to the author. For quick reference I pasted the main logic below:

var scripts = document.getElementsByTagName('script');
var myScript = scripts[ scripts.length - 1 ];

var queryString = myScript.src.replace(/^[^\?]+\??/,'');

var params = parseQuery( queryString );

function parseQuery ( query ) {
  var Params = new Object ();
  if ( ! query ) return Params; // return empty object
  var Pairs = query.split(/[;&]/);
  for ( var i = 0; i < Pairs.length; i++ ) {
    var KeyVal = Pairs[i].split('=');
    if ( ! KeyVal || KeyVal.length != 2 ) continue;
    var key = unescape( KeyVal[0] );
    var val = unescape( KeyVal[1] );
    val = val.replace(/\+/g, ' ');
    Params[key] = val;
  }
  return Params;
}

What are the applications of binary trees?

Nearly all database (and database-like) programs use a binary tree to implement their indexing systems.

Deleting an SVN branch

Sure: svn rm the unwanted folder, and commit.

To avoid this situation in the future, I would follow the recommended layout for SVN projects:

  • Put your code in the /someproject/trunk folder (or just /trunk if you want to put only one project in the repository)
  • Created branches as /someproject/branches/somebranch
  • Put tags under /someproject/tags

Now when you check out a working copy, be sure to check out only trunk or some individual branch. Don't check everything out in one huge working copy containing all branches.1

1Unless you know what you're doing, in which case you know how to create shallow working copies.

How to remove youtube branding after embedding video in web page?

It would be Better if you can use html5 video player or any other player (but not jwplayer) which can play youtube source video.

Below is an example source url of a video: https://redirector.googlevideo.com/videoplayback?requiressl=yes&id=a1385c04a9ecb45b&itag=22&source=picasa&cmo=secure_transport%3Dyes&ip=0.0.0.0&ipbits=0&expire=1440066674&sparams=requiressl%2Cid%2Citag%2Csource%2Cip%2Cipbits%2Cexpire&signature=86FE7D007A1DC990288890ED4EC7AA2D31A2ABF2.A0A23B872725261C457B67FD4757F3EB856AEE0E&key=lh1

Open this using simple html5 video player (Replace XXXXXX with source url or any downloadable url) :

    <video width="640" height="480" autoplay controls>
  <source src="XXXXXX" type="video/mp4">
 </video>

You can also use many other video players also.

PHP 7: Missing VCRUNTIME140.dll

Installing vc_redist.x86.exe works for me even though you have a 64-bit machine.

Twitter API returns error 215, Bad Authentication Data

This might help someone who use Zend_Oauth_Client to work with twitter api. This working config:

$accessToken = new Zend_Oauth_Token_Access();
$accessToken->setToken('accessToken');
$accessToken->setTokenSecret('accessTokenSecret');

$client = $accessToken->getHttpClient(array(
    'requestScheme' => Zend_Oauth::REQUEST_SCHEME_HEADER,
    'version' => '1.0', // it was 1.1 and I got 215 error.
    'signatureMethod' => 'HMAC-SHA1',
    'consumerKey' => 'foo',
    'consumerSecret' => 'bar',
    'requestTokenUrl' => 'https://api.twitter.com/oauth/request_token',
    'authorizeUrl' => 'https://api.twitter.com/oauth/authorize',
    'accessTokenUrl' => 'https://api.twitter.com/oauth/access_token',
    'timeout' => 30
));

It look like twitter api 1.0 allows oauth version to be 1.1 and 1.0, where twitter api 1.1 require only oauth version to be 1.0.

P.S We do not use Zend_Service_Twitter as it does not allow send custom params on status update.

How can I get enum possible values in a MySQL database?

MySQL Reference

If you want to determine all possible values for an ENUM column, use SHOW COLUMNS FROM tbl_name LIKE enum_col and parse the ENUM definition in the Type column of the output.

You would want something like:

$sql = "SHOW COLUMNS FROM `table` LIKE 'column'";
$result = $db->query($sql);
$row = $result->fetchRow();
$type = $row['Type'];
preg_match('/enum\((.*)\)$/', $type, $matches);
$vals = explode(',', $matches[1]);

This will give you the quoted values. MySQL always returns these enclosed in single quotes. A single quote in the value is escaped by a single quote. You can probably safely call trim($val, "'") on each of the array elements. You'll want to convert '' into just '.

The following will return $trimmedvals array items without quotes:

$trimmedvals = array();
foreach($vals as $key => $value) {
$value=trim($value, "'");
$trimmedvals[] = $value;
}

What's the best way to calculate the size of a directory in .NET?

public static long GetDirSize(string path)
{
    try
    {
        return Directory.EnumerateFiles(path).Sum(x => new FileInfo(x).Length)  
            +
               Directory.EnumerateDirectories(path).Sum(x => GetDirSize(x));
    }
    catch
    {
        return 0L;
    }
}

Sum rows in data.frame or matrix

you can use rowSums

rowSums(data) should give you what you want.

How to start nginx via different port(other than 80)

If you are on windows then below port related server settings are present in file nginx.conf at < nginx installation path >/conf folder.

server {
    listen       80;
    server_name  localhost;
....

Change the port number and restart the instance.

Swift: Reload a View Controller

If you are using a navigation controller you can segue again to the current UIViewController and it will be refreshed. Here I use a UIButton for refreshing

JQuery select2 set default value from an option in list?

For ajax select2 multiple select dropdown i did like this;

  //preset element values
  //topics is an array of format [{"id":"","text":""}, .....]
        $(id).val(topics);
          setTimeout(function(){
           ajaxTopicDropdown(id,
                2,location.origin+"/api for gettings topics/",
                "Pick a topic", true, 5);                      
            },1);
        // ajaxtopicDropdown is dry fucntion to get topics for diffrent element and url

How to list active / open connections in Oracle?

select status, count(1) as connectionCount from V$SESSION group by status;

Caused by: org.flywaydb.core.api.FlywayException: Validate failed. Migration Checksum mismatch for migration 2

use this query in your local DB.

  1. select * from schema_version delete from schema_version where checksum Column = -1729781252;

    Note: -1729781252 is the "Resolved locally" value.

  2. Build and start the server.

Get mouse wheel events in jQuery?

I was stuck in this issue today and found this code is working fine for me

$('#content').on('mousewheel', function(event) {
    //console.log(event.deltaX, event.deltaY, event.deltaFactor);
    if(event.deltaY > 0) {
      console.log('scroll up');
    } else {
      console.log('scroll down');
    }
});

Adding images to an HTML document with javascript

With a little research i found that javascript does not know that a Document Object Exist unless the Object has Already loaded before the script code (As javascript reads down a page).

<head>
    <script type="text/javascript">
        function insert(){
            var src = document.getElementById("gamediv");
            var img = document.createElement("img");
            img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
            src.appendChild(img);
        }
     </script>
 </head>
 <body>
     <div id="gamediv">
         <script type="text/javascript">
             insert();
         </script>
     </div>
 </body>

Play sound on button click android

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {
    MediaPlayer mp;
    Button one;

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

        mp = MediaPlayer.create(this, R.raw.soho);
        one = (Button)this.findViewById(R.id.button1);

        one.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                mp.start();
            }
        });
    }
}

sql server #region

I've used a technique similar to McVitie's, and only in stored procedures or scripts that are pretty long. I will break down certain functional portions like this:

BEGIN /** delete queries **/

DELETE FROM blah_blah

END /** delete queries **/

BEGIN /** update queries **/

UPDATE sometable SET something = 1

END /** update queries **/

This method shows up fairly nice in management studio and is really helpful in reviewing code. The collapsed piece looks sort of like:

BEGIN /** delete queries **/ ... /** delete queries **/

I actually prefer it this way because I know that my BEGIN matches with the END this way.

How can I tell where mongoDB is storing data? (its not in the default /data/db!)

Actually, the default directory where the mongod instance stores its data is

/data/db on Linux and OS X,

\data\db on Windows

To check the same, you can look for dbPath settings in mongodb configuration file.

  • On Linux, the location is /etc/mongod.conf, if you have used package manager to install MongoDB. Run the following command to check the specified directory:
    grep dbpath /etc/mongodb.conf
    
  • On Windows, the location is <install directory>/bin/mongod.cfg. Open mongod.cfg file and check for dbPath option.
  • On macOS, the location is /usr/local/etc/mongod.conf when installing from MongoDB’s official Homebrew tap.

The default mongod.conf configuration file included with package manager installations uses the following platform-specific default values for storage.dbPath:

+--------------------------+-----------------+------------------------+
|         Platform         | Package Manager | Default storage.dbPath |
+--------------------------+-----------------+------------------------+
| RHEL / CentOS and Amazon | yum             | /var/lib/mongo         |
| SUSE                     | zypper          | /var/lib/mongo         |
| Ubuntu and Debian        | apt             | /var/lib/mongodb       |
| macOS                    | brew            | /usr/local/var/mongodb |
+--------------------------+-----------------+------------------------+

The storage.dbPath setting in the configuration file is available only for mongod.

The Linux package init scripts do not expect storage.dbPath to change from the defaults. If you use the Linux packages and change storage.dbPath, you will have to use your own init scripts and disable the built-in scripts.

Source

The given key was not present in the dictionary. Which key?

string Value = dic.ContainsKey("Name") ? dic["Name"] : "Required Name"

With this code, we will get string data in 'Value'. If key 'Name' exists in the dictionary 'dic' then fetch this value, else returns "Required Name" string.

RandomForestClassfier.fit(): ValueError: could not convert string to float

LabelEncoding worked for me (basically you've to encode your data feature-wise) (mydata is a 2d array of string datatype):

myData=np.genfromtxt(filecsv, delimiter=",", dtype ="|a20" ,skip_header=1);

from sklearn import preprocessing
le = preprocessing.LabelEncoder()
for i in range(*NUMBER OF FEATURES*):
    myData[:,i] = le.fit_transform(myData[:,i])

How to pass an array into a function, and return the results with an array

I always return multiple values by using a combination of list() and array()s:

function DecideStuffToReturn() {
    $IsValid = true;
    $AnswerToLife = 42;

    // Build the return array.
    return array($IsValid, $AnswerToLife);
}

// Part out the return array in to multiple variables.
list($IsValid, $AnswerToLife) = DecideStuffToReturn();

You can name them whatever you like. I chose to keep the function variables and the return variables the same for consistency but you can call them whatever you like.

See list() for more information.

Text overwrite in visual studio 2010

Ran into this issue with Parallels and VS 2013. Command + Insert also fixed it in my setup, in addition to the accepted answer. On my Windows USB keyboard Command == WindowsKey.

PHP strtotime +1 month adding an extra month

It's jumping to March because today is 29th Jan, and adding a month gives 29th Feb, which doesn't exist, so it's moving to the next valid date.

This will happen on the 31st of a lot of months as well, but is obviously more noticable in the case of January to Feburary because Feb is shorter.

If you're not interested in the day of month and just want it to give the next month, you should specify the input date as the first of the current month. This will always give you the correct answer if you add a month.

For the same reason, if you want to always get the last day of the next month, you should start by calculating the first of the month after the one you want, and subtracting a day.

Iterate through the fields of a struct in Go

Maybe too late :))) but there is another solution that you can find the key and value of structs and iterate over that

package main

import (
    "fmt"
    "reflect"
)

type person struct {
    firsName string
    lastName string
    iceCream []string
}

func main() {
    u := struct {
        myMap    map[int]int
        mySlice  []string
        myPerson person
    }{
        myMap:   map[int]int{1: 10, 2: 20},
        mySlice: []string{"red", "green"},
        myPerson: person{
            firsName: "Esmaeil",
            lastName: "Abedi",
            iceCream: []string{"Vanilla", "chocolate"},
        },
    }
    v := reflect.ValueOf(u)
    for i := 0; i < v.NumField(); i++ {
        fmt.Println(v.Type().Field(i).Name)
        fmt.Println("\t", v.Field(i))
    }
}
and there is no *panic* for v.Field(i)

Eclipse: Set maximum line length for auto formatting?

Click Project->preferences. Type format into the search - you should see java->code style->formatter. Click that, then edit - finally, the line wrapping tab - its there :)

how can I login anonymously with ftp (/usr/bin/ftp)?

Anonymous ftp logins are usually the username 'anonymous' with the user's email address as the password. Some servers parse the password to ensure it looks like an email address.

User:  anonymous
Password:  [email protected]

Black transparent overlay on image hover with only CSS?

You were close. This will work:

.image { position: relative; border: 1px solid black; width: 200px; height: 200px; }
.image img { max-width: 100%; max-height: 100%; }
.overlay { position: absolute; top: 0; left: 0; right:0; bottom:0; display: none; background-color: rgba(0,0,0,0.5); }
.image:hover .overlay { display: block; }

You needed to put the :hover on image, and make the .overlay cover the whole image by adding right:0; and bottom:0.

jsfiddle: http://jsfiddle.net/Zf5am/569/

When does Git refresh the list of remote branches?

Use git fetch to fetch all latest created branches.

DbEntityValidationException - How can I easily tell what caused the error?

Use try block in your code like

try
{
    // Your code...
    // Could also be before try if you know the exception occurs in SaveChanges

    context.SaveChanges();
}
catch (DbEntityValidationException e)
{
    foreach (var eve in e.EntityValidationErrors)
    {
        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
            eve.Entry.Entity.GetType().Name, eve.Entry.State);
        foreach (var ve in eve.ValidationErrors)
        {
            Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                ve.PropertyName, ve.ErrorMessage);
        }
    }
    throw;
}

You can check the details here as well

  1. http://mattrandle.me/viewing-entityvalidationerrors-in-visual-studio/

  2. Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

  3. http://blogs.infosupport.com/improving-dbentityvalidationexception/

$http.get(...).success is not a function

The .success syntax was correct up to Angular v1.4.3.

For versions up to Angular v.1.6, you have to use then method. The then() method takes two arguments: a success and an error callback which will be called with a response object.

Using the then() method, attach a callback function to the returned promise.

Something like this:

app.controller('MainCtrl', function ($scope, $http){
   $http({
      method: 'GET',
      url: 'api/url-api'
   }).then(function (response){

   },function (error){

   });
}

See reference here.

Shortcut methods are also available.

$http.get('api/url-api').then(successCallback, errorCallback);

function successCallback(response){
    //success code
}
function errorCallback(error){
    //error code
}

The data you get from the response is expected to be in JSON format. JSON is a great way of transporting data, and it is easy to use within AngularJS

The major difference between the 2 is that .then() call returns a promise (resolved with a value returned from a callback) while .success() is more traditional way of registering callbacks and doesn't return a promise.

Styling every 3rd item of a list using CSS?

:nth-child is the answer you are looking for.

Setting Authorization Header of HttpClient

I suggest to you:

HttpClient.DefaultRequestHeaders.Add("Authorization", "Bearer <token>");

And then you can use it like that:

var response = await client.GetAsync(url);
if (response.IsSuccessStatusCode)
{
    responseMessage = await response.Content.ReadAsAsync<ResponseMessage>();
}

Log4Net configuring log level

Use threshold.

For example:

   <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
        <threshold value="WARN"/>
        <param name="File" value="File.log" />
        <param name="AppendToFile" value="true" />
        <param name="RollingStyle" value="Size" />
        <param name="MaxSizeRollBackups" value="10" />
        <param name="MaximumFileSize" value="1024KB" />
        <param name="StaticLogFileName" value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <param name="Header" value="[Server startup]&#13;&#10;" />
            <param name="Footer" value="[Server shutdown]&#13;&#10;" />
            <param name="ConversionPattern" value="%d %m%n" />
        </layout>
    </appender>
    <appender name="EventLogAppender" type="log4net.Appender.EventLogAppender" >
        <threshold value="ERROR"/>
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread]- %message%newline" />
        </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
        <threshold value="INFO"/>
        <layout type="log4net.Layout.PatternLayout">
            <param name="ConversionPattern" value="%d [%thread] %m%n" />
        </layout>
    </appender>

In this example all INFO and above are sent to Console, all WARN are sent to file and ERRORs are sent to the Event-Log.

Android open camera from button

public class camera_act extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera_act);
         ImageView imageView = findViewById(R.id.image);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(intent,90);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode,resultCode,data);
       Bitmap bitmap = data.getExtras.get("imageKey");
       imageView.setBitmapImage(bitmap);
            
        }
    }
}

How does one remove a Docker image?

docker rm container_name

docker rmi image_name

docker help

rm Remove one or more containers

rmi Remove one or more images

Default SecurityProtocol in .NET 4.5

I got the problem when my customer upgraded TLS from 1.0 to 1.2. My application is using .net framework 3.5 and run on server. So i fixed it by this way:

  1. Fix the program

Before call HttpWebRequest.GetResponse() add this command:

ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolTypeExtensions.Tls11 | SecurityProtocolTypeExtensions.Tls12;

Extensions 2 DLLs by adding 2 new classes: System.Net and System.Security.Authentication

    namespace System.Net
    {
        using System.Security.Authentication;
        public static class SecurityProtocolTypeExtensions
        {
            public const SecurityProtocolType Tls12 = (SecurityProtocolType)SslProtocolsExtensions.Tls12;
            public const SecurityProtocolType Tls11 = (SecurityProtocolType)SslProtocolsExtensions.Tls11;
            public const SecurityProtocolType SystemDefault = (SecurityProtocolType)0;
        }
    } 

    namespace System.Security.Authentication
    {
        public static class SslProtocolsExtensions
        {
            public const SslProtocols Tls12 = (SslProtocols)0x00000C00;
            public const SslProtocols Tls11 = (SslProtocols)0x00000300;
        }
    } 
  1. Update Microsoft batch

Download batch:

  • For windows 2008 R2: windows6.1-kb3154518-x64.msu
  • For windows 2012 R2: windows8.1-kb3154520-x64.msu

For download batch and more details you can see here:

https://support.microsoft.com/en-us/help/3154518/support-for-tls-system-default-versions-included-in-the-.net-framework-3.5.1-on-windows-7-sp1-and-server-2008-r2-sp1

How to Set Focus on Input Field using JQuery

Justin's answer did not work for me (Chromium 18, Firefox 43.0.1). jQuery's .focus() creates visual highlight, but text cursor does not appear in the field (jquery 3.1.0).

Inspired by https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ , I added autofocus attribute to the input field and voila!

function addfield() {
    n=$('table tr').length;
    $('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');
    $('input[name="aa"'+n+']').focus();
}

How to set top-left alignment for UILabel for iOS application?

If what you need is non-editable text that by default starts at the top left corner you can simply use a Text View instead of a label and then set its state to non-editable, like this:

textview.isEditable = false

Way easier than messing with the labels...

Cheers!

Declare a constant array

From Effective Go:

Constants in Go are just that—constant. They are created at compile time, even when defined as locals in functions, and can only be numbers, characters (runes), strings or booleans. Because of the compile-time restriction, the expressions that define them must be constant expressions, evaluatable by the compiler. For instance, 1<<3 is a constant expression, while math.Sin(math.Pi/4) is not because the function call to math.Sin needs to happen at run time.

Slices and arrays are always evaluated during runtime:

var TestSlice = []float32 {.03, .02}
var TestArray = [2]float32 {.03, .02}
var TestArray2 = [...]float32 {.03, .02}

[...] tells the compiler to figure out the length of the array itself. Slices wrap arrays and are easier to work with in most cases. Instead of using constants, just make the variables unaccessible to other packages by using a lower case first letter:

var ThisIsPublic = [2]float32 {.03, .02}
var thisIsPrivate = [2]float32 {.03, .02}

thisIsPrivate is available only in the package it is defined. If you need read access from outside, you can write a simple getter function (see Getters in golang).

Importing large sql file to MySql via command line

The solution I use for large sql restore is a mysqldumpsplitter script. I split my sql.gz into individual tables. then load up something like mysql workbench and process it as a restore to the desired schema.

Here is the script https://github.com/kedarvj/mysqldumpsplitter

And this works for larger sql restores, my average on one site I work with is a 2.5gb sql.gz file, 20GB uncompressed, and ~100Gb once restored fully

How to load all modules in a folder?

Look at the pkgutil module from the standard library. It will let you do exactly what you want as long as you have an __init__.py file in the directory. The __init__.py file can be empty.

What's the difference between a Python module and a Python package?

Any Python file is a module, its name being the file's base name without the .py extension. A package is a collection of Python modules: while a module is a single Python file, a package is a directory of Python modules containing an additional __init__.py file, to distinguish a package from a directory that just happens to contain a bunch of Python scripts. Packages can be nested to any depth, provided that the corresponding directories contain their own __init__.py file.

The distinction between module and package seems to hold just at the file system level. When you import a module or a package, the corresponding object created by Python is always of type module. Note, however, when you import a package, only variables/functions/classes in the __init__.py file of that package are directly visible, not sub-packages or modules. As an example, consider the xml package in the Python standard library: its xml directory contains an __init__.py file and four sub-directories; the sub-directory etree contains an __init__.py file and, among others, an ElementTree.py file. See what happens when you try to interactively import package/modules:

>>> import xml
>>> type(xml)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'etree'
>>> import xml.etree
>>> type(xml.etree)
<type 'module'>
>>> xml.etree.ElementTree
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'ElementTree'
>>> import xml.etree.ElementTree
>>> type(xml.etree.ElementTree)
<type 'module'>
>>> xml.etree.ElementTree.parse
<function parse at 0x00B135B0>

In Python there also are built-in modules, such as sys, that are written in C, but I don't think you meant to consider those in your question.

Hex colors: Numeric representation for "transparent"?

Transparency is a property outside the color itself, also known as alpha component. You can't code it as RGB.

If you want a transparent background, you can do this:

background: transparent;

Additionally, I don't know if it might be helpful or not but, you could set the opacity property:

.half{
  opacity: 0.5;
  filter: alpha(opacity=50);
}

You need both in order to get it working in IE and all other decent browsers.

How can I find out if I have Xcode commandline tools installed?

I was able to find my version of Xcode on maxOS Sierra using this command:

pkgutil --pkg-info=com.apple.pkg.CLTools_Executables | grep version

as per this answer.

How to read barcodes with the camera on Android?

Here is a sample code: my app uses ZXing Barcode Scanner.

  1. You need these 2 classes: IntentIntegrator and IntentResult

  2. Call scanner (e.g. OnClickListener, OnMenuItemSelected...), "PRODUCT_MODE" - it scans standard 1D barcodes (you can add more).:

    IntentIntegrator.initiateScan(this, 
               "Warning", 
               "ZXing Barcode Scanner is not installed, download?",
               "Yes", "No",
               "PRODUCT_MODE");
    
  3. Get barcode as a result:

    public void onActivityResult(int requestCode, int resultCode, Intent intent) {  
      switch (requestCode) {
      case IntentIntegrator.REQUEST_CODE:
         if (resultCode == Activity.RESULT_OK) {
    
            IntentResult intentResult = 
               IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
    
            if (intentResult != null) {
    
               String contents = intentResult.getContents();
               String format = intentResult.getFormatName();
    
               this.elemQuery.setText(contents);
               this.resume = false;
               Log.d("SEARCH_EAN", "OK, EAN: " + contents + ", FORMAT: " + format);
            } else {
               Log.e("SEARCH_EAN", "IntentResult je NULL!");
            }
         } else if (resultCode == Activity.RESULT_CANCELED) {
            Log.e("SEARCH_EAN", "CANCEL");
         }
      }
    }
    

contents holds barcode number

Should I call Close() or Dispose() for stream objects?

A quick jump into Reflector.NET shows that the Close() method on StreamWriter is:

public override void Close()
{
    this.Dispose(true);
    GC.SuppressFinalize(this);
}

And StreamReader is:

public override void Close()
{
    this.Dispose(true);
}

The Dispose(bool disposing) override in StreamReader is:

protected override void Dispose(bool disposing)
{
    try
    {
        if ((this.Closable && disposing) && (this.stream != null))
        {
            this.stream.Close();
        }
    }
    finally
    {
        if (this.Closable && (this.stream != null))
        {
            this.stream = null;
            /* deleted for brevity */
            base.Dispose(disposing);
        }
    }
}

The StreamWriter method is similar.

So, reading the code it is clear that that you can call Close() & Dispose() on streams as often as you like and in any order. It won't change the behaviour in any way.

So it comes down to whether or not it is more readable to use Dispose(), Close() and/or using ( ... ) { ... }.

My personal preference is that using ( ... ) { ... } should always be used when possible as it helps you to "not run with scissors".

But, while this helps correctness, it does reduce readability. In C# we already have plethora of closing curly braces so how do we know which one actually performs the close on the stream?

So I think it is best to do this:

using (var stream = ...)
{
    /* code */

    stream.Close();
}

It doesn't affect the behaviour of the code, but it does aid readability.

Handling InterruptedException in Java

As it happens I was just reading about this this morning on my way to work in Java Concurrency In Practice by Brian Goetz. Basically he says you should do one of three things

  1. Propagate the InterruptedException - Declare your method to throw the checked InterruptedException so that your caller has to deal with it.

  2. Restore the Interrupt - Sometimes you cannot throw InterruptedException. In these cases you should catch the InterruptedException and restore the interrupt status by calling the interrupt() method on the currentThread so the code higher up the call stack can see that an interrupt was issued, and quickly return from the method. Note: this is only applicable when your method has "try" or "best effort" semantics, i. e. nothing critical would happen if the method doesn't accomplish its goal. For example, log() or sendMetric() may be such method, or boolean tryTransferMoney(), but not void transferMoney(). See here for more details.

  3. Ignore the interruption within method, but restore the status upon exit - e. g. via Guava's Uninterruptibles. Uninterruptibles take over the boilerplate code like in the Noncancelable Task example in JCIP § 7.1.3.

'git status' shows changed files, but 'git diff' doesn't

git diff -a treats all file as text and it works for me.

How to store JSON object in SQLite database

https://github.com/requery/sqlite-android allows you to query JSON fields (and arrays in them, I've tried it and am using it). Before that I was just storing JSON strings into a TEXT column. It supports FTS3, FTS4, & JSON1

As of July 2019, it still gets version bumps every now and then, so it isn't a dead project.

Should import statements always be at the top of a module?

Curt makes a good point: the second version is clearer and will fail at load time rather than later, and unexpectedly.

Normally I don't worry about the efficiency of loading modules, since it's (a) pretty fast, and (b) mostly only happens at startup.

If you have to load heavyweight modules at unexpected times, it probably makes more sense to load them dynamically with the __import__ function, and be sure to catch ImportError exceptions, and handle them in a reasonable manner.

SELECT *, COUNT(*) in SQLite

If you want to count the number of records in your table, simply run:

    SELECT COUNT(*) FROM your_table;

Where is SQLite database stored on disk?

If you are running Rails (its the default db in Rails) check the {RAILS_ROOT}/config/database.yml file and you will see something like:

database: db/development.sqlite3

This means that it will be in the {RAILS_ROOT}/db directory.

How can I change the image of an ImageView?

if (android.os.Build.VERSION.SDK_INT >= 21) {
            storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position], context.getTheme()));
} else {
            storeViewHolder.storeNameTextView.setImageDrawable(context.getResources().getDrawable(array[position]));
}

How can I run a directive after the dom has finished rendering?

Here is how I do it:

app.directive('example', function() {

    return function(scope, element, attrs) {
        angular.element(document).ready(function() {
                //MANIPULATE THE DOM
        });
    };

});

How to add subject alernative name to ssl certs?

When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR

keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com

complete example here: How to create CSR with SANs using keytool

missing private key in the distribution certificate on keychain

To add on to others' answers, if you don't have access to that private key anymore it's fairly simple to get back up and running:

  1. revoke your active certificate in the provisioning portal
  2. create new developer certificate (keychain access/.../request for csr...etc.)
  3. download and install a new certificate
  4. create a new provisioning profile for existing app id (on provisioning portal)
  5. download and install new provisioning profile and in the build, settings set the appropriate code signing identities

White space at top of page

This particular answer shows that h1 elements have an implicit margin-top that can cause the whitespace

https://stackoverflow.com/a/20021854/2129219

The suggestion to remove it is helpful, and certainly eye opening to how this is happening

h1 { margin-top: 0; }

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

How to concatenate two IEnumerable<T> into a new IEnumerable<T>?

The Concat method will return an object which implements IEnumerable<T> by returning an object (call it Cat) whose enumerator will attempt to use the two passed-in enumerable items (call them A and B) in sequence. If the passed-in enumerables represent sequences which will not change during the lifetime of Cat, and which can be read from without side-effects, then Cat may be used directly. Otherwise, it may be a good idea to call ToList() on Cat and use the resulting List<T> (which will represent a snapshot of the contents of A and B).

Some enumerables take a snapshot when enumeration begins, and will return data from that snapshot if the collection is modified during enumeration. If B is such an enumerable, then any change to B which occurs before Cat has reached the end of A will show up in Cat's enumeration, but changes which occur after that will not. Such semantics may likely be confusing; taking a snapshot of Cat can avoid such issues.

How to specify function types for void (not Void) methods in Java8?

You are trying to use the wrong interface type. The type Function is not appropriate in this case because it receives a parameter and has a return value. Instead you should use Consumer (formerly known as Block)

The Function type is declared as

interface Function<T,R> {
  R apply(T t);
}

However, the Consumer type is compatible with that you are looking for:

interface Consumer<T> {
   void accept(T t);
}

As such, Consumer is compatible with methods that receive a T and return nothing (void). And this is what you want.

For instance, if I wanted to display all element in a list I could simply create a consumer for that with a lambda expression:

List<String> allJedi = asList("Luke","Obiwan","Quigon");
allJedi.forEach( jedi -> System.out.println(jedi) );

You can see above that in this case, the lambda expression receives a parameter and has no return value.

Now, if I wanted to use a method reference instead of a lambda expression to create a consume of this type, then I need a method that receives a String and returns void, right?.

I could use different types of method references, but in this case let's take advantage of an object method reference by using the println method in the System.out object, like this:

Consumer<String> block = System.out::println

Or I could simply do

allJedi.forEach(System.out::println);

The println method is appropriate because it receives a value and has a return type void, just like the accept method in Consumer.

So, in your code, you need to change your method signature to somewhat like:

public static void myForEach(List<Integer> list, Consumer<Integer> myBlock) {
   list.forEach(myBlock);
}

And then you should be able to create a consumer, using a static method reference, in your case by doing:

myForEach(theList, Test::displayInt);

Ultimately, you could even get rid of your myForEach method altogether and simply do:

theList.forEach(Test::displayInt);

About Functions as First Class Citizens

All been said, the truth is that Java 8 will not have functions as first-class citizens since a structural function type will not be added to the language. Java will simply offer an alternative way to create implementations of functional interfaces out of lambda expressions and method references. Ultimately lambda expressions and method references will be bound to object references, therefore all we have is objects as first-class citizens. The important thing is the functionality is there since we can pass objects as parameters, bound them to variable references and return them as values from other methods, then they pretty much serve a similar purpose.

Button Center CSS

Another nice option is to use :

width: 40%;
margin-left: 30%;
margin-right: 30%

Is there a built-in function to print all the current properties and values of an object?

You can try the Flask Debug Toolbar.
https://pypi.python.org/pypi/Flask-DebugToolbar

from flask import Flask
from flask_debugtoolbar import DebugToolbarExtension

app = Flask(__name__)

# the toolbar is only enabled in debug mode:
app.debug = True

# set a 'SECRET_KEY' to enable the Flask session cookies
app.config['SECRET_KEY'] = '<replace with a secret key>'

toolbar = DebugToolbarExtension(app)

How to echo text during SQL script execution in SQLPLUS

You can use SET ECHO ON in the beginning of your script to achieve that, however, you have to specify your script using @ instead of < (also had to add EXIT at the end):

test.sql

SET ECHO ON

SELECT COUNT(1) FROM dual;

SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

EXIT

terminal

sqlplus hr/oracle@orcl @/tmp/test.sql > /tmp/test.log

test.log

SQL> 
SQL> SELECT COUNT(1) FROM dual;

  COUNT(1)
----------
     1

SQL> 
SQL> SELECT COUNT(1) FROM (SELECT 1 FROM dual UNION SELECT 2 FROM dual);

  COUNT(1)
----------
     2

SQL> 
SQL> EXIT

Big-oh vs big-theta

Because there are algorithms whose best-case is quick, and thus it's technically a big O, not a big Theta.

Big O is an upper bound, big Theta is an equivalence relation.

Angular - "has no exported member 'Observable'"

This might be helpful in Angular 6 for more info refer this Document

  1. rxjs: Creation methods, types, schedulers and utilities
import { Observable, Subject, asapScheduler, pipe, of, from, interval, merge, fromEvent } from 'rxjs';
  1. rxjs/operators: All pipeable operators:
import { map, filter, scan } from 'rxjs/operators';
  1. rxjs/webSocket: The web socket subject implementation
import { webSocket } from 'rxjs/webSocket';
  1. rxjs/ajax: The Rx ajax implementation
import { ajax } from 'rxjs/ajax';
  1. rxjs/testing: The testing utilities
import { TestScheduler } from 'rxjs/testing';

Java : Accessing a class within a package, which is the better way?

As already said, on runtime there is no difference (in the class file it is always fully qualified, and after loading and linking the class there are direct pointers to the referred method), and everything in the java.lang package is automatically imported, as is everything in the current package.

The compiler might have to search some microseconds longer, but this should not be a reason - decide for legibility for human readers.

By the way, if you are using lots of static methods (from Math, for example), you could also write

import static java.lang.Math.*;

and then use

sqrt(x)

directly. But only do this if your class is math heavy and it really helps legibility of bigger formulas, since the reader (as the compiler) first would search in the same class and maybe in superclasses, too. (This applies analogously for other static methods and static variables (or constants), too.)

Detect whether a Python string is a number or a letter

For a string of length 1 you can simply perform isdigit() or isalpha()

If your string length is greater than 1, you can make a function something like..

def isinteger(a):
    try:
        int(a)
        return True
    except ValueError:
        return False

How to run a specific Android app using Terminal?

I keep this build-and-run script handy, whenever I am working from command line:

#!/usr/bin/env bash

PACKAGE=com.example.demo
ACTIVITY=.MainActivity
APK_LOCATION=app/build/outputs/apk/app-debug.apk
echo "Package: $PACKAGE"

echo "Building the project with tasks: $TASKS"
./gradlew $TASKS

echo "Uninstalling $PACKAGE"
adb uninstall $PACKAGE

echo "Installing $APK_LOCATION"
adb install $APK_LOCATION

echo "Starting $ACTIVITY"
adb shell am start -n $PACKAGE/$ACTIVITY

How can I change CSS display none or block property using jQuery?

In my case I was doing show / hide elements of a form according to whether an input element was empty or not, so that when hiding the elements the element following the hidden ones was repositioned occupying its space it was necessary to do a float: left of the element of such an element. Even using a plugin as dependsOn it was necessary to use float.

Delete all rows in an HTML table

this is a simple code I just wrote to solve this, without removing the header row (first one).

var Tbl = document.getElementById('tblId');
while(Tbl.childNodes.length>2){Tbl.removeChild(Tbl.lastChild);}

Hope it works for you!!.

How to write the Fibonacci Sequence?

15 minutes into a tutorial I used when learning Python, it asked the reader to write a program that would calculate a Fibonacci sequence from 3 input numbers (first Fibonacci number, second number, and number at which to stop the sequence). The tutorial had only covered variables, if/thens, and loops up to that point. No functions yet. I came up with the following code:

sum = 0
endingnumber = 1                

print "\n.:Fibonacci sequence:.\n"

firstnumber = input("Enter the first number: ")
secondnumber = input("Enter the second number: ")
endingnumber = input("Enter the number to stop at: ")

if secondnumber < firstnumber:

    print "\nSecond number must be bigger than the first number!!!\n"

else:

while sum <= endingnumber:

    print firstnumber

    if secondnumber > endingnumber:

        break

    else:

        print secondnumber
        sum = firstnumber + secondnumber
        firstnumber = sum
        secondnumber = secondnumber + sum

As you can see, it's really inefficient, but it DOES work.

How to update record using Entity Framework 6?

This if for Entity Framework 6.2.0.

If you have a specific DbSet and an item that needs to be either updated or created:

var name = getNameFromService();

var current = _dbContext.Names.Find(name.BusinessSystemId, name.NameNo);
if (current == null)
{
    _dbContext.Names.Add(name);
}
else
{
    _dbContext.Entry(current).CurrentValues.SetValues(name);
}
_dbContext.SaveChanges();

However this can also be used for a generic DbSet with a single primary key or a composite primary key.

var allNames = NameApiService.GetAllNames();
GenericAddOrUpdate(allNames, "BusinessSystemId", "NameNo");

public virtual void GenericAddOrUpdate<T>(IEnumerable<T> values, params string[] keyValues) where T : class
{
    foreach (var value in values)
    {
        try
        {
            var keyList = new List<object>();

            //Get key values from T entity based on keyValues property
            foreach (var keyValue in keyValues)
            {
                var propertyInfo = value.GetType().GetProperty(keyValue);
                var propertyValue = propertyInfo.GetValue(value);
                keyList.Add(propertyValue);
            }

            GenericAddOrUpdateDbSet(keyList, value);
            //Only use this when debugging to catch save exceptions
            //_dbContext.SaveChanges();
        }
        catch
        {
            throw;
        }
    }
    _dbContext.SaveChanges();
}

public virtual void GenericAddOrUpdateDbSet<T>(List<object> keyList, T value) where T : class
{
    //Get a DbSet of T type
    var someDbSet = Set(typeof(T));

    //Check if any value exists with the key values
    var current = someDbSet.Find(keyList.ToArray());
    if (current == null)
    {
        someDbSet.Add(value);
    }
    else
    {
        Entry(current).CurrentValues.SetValues(value);
    }
}

Getting the Username from the HKEY_USERS values

for /f "tokens=8 delims=\" %a in ('reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\hivelist" ^| find "UsrClass.dat"') do echo %a

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'}

"CASE" statement within "WHERE" clause in SQL Server 2008

Thanks for this question, actually I am looking for something else which is in below query. this may helps someone.

      SELECT DISTINCT CASE WHEN OPPORTUNITY='' THEN '(BLANK)' ELSE OPPORTUNITY END
  AS OPP,LEN(OPPORTUNITY) FROM [DBO].[TBL]

above query is to fill in dropdown which blank values shows as "(blank)". Also if we pass this value into sql where clause to get blank values with other values I don't know how to handle that. And finally came up with below solution this may helps to somebody.

here it is ,

 DECLARE @OPP TABLE (OPP VARCHAR(100))
  INSERT INTO @OPP VALUES('(BLANK)'),('UNFUNDED'),('FUNDED/NOT COMMITTED')
SELECT DISTINCT [OPPORTUNITY]
FROM [DBO].[TBL]   WHERE    (  CASE WHEN   OPPORTUNITY ='' THEN '(BLANK)' ELSE OPPORTUNITY END IN (SELECT OPP FROM @OPP))
ORDER BY 1 

Contain an image within a div?

Here is javascript I wrote to do just this.

function ImageTile(parentdiv, imagediv) {
imagediv.style.position = 'absolute';

function load(image) {
    //
    // Reset to auto so that when the load happens it resizes to fit our image and that
    // way we can tell what size our image is. If we don't do that then it uses the last used
    // values to auto-size our image and we don't know what the actual size of the image is.
    //
    imagediv.style.height = "auto";
    imagediv.style.width = "auto";
    imagediv.style.top = 0;
    imagediv.style.left = 0;

    imagediv.src = image;
}

//bind load event (need to wait for it to finish loading the image)
imagediv.onload = function() {
    var vpWidth = parentdiv.clientWidth;
    var vpHeight = parentdiv.clientHeight;
    var imgWidth = this.clientWidth;
    var imgHeight = this.clientHeight;

    if (imgHeight > imgWidth) {
        this.style.height = vpHeight + 'px';
        var width = ((imgWidth/imgHeight) * vpHeight);
        this.style.width = width + 'px';
        this.style.left = ((vpWidth - width)/2) + 'px';
    } else {
        this.style.width = vpWidth + 'px';
        var height = ((imgHeight/imgWidth) * vpWidth);
        this.style.height = height + 'px';
        this.style.top = ((vpHeight - height)/2) + 'px';
    }
};

return {
    "load": load
};

}

And to use it just do something like this:

 var tile1 = ImageTile(document.documentElement, document.getElementById("tile1"));
 tile1.load(url);

I use this for a slideshow in which I have two of these "tiles" and I fade one out and the other in. The loading is done on the "tile" that is not visible to avoid the jarring visual affect of the resetting of the style back to "auto".

How to write a unit test for a Spring Boot Controller endpoint

Spring MVC offers a standaloneSetup that supports testing relatively simple controllers, without the need of context.

Build a MockMvc by registering one or more @Controller's instances and configuring Spring MVC infrastructure programmatically. This allows full control over the instantiation and initialization of controllers, and their dependencies, similar to plain unit tests while also making it possible to test one controller at a time.

An example test for your controller can be something as simple as

public class DemoApplicationTests {

    private MockMvc mockMvc;

    @Before
    public void setup() {
        this.mockMvc = standaloneSetup(new HelloWorld()).build();
    }

    @Test
    public void testSayHelloWorld() throws Exception {
        this.mockMvc.perform(get("/")
           .accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
           .andExpect(status().isOk())
           .andExpect(content().contentType("application/json"));

    }
}

Twitter Bootstrap dropdown menu

<!DOCTYPE html>
<html lang="en">
<head>
    <!-- core CSS -->
    <link href="http://webdesign9.in/css/bootstrap.min.css" rel="stylesheet">
    <link href="http://webdesign9.in/css/font-awesome.min.css" rel="stylesheet">
    <link href="http://webdesign9.in/css/responsive.css" rel="stylesheet">
    <!--[if lt IE 9]>
    <script src="js/html5shiv.js"></script>
    <script src="js/respond.min.js"></script>
    <![endif]-->       
</head><!--/head-->
<body class="homepage">
    <header id="header">
        <nav class="navbar navbar-inverse" role="banner">
            <div class="container">
                <div class="navbar-header">
                    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                        <span class="sr-only">Toggle navigation</span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                        <span class="icon-bar"></span>
                    </button>
                    <a class="navbar-brand" title="Web Design Company in Mumbai" href="index.php"><img src="images/logo.png" alt="The Best Web Design Company in Mumbai" /></a>
                </div>
                <div class="collapse navbar-collapse navbar-right">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="index.php">Home</a></li>
                        <li><a href="about.php">About Us</a></li>
                        <li><a href="services.php">Services</a></li>
                        <li><a href="term-condition.php">Terms &amp; Condition</a></li></li>
                        <li><a href="contact.php">Contact</a></li>                        
                    </ul>
                </div>
            </div><!--/.container-->
        </nav><!--/nav-->
    </header><!--/header-->
    <script src="http://webdesign9.in/js/jquery.js"></script>
    <script src="http://webdesign9.in/js/bootstrap.min.js"></script>
</body>
</html>

How to evaluate a math expression given in string form?

External library like RHINO or NASHORN can be used to run javascript. And javascript can evaluate simple formula without parcing the string. No performance impact as well if code is written well. Below is an example with RHINO -

public class RhinoApp {
    private String simpleAdd = "(12+13+2-2)*2+(12+13+2-2)*2";

public void runJavaScript() {
    Context jsCx = Context.enter();
    Context.getCurrentContext().setOptimizationLevel(-1);
    ScriptableObject scope = jsCx.initStandardObjects();
    Object result = jsCx.evaluateString(scope, simpleAdd , "formula", 0, null);
    Context.exit();
    System.out.println(result);
}

CR LF notepad++ removal

Goto View -> Show Symbol -> Show All Characters. Uncheck it. There you go.!!

enter image description here

Fade In Fade Out Android Animation in Java

Here is what I used to fade in/out Views, hope this helps someone.

private void crossFadeAnimation(final View fadeInTarget, final View fadeOutTarget, long duration){
    AnimatorSet mAnimationSet = new AnimatorSet();
    ObjectAnimator fadeOut = ObjectAnimator.ofFloat(fadeOutTarget, View.ALPHA,  1f, 0f);
    fadeOut.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
        }

        @Override
        public void onAnimationEnd(Animator animation) {
            fadeOutTarget.setVisibility(View.GONE);
        }

        @Override
        public void onAnimationCancel(Animator animation) {
        }

        @Override
        public void onAnimationRepeat(Animator animation) {
        }
    });
    fadeOut.setInterpolator(new LinearInterpolator());

    ObjectAnimator fadeIn = ObjectAnimator.ofFloat(fadeInTarget, View.ALPHA, 0f, 1f);
    fadeIn.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) {
            fadeInTarget.setVisibility(View.VISIBLE);
        }

        @Override
        public void onAnimationEnd(Animator animation) {}

        @Override
        public void onAnimationCancel(Animator animation) {}

        @Override
        public void onAnimationRepeat(Animator animation) {}
    });
    fadeIn.setInterpolator(new LinearInterpolator());
    mAnimationSet.setDuration(duration);
    mAnimationSet.playTogether(fadeOut, fadeIn);
    mAnimationSet.start();
}

Allow docker container to connect to a local/host postgres database

To set up something simple that allows a Postgresql connection from the docker container to my localhost I used this in postgresql.conf:

listen_addresses = '*'

And added this pg_hba.conf:

host    all             all             172.17.0.0/16           password

Then do a restart. My client from the docker container (which was at 172.17.0.2) could then connect to Postgresql running on my localhost using host:password, database, username and password.

How to set the default value of an attribute on a Laravel model

The other answers are not working for me - they may be outdated. This is what I used as my solution for auto setting an attribute:

/**
 * The "booting" method of the model.
 *
 * @return void
 */
protected static function boot()
{
    parent::boot();

    // auto-sets values on creation
    static::creating(function ($query) {
        $query->is_voicemail = $query->is_voicemail ?? true;
    });
}

Trigger back-button functionality on button click in Android

layout.xml

<Button
    android:id="@+id/buttonBack"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:onClick="finishActivity"
    android:text="Back" />

Activity.java

public void finishActivity(View v){
    finish();
}

Related:

How to calculate UILabel width based on text length?

CGSize expectedLabelSize = [yourString sizeWithFont:yourLabel.font 
                        constrainedToSize:maximumLabelSize 
                        lineBreakMode:yourLabel.lineBreakMode]; 

What is -[NSString sizeWithFont:forWidth:lineBreakMode:] good for?

this question might have your answer, it worked for me.


For 2014, I edited in this new version, based on the ultra-handy comment by Norbert below! This does everything. Cheers

// yourLabel is your UILabel.

float widthIs = 
 [self.yourLabel.text
  boundingRectWithSize:self.yourLabel.frame.size                                           
  options:NSStringDrawingUsesLineFragmentOrigin
  attributes:@{ NSFontAttributeName:self.yourLabel.font }
  context:nil]
   .size.width;

NSLog(@"the width of yourLabel is %f", widthIs);

How do you trigger a block after a delay, like -performSelector:withObject:afterDelay:?

Xcode 10.2 and Swift 5 and above

DispatchQueue.main.asyncAfter(deadline: .now() + 2, execute: {
   // code to execute                 
})

Hashmap with Streams in Java 8 Streams to collect value of Map

Using keySet-

id1.keySet().stream()
        .filter(x -> x == 1)
        .map(x -> id1.get(x))
        .collect(Collectors.toList())

input type="submit" Vs button tag are they interchangeable?

http://www.w3.org/TR/html4/interact/forms.html#h-17.5

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content. For example, a BUTTON element that contains an image functions like and may resemble an INPUT element whose type is set to "image", but the BUTTON element type allows content.

So for functionality only they're interchangeable!

(Don't forget, type="submit" is the default with button, so leave it off!)

Why doesn't C++ have a garbage collector?

What type? should it be optimised for embedded washing machine controllers, cell phones, workstations or supercomputers?
Should it prioritise gui responsiveness or server loading?
should it use lots of memory or lots of CPU?

C/c++ is used in just too many different circumstances. I suspect something like boost smart pointers will be enough for most users

Edit - Automatic garbage collectors aren't so much a problem of performance (you can always buy more server) it's a question of predicatable performance.
Not knowing when the GC is going to kick in is like employing a narcoleptic airline pilot, most of the time they are great - but when you really need responsiveness!

Failed to load resource: the server responded with a status of 404 (Not Found) error in server

By default, IUSR account is used for anonymous user.

All you need to do is:

IIS -> Authentication --> Set Anonymous Authentication to Application Pool Identity.

Problem solved :)

Is there a simple way to remove multiple spaces in a string?

import re
string = re.sub('[ \t\n]+', ' ', 'The     quick brown                \n\n             \t        fox')

This will remove all the tabs, new lines and multiple white spaces with single white space.

How does PHP 'foreach' actually work?

NOTE FOR PHP 7

To update on this answer as it has gained some popularity: This answer no longer applies as of PHP 7. As explained in the "Backward incompatible changes", in PHP 7 foreach works on copy of the array, so any changes on the array itself are not reflected on foreach loop. More details at the link.

Explanation (quote from php.net):

The first form loops over the array given by array_expression. On each iteration, the value of the current element is assigned to $value and the internal array pointer is advanced by one (so on the next iteration, you'll be looking at the next element).

So, in your first example you only have one element in the array, and when the pointer is moved the next element does not exist, so after you add new element foreach ends because it already "decided" that it it as the last element.

In your second example, you start with two elements, and foreach loop is not at the last element so it evaluates the array on the next iteration and thus realises that there is new element in the array.

I believe that this is all consequence of On each iteration part of the explanation in the documentation, which probably means that foreach does all logic before it calls the code in {}.

Test case

If you run this:

<?
    $array = Array(
        'foo' => 1,
        'bar' => 2
    );
    foreach($array as $k=>&$v) {
        $array['baz']=3;
        echo $v." ";
    }
    print_r($array);
?>

You will get this output:

1 2 3 Array
(
    [foo] => 1
    [bar] => 2
    [baz] => 3
)

Which means that it accepted the modification and went through it because it was modified "in time". But if you do this:

<?
    $array = Array(
        'foo' => 1,
        'bar' => 2
    );
    foreach($array as $k=>&$v) {
        if ($k=='bar') {
            $array['baz']=3;
        }
        echo $v." ";
    }
    print_r($array);
?>

You will get:

1 2 Array
(
    [foo] => 1
    [bar] => 2
    [baz] => 3
)

Which means that array was modified, but since we modified it when the foreach already was at the last element of the array, it "decided" not to loop anymore, and even though we added new element, we added it "too late" and it was not looped through.

Detailed explanation can be read at How does PHP 'foreach' actually work? which explains the internals behind this behaviour.

How do I check if a type is a subtype OR the type of an object?

If you're trying to do it in a Xamarin Forms PCL project, the above solutions using IsAssignableFrom gives an error:

Error: 'Type' does not contain a definition for 'IsAssignableFrom' and no extension method 'IsAssignableFrom' accepting a first argument of type 'Type' could be found (are you missing a using directive or an assembly reference?)

because IsAssignableFrom asks for a TypeInfo object. You can use the GetTypeInfo() method from System.Reflection:

typeof(BaseClass).GetTypeInfo().IsAssignableFrom(typeof(unknownType).GetTypeInfo())

C#: How would I get the current time into a string?

string t = DateTime.Now.ToString("h/m/s tt");
string t2 = DateTime.Now.ToString("hh:mm:ss tt");
string d = DateTime.Now.ToString("MM/dd/yy");

http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx

Pass arguments to Constructor in VBA

Here's a little trick I'm using lately and brings good results. I would like to share with those who have to fight often with VBA.

1.- Implement a public initiation subroutine in each of your custom classes. I call it InitiateProperties throughout all my classes. This method has to accept the arguments you would like to send to the constructor.

2.- Create a module called factory, and create a public function with the word "Create" plus the same name as the class, and the same incoming arguments as the constructor needs. This function has to instantiate your class, and call the initiation subroutine explained in point (1), passing the received arguments. Finally returned the instantiated and initiated method.

Example:

Let's say we have the custom class Employee. As the previous example, is has to be instantiated with name and age.

This is the InitiateProperties method. m_name and m_age are our private properties to be set.

Public Sub InitiateProperties(name as String, age as Integer)

    m_name = name
    m_age = age

End Sub

And now in the factory module:

Public Function CreateEmployee(name as String, age as Integer) as Employee

    Dim employee_obj As Employee
    Set employee_obj = new Employee

    employee_obj.InitiateProperties name:=name, age:=age
    set CreateEmployee = employee_obj

End Function

And finally when you want to instantiate an employee

Dim this_employee as Employee
Set this_employee = factory.CreateEmployee(name:="Johnny", age:=89)

Especially useful when you have several classes. Just place a function for each in the module factory and instantiate just by calling factory.CreateClassA(arguments), factory.CreateClassB(other_arguments), etc.

EDIT

As stenci pointed out, you can do the same thing with a terser syntax by avoiding to create a local variable in the constructor functions. For instance the CreateEmployee function could be written like this:

Public Function CreateEmployee(name as String, age as Integer) as Employee

    Set CreateEmployee = new Employee
    CreateEmployee.InitiateProperties name:=name, age:=age

End Function

Which is nicer.

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

SQL Server 2008 - Login failed. The login is from an untrusted domain and cannot be used with Windows authentication

You're not passing any credentials to sqlcmd.exe

So it's trying to authenticate you using the Windows Login credentials, but you mustn't have your SQL Server setup to accept those credentials...

When you were installing it, you would have had to supply a Server Admin password (for the sa account)

Try...

sqlcmd.exe -U sa -P YOUR_PASSWORD -S ".\SQL2008"

for reference, theres more details here...

How to pass data from Javascript to PHP and vice versa?

Using cookies is a easy way. You can use jquery and a pluging as jquery.cookie or create your own. Using Jquery + jquery.cookie, by example

   <script>
   var php_value = '<?php echo $php_variable; ?>';

   var infobar_active = $.cookie('php_value');
   var infobar_alert  = any_process(infobar_active);

    //set a cookie to readit via php
   $.cookie('infobar_alerta', infobar_alerta );

   </script>

   <?php 

    var js_value = code to read a cookie

   ?>

I've found this usefull Server-Side and Hybrid Frameworks: http://www.phplivex.com/ http://www.ashleyit.com/rs/

I've been using Ashley's RSJS Script to update values in HTML without any problem for a long time until I met JQuery (ajax, load, etc.)

Can't open file 'svn/repo/db/txn-current-lock': Permission denied

In addition to the repository permissions, the /tmp directory must also be writeable by all users.

Pass PDO prepared statement to variables

Instead of using ->bindParam() you can pass the data only at the time of ->execute():

$data = [   ':item_name' => $_POST['item_name'],   ':item_type' => $_POST['item_type'],   ':item_price' => $_POST['item_price'],   ':item_description' => $_POST['item_description'],   ':image_location' => 'images/'.$_FILES['file']['name'],   ':status' => 0,   ':id' => 0, ];  $stmt->execute($data); 

In this way you would know exactly what values are going to be sent.

Bluetooth pairing without user confirmation

If you are asking if you can pair two devices without the user EVER approving the pairing, no it cannot be done, it is a security feature. If you are paired over Bluetooth there is no need to exchange data over NFC, just exchange data over the Bluetooth link.

I don't think you can circumvent Bluetooth security by passing an authentication packet over NFC, but I could be wrong.

Using colors with printf

This is a little function that prints colored text using bash scripting. You may add as many styles as you want, and even print tabs and new lines:

#!/bin/bash

# prints colored text
print_style () {

    if [ "$2" == "info" ] ; then
        COLOR="96m";
    elif [ "$2" == "success" ] ; then
        COLOR="92m";
    elif [ "$2" == "warning" ] ; then
        COLOR="93m";
    elif [ "$2" == "danger" ] ; then
        COLOR="91m";
    else #default color
        COLOR="0m";
    fi

    STARTCOLOR="\e[$COLOR";
    ENDCOLOR="\e[0m";

    printf "$STARTCOLOR%b$ENDCOLOR" "$1";
}

print_style "This is a green text " "success";
print_style "This is a yellow text " "warning";
print_style "This is a light blue with a \t tab " "info";
print_style "This is a red text with a \n new line " "danger";
print_style "This has no color";

Tools for creating Class Diagrams

I have used both Poseidon UML and Enterprise Architect and must say that I prefer Poseidon but wasn't fully satisfied with any of them.

Angular4 - No value accessor for form control

You can use formControlName only on directives which implement ControlValueAccessor.

Implement the interface

So, in order to do what you want, you have to create a component which implements ControlValueAccessor, which means implementing the following three functions:

  • writeValue (tells Angular how to write value from model into view)
  • registerOnChange (registers a handler function that is called when the view changes)
  • registerOnTouched (registers a handler to be called when the component receives a touch event, useful for knowing if the component has been focused).

Register a provider

Then, you have to tell Angular that this directive is a ControlValueAccessor (interface is not gonna cut it since it is stripped from the code when TypeScript is compiled to JavaScript). You do this by registering a provider.

The provider should provide NG_VALUE_ACCESSOR and use an existing value. You'll also need a forwardRef here. Note that NG_VALUE_ACCESSOR should be a multi provider.

For example, if your custom directive is named MyControlComponent, you should add something along the following lines inside the object passed to @Component decorator:

providers: [
  { 
    provide: NG_VALUE_ACCESSOR,
    multi: true,
    useExisting: forwardRef(() => MyControlComponent),
  }
]

Usage

Your component is ready to be used. With template-driven forms, ngModel binding will now work properly.

With reactive forms, you can now properly use formControlName and the form control will behave as expected.

Resources

C - determine if a number is prime

OK, so forget about C. Suppose I give you a number and ask you to determine if it's prime. How do you do it? Write down the steps clearly, then worry about translating them into code.

Once you have the algorithm determined, it will be much easier for you to figure out how to write a program, and for others to help you with it.

edit: Here's the C# code you posted:

static bool IsPrime(int number) {
    for (int i = 2; i < number; i++) {
        if (number % i == 0 && i != number) return false;
    }
    return true;
}

This is very nearly valid C as is; there's no bool type in C, and no true or false, so you need to modify it a little bit (edit: Kristopher Johnson correctly points out that C99 added the stdbool.h header). Since some people don't have access to a C99 environment (but you should use one!), let's make that very minor change:

int IsPrime(int number) {
    int i;
    for (i=2; i<number; i++) {
        if (number % i == 0 && i != number) return 0;
    }
    return 1;
}

This is a perfectly valid C program that does what you want. We can improve it a little bit without too much effort. First, note that i is always less than number, so the check that i != number always succeeds; we can get rid of it.

Also, you don't actually need to try divisors all the way up to number - 1; you can stop checking when you reach sqrt(number). Since sqrt is a floating-point operation and that brings a whole pile of subtleties, we won't actually compute sqrt(number). Instead, we can just check that i*i <= number:

int IsPrime(int number) {
    int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

One last thing, though; there was a small bug in your original algorithm! If number is negative, or zero, or one, this function will claim that the number is prime. You likely want to handle that properly, and you may want to make number be unsigned, since you're more likely to care about positive values only:

int IsPrime(unsigned int number) {
    if (number <= 1) return 0; // zero and one are not prime
    unsigned int i;
    for (i=2; i*i<=number; i++) {
        if (number % i == 0) return 0;
    }
    return 1;
}

This definitely isn't the fastest way to check if a number is prime, but it works, and it's pretty straightforward. We barely had to modify your code at all!

NoSql vs Relational database

Just adding to all the information given above

NoSql Advantages:

1) NoSQL is good if you want to be production ready fast due to its support for schema-less and object oriented architecture.

2) NoSql db's are eventually consistent which in simple language means they will not provide any lock on the data(documents) as in case of RDBMS and what does it mean is latest snapshot of data is always available and thus increase the latency of your application.

3) It uses MVCC (Multi view concurrency control) strategy for maintaining and creating snapshot of data(documents).

4) If you want to have indexed data you can create view which will automatically index the data by the view definition you provide.

NoSql Disadvantages:

1) Its definitely not suitable for big heavy transactional applications as it is eventually consistent and does not support ACID properties.

2) Also it creates multiple snapshots (revisions) of your data (documents) as it uses MVCC methodology for concurrency control, as a result of which space get consumed faster than before which makes compaction and hence reindexing more frequent and it will slow down your application response as the data and transaction in your application grows. To counter that you can horizontally scale the nodes but then again it will be higher cost as compare sql database.

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

This worked for me:

cp <path_to>/libstdc++.so.6 $PWD
./<executable>

This tidbit came from @kerin (comment provided above):

you might check out http://stackoverflow.com/questions/13636513/linking-libstdc-statically-any-gotchas

From that link:

If you put the newer libstdc++.so in the same directory as the executable it will be found at run-time, problem solved.

The error I was getting mentioned that libstdc++.so.6 was coming from /usr/lib64/, but this is not the library I linked against! The message looked like:

<executing_binary>: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.21' not found (required by <executing_binary>)

I did verify that LD_LIBRARY_PATH had the directory (and that it was the first path). For some reason at runtime it was still looking at /usr/lib64/libstdc++.so.6.

I took the advice from the article above and copied the libstdc++.so.6 from where I linked into the directory with my executable, ran from there, and it worked!

how to implement login auth in node.js

To add to Farid's pseudo-answer,

Consider using Passport.js over everyauth.

The answers to this question provide some insight to the differences.


There are plenty of benefits to offloading your user authentication to Google, Facebook or another website. If your application's requirements are such that you could use Passport as your sole authentication provider or alongside traditional login, it can make the experience easier for your users.

How do I get the current time only in JavaScript

function getCurrentTime(){
    var date = new Date();
    var hh = date.getHours();
    var mm = date.getMinutes();

    hh = hh < 10 ? '0'+hh : hh; 
    mm = mm < 10 ? '0'+mm : mm;

    curr_time = hh+':'+mm;
    return curr_time;
}

Center a DIV horizontally and vertically

After trying a lot of things I find a way that works. I share it here if it is useful to anyone. You can see it here working: http://jsbin.com/iquviq/30/edit

.content {
        width: 200px;
        height: 600px;
        background-color: blue;
        position: absolute; /*Can also be `fixed`*/
        left: 0;
        right: 0;
        top: 0;
        bottom: 0;
        margin: auto;
        /*Solves a problem in which the content is being cut when the div is smaller than its' wrapper:*/
        max-width: 100%;
        max-height: 100%;
        overflow: auto;
}

datetime to string with series in python pandas

There is no str accessor for datetimes and you can't do dates.astype(str) either, you can call apply and use datetime.strftime:

In [73]:

dates = pd.to_datetime(pd.Series(['20010101', '20010331']), format = '%Y%m%d')
dates.apply(lambda x: x.strftime('%Y-%m-%d'))
Out[73]:
0    2001-01-01
1    2001-03-31
dtype: object

You can change the format of your date strings using whatever you like: strftime() and strptime() Behavior.

Update

As of version 0.17.0 you can do this using dt.strftime

dates.dt.strftime('%Y-%m-%d')

will now work

Laravel 5 Carbon format datetime

Just use the date() and strtotime() function and save your time

$suborder['payment_date'] = date('d-m-Y', strtotime($item['created_at']));

Don't stress!!!

How to programmatically set the ForeColor of a label to its default?

labelname.ForeColor = Color.Colorname;   ­­­­

Bootstrap Alert Auto Close

This is a good approach to show animation in and out using jQuery

  $(document).ready(function() {
      // show the alert
      $(".alert").first().hide().slideDown(500).delay(4000).slideUp(500, function () {
         $(this).remove(); 
      });
  });

Is there a way to list open transactions on SQL Server 2000 database?

You can get all the information of active transaction by the help of below query

SELECT
trans.session_id AS [SESSION ID],
ESes.host_name AS [HOST NAME],login_name AS [Login NAME],
trans.transaction_id AS [TRANSACTION ID],
tas.name AS [TRANSACTION NAME],tas.transaction_begin_time AS [TRANSACTION 
BEGIN TIME],
tds.database_id AS [DATABASE ID],DBs.name AS [DATABASE NAME]
FROM sys.dm_tran_active_transactions tas
JOIN sys.dm_tran_session_transactions trans
ON (trans.transaction_id=tas.transaction_id)
LEFT OUTER JOIN sys.dm_tran_database_transactions tds
ON (tas.transaction_id = tds.transaction_id )
LEFT OUTER JOIN sys.databases AS DBs
ON tds.database_id = DBs.database_id
LEFT OUTER JOIN sys.dm_exec_sessions AS ESes
ON trans.session_id = ESes.session_id
WHERE ESes.session_id IS NOT NULL

and it will give below similar result enter image description here

and you close that transaction by the help below KILL query by refering session id

KILL 77

How to get first element in a list of tuples?

if the tuples are unique then this can work

>>> a = [(1, u'abc'), (2, u'def')]
>>> a
[(1, u'abc'), (2, u'def')]
>>> dict(a).keys()
[1, 2]
>>> dict(a).values()
[u'abc', u'def']
>>> 

Add days Oracle SQL

Some disadvantage of "INTERVAL '1' DAY" is that bind variables cannot be used for the number of days added. Instead, numtodsinterval can be used, like in this small example:

select trunc(sysdate) + numtodsinterval(:x, 'day') tag
from dual

See also: NUMTODSINTERVAL in Oracle Database Online Documentation

Is header('Content-Type:text/plain'); necessary at all?

Define "necessary".

It is necessary if you want the browser to know what the type of the file is. PHP automatically sets the Content-Type header to text/html if you don't override it so your browser is treating it as an HTML file that doesn't contain any HTML. If your output contained any HTML you'd see very different outcomes. If you were to send:

<b><i>test</i></b>

a Content-Type: text/html would output:

test

whereas Content-Type: text/plain would output:

<b><i>test</i></b>

TLDR Version: If you really are only outputing text then it doesn't really matter, but it IS wrong.