Programs & Examples On #Geoip

GeoIP is the process of analyzing an IP address and determining the geographical location of that end point.

Identifying country by IP address

No you can't - IP addresses get reallocated and reassigned from time to time, so the mapping of IP to location will also change over time.

If you want to find out the location that an IP address currently maps to you can either download a geolocation database, such as GeoLite from MaxMind, or use an API like http://ipinfo.io (my own service) which will also give you additional details:

$ curl ipinfo.io/8.8.8.8
{
  "ip": "8.8.8.8",
  "hostname": "google-public-dns-a.google.com",
  "loc": "37.385999999999996,-122.0838",
  "org": "AS15169 Google Inc.",
  "city": "Mountain View",
  "region": "California",
  "country": "US",
  "phone": 650
}

Get Country of IP Address with PHP

Use the widget www.feedsalive.com, to get the country informations & last page information as well.

Getting the location from an IP address

I like the free GeoLite City from Maxmind which works for most applications and from which you can upgrade to a paying version if it's not precise enough. There is a PHP API included, as well as for other languages. And if you are running Lighttpd as a webserver, you can even use a module to get the information in the SERVER variable for every visitor if that's what you need.

I should add there is also a free Geolite Country (which would be faster if you don't need to pinpoint the city the IP is from) and Geolite ASN (if you want to know who owns the IP) and that finally all these are downloadable on your own server, are updated every month and are pretty quick to lookup with the provided APIs as they state "thousands of lookups per second".

How to ignore PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException?

FWIW, on Ubuntu 10.04.2 LTS installing the ca-certificates-java and the ca-certificates packages fixed this problem for me.

Why boolean in Java takes only true or false? Why not 1 or 0 also?

One thing that other answers haven't pointed out is that one advantage of not treating integers as truth values is that it avoids this C / C++ bug syndrome:

int i = 0;
if (i = 1) {
    print("the sky is falling!\n");
} 

In C / C++, the mistaken use of = rather than == causes the condition to unexpectedly evaluate to "true" and update i as an accidental side-effect.

In Java, that is a compilation error, because the value of the assigment i = 1 has type int and a boolean is required at that point. The only case where you'd get into trouble in Java is if you write lame code like this:

boolean ok = false;
if (ok = true) {  // bug and lame style
    print("the sky is falling!\n");
}

... which anyone with an ounce of "good taste" would write as ...

boolean ok = false;
if (ok) {
    print("the sky is falling!\n");
}

Compare two folders which has many files inside contents

I used

diff -rqyl folder1 folder2 --exclude=node_modules

in my nodejs apps.

How do I clone a job in Jenkins?

if you want to copy in same Jenkins but in different subfolders, create new item -> use copy from. new Job will be cloned in same directory. Then use move option to move it in desired directory

How to get an isoformat datetime string including the default timezone?

Something like the following example. Note I'm in Eastern Australia (UTC + 10 hours at the moment).

>>> import datetime
>>> dtnow = datetime.datetime.now();dtutcnow = datetime.datetime.utcnow()
>>> dtnow
datetime.datetime(2010, 8, 4, 9, 33, 9, 890000)
>>> dtutcnow
datetime.datetime(2010, 8, 3, 23, 33, 9, 890000)
>>> delta = dtnow - dtutcnow
>>> delta
datetime.timedelta(0, 36000)
>>> hh,mm = divmod((delta.days * 24*60*60 + delta.seconds + 30) // 60, 60)
>>> hh,mm
(10, 0)
>>> "%s%+02d:%02d" % (dtnow.isoformat(), hh, mm)
'2010-08-04T09:33:09.890000+10:00'
>>>

How to specify table's height such that a vertical scroll bar appears?

This CSS also shows a fixed height HTML table. It sets the height of the HTML tbody to 400 pixels and the HTML tbody scrolls when the it is larger, retaining the HTML thead as a non-scrolling element.

In addition, each th cell in the heading and each td cell the body should be styled for the desired fixed width.

#the-table {
  display: block;
  background: white; /* optional */
}

#the-table thead {
  text-align: left; /* optional */
}

#the-table tbody {
  display: block;
  max-height: 400px;
  overflow-y: scroll;
}

ASP.NET MVC Dropdown List From SelectList

You are missing setting what field is the Text and Value in the SelectList itself. That is why it does a .ToString() on each object in the list. You could think that given it is a list of SelectListItem it should be smart enough to detect this... but it is not.

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
        new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text", 1);

BTW, you can use a list of array of any type... and then just set the name of the properties that will act as Text and Value.

I think it is better to do it like this:

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text");

I removed the -1 item, and the setting of each items selected true/false.

Then, in your view:

@Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")

This way, if you set the "Select one" item, and you don't set one item as selected in the SelectList, the UserType will be null (the UserType need to be int? ).

If you need to set one of the SelectList items as selected, you can use:

u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

Place @JsonIgnore on the field or its getter, or create a custom dto

@JsonIgnore
private String encryptedPwd;

or as mentioned above by ceekay annotate it with @JsonProperty where access attribute is set to write only

@JsonProperty( value = "password", access = JsonProperty.Access.WRITE_ONLY)
private String encryptedPwd;

What is the best way to auto-generate INSERT statements for a SQL Server table?

As mentioned by @Mike Ritacco but updated for SSMS 2008 R2

  1. Right click on the database name
  2. Choose Tasks > Generate scripts
  3. Depending on your settings the intro page may show or not
  4. Choose 'Select specific database objects',
  5. Expand the tree view and check the relevant tables
  6. Click Next
  7. Click Advanced
  8. Under General section, choose the appropriate option for 'Types of data to script'
  9. Complete the wizard

You will then get all of the INSERT statements for the data straight out of SSMS.

EDIT 2016-10-25 SQL Server 2016/SSMS 13.0.15900.1

  1. Right click on the database name

  2. Choose Tasks > Generate scripts

  3. Depending on your settings the intro page may show or not

  4. Choose 'Select specific database objects',

  5. Expand the tree view and check the relevant tables

  6. Click Next

  7. Click Advanced

  8. Under General section, choose the appropriate option for 'Types of data to script'

  9. Click OK

  10. Pick whether you want the output to go to a new query, the clipboard or a file

  11. Click Next twice

  12. Your script is prepared in accordance with the settings you picked above

  13. Click Finish

Appending to an empty DataFrame in Pandas?

You can concat the data in this way:

InfoDF = pd.DataFrame()
tempDF = pd.DataFrame(rows,columns=['id','min_date'])

InfoDF = pd.concat([InfoDF,tempDF])

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

html text input onchange event

Use the oninput event

<input type="text" oninput="myFunction();" />

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

Bash: If/Else statement in one line

There is no need to explicitly check $?. Just do:

ps aux | grep some_proces[s] > /tmp/test.txt && echo 1 || echo 0 

Note that this relies on echo not failing, which is certainly not guaranteed. A more reliable way to write this is:

if ps aux | grep some_proces[s] > /tmp/test.txt; then echo 1; else echo 0; fi

SQL Server dynamic PIVOT query?

Dynamic SQL PIVOT

Different approach for creating columns string

create table #temp
(
    date datetime,
    category varchar(3),
    amount money
)

insert into #temp values ('1/1/2012', 'ABC', 1000.00)
insert into #temp values ('2/1/2012', 'DEF', 500.00)
insert into #temp values ('2/1/2012', 'GHI', 800.00)
insert into #temp values ('2/10/2012', 'DEF', 700.00)
insert into #temp values ('3/1/2012', 'ABC', 1100.00)

DECLARE @cols  AS NVARCHAR(MAX)='';
DECLARE @query AS NVARCHAR(MAX)='';

SELECT @cols = @cols + QUOTENAME(category) + ',' FROM (select distinct category from #temp ) as tmp
select @cols = substring(@cols, 0, len(@cols)) --trim "," at end

set @query = 
'SELECT * from 
(
    select date, amount, category from #temp
) src
pivot 
(
    max(amount) for category in (' + @cols + ')
) piv'

execute(@query)
drop table #temp

Result

date                    ABC     DEF     GHI
2012-01-01 00:00:00.000 1000.00 NULL    NULL
2012-02-01 00:00:00.000 NULL    500.00  800.00
2012-02-10 00:00:00.000 NULL    700.00  NULL
2012-03-01 00:00:00.000 1100.00 NULL    NULL

Resetting Select2 value in dropdown with reset button

version 4.0

$('#d').val('').trigger('change');

This is the correct solution from now on according to deprecated message thrown in debug mode: "The select2("val") method has been deprecated and will be removed in later Select2 versions. Use $element.val() instead"

How to stop java process gracefully?

Thanks for you answers. Shutdown hooks seams like something that would work in my case. But I also bumped into the thing called Monitoring and Management beans:
http://java.sun.com/j2se/1.5.0/docs/guide/management/overview.html
That gives some nice possibilities, for remote monitoring, and manipulation of the java process. (Was introduced in Java 5)

Google Play Services Missing in Emulator (Android 4.4.2)

google play service is just a library to create application but in order to use application that use google play service library , you need to install google play in your emulator.and for that it need the unique device id. and device id is only on the real device not have on emulator. so for testing it , you need real android device.

Difference between git checkout --track origin/branch and git checkout -b branch origin/branch

The two commands have the same effect (thanks to Robert Siemer’s answer for pointing it out).

The practical difference comes when using a local branch named differently:

  • git checkout -b mybranch origin/abranch will create mybranch and track origin/abranch
  • git checkout --track origin/abranch will only create 'abranch', not a branch with a different name.

(That is, as commented by Sebastian Graf, if the local branch did not exist already.
If it did, you would need git checkout -B abranch origin/abranch)


Note: with Git 2.23 (Q3 2019), that would use the new command git switch:

git switch -c <branch> --track <remote>/<branch>

If the branch exists in multiple remotes and one of them is named by the checkout.defaultRemote configuration variable, we'll use that one for the purposes of disambiguation, even if the <branch> isn't unique across all remotes.
Set it to e.g. checkout.defaultRemote=origin to always checkout remote branches from there if <branch> is ambiguous but exists on the 'origin' remote.

Here, '-c' is the new '-b'.


First, some background: Tracking means that a local branch has its upstream set to a remote branch:

# git config branch.<branch-name>.remote origin
# git config branch.<branch-name>.merge refs/heads/branch

git checkout -b branch origin/branch will:

  • create/reset branch to the point referenced by origin/branch.
  • create the branch branch (with git branch) and track the remote tracking branch origin/branch.

When a local branch is started off a remote-tracking branch, Git sets up the branch (specifically the branch.<name>.remote and branch.<name>.merge configuration entries) so that git pull will appropriately merge from the remote-tracking branch.
This behavior may be changed via the global branch.autosetupmerge configuration flag. That setting can be overridden by using the --track and --no-track options, and changed later using git branch --set-upstream-to.


And git checkout --track origin/branch will do the same as git branch --set-upstream-to):

 # or, since 1.7.0
 git branch --set-upstream upstream/branch branch
 # or, since 1.8.0 (October 2012)
 git branch --set-upstream-to upstream/branch branch
 # the short version remains the same:
 git branch -u upstream/branch branch

It would also set the upstream for 'branch'.

(Note: git1.8.0 will deprecate git branch --set-upstream and replace it with git branch -u|--set-upstream-to: see git1.8.0-rc1 announce)


Having an upstream branch registered for a local branch will:

  • tell git to show the relationship between the two branches in git status and git branch -v.
  • directs git pull without arguments to pull from the upstream when the new branch is checked out.

See "How do you make an existing git branch track a remote branch?" for more.

python multithreading wait till all threads finished

In Python3, since Python 3.2 there is a new approach to reach the same result, that I personally prefer to the traditional thread creation/start/join, package concurrent.futures: https://docs.python.org/3/library/concurrent.futures.html

Using a ThreadPoolExecutor the code would be:

from concurrent.futures.thread import ThreadPoolExecutor
import time

def call_script(ordinal, arg):
    print('Thread', ordinal, 'argument:', arg)
    time.sleep(2)
    print('Thread', ordinal, 'Finished')

args = ['argumentsA', 'argumentsB', 'argumentsC']

with ThreadPoolExecutor(max_workers=2) as executor:
    ordinal = 1
    for arg in args:
        executor.submit(call_script, ordinal, arg)
        ordinal += 1
print('All tasks has been finished')

The output of the previous code is something like:

Thread 1 argument: argumentsA
Thread 2 argument: argumentsB
Thread 1 Finished
Thread 2 Finished
Thread 3 argument: argumentsC
Thread 3 Finished
All tasks has been finished

One of the advantages is that you can control the throughput setting the max concurrent workers.

scp copy directory to another server with private key auth

The command looks quite fine. Could you try to run -v (verbose mode) and then we can figure out what it is wrong on the authentication?

Also as mention in the other answer, maybe could be this issue - that you need to convert the keys (answered already here): How to convert SSH keypairs generated using PuttyGen(Windows) into key-pairs used by ssh-agent and KeyChain(Linux) OR http://winscp.net/eng/docs/ui_puttygen (depending what you need)

Passing HTML to template using Flask/Jinja2

the ideal way is to

{{ something|safe }}

than completely turning off auto escaping.

Unable to allocate array with shape and data type

I came across this problem on Windows too. The solution for me was to switch from a 32-bit to a 64-bit version of Python. Indeed, a 32-bit software, like a 32-bit CPU, can adress a maximum of 4 GB of RAM (2^32). So if you have more than 4 GB of RAM, a 32-bit version cannot take advantage of it.

With a 64-bit version of Python (the one labeled x86-64 in the download page), the issue disappeared.

You can check which version you have by entering the interpreter. I, with a 64-bit version, now have: Python 3.7.5rc1 (tags/v3.7.5rc1:4082f600a5, Oct 1 2019, 20:28:14) [MSC v.1916 64 bit (AMD64)], where [MSC v.1916 64 bit (AMD64)] means "64-bit Python".

Note : as of the time of this writing (May 2020), matplotlib is not available on python39, so I recommand installing python37, 64 bits.

Sources :

How do I update Node.js?

$ npm install -g npm stable

worked for me to update npm

to call onChange event after pressing Enter key

I prefer onKeyUp since it only fires when the key is released. onKeyDown, on the other hand, will fire multiple times if for some reason the user presses and holds the key. For example, when listening for "pressing" the Enter key to make a network request, you don't want that to fire multiple times since it can be expensive.

// handler could be passed as a prop
<input type="text" onKeyUp={handleKeyPress} />

handleKeyPress(e) {
if (e.key === 'Enter') {
  // do whatever
}

}

Also, stay away from keyCode since it will be deprecated some time.

What's the best way to parse command line arguments?

I extended Erco's approach to allow for required positional arguments and for optional arguments. These should precede the -d, -v etc. arguments.

Positional and optional arguments can be retrieved with PosArg(i) and OptArg(i, default) respectively. When an optional argument is found the start position of searching for options (e.g. -i) is moved 1 ahead to avoid causing an 'unexpected' fatal.

import os,sys


def HelpAndExit():
    print("<<your help output goes here>>")
    sys.exit(1)

def Fatal(msg):
    sys.stderr.write("%s: %s\n" % (os.path.basename(sys.argv[0]), msg))
    sys.exit(1)

def NextArg(i):
    '''Return the next command line argument (if there is one)'''
    if ((i+1) >= len(sys.argv)):
        Fatal("'%s' expected an argument" % sys.argv[i])
    return(1, sys.argv[i+1])

def PosArg(i):
    '''Return positional argument'''
    if i >= len(sys.argv):
        Fatal("'%s' expected an argument" % sys.argv[i])
    return sys.argv[i]

def OptArg(i, default):
    '''Return optional argument (if there is one)'''
    if i >= len(sys.argv):
        Fatal("'%s' expected an argument" % sys.argv[i])
    if sys.argv[i][:1] != '-':
        return True, sys.argv[i]
    else:
        return False, default


### MAIN
if __name__=='__main__':

    verbose = 0
    debug   = 0
    infile  = "infile"
    outfile = "outfile"
    options_start = 3

    # --- Parse two positional parameters ---
    n1 = int(PosArg(1))
    n2 = int(PosArg(2))

    # --- Parse an optional parameters ---
    present, a3 = OptArg(3,50)
    n3 = int(a3)
    options_start += int(present)

    # --- Parse rest of command line ---
    skip = 0
    for i in range(options_start, len(sys.argv)):
        if not skip:
            if   sys.argv[i][:2] == "-d": debug ^= 1
            elif sys.argv[i][:2] == "-v": verbose ^= 1
            elif sys.argv[i][:2] == "-i": (skip,infile)  = NextArg(i)
            elif sys.argv[i][:2] == "-o": (skip,outfile) = NextArg(i)
            elif sys.argv[i][:2] == "-h": HelpAndExit()
            elif sys.argv[i][:1] == "-":  Fatal("'%s' unknown argument" % sys.argv[i])
            else:                         Fatal("'%s' unexpected" % sys.argv[i])
        else: skip = 0

    print("Number 1 = %d" % n1)
    print("Number 2 = %d" % n2)
    print("Number 3 = %d" % n3)
    print("Debug    = %d" % debug)
    print("verbose  = %d" % verbose)
    print("infile   = %s" % infile)
    print("outfile  = %s" % outfile) 

Use NSInteger as array index

According to the error message, you declared myLoc as a pointer to an NSInteger (NSInteger *myLoc) rather than an actual NSInteger (NSInteger myLoc). It needs to be the latter.

Entity Framework The underlying provider failed on Open

Try this- Open the command prompt as administrator and type this netsh Winsock reset

Restart your system and try again.

How do I disable form fields using CSS?

input[name=username] { disabled: true; /* Does not work */ }

I know this question is quite old but for other users who come across this problem, I suppose the easiest way to disable input is simply by ':disabled'

<input type="text" name="username" value="admin" disabled />
<style type="text/css">
  input[name=username]:disabled {
    opacity: 0.5 !important; /* Fade effect */
    cursor: not-allowed; /* Cursor change to disabled state*/
  }
</style>

In reality, if you have some script to disable the input dynamically/automatically with javascript or jquery that would automatically disable based on the condition you add.

In jQuery for Example:

if (condition) {
// Make this input prop disabled state
  $('input').prop('disabled', true);
}
else {
// Do something else
}

Hope the answer in CSS helps.

Refreshing page on click of a button

This question actually is not JSP related, it is HTTP related. you can just do:

window.location = window.location;

Positioning <div> element at center of screen

try this

<table style="height: 100%; left: 0; position: absolute; text-align: center; width: 100%;">
 <tr>
  <td>
   <div style="text-align: left; display: inline-block;">
    Your Html code Here
   </div>
  </td>
 </tr>
</table>

Or this

<div style="height: 100%; left: 0; position: absolute; text-align: center; width: 100%; display: table">
 <div style="display: table-row">
  <div style="display: table-cell; vertical-align:middle;">
   <div style="text-align: left; display: inline-block;">
    Your Html code here
   </div>
  </div>
 </div>
</div>

In android how to set navigation drawer header image and name programmatically in class file?

It's and old post, but it's new for me. So, it is straight forward! In this part of the code:

 public boolean onNavigationItemSelected(MenuItem item) {

} , I bound an ImageView to the LinearLayout, which contains the ImageView from the example, listed below. Mind: it's the same code you get when you start a new project, and choose the template "Navigation Drawer Activity":

<ImageView
android:id="@+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="@dimen/nav_header_vertical_spacing"
android:src="@android:drawable/sym_def_app_icon" />

I gave the LinearLayout and ID, inside nav_header_main.xml (in my case I chose 'navigation_header_container' , so it went this way:

LinearLayout lV = (LinearLayout) findViewById(R.id.navigation_header_container);

    ivCloseDrawer = (ImageView) lV.findViewById(R.id.imageView);
    ivCloseDrawer.setOnClickListener(new View.OnClickListener()
    {
        @Override
        public void onClick(View v)
        {
            drawer.closeDrawer(GravityCompat.START);
        }
    });

Note: I have a private ImageView ivCloseDrawer declared at the top, before onCreate (MainActivity).

It worked fine! Hope it helps, Best Regards.

How do you create a temporary table in an Oracle database?

Yep, Oracle has temporary tables. Here is a link to an AskTom article describing them and here is the official oracle CREATE TABLE documentation.

However, in Oracle, only the data in a temporary table is temporary. The table is a regular object visible to other sessions. It is a bad practice to frequently create and drop temporary tables in Oracle.

CREATE GLOBAL TEMPORARY TABLE today_sales(order_id NUMBER)
ON COMMIT PRESERVE ROWS;

Oracle 18c added private temporary tables, which are single-session in-memory objects. See the documentation for more details. Private temporary tables can be dynamically created and dropped.

CREATE PRIVATE TEMPORARY TABLE ora$ptt_today_sales AS
SELECT * FROM orders WHERE order_date = SYSDATE;

Temporary tables can be useful but they are commonly abused in Oracle. They can often be avoided by combining multiple steps into a single SQL statement using inline views.

Convert a video to MP4 (H.264/AAC) with ffmpeg

Software patents led Debian/Ubuntu to disable the H.264 and AAC encoders in ffmpeg. See /usr/share/doc/ffmpeg/README.Debian.gz.

So go install x264, mplayer/mencoder, and Nero's AAC encoder. (Or, if you want to use all Free software, and don't care so much about audio quality, then sudo aptitude install faac.)

I don't remember if the medibuntu package of mencoder includes x264 vid encoding, since I build my own from git x264 and svn mplayer sources. (x264 is very actively developed, with significant quality and speed improvements frequently added.) http://git.videolan.org/?p=x264.git;a=summary

x264 is also packaged, but you should check that it's up to date enough to include weightp with recent bugfixes, and even more recent speed improvements...

Or if you're already willing to convert from .flv, instead of going from the high-quality source the flv was made from, then probably whatever recent version of x264 you can find will be fine.

How can I check the size of a collection within a Django template?

A list is considered to be False if it has no elements, so you can do something like this:

{% if mylist %}
    <p>I have a list!</p>
{% else %}
    <p>I don't have a list!</p>
{% endif %}

How to load up CSS files using Javascript?

I guess something like this script would do:

<script type="text/javascript" src="/js/styles.js"></script>

This JS file contains the following statement:

if (!document.getElementById) document.write('<link rel="stylesheet" type="text/css" href="/css/versions4.css">');

The address of the javascript and css would need to be absolute if they are to refer to your site.

Many CSS import techniques are discussed in this "Say no to CSS hacks with branching techniques" article.

But the "Using JavaScript to dynamically add Portlet CSS stylesheets" article mentions also the CreateStyleSheet possibility (proprietary method for IE):

<script type="text/javascript">
//<![CDATA[
if(document.createStyleSheet) {
  document.createStyleSheet('http://server/stylesheet.css');
}
else {
  var styles = "@import url(' http://server/stylesheet.css ');";
  var newSS=document.createElement('link');
  newSS.rel='stylesheet';
  newSS.href='data:text/css,'+escape(styles);
  document.getElementsByTagName("head")[0].appendChild(newSS);
}
//]]>

Check if Cell value exists in Column, and then get the value of the NEXT Cell

Use a different function, like VLOOKUP:

=IF(ISERROR(MATCH(A1,B:B, 0)), "No Match", VLOOKUP(A1,B:C,2,FALSE))

Changing Placeholder Text Color with Swift

Swift 3 (probably 2), you can override didSet on placeholder in UITextField subclass to apply attribute on it, this way:

override var placeholder: String? {

    didSet {
        guard let tmpText = placeholder else {
            self.attributedPlaceholder = NSAttributedString(string: "")
            return
        }

        let textRange = NSMakeRange(0, tmpText.characters.count)
        let attributedText = NSMutableAttributedString(string: tmpText)
        attributedText.addAttribute(NSForegroundColorAttributeName , value:UIColor(white:147.0/255.0, alpha:1.0), range: textRange)

        self.attributedPlaceholder = attributedText
    }
}

Deadly CORS when http://localhost is the origin

Chrome will make requests with CORS from a localhost origin just fine. This isn't a problem with Chrome.

The reason you can't load http://stackoverflow.com is that the Access-Control-Allow-Origin headers weren't allowing your localhost origin.

How to vertically align text with icon font?

Add this to your CSS:

.menu i.large.icon,
.menu i.large.basic.icon {
    vertical-align:baseline;
}

DEMO

Where can I download IntelliJ IDEA Color Schemes?

Please note there are two very nice color schemes by default in IDEA 10.

The one that is included is named Railcasts. It is included with the Ruby plugin (free official plugin, install via plugin manager).

Railcasts IDEA 10 color scheme

How to check if JSON return is empty with jquery

$.getJSON(url,function(json){
if ( json.length == 0 ) 
{
console.log("NO !")
}
});

Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX AVX2

Update the tensorflow binary for your CPU & OS using this command

pip install --ignore-installed --upgrade "Download URL"

The download url of the whl file can be found here

https://github.com/lakshayg/tensorflow-build

XPath using starts-with function

Use:

/*/ITEM[starts-with(REVENUE_YEAR,'2552')]/REGION

Note: Unless your host language can't handle element instance as result, do not use text nodes specially in mixed content data model. Do not start expressions with // operator when the schema is well known.

Inserting multiple rows in mysql

If you have your data in a text-file, you can use LOAD DATA INFILE.

When loading a table from a text file, use LOAD DATA INFILE. This is usually 20 times faster than using INSERT statements.

Optimizing INSERT Statements

You can find more tips on how to speed up your insert statements on the link above.

How to print formatted BigDecimal values?

I know this question is very old, but I was making similar thing in my kotlin app recently. So here is an example if anyone needs it:

val dfs = DecimalFormatSymbols.getInstance(Locale.getDefault())
val bigD = BigDecimal("1e+30")
val formattedBigD = DecimalFormat("#,##0.#",dfs).format(bigD)

Result displaying $formattedBigD:

1,000,000,000,000,000,000,000,000,000,000

How to set HTML Auto Indent format on Sublime Text 3?

One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.

Another option is to install the Emmet plugin (http://emmet.io/), which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:

p [tab][enter] Hello world!

When you type p [tab] Emmet expands it to:

<p></p>

Pressing [enter] then further expands it to:

<p>

</p>

With the cursor indented and on the line between the tags. Meaning that typing text results in:

<p>
    Hello, world!
</p>

Get git branch name in Jenkins Pipeline/Jenkinsfile

FWIW the only thing that worked for me in PR builds was ${CHANGE_BRANCH}

(may not work on master, haven't seen that yet)

Adding background image to div using CSS

You can try this also for setting the class in a div section:

_x000D_
_x000D_
/** CSS **/
.content {
    background: url('http://www.gransebryan.com/wp-content/uploads/2016/03/bryan-ganzon-granse-who.png') center no-repeat;
}

.displaybg {
   text-align: center;
   color: #FFF;
}
_x000D_
<div class="content">

    <p class="displaybg">This is just a test</p>

</div>
_x000D_
_x000D_
_x000D_

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

XPath: How to select elements based on their value?

The condition below:

//Element[@attribute1="abc" and @attribute2="xyz" and Data]

checks for the existence of the element Data within Element and not for element value Data.

Instead you can use

//Element[@attribute1="abc" and @attribute2="xyz" and text()="Data"]

How to initialize an array of custom objects

I'd do something along these lines:

$myitems =
@([pscustomobject]@{name="Joe";age=32;info="something about him"},
[pscustomobject]@{name="Sue";age=29;info="something about her"},
[pscustomobject]@{name="Cat";age=12;info="something else"})

Note that this only works in PowerShell 3, but since you did not mention the version in your question I'm assuming this does not matter for you.

Update

It has been mentioned in comments that if you do the following:

$younger = $myitems | Where-Object { $_.age -lt 20 } 
Write-Host "people younger than 20: $($younger.Length)" 

You won't get 1 as you might expect. This happens when a single pscustomobject is returned. Now this is not a problem for most of other objects in PowerShell, because they have surrogate properties for Length and Count. Unfortunately pscustomobject does not. This is fixed in PowerShell 6.1.0. You can work around this by using operator @():

$younger = @($myitems | Where-Object { $_.age -lt 20 })

For more background see here and here.

Update 2

In PowerShell 5 one can use Classes to acheive similar functionality. For example you can define a class like this:

class Person {
    [string]$name
    [int]$age
    [string]$info; `
`
    Person(
    [string]$name,
    [int]$age,
    [string]$info
    ){
        $this.name = $name
        $this.age = $age
        $this.info = $info
    }
}

Backticks here are so that you could copy and paste it to the command line, they are not required in a script. Once the class is defined you can the create an array the usual way:

$myitems =@([Person]::new("Joe",32,"something about him"),
[Person]::new("Sue",29,"something about her"),
[Person]::new("Cat",12,"something else"))

Note that this way does not have the drawback mentioned in the previous update, even in PowerShell 5.

Update 3

You can also intialize a class object with a hashtable, similar to the first example. For that you need to make sure that a default contructor defined. If you do not provide any constructors, one will be created for you, but if you provide a non-default one, default constructor won't be there and you will need to define it explicitly. Here is an example with default constructor that is auto-created:

class Person {
    [string]$name
    [int]$age
    [string]$info;
}

With that you can:

$person = @([Person]@{name='Kevin';age=36;info="something about him"}
[Person]@{name='Sue';age=29;info="something about her"}
[Person]@{name='Cat';age=12;info="something else"})

This is a bit more verbose, but also a bit more explicit. Thanks to @js2010 for pointing this out.

java.net.SocketException: Connection reset

Connection reset simply means that a TCP RST was received. This happens when your peer receives data that it can't process, and there can be various reasons for that.

The simplest is when you close the socket, and then write more data on the output stream. By closing the socket, you told your peer that you are done talking, and it can forget about your connection. When you send more data on that stream anyway, the peer rejects it with an RST to let you know it isn't listening.

In other cases, an intervening firewall or even the remote host itself might "forget" about your TCP connection. This could happen if you don't send any data for a long time (2 hours is a common time-out), or because the peer was rebooted and lost its information about active connections. Sending data on one of these defunct connections will cause a RST too.


Update in response to additional information:

Take a close look at your handling of the SocketTimeoutException. This exception is raised if the configured timeout is exceeded while blocked on a socket operation. The state of the socket itself is not changed when this exception is thrown, but if your exception handler closes the socket, and then tries to write to it, you'll be in a connection reset condition. setSoTimeout() is meant to give you a clean way to break out of a read() operation that might otherwise block forever, without doing dirty things like closing the socket from another thread.

jQuery: Slide left and slide right

If you don't want something bloated like jQuery UI, try my custom animations: https://github.com/yckart/jquery-custom-animations

For you, blindLeftToggle and blindRightToggle is the appropriate choice.

http://jsfiddle.net/ARTsinn/65QsU/

Node.js: socket.io close client connection

For socket.io version 1.4.5:

On server:

socket.on('end', function (){
    socket.disconnect(0);
});

On client:

var io = io();
io.emit('end');

SQL Server: how to create a stored procedure

To Create SQL server Store procedure in SQL server management studio

  • Expand your database
  • Expand programmatically
  • Right-click on Stored-procedure and Select "new Stored Procedure"

Now, Write your Store procedure, for example, it can be something like below

USE DatabaseName;  
GO  
CREATE PROCEDURE ProcedureName 
 @LastName nvarchar(50),   
 @FirstName nvarchar(50)   
AS   

SET NOCOUNT ON;  
 
//Your SQL query here, like
Select  FirstName, LastName, Department  
FROM HumanResources.vEmployeeDepartmentHistory  
WHERE FirstName = @FirstName AND LastName = @LastName  
GO  

Where, DatabaseName = name of your database
ProcedureName = name of SP
InputValue = your input parameter value (@LastName and @FirstName) and type = parameter type example nvarchar(50) etc.

Source: Stored procedure in sql server (With Example)

To Execute the above stored procedure you can use sample query as below

EXECUTE ProcedureName @FirstName = N'Pilar', @LastName = N'Ackerman';  

SQL Server Error : String or binary data would be truncated

this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in this case: you specify transaction_status varchar(10) but you actually trying to store
_transaction_status which contain 19 characters. that's why you faced this type of error in this code..

URLEncoder not able to translate space character

Encode Query params

org.apache.commons.httpclient.util.URIUtil
    URIUtil.encodeQuery(input);

OR if you want to escape chars within URI

public static String escapeURIPathParam(String input) {
  StringBuilder resultStr = new StringBuilder();
  for (char ch : input.toCharArray()) {
   if (isUnsafe(ch)) {
    resultStr.append('%');
    resultStr.append(toHex(ch / 16));
    resultStr.append(toHex(ch % 16));
   } else{
    resultStr.append(ch);
   }
  }
  return resultStr.toString();
 }

 private static char toHex(int ch) {
  return (char) (ch < 10 ? '0' + ch : 'A' + ch - 10);
 }

 private static boolean isUnsafe(char ch) {
  if (ch > 128 || ch < 0)
   return true;
  return " %$&+,/:;=?@<>#%".indexOf(ch) >= 0;
 }

Why does DEBUG=False setting make my django Static Files Access fail?

I did the following changes to my project/urls.py and it worked for me

Add this line : from django.conf.urls import url

and add : url(r'^media/(?P.*)$', serve, {'document_root': settings.MEDIA_ROOT, }), in urlpatterns.

How to read GET data from a URL using JavaScript?

I think this should also work:

function $_GET(q,s) {
    s = (s) ? s : window.location.search;
    var re = new RegExp('&amp;'+q+'=([^&amp;]*)','i');
    return (s=s.replace(/^\?/,'&amp;').match(re)) ?s=s[1] :s='';
}

Just call it like this:

var value = $_GET('myvariable');

What underlies this JavaScript idiom: var self = this?

It's a JavaScript quirk. When a function is a property of an object, more aptly called a method, this refers to the object. In the example of an event handler, the containing object is the element that triggered the event. When a standard function is invoked, this will refer to the global object. When you have nested functions as in your example, this does not relate to the context of the outer function at all. Inner functions do share scope with the containing function, so developers will use variations of var that = this in order to preserve the this they need in the inner function.

How to send emails from my Android application?

I was using something along the lines of the currently accepted answer in order to send emails with an attached binary error log file. GMail and K-9 send it just fine and it also arrives fine on my mail server. The only problem was my mail client of choice Thunderbird which had troubles with opening / saving the attached log file. In fact it simply didn't save the file at all without complaining.

I took a look at one of these mail's source codes and noticed that the log file attachment had (understandably) the mime type message/rfc822. Of course that attachment is not an attached email. But Thunderbird cannot cope with that tiny error gracefully. So that was kind of a bummer.

After a bit of research and experimenting I came up with the following solution:

public Intent createEmailOnlyChooserIntent(Intent source,
    CharSequence chooserTitle) {
    Stack<Intent> intents = new Stack<Intent>();
    Intent i = new Intent(Intent.ACTION_SENDTO, Uri.fromParts("mailto",
            "[email protected]", null));
    List<ResolveInfo> activities = getPackageManager()
            .queryIntentActivities(i, 0);

    for(ResolveInfo ri : activities) {
        Intent target = new Intent(source);
        target.setPackage(ri.activityInfo.packageName);
        intents.add(target);
    }

    if(!intents.isEmpty()) {
        Intent chooserIntent = Intent.createChooser(intents.remove(0),
                chooserTitle);
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS,
                intents.toArray(new Parcelable[intents.size()]));

        return chooserIntent;
    } else {
        return Intent.createChooser(source, chooserTitle);
    }
}

It can be used as follows:

Intent i = new Intent(Intent.ACTION_SEND);
i.setType("*/*");
i.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(crashLogFile));
i.putExtra(Intent.EXTRA_EMAIL, new String[] {
    ANDROID_SUPPORT_EMAIL
});
i.putExtra(Intent.EXTRA_SUBJECT, "Crash report");
i.putExtra(Intent.EXTRA_TEXT, "Some crash report details");

startActivity(createEmailOnlyChooserIntent(i, "Send via email"));

As you can see, the createEmailOnlyChooserIntent method can be easily fed with the correct intent and the correct mime type.

It then goes through the list of available activities that respond to an ACTION_SENDTO mailto protocol intent (which are email apps only) and constructs a chooser based on that list of activities and the original ACTION_SEND intent with the correct mime type.

Another advantage is that Skype is not listed anymore (which happens to respond to the rfc822 mime type).

Android Studio - Gradle sync project failed

I had a "Install build tools and sync" link in the lower right hand corner of my screen. I clicked on that and it fixed the issue.

DataGridView changing cell background color

dataGridView1.Rows[i].Cells[7].Style.BackColor = Color.LightGreen;

Count occurrences of a char in a string using Bash

I Would suggest the following:

var="any given string"
N=${#var}
G=${var//g/}
G=${#G}
(( G = N - G ))
echo "$G"

No call to any other program

Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

Thanks for the question. For YouTube iframe the first issue is the URL you have given, is it embedded URL or URL link from address bar. this error for non embed URL but if you want to give non embed URL then you need to code in "safe Pipe" like(for both non embedded or embed URL ) :

import {Pipe, PipeTransform} from '@angular/core';
import {DomSanitizer} from '@angular/platform-browser';

@Pipe({name: 'safe'})
export class SafePipe implements PipeTransform {

constructor(private sanitizer: DomSanitizer) {

}

transform(value: any, url: any): any {
    if (value && !url) {
        const regExp = /^.*(youtu.be\/|v\/|u\/\w\/|embed\/|watch\?v=|\&v=)([^#\&\?]*).*/;
        let match = value.match(regExp);
        if (match && match[2].length == 11) {
            console.log(match[2]);
            let sepratedID = match[2];
            let embedUrl = '//www.youtube.com/embed/' + sepratedID;
            return this.sanitizer.bypassSecurityTrustResourceUrl(embedUrl);
        }

     }

   }
}

it will split out "vedioId". You have to get video id then set to URL as embedded. In Html

 <div>
   <iframe width="100%" height="300" [src]="video.url | safe"></iframe>
 </div>

Angular 2/5 thanks again.

Query to get only numbers from a string

If you are using Postgres and you have data like '2000 - some sample text' then try substring and position combination, otherwise if in your scenario there is no delimiter, you need to write regex:

SUBSTRING(Column_name from 0 for POSITION('-' in column_name) - 1) as 
number_column_name

Maintain aspect ratio of div but fill screen width and height in CSS?

Danield's answer is good, but it can only be used when the div fills the whole viewport, or by using a bit of calc, can be used if the width and height of the other content in the viewport is known.

However, by combining the margin-bottom trick with the method in the aforementioned answer, the problem can be reduced to just having to know the height of the other content. This is useful if you have a fixed height header, but the width of the sidebar, for example, is not known.

_x000D_
_x000D_
body {_x000D_
  margin: 0;_x000D_
  margin-top: 100px; /* simulating a header */_x000D_
}_x000D_
_x000D_
main {_x000D_
  margin: 0 auto;_x000D_
  max-width: calc(200vh - 200px);_x000D_
}_x000D_
_x000D_
section {_x000D_
  padding-bottom: 50%;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
div {_x000D_
  position:absolute;_x000D_
  background-color: red;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  bottom: 0;_x000D_
  right: 0;_x000D_
}
_x000D_
<main>_x000D_
  <section>_x000D_
    <div></div>_x000D_
  </section>_x000D_
</main>
_x000D_
_x000D_
_x000D_

Here it is in a jsfiddle using scss, which makes it more obvious where the values come from.

How to replace local branch with remote branch entirely in Git?

git checkout .

i always use this command to replace my local changes with repository changes. git checkout space dot.

What is the difference between 127.0.0.1 and localhost

The main difference is that the connection can be made via Unix Domain Socket, as stated here: localhost vs. 127.0.0.1

How do I pass an object to HttpClient.PostAsync and serialize as a JSON body?

A simple solution is to use Microsoft ASP.NET Web API 2.2 Client from NuGet.

Then you can simply do this and it'll serialize the object to JSON and set the Content-Type header to application/json; charset=utf-8:

var data = new
{
    name = "Foo",
    category = "article"
};

var client = new HttpClient();
client.BaseAddress = new Uri(baseUri);
client.DefaultRequestHeaders.Add("token", token);
var response = await client.PostAsJsonAsync("", data);

How to get the list of files in a directory in a shell script?

Here's another way of listing files inside a directory (using a different tool, not as efficient as some of the other answers).

cd "search_dir"
for [ z in `echo *` ]; do
    echo "$z"
done

echo * Outputs all files of the current directory. The for loop iterates over each file name and prints to stdout.

Additionally, If looking for directories inside the directory then place this inside the for loop:

if [ test -d $z ]; then
    echo "$z is a directory"
fi

test -d checks if the file is a directory.

How to export JSON from MongoDB using Robomongo

Using a robomongo shell script:

//on the same db
var cursor = db.collectionname.find();

while (cursor.hasNext()) {
    var record = cursor.next();   
    db.new_collectionname.save(record);
}

Using mongodb's export and import command

You can add the --jsonArray parameter / flag to your mongoexport command, this exports the result as single json array.

Then just specify the --jsonArray flag again when importing.

Or remove the starting and ending array brackets [] in the file, then your modified & exported file will import with the mongoimport command without the --jsonArray flag.

More on Export here: https://docs.mongodb.org/manual/reference/program/mongoexport/#cmdoption--jsonArray

Import here: https://docs.mongodb.org/manual/reference/program/mongoimport/#cmdoption--jsonArray

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

This may not be relevant to your specific issue, but I had a similar problem when the pickle archive had been created using gzip.

For example if a compressed pickle archive is made like this,

import gzip, pickle
with gzip.open('test.pklz', 'wb') as ofp:
    pickle.dump([1,2,3], ofp)

Trying to open it throws the errors

 with open('test.pklz', 'rb') as ifp:
     print(pickle.load(ifp))
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
_pickle.UnpicklingError: invalid load key, ''.

But, if the pickle file is opened using gzip all is harmonious

with gzip.open('test.pklz', 'rb') as ifp:
    print(pickle.load(ifp))

[1, 2, 3]

Grab a segment of an array in Java without creating a new array on heap

Use java.nio.Buffer's. It's a lightweight wrapper for buffers of various primitive types and helps manage slicing, position, conversion, byte ordering, etc.

If your bytes originate from a Stream, the NIO Buffers can use "direct mode" which creates a buffer backed by native resources. This can improve performance in a lot of cases.

How to convert string to integer in C#

int i;

string result = Something;

i = Convert.ToInt32(result);

dynamically add and remove view to viewpager

I did a similar program. hope this would help you.In its first activity four grid data can be selected. On the next activity, there is a view pager which contains two mandatory pages.And 4 more pages will be there, which will be visible corresponding to the grid data selected.

Following is the mainactivty MainActivity

    package com.example.jeffy.viewpagerapp;
    import android.content.Context;
    import android.content.Intent;
    import android.content.SharedPreferences;
    import android.database.Cursor;
    import android.database.SQLException;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;
    import android.os.Bundle;
    import android.os.Parcel;
    import android.support.design.widget.FloatingActionButton;
    import android.support.design.widget.Snackbar;
    import android.support.v7.app.AppCompatActivity;
    import android.support.v7.widget.Toolbar;
    import android.util.Log;
    import android.view.View;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.widget.AdapterView;
    import android.widget.Button;
    import android.widget.GridView;
    import java.lang.reflect.Array;
    import java.util.ArrayList;
    public class MainActivity extends AppCompatActivity {
    SharedPreferences pref;
    SharedPreferences.Editor editor;
    GridView gridView;
    Button button;
    private static final String DATABASE_NAME = "dbForTest.db";
    private static final int DATABASE_VERSION = 1;
    private static final String TABLE_NAME = "diary";
    private static final String TITLE = "id";
    private static final String BODY = "content";
    DBHelper  dbHelper = new DBHelper(this);
    ArrayList<String> frags = new ArrayList<String>();
    ArrayList<FragmentArray> fragmentArray = new ArrayList<FragmentArray>();
    String[] selectedData;
    Boolean port1=false,port2=false,port3=false,port4=false;
    int Iport1=1,Iport2=1,Iport3=1,Iport4=1,location;



    // This Data show in grid ( Used by adapter )
        CustomGridAdapter customGridAdapter = new           CustomGridAdapter(MainActivity.this,GRID_DATA);
    static final String[ ] GRID_DATA = new String[] {
            "1" ,
            "2",
            "3" ,
            "4"
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        frags.add("TabFragment3");
        frags.add("TabFragment4");
        frags.add("TabFragment5");
        frags.add("TabFragment6");
        dbHelper = new DBHelper(this);
        dbHelper.insertContact(1,0);
        dbHelper.insertContact(2,0);
        dbHelper.insertContact(3,0);
        dbHelper.insertContact(4,0);
        final Bundle selected = new Bundle();
        button = (Button) findViewById(R.id.button);
        pref = getApplicationContext().getSharedPreferences("MyPref", MODE_PRIVATE);
        editor = pref.edit();
        gridView = (GridView) findViewById(R.id.gridView1);

        gridView.setAdapter(customGridAdapter);

        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
              //view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                location = position + 1;
                if (position == 0) {
                    Iport1++;
                    Iport1 = Iport1 % 2;
                    if (Iport1 % 2 == 1) {
                        //dbHelper.updateContact(1,1);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(1,1);
                    } else {
                        //dbHelper.updateContact(1,0);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(1, 0);
                    }
                }
                if (position == 1) {
                    Iport2++;
                    Iport1 = Iport1 % 2;
                    if (Iport2 % 2 == 1) {
                        //dbHelper.updateContact(2,1);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(2, 1);
                    } else {
                        //dbHelper.updateContact(2,0);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(2,0);
                    }
                }
                if (position == 2) {
                    Iport3++;
                    Iport3 = Iport3 % 2;
                    if (Iport3 % 2 == 1) {
                        //dbHelper.updateContact(3,1);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(3, 1);
                    } else {
                        //dbHelper.updateContact(3,0);
                        view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(3, 0);
                    }
                }
                if (position == 3) {
                    Iport4++;
                    Iport4 = Iport4 % 2;
                    if (Iport4 % 2 == 1) {
                        //dbHelper.updateContact(4,1);
                       view.findViewById(R.id.grid_item_image).setVisibility(View.VISIBLE);
                        dbHelper.updateContact(4, 1);
                    } else {
                        //dbHelper.updateContact(4,0);
                       view.findViewById(R.id.grid_item_image).setVisibility(View.INVISIBLE);
                        dbHelper.updateContact(4,0);
                    }
                }
            }
        });
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                editor.putInt("port1", Iport1);
                editor.putInt("port2", Iport2);
                editor.putInt("port3", Iport3);
                editor.putInt("port4", Iport4);
                Intent i = new Intent(MainActivity.this,Main2Activity.class);
                if(Iport1==1)
                    i.putExtra("3","TabFragment3");
                else
                    i.putExtra("3", "");
                if(Iport2==1)
                    i.putExtra("4","TabFragment4");
                else
                    i.putExtra("4","");
                if(Iport3==1)
                    i.putExtra("5", "TabFragment5");
                else
                    i.putExtra("5","");
                if(Iport4==1)
                    i.putExtra("6", "TabFragment6");
                else
                    i.putExtra("6","");
                dbHelper.updateContact(0, Iport1);
                dbHelper.updateContact(1, Iport2);
                dbHelper.updateContact(2, Iport3);
                dbHelper.updateContact(3, Iport4);
                startActivity(i);
            }
        });
    }
}

Here TabFragment1,TabFragment2 etc are fragment to be displayed on the viewpager.And I am not showing the layouts since they are out of scope of this project.

MainActivity will intent to Main2Activity Main2Activity

    package com.example.jeffy.viewpagerapp;

import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.design.widget.CollapsingToolbarLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.FrameLayout;

import java.util.ArrayList;

public class Main2Activity extends AppCompatActivity {

    private ViewPager pager = null;
    private PagerAdapter pagerAdapter = null;
    DBHelper dbHelper;
    Cursor rs;
    int port1,port2,port3,port4;
    //-----------------------------------------------------------------------------
    @Override
    public void onCreate (Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.MyToolbar);
        setSupportActionBar(toolbar);

        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        CollapsingToolbarLayout collapsingToolbar =
                (CollapsingToolbarLayout) findViewById(R.id.collapse_toolbar);


        NestedScrollView scrollView = (NestedScrollView) findViewById (R.id.nested);
        scrollView.setFillViewport (true);

        ArrayList<String > selectedPort = new ArrayList<String>();

        Intent intent = getIntent();
        String Tab3 = intent.getStringExtra("3");
        String Tab4 = intent.getStringExtra("4");
        String Tab5 = intent.getStringExtra("5");
        String Tab6 = intent.getStringExtra("6");

        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
        tabLayout.addTab(tabLayout.newTab().setText("View"));
        tabLayout.addTab(tabLayout.newTab().setText("All"));

        selectedPort.add("TabFragment1");
        selectedPort.add("TabFragment2");
        if(Tab3!=null && !TextUtils.isEmpty(Tab3))
        selectedPort.add(Tab3);
        if(Tab4!=null && !TextUtils.isEmpty(Tab4))
        selectedPort.add(Tab4);
        if(Tab5!=null && !TextUtils.isEmpty(Tab5))
        selectedPort.add(Tab5);
        if(Tab6!=null && !TextUtils.isEmpty(Tab6))
        selectedPort.add(Tab6);



        dbHelper = new DBHelper(this);
//        rs=dbHelper.getData(1);
//        port1 = rs.getInt(rs.getColumnIndex("id"));
//
//        rs=dbHelper.getData(2);
//        port2 = rs.getInt(rs.getColumnIndex("id"));
//
//        rs=dbHelper.getData(3);
//        port3 = rs.getInt(rs.getColumnIndex("id"));
//
//        rs=dbHelper.getData(4);
//        port4 = rs.getInt(rs.getColumnIndex("id"));


        Log.i(">>>>>>>>>>>>>>", "port 1" + port1 + "port 2" + port2 + "port 3" + port3 + "port 4" + port4);

        if(Tab3!=null && !TextUtils.isEmpty(Tab3))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 0"));
        if(Tab3!=null && !TextUtils.isEmpty(Tab4))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
        if(Tab3!=null && !TextUtils.isEmpty(Tab5))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
        if(Tab3!=null && !TextUtils.isEmpty(Tab6))
        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
        final PagerAdapter adapter = new PagerAdapter
                (getSupportFragmentManager(), tabLayout.getTabCount(), selectedPort);
        viewPager.setAdapter(adapter);
        viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
        tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
//        setContentView(R.layout.activity_main2);
//        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//        setSupportActionBar(toolbar);

//        TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
//        tabLayout.addTab(tabLayout.newTab().setText("View"));
//        tabLayout.addTab(tabLayout.newTab().setText("All"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 0"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 1"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 2"));
//        tabLayout.addTab(tabLayout.newTab().setText("Tab 3"));
//        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);


}
    }

ViewPagerAdapter Viewpageradapter.class

package com.example.jeffy.viewpagerapp;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.View;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Jeffy on 25-01-2016.
 */
public class PagerAdapter extends FragmentStatePagerAdapter {
    int mNumOfTabs;

    List<String> values;

    public PagerAdapter(FragmentManager fm, int NumOfTabs, List<String> Port) {
        super(fm);
        this.mNumOfTabs = NumOfTabs;
        this.values= Port;
    }


    @Override
    public Fragment getItem(int position) {


        String fragmentName = values.get(position);
        Class<?> clazz = null;
        Object fragment = null;
        try {
            clazz = Class.forName("com.example.jeffy.viewpagerapp."+fragmentName);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            fragment = clazz.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }

        return (Fragment) fragment;
    }

    @Override
    public int getCount() {
        return values.size();
    }
}

Layout for main2activity acticity_main2.xml

    <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/main_content"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fitsSystemWindows="true">

        <android.support.design.widget.AppBarLayout
            android:id="@+id/MyAppbar"
            android:layout_width="match_parent"
            android:layout_height="256dp"
            android:fitsSystemWindows="true">

            <android.support.design.widget.CollapsingToolbarLayout
                android:id="@+id/collapse_toolbar"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                app:layout_scrollFlags="scroll|exitUntilCollapsed"
                android:background="@color/material_deep_teal_500"
                android:fitsSystemWindows="true">

                <ImageView
                    android:id="@+id/bgheader"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:scaleType="centerCrop"
                    android:fitsSystemWindows="true"
                    android:background="@drawable/screen"
                    app:layout_collapseMode="pin" />

                <android.support.v7.widget.Toolbar
                    android:id="@+id/MyToolbar"
                    android:layout_width="match_parent"
                    android:layout_height="?attr/actionBarSize"
                    app:layout_collapseMode="parallax" />





            </android.support.design.widget.CollapsingToolbarLayout>

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.widget.NestedScrollView
            android:layout_width="match_parent"
            android:id="@+id/nested"
            android:layout_height="match_parent"
            android:layout_gravity="fill_vertical"
            app:layout_behavior="@string/appbar_scrolling_view_behavior">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <android.support.design.widget.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/MyToolbar"
            android:background="?attr/colorPrimary"
            android:elevation="6dp"
            android:minHeight="?attr/actionBarSize"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"/>


        <android.support.v4.view.ViewPager
            xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/view_pager"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >

        </android.support.v4.view.ViewPager>
    </LinearLayout>


        </android.support.v4.widget.NestedScrollView>

    </android.support.design.widget.CoordinatorLayout>

Mainactivity layout
activity_main.xml

        <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.example.jeffy.viewpagerapp.MainActivity"
    tools:showIn="@layout/activity_main">


<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <GridView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/gridView1"
        android:numColumns="2"
        android:gravity="center"
        android:columnWidth="100dp"
        android:stretchMode="columnWidth"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

    </GridView>

    <Button
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SAVE"
        android:id="@+id/button" />

</LinearLayout>




</RelativeLayout>

Hope this would help someone... Click up button please if this helped you

Simple way to sort strings in the (case sensitive) alphabetical order

The simple way to solve the problem is to use ComparisonChain from Guava http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/ComparisonChain.html

private static Comparator<String> stringAlphabeticalComparator = new Comparator<String>() {
        public int compare(String str1, String str2) {
            return ComparisonChain.start().
                                compare(str1,str2, String.CASE_INSENSITIVE_ORDER).
                                compare(str1,str2).
                                result();
         }
 };
Collections.sort(list, stringAlphabeticalComparator);

The first comparator from the chain will sort strings according to the case insensitive order, and the second comparator will sort strings according to the case insensitive order. As excepted strings appear in the result according to the alphabetical order:

"AA","Aa","aa","Development","development"

Creating your own header file in C

header files contain prototypes for functions you define in a .c or .cpp/.cxx file (depending if you're using c or c++). You want to place #ifndef/#defines around your .h code so that if you include the same .h twice in different parts of your programs, the prototypes are only included once.

client.h

#ifndef CLIENT_H
#define CLIENT_H

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);


#endif /** CLIENT_H */

Then you'd implement the .h in a .c file like so:

client.c

#include "client.h"

short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
 short ret = -1;
 //some implementation here
 return ret;
}

Moving from one activity to another Activity in Android

You can do

Intent i = new Intent(classname.this , targetclass.class);
startActivity(i);

Retrieve the commit log for a specific line in a file?

Simplifying @matt's answer -

git blame -L14,15 -- <file_path>

Here you will get a blame for a lines 14 to 15.

Since -L option expects Range as a param we can't get a Blame for a single line using the -L option`.

Reference

MySQL Calculate Percentage

try this

   SELECT group_name, employees, surveys, COUNT( surveys ) AS test1, 
        concat(round(( surveys/employees * 100 ),2),'%') AS percentage
    FROM a_test
    GROUP BY employees

DEMO HERE

The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

My problem turned out to be blank spaces in the txt file that I was using to feed the WMI Powershell script.

Filter element based on .data() key/value

Two things I noticed (they may be mistakes from when you wrote it down though).

  1. You missed a dot in the first example ( $('.navlink').click )
  2. For filter to work, you have to return a value ( return $(this).data("selected")==true )

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

What works for me was right-click on the .ps1 file and then properties. Click the "UNBLOCK" button. Works great fir me after spending hours trying to change the policies.

Replace a newline in TSQL

If you have an issue where you only want to remove trailing characters, you can try this:

WHILE EXISTS
(SELECT * FROM @ReportSet WHERE
    ASCII(right(addr_3,1)) = 10
    OR ASCII(right(addr_3,1)) = 13
    OR ASCII(right(addr_3,1)) = 32)
BEGIN
    UPDATE @ReportSet
    SET addr_3 = LEFT(addr_3,LEN(addr_3)-1)
    WHERE 
    ASCII(right(addr_3,1)) = 10
    OR ASCII(right(addr_3,1)) = 13
    OR ASCII(right(addr_3,1)) = 32
END

This solved a problem I had with addresses where a procedure created a field with a fixed number of lines, even if those lines were empty. To save space in my SSRS report, I cut them down.

Git: How to commit a manually deleted file?

It says right there in the output of git status:

#   (use "git add/rm <file>..." to update what will be committed)

so just do:

git rm <filename>

Undefined reference to pthread_create in Linux

check man page and you will get.

Compile and link with -pthread.

SYNOPSIS
       #include <pthread.h>

       int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
                          void *(*start_routine) (void *), void *arg);


       Compile and link with -pthread.
       ....

How do you run a Python script as a service in Windows?

The accepted answer using win32serviceutil works but is complicated and makes debugging and changes harder. It is far easier to use NSSM (the Non-Sucking Service Manager). You write and comfortably debug a normal python program and when it finally works you use NSSM to install it as a service in less than a minute:

From an elevated (admin) command prompt you run nssm.exe install NameOfYourService and you fill-in these options:

  • path: (the path to python.exe e.g. C:\Python27\Python.exe)
  • Arguments: (the path to your python script, e.g. c:\path\to\program.py)

By the way, if your program prints useful messages that you want to keep in a log file NSSM can also handle this and a lot more for you.

Functional, Declarative, and Imperative Programming

At the time of writing this, the top voted answers on this page are imprecise and muddled on the declarative vs. imperative definition, including the answer that quotes Wikipedia. Some answers are conflating the terms in different ways.

Refer also to my explanation of why spreadsheet programming is declarative, regardless that the formulas mutate the cells.

Also, several answers claim that functional programming must be a subset of declarative. On that point it depends if we differentiate "function" from "procedure". Lets handle imperative vs. declarative first.

Definition of declarative expression

The only attribute that can possibly differentiate a declarative expression from an imperative expression is the referential transparency (RT) of its sub-expressions. All other attributes are either shared between both types of expressions, or derived from the RT.

A 100% declarative language (i.e. one in which every possible expression is RT) does not (among other RT requirements) allow the mutation of stored values, e.g. HTML and most of Haskell.

Definition of RT expression

RT is often referred to as having "no side-effects". The term effects does not have a precise definition, so some people don't agree that "no side-effects" is the same as RT. RT has a precise definition:

An expression e is referentially transparent if for all programs p every occurrence of e in p can be replaced with the result of evaluating e, without affecting the observable result of p.

Since every sub-expression is conceptually a function call, RT requires that the implementation of a function (i.e. the expression(s) inside the called function) may not access the mutable state that is external to the function (accessing the mutable local state is allowed). Put simply, the function (implementation) should be pure.

Definition of pure function

A pure function is often said to have "no side-effects". The term effects does not have a precise definition, so some people don't agree.

Pure functions have the following attributes.

  • the only observable output is the return value.
  • the only output dependency is the arguments.
  • arguments are fully determined before any output is generated.

Remember that RT applies to expressions (which includes function calls) and purity applies to (implementations of) functions.

An obscure example of impure functions that make RT expressions is concurrency, but this is because the purity is broken at the interrupt abstraction layer. You don't really need to know this. To make RT expressions, you call pure functions.

Derivative attributes of RT

Any other attribute cited for declarative programming, e.g. the citation from 1999 used by Wikipedia, either derives from RT, or is shared with imperative programming. Thus proving that my precise definition is correct.

Note, immutability of external values is a subset of the requirements for RT.

  • Declarative languages don't have looping control structures, e.g. for and while, because due to immutability, the loop condition would never change.

  • Declarative languages don't express control-flow other than nested function order (a.k.a logical dependencies), because due to immutability, other choices of evaluation order do not change the result (see below).

  • Declarative languages express logical "steps" (i.e. the nested RT function call order), but whether each function call is a higher level semantic (i.e. "what to do") is not a requirement of declarative programming. The distinction from imperative is that due to immutability (i.e. more generally RT), these "steps" cannot depend on mutable state, rather only the relational order of the expressed logic (i.e. the order of nesting of the function calls, a.k.a. sub-expressions).

For example, the HTML paragraph <p> cannot be displayed until the sub-expressions (i.e. tags) in the paragraph have been evaluated. There is no mutable state, only an order dependency due to the logical relationship of tag hierarchy (nesting of sub-expressions, which are analogously nested function calls).

  • Thus there is the derivative attribute of immutability (more generally RT), that declarative expressions, express only the logical relationships of the constituent parts (i.e. of the sub-expression function arguments) and not mutable state relationships.

Evaluation order

The choice of evaluation order of sub-expressions can only give a varying result when any of the function calls are not RT (i.e. the function is not pure), e.g. some mutable state external to a function is accessed within the function.

For example, given some nested expressions, e.g. f( g(a, b), h(c, d) ), eager and lazy evaluation of the function arguments will give the same results if the functions f, g, and h are pure.

Whereas, if the functions f, g, and h are not pure, then the choice of evaluation order can give a different result.

Note, nested expressions are conceptually nested functions, since expression operators are just function calls masquerading as unary prefix, unary postfix, or binary infix notation.

Tangentially, if all identifiers, e.g. a, b, c, d, are immutable everywhere, state external to the program cannot be accessed (i.e. I/O), and there is no abstraction layer breakage, then functions are always pure.

By the way, Haskell has a different syntax, f (g a b) (h c d).

Evaluation order details

A function is a state transition (not a mutable stored value) from the input to the output. For RT compositions of calls to pure functions, the order-of-execution of these state transitions is independent. The state transition of each function call is independent of the others, due to lack of side-effects and the principle that an RT function may be replaced by its cached value. To correct a popular misconception, pure monadic composition is always declarative and RT, in spite of the fact that Haskell's IO monad is arguably impure and thus imperative w.r.t. the World state external to the program (but in the sense of the caveat below, the side-effects are isolated).

Eager evaluation means the functions arguments are evaluated before the function is called, and lazy evaluation means the arguments are not evaluated until (and if) they are accessed within the function.

Definition: function parameters are declared at the function definition site, and function arguments are supplied at the function call site. Know the difference between parameter and argument.

Conceptually, all expressions are (a composition of) function calls, e.g. constants are functions without inputs, unary operators are functions with one input, binary infix operators are functions with two inputs, constructors are functions, and even control statements (e.g. if, for, while) can be modeled with functions. The order that these argument functions (do not confuse with nested function call order) are evaluated is not declared by the syntax, e.g. f( g() ) could eagerly evaluate g then f on g's result or it could evaluate f and only lazily evaluate g when its result is needed within f.

Caveat, no Turing complete language (i.e. that allows unbounded recursion) is perfectly declarative, e.g. lazy evaluation introduces memory and time indeterminism. But these side-effects due to the choice of evaluation order are limited to memory consumption, execution time, latency, non-termination, and external hysteresis thus external synchronization.

Functional programming

Because declarative programming cannot have loops, then the only way to iterate is functional recursion. It is in this sense that functional programming is related to declarative programming.

But functional programming is not limited to declarative programming. Functional composition can be contrasted with subtyping, especially with respect to the Expression Problem, where extension can be achieved by either adding subtypes or functional decomposition. Extension can be a mix of both methodologies.

Functional programming usually makes the function a first-class object, meaning the function type can appear in the grammar anywhere any other type may. The upshot is that functions can input and operate on functions, thus providing for separation-of-concerns by emphasizing function composition, i.e. separating the dependencies among the subcomputations of a deterministic computation.

For example, instead of writing a separate function (and employing recursion instead of loops if the function must also be declarative) for each of an infinite number of possible specialized actions that could be applied to each element of a collection, functional programming employs reusable iteration functions, e.g. map, fold, filter. These iteration functions input a first-class specialized action function. These iteration functions iterate the collection and call the input specialized action function for each element. These action functions are more concise because they no longer need to contain the looping statements to iterate the collection.

However, note that if a function is not pure, then it is really a procedure. We can perhaps argue that functional programming that uses impure functions, is really procedural programming. Thus if we agree that declarative expressions are RT, then we can say that procedural programming is not declarative programming, and thus we might argue that functional programming is always RT and must be a subset of declarative programming.

Parallelism

This functional composition with first-class functions can express the depth in the parallelism by separating out the independent function.

Brent’s Principle: computation with work w and depth d can be implemented in a p-processor PRAM in time O(max(w/p, d)).

Both concurrency and parallelism also require declarative programming, i.e. immutability and RT.

So where did this dangerous assumption that Parallelism == Concurrency come from? It’s a natural consequence of languages with side-effects: when your language has side-effects everywhere, then any time you try to do more than one thing at a time you essentially have non-determinism caused by the interleaving of the effects from each operation. So in side-effecty languages, the only way to get parallelism is concurrency; it’s therefore not surprising that we often see the two conflated.

FP evaluation order

Note the evaluation order also impacts the termination and performance side-effects of functional composition.

Eager (CBV) and lazy (CBN) are categorical duels[10], because they have reversed evaluation order, i.e. whether the outer or inner functions respectively are evaluated first. Imagine an upside-down tree, then eager evaluates from function tree branch tips up the branch hierarchy to the top-level function trunk; whereas, lazy evaluates from the trunk down to the branch tips. Eager doesn't have conjunctive products ("and", a/k/a categorical "products") and lazy doesn't have disjunctive coproducts ("or", a/k/a categorical "sums")[11].

Performance

  • Eager

As with non-termination, eager is too eager with conjunctive functional composition, i.e. compositional control structure does unnecessary work that isn't done with lazy. For example, eager eagerly and unnecessarily maps the entire list to booleans, when it is composed with a fold that terminates on the first true element.

This unnecessary work is the cause of the claimed "up to" an extra log n factor in the sequential time complexity of eager versus lazy, both with pure functions. A solution is to use functors (e.g. lists) with lazy constructors (i.e. eager with optional lazy products), because with eager the eagerness incorrectness originates from the inner function. This is because products are constructive types, i.e. inductive types with an initial algebra on an initial fixpoint[11]

  • Lazy

As with non-termination, lazy is too lazy with disjunctive functional composition, i.e. coinductive finality can occur later than necessary, resulting in both unnecessary work and non-determinism of the lateness that isn't the case with eager[10][11]. Examples of finality are state, timing, non-termination, and runtime exceptions. These are imperative side-effects, but even in a pure declarative language (e.g. Haskell), there is state in the imperative IO monad (note: not all monads are imperative!) implicit in space allocation, and timing is state relative to the imperative real world. Using lazy even with optional eager coproducts leaks "laziness" into inner coproducts, because with lazy the laziness incorrectness originates from the outer function (see the example in the Non-termination section, where == is an outer binary operator function). This is because coproducts are bounded by finality, i.e. coinductive types with a final algebra on an final object[11].

Lazy causes indeterminism in the design and debugging of functions for latency and space, the debugging of which is probably beyond the capabilities of the majority of programmers, because of the dissonance between the declared function hierarchy and the runtime order-of-evaluation. Lazy pure functions evaluated with eager, could potentially introduce previously unseen non-termination at runtime. Conversely, eager pure functions evaluated with lazy, could potentially introduce previously unseen space and latency indeterminism at runtime.

Non-termination

At compile-time, due to the Halting problem and mutual recursion in a Turing complete language, functions can't generally be guaranteed to terminate.

  • Eager

With eager but not lazy, for the conjunction of Head "and" Tail, if either Head or Tail doesn't terminate, then respectively either List( Head(), Tail() ).tail == Tail() or List( Head(), Tail() ).head == Head() is not true because the left-side doesn't, and right-side does, terminate.

Whereas, with lazy both sides terminate. Thus eager is too eager with conjunctive products, and non-terminates (including runtime exceptions) in those cases where it isn't necessary.

  • Lazy

With lazy but not eager, for the disjunction of 1 "or" 2, if f doesn't terminate, then List( f ? 1 : 2, 3 ).tail == (f ? List( 1, 3 ) : List( 2, 3 )).tail is not true because the left-side terminates, and right-side doesn't.

Whereas, with eager neither side terminates so the equality test is never reached. Thus lazy is too lazy with disjunctive coproducts, and in those cases fails to terminate (including runtime exceptions) after doing more work than eager would have.

[10] Declarative Continuations and Categorical Duality, Filinski, sections 2.5.4 A comparison of CBV and CBN, and 3.6.1 CBV and CBN in the SCL.

[11] Declarative Continuations and Categorical Duality, Filinski, sections 2.2.1 Products and coproducts, 2.2.2 Terminal and initial objects, 2.5.2 CBV with lazy products, and 2.5.3 CBN with eager coproducts.

Should I write script in the body or the head of the html?

The problem with writing scripts at the head of a page is blocking. The browser must stop processing the page until the script is download, parsed and executed. The reason for this is pretty clear, these scripts might insert more into the page changing the result of the rendering, they also may remove things that dont need to be rendered, etc.

Some of the more modern browsers violate this rule by not blocking on the downloading the scripts (ie8 was the first) but overall the download isn't the majority of the time spent blocking.

Check out Even Faster Websites, I just finished reading it and it goes over all of the fast ways to get scripts onto a page, Including putting scripts at the bottom of the page to allow rendering to complete (better UX).

Call ASP.NET function from JavaScript?

I think blog post How to fetch & show SQL Server database data in ASP.NET page using Ajax (jQuery) will help you.

JavaScript Code

<script src="http://code.jquery.com/jquery-3.3.1.js" />
<script language="javascript" type="text/javascript">

    function GetCompanies() {
        $("#UpdatePanel").html("<div style='text-align:center; background-color:yellow; border:1px solid red; padding:3px; width:200px'>Please Wait...</div>");
        $.ajax({
            type: "POST",
            url: "Default.aspx/GetCompanies",
            data: "{}",
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            success: OnSuccess,
            error: OnError
        });
    }

    function OnSuccess(data) {
        var TableContent = "<table border='0'>" +
                                "<tr>" +
                                    "<td>Rank</td>" +
                                    "<td>Company Name</td>" +
                                    "<td>Revenue</td>" +
                                    "<td>Industry</td>" +
                                "</tr>";
        for (var i = 0; i < data.d.length; i++) {
            TableContent += "<tr>" +
                                    "<td>"+ data.d[i].Rank +"</td>" +
                                    "<td>"+data.d[i].CompanyName+"</td>" +
                                    "<td>"+data.d[i].Revenue+"</td>" +
                                    "<td>"+data.d[i].Industry+"</td>" +
                                "</tr>";
        }
        TableContent += "</table>";

        $("#UpdatePanel").html(TableContent);
    }

    function OnError(data) {

    }
</script>

ASP.NET Server Side Function

[WebMethod]
[ScriptMethod(ResponseFormat= ResponseFormat.Json)]
public static List<TopCompany> GetCompanies()
{
    System.Threading.Thread.Sleep(5000);
    List<TopCompany> allCompany = new List<TopCompany>();
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        allCompany = dc.TopCompanies.ToList();
    }
    return allCompany;
}

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

In tensorflow you create graphs and pass values to that graph. Graph does all the hardwork and generate the output based on the configuration that you have made in the graph. Now When you pass values to the graph then first you need to create a tensorflow session.

tf.Session()

Once session is initialized then you are supposed to use that session because all the variables and settings are now part of the session. So, there are two ways to pass external values to the graph so that graph accepts them. One is to call the .run() while you are using the session being executed.

Other way which is basically a shortcut to this is to use .eval(). I said shortcut because the full form of .eval() is

tf.get_default_session().run(values)

You can check that yourself. At the place of values.eval() run tf.get_default_session().run(values). You must get the same behavior.

what eval is doing is using the default session and then executing run().

How to update/modify an XML file in python?

Useful Python XML parsers:

  1. Minidom - functional but limited
  2. ElementTree - decent performance, more functionality
  3. lxml - high-performance in most cases, high functionality including real xpath support

Any of those is better than trying to update the XML file as strings of text.

What that means to you:

Open your file with an XML parser of your choice, find the node you're interested in, replace the value, serialize the file back out.

How generate unique Integers based on GUIDs

Eric Lippert did a very interesting (as always) post about the probability of hash collisions.

You should read it all but he concluded with this very illustrative graphic:

Probability of hash collisions

Related to your specific question, I would also go with GetHashCode since collisions will be unavoidable either way.

Display text on MouseOver for image in html

You can use title attribute.

<img src="smiley.gif"  title="Smiley face"/>

You can change the source of image as you want.

And as @Gray commented:

You can also use the title on other things like <a ... anchors, <p>, <div>, <input>, etc. See: this

How to convert timestamps to dates in Bash?

I have written a script that does this myself:

#!/bin/bash
LANG=C
if [ -z "$1" ]; then
    if [  "$(tty)" = "not a tty" ]; then
            p=`cat`;
    else
            echo "No timestamp given."
            exit
    fi
else
    p=$1
fi
echo $p | gawk '{ print strftime("%c", $0); }'

Hidden features of Windows batch files

Total control over output with spacing and escape characters.:

echo.    ^<resourceDir^>/%basedir%/resources^</resourceDir^>

IF EXISTS condition not working with PLSQL

Unfortunately PL/SQL doesn't have IF EXISTS operator like SQL Server. But you can do something like this:

begin
  for x in ( select count(*) cnt
               from dual 
              where exists (
                select 1 from courseoffering co
                  join co_enrolment ce on ce.co_id = co.co_id
                 where ce.s_regno = 403 
                   and ce.coe_completionstatus = 'C' 
                   and co.c_id = 803 ) )
  loop
        if ( x.cnt = 1 ) 
        then
           dbms_output.put_line('exists');
        else 
           dbms_output.put_line('does not exist');
        end if;
  end loop;
end;
/

Can't use Swift classes inside Objective-C

XCode 11.3.1:

When I want to use an Swift inner class in a objc code, it does not compile for ther error "undefined symbol"(for bother inner class and outer class), I checked the generated "-swift.h" header and both classes are there.

After trying for hours I convert the inner class to a normal class and it compiles.

I clean the project, delete the DerivedData folder and it compiles.

Horizontal scroll on overflow of table

   .search-table-outter {border:2px solid red; overflow-x:scroll;}
   .search-table{table-layout: fixed; margin:40px auto 0px auto;   }
   .search-table, td, th{border-collapse:collapse; border:1px solid #777;}
   th{padding:20px 7px; font-size:15px; color:#444; background:#66C2E0;}
   td{padding:5px 10px; height:35px;}

You should provide scroll in div.

PHP: Inserting Values from the Form into MySQL

The following code just declares a string variable that contains a MySQL query:

$sql = "INSERT INTO users (username, password, email)
    VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";

It does not execute the query. In order to do that you need to use some functions but let me explain something else first.

NEVER TRUST USER INPUT: You should never append user input (such as form input from $_GET or $_POST) directly to your query. Someone can carefully manipulate the input in such a way so that it can cause great damage to your database. That's called SQL Injection. You can read more about it here

To protect your script from such an attack you must use Prepared Statements. More on prepared statements here

Include prepared statements to your code like this:

$sql = "INSERT INTO users (username, password, email)
    VALUES (?,?,?)";

Notice how the ? are used as placeholders for the values. Next you should prepare the statement using mysqli_prepare:

$stmt = mysqli_prepare($sql);

Then start binding the input variables to the prepared statement:

$stmt->bind_param("sss", $_POST['username'], $_POST['email'], $_POST['password']);

And finally execute the prepared statements. (This is where the actual insertion takes place)

$stmt->execute();

NOTE Although not part of the question, I strongly advice you to never store passwords in clear text. Instead you should use password_hash to store a hash of the password

Find text in string with C#

  string WordInBetween(string sentence, string wordOne, string wordTwo)
        {

            int start = sentence.IndexOf(wordOne) + wordOne.Length + 1;

            int end = sentence.IndexOf(wordTwo) - start - 1;

            return sentence.Substring(start, end);


        }

C# Break out of foreach loop after X number of items

Just use break, like that:

int cont = 0;
foreach (ListViewItem lvi in listView.Items) {
   if(cont==50) { //if listViewItem reach 50 break out.
      break; 
   }
   cont++;   //increment cont.
}

Read Numeric Data from a Text File in C++

It can depend, especially on whether your file will have the same number of items on each row or not. If it will, then you probably want a 2D matrix class of some sort, usually something like this:

class array2D { 
    std::vector<double> data;
    size_t columns;
public:
    array2D(size_t x, size_t y) : columns(x), data(x*y) {}

    double &operator(size_t x, size_t y) {
       return data[y*columns+x];
    }
};

Note that as it's written, this assumes you know the size you'll need up-front. That can be avoided, but the code gets a little larger and more complex.

In any case, to read the numbers and maintain the original structure, you'd typically read a line at a time into a string, then use a stringstream to read numbers from the line. This lets you store the data from each line into a separate row in your array.

If you don't know the size ahead of time or (especially) if different rows might not all contain the same number of numbers:

11 12 13
23 34 56 78

You might want to use a std::vector<std::vector<double> > instead. This does impose some overhead, but if different rows may have different sizes, it's an easy way to do the job.

std::vector<std::vector<double> > numbers;

std::string temp;

while (std::getline(infile, temp)) {
    std::istringstream buffer(temp);
    std::vector<double> line((std::istream_iterator<double>(buffer)),
                             std::istream_iterator<double>());

    numbers.push_back(line);
}

...or, with a modern (C++11) compiler, you can use brackets for line's initialization:

    std::vector<double> line{std::istream_iterator<double>(buffer),
                             std::istream_iterator<double>()};

Border around each cell in a range

I have a set of 15 subroutines I add to every Coded Excel Workbook I create and this is one of them. The following routine clears the area and creates a border.

Sample Call:

Call BoxIt(Range("A1:z25"))

Subroutine:

Sub BoxIt(aRng As Range)
On Error Resume Next

    With aRng

        'Clear existing
        .Borders.LineStyle = xlNone

        'Apply new borders
        .BorderAround xlContinuous, xlThick, 0
        With .Borders(xlInsideVertical)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .Weight = xlMedium
        End With
        With .Borders(xlInsideHorizontal)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .Weight = xlMedium
        End With
    End With

End Sub

Find the division remainder of a number

Use the % instead of the / when you divide. This will return the remainder for you. So in your case

26 % 7 = 5

Scroll Element into View with Selenium

Selenium can scroll to some element in the scrollbar automatically for some simple UI, but for lazy-load UI, scrollToElement is still needed.

This is my implementation in Java with JavascriptExecutor. You can find more details in Satix source code: http://www.binpress.com/app/satix-seleniumbased-automation-testing-in-xml/1958

public static void perform(WebDriver driver, String Element, String ElementBy, By by) throws Exception {
 try {
  //long start_time = System.currentTimeMillis();           
  StringBuilder js = new StringBuilder();
  String browser = "firefox";

  if (ElementBy.equals("id")) {
   js.append("var b = document.getElementById(\"" +
    Element + "\");");
  } else if (ElementBy.equals("xpath")) {
   if (!"IE".equals(browser)) {
    js.append("var b = document.evaluate(\"" +
     Element +
     "\", document, null, XPathResult.ANY_TYPE, null).iterateNext();");
   } else {
    throw new Exception("Action error: xpath is not supported in scrollToElement Action in IE");
   }
  } else if (ElementBy.equals("cssSelector")) {
   js.append("var b = document.querySelector(\"" +
    Element + "\");");
  } else {
   throw new Exception("Scroll Action error");
  }

  String getScrollHeightScript = js.toString() + "var o = new Array(); o.push(b.scrollHeight); return o;";

  js.append("b.scrollTop = b.scrollTop + b.clientHeight;");
  js.append("var tmp = b.scrollTop + b.clientHeight;");
  js.append("var o = new Array(); o.push(tmp); return o;");

  int tries = 1;
  String scrollTop = "0";
  while (tries > 0) {
   try {
    String scrollHeight = ((JavascriptExecutor) driver).executeScript(getScrollHeightScript).toString();
    if (scrollTop.equals(scrollHeight)) {
     break;
    } else if (driver.findElement(by).isDisplayed()) {
     break;
    }
    Object o = ((JavascriptExecutor) driver).executeScript(js.toString());
    scrollTop = o.toString();
    Thread.sleep(interval);
    tries++;
   } catch (Exception e) {
    throw new Exception("Action error:" +
     " javascript execute error : " + e.getMessage() + ", javascript : " + js.toString());
   }
  }

 } catch (Exception e) {
  try {
   ScreenshotCapturerUtil.saveScreenShot(driver, CLASSNAME);
  } catch (IOException e1) {
   throw new Exception("Save screenshot error!", e1);
  }
  throw e;
 }
}

Grant Select on all Tables Owned By Specific User

tables + views + error reporting

SET SERVEROUT ON
DECLARE
  o_type VARCHAR2(60) := '';
  o_name VARCHAR2(60) := '';
  o_owner VARCHAR2(60) := '';
  l_error_message VARCHAR2(500) := '';
BEGIN
  FOR R IN (SELECT owner, object_type, object_name
            FROM all_objects 
            WHERE owner='SCHEMANAME'
            AND object_type IN ('TABLE','VIEW')
            ORDER BY 1,2,3) LOOP
    BEGIN
    o_type := r.object_type;
    o_owner := r.owner;
    o_name := r.object_name;
    DBMS_OUTPUT.PUT_LINE(o_type||' '||o_owner||'.'||o_name);
    EXECUTE IMMEDIATE 'grant select on '||o_owner||'.'||o_name||' to USERNAME';
    EXCEPTION
      WHEN OTHERS THEN
        l_error_message := sqlerrm;
        DBMS_OUTPUT.PUT_LINE('Error with '||o_type||' '||o_owner||'.'||o_name||': '|| l_error_message);
        CONTINUE;
    END;
  END LOOP;
END;
/

Deep copy, shallow copy, clone

  • Deep copy: Clone this object and every reference to every other object it has
  • Shallow copy: Clone this object and keep its references
  • Object clone() throws CloneNotSupportedException: It is not specified whether this should return a deep or shallow copy, but at the very least: o.clone() != o

Cloud Firestore collection count

There is no direct option available. You cant't do db.collection("CollectionName").count(). Below are the two ways by which you can find the count of number of documents within a collection.

1 :- Get all the documents in the collection and then get it's size.(Not the best Solution)

db.collection("CollectionName").get().subscribe(doc=>{
console.log(doc.size)
})

By using above code your document reads will be equal to the size of documents within a collection and that is the reason why one must avoid using above solution.

2:- Create a separate document with in your collection which will store the count of number of documents in the collection.(Best Solution)

db.collection("CollectionName").doc("counts")get().subscribe(doc=>{
console.log(doc.count)
})

Above we created a document with name counts to store all the count information.You can update the count document in the following way:-

  • Create a firestore triggers on the document counts
  • Increment the count property of counts document when a new document is created.
  • Decrement the count property of counts document when a document is deleted.

w.r.t price (Document Read = 1) and fast data retrieval the above solution is good.

Location of sqlite database on the device

The Context contains many path functions: Context.getXXXPath()
One of them is android.content.Context.getDatabasePath(String dbname) that returns the absolute path of a database called dbname.

Context ctx = this; // for Activity, or Service. Otherwise simply get the context.
String dbname = "mydb.db";
Path dbpath = ctx.getDatabasePath(dbname);

The returned path, in this case, would be something like:

/data/data/com.me.myapp/databases/mydb.db

Note that this path is autogenerated if using SQLiteOpenHelper to open the DB.

Rounding to 2 decimal places in SQL

This works too. The below statement rounds to two decimal places.

SELECT ROUND(92.258,2) from dual;

__init__ and arguments in Python

The fact that your method does not use the self argument (which is a reference to the instance that the method is attached to) doesn't mean you can leave it out. It always has to be there, because Python is always going to try to pass it in.

Change Default branch in gitlab

To change the default branch in Gitlab 7.7.2:

  • Click Settings in the left-hand bar
  • Change the Default Branch to the desired branch
  • Click Save Changes.

WAMP Server doesn't load localhost

Solution(s) for this, found in the official wampserver.com forums:

SOLUTION #1:

This problem is caused by Windows (7) in combination with any software that also uses port 80 (like Skype or IIS (which is installed on most developer machines)). A video solution can be found here (34.500+ views, damn, this seems to be a big thing ! EDIT: The video now has ~60.000 views ;) )

To make it short: open command line tool, type "netstat -aon" and look for any lines that end of ":80". Note thatPID on the right side. This is the process id of the software which currently usesport 80. Press AltGr + Ctrl + Del to get into the Taskmanager. Switch to the tab where you can see all services currently running, ordered by PID. Search for that PID you just notices and stop that thing (right click). To prevent this in future, you should config the software's port settings (skype can do that).

SOLUTION #2:

left click the wamp icon in the taskbar, go to apache > httpd.conf and edit this file: change "listen to port .... 80" to 8080. Restart. Done !

SOLUTION #3:

Port 80 blocked by "Microsoft Web Deployment Service", simply deinstall this, more info here

By the way, it's not Microsoft's fault, it's a stupid usage of ports by most WAMP stacks.

IMPORTANT: you have to use localhost or 127.0.0.1 now with port 8080, this means 127.0.0.1:8080 or localhost:8080.

What are Transient and Volatile Modifiers?

Transient :

First need to know where it needed how it bridge the gap.

1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.

2) Transient keyword cannot be used along with static keyword.

3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

Note 1) Transient is mainly use for serialzation process. For that the class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.

Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

How to order citations by appearance using BibTeX?

Just a brief note - I'm using a modified version of plain.bst sitting in the directory with my Latex files; it turns out having sorting by order of appearance is a relatively easy change; just find the piece of code:

...
ITERATE {presort}

SORT
...

... and comment it - I turned it to:

...
%% % avoid sort:
%% ITERATE {presort}
%%
%% SORT
...

... and then, after running bibtex, pdflatex, pdflatex - the citations will be sorted by order of appearance (that is, they will be unsorted :) ).

Cheers!

EDIT: just realized that what I wrote is actually in the comment by @ChrisN: "can you edit it to remove the SORT command" ;)

install apt-get on linux Red Hat server

If you insist on using yum, try yum install apt. As read on this site: Link

Output array to CSV in Ruby

To a file:

require 'csv'
CSV.open("myfile.csv", "w") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

To a string:

require 'csv'
csv_string = CSV.generate do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

Toggle Class in React

Toggle function in react

At first you should create constructor like this

constructor(props) {
        super(props);
        this.state = {
            close: true,
        };
    }

Then create a function like this

yourFunction = () => {
        this.setState({
            close: !this.state.close,
        });
    };

then use this like

render() {
        const {close} = this.state;
        return (

            <Fragment>

                 <div onClick={() => this.yourFunction()}></div>

                 <div className={close ? "isYourDefaultClass" : "isYourOnChangeClass"}></div>

            </Fragment>
        )
    }
}

Please give better solutions

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

I struggled with the same problem. I have stored dates in SQL Server with format 'YYYY-MM-DD HH:NN:SS' for about 20 years, but today that was not able anymore from a C# solution using OleDbCommand and a UPDATE query.

The solution to my problem was to remove the hyphen - in the format, so the resulting formatting is now 'YYYYMMDD HH:MM:SS'. I have no idea why my previous formatting not works anymore, but I suspect there is something to do with some Windows updates for ADO.

Percentage Height HTML 5/CSS

You can use 100vw / 100vh. CSS3 gives us viewport-relative units. 100vw means 100% of the viewport width. 100vh; 100% of the height.

    <div style="display:flex; justify-content: space-between;background-color: lightyellow; width:100%; height:85vh">
        <div style="width:70%; height: 100%; border: 2px dashed red"></div>
        <div style="width:30%; height: 100%; border: 2px dashed red"></div>
    </div>

How to find a value in an array and remove it by using PHP array functions?

Just in case you want to use any of mentioned codes, be aware that array_search returns FALSE when the "needle" is not found in "haystack" and therefore these samples would unset the first (zero-indexed) item. Use this instead:

<?php
$haystack = Array('one', 'two', 'three');
if (($key = array_search('four', $haystack)) !== FALSE) {
  unset($haystack[$key]);
}
var_dump($haystack);

The above example will output:

Array
(
    [0] => one
    [1] => two
    [2] => three
)

And that's good!

How to specify legend position in matplotlib in graph coordinates

In addition to @ImportanceOfBeingErnest's post, I use the following line to add a legend at an absolute position in a plot.

plt.legend(bbox_to_anchor=(1.0,1.0),\
    bbox_transform=plt.gcf().transFigure)

For unknown reasons, bbox_transform=fig.transFigure does not work with me.

How to define an enumerated type (enum) in C?

You're trying to declare strategy twice, and that's why you're getting the above error. The following works without any complaints (compiled with gcc -ansi -pedantic -Wall):

#include <stdio.h>

enum { RANDOM, IMMEDIATE, SEARCH } strategy = IMMEDIATE;

int main(int argc, char** argv){
    printf("strategy: %d\n", strategy);

    return 0;
}

If instead of the above, the second line were changed to:

...
enum { RANDOM, IMMEDIATE, SEARCH } strategy;
strategy = IMMEDIATE;
...

From the warnings, you could easily see your mistake:

enums.c:5:1: warning: data definition has no type or storage class [enabled by default]
enums.c:5:1: warning: type defaults to ‘int’ in declaration of ‘strategy’ [-Wimplicit-int]
enums.c:5:1: error: conflicting types for ‘strategy’
enums.c:4:36: note: previous declaration of ‘strategy’ was here

So the compiler took strategy = IMMEDIATE for a declaration of a variable called strategy with default type int, but there was already a previous declaration of a variable with this name.

However, if you placed the assignment in the main() function, it would be a valid code:

#include <stdio.h>

enum { RANDOM, IMMEDIATE, SEARCH } strategy = IMMEDIATE;

int main(int argc, char** argv){
    strategy=SEARCH;
    printf("strategy: %d\n", strategy);

    return 0;
}

Sublime Text 2 - View whitespace characters

In selected text, SPACE is shown as dot (.) and TAB as a dash (-).

How is the AND/OR operator represented as in Regular Expressions?

Not an expert in regex, but you can do ^((part1|part2)|(part1, part2))$. In words: "part 1 or part2 or both"

How to get folder directory from HTML input type "file" or any other way?

You're most likely looking at using a flash/silverlight/activeX control. The <input type="file" /> control doesn't handle that.

If you don't mind the user selecting a file as a means to getting its directory, you may be able to bind to that control's change event then strip the filename portion and save the path somewhere--but that's about as good as it gets.

Keep in mind that webpages are designed to interact with servers. Nothing about providing a local directory to a remote server is "typical" (a server can't access it so why ask for it?); however files are a means to selectively passing information.

Getting current directory in .NET web application

Use this code:

 HttpContext.Current.Server.MapPath("~")

Detailed Reference:

Server.MapPath specifies the relative or virtual path to map to a physical directory.

  • Server.MapPath(".") returns the current physical directory of the file (e.g. aspx) being executed
  • Server.MapPath("..") returns the parent directory
  • Server.MapPath("~") returns the physical path to the root of the application
  • Server.MapPath("/") returns the physical path to the root of the domain name (is not necessarily the same as the root of the application)

An example:

Let's say you pointed a web site application (http://www.example.com/) to

C:\Inetpub\wwwroot

and installed your shop application (sub web as virtual directory in IIS, marked as application) in

D:\WebApps\shop

For example, if you call Server.MapPath in following request:

http://www.example.com/shop/products/GetProduct.aspx?id=2342

then:

Server.MapPath(".") returns D:\WebApps\shop\products
Server.MapPath("..") returns D:\WebApps\shop
Server.MapPath("~") returns D:\WebApps\shop
Server.MapPath("/") returns C:\Inetpub\wwwroot
Server.MapPath("/shop") returns D:\WebApps\shop

If Path starts with either a forward (/) or backward slash (), the MapPath method returns a path as if Path were a full, virtual path.

If Path doesn't start with a slash, the MapPath method returns a path relative to the directory of the request being processed.

Note: in C#, @ is the verbatim literal string operator meaning that the string should be used "as is" and not be processed for escape sequences.

Footnotes

Server.MapPath(null) and Server.MapPath("") will produce this effect too.

how to change language for DataTable

//Spanish
$('#TableName').DataTable({
    "language": {
        "sProcessing":    "Procesando...",
        "sLengthMenu":    "Mostrar _MENU_ registros",
        "sZeroRecords":   "No se encontraron resultados",
        "sEmptyTable":    "Ningún dato disponible en esta tabla",
        "sInfo":          "Mostrando registros del _START_ al _END_ de un total de _TOTAL_ registros",
        "sInfoEmpty":     "Mostrando registros del 0 al 0 de un total de 0 registros",
        "sInfoFiltered":  "(filtrado de un total de _MAX_ registros)",
        "sInfoPostFix":   "",
        "sSearch":        "Buscar:",
        "sUrl":           "",
        "sInfoThousands":  ",",
        "sLoadingRecords": "Cargando...",
        "oPaginate": {
            "sFirst":    "Primero",
            "sLast":    "Último",
            "sNext":    "Siguiente",
            "sPrevious": "Anterior"
        },
        "oAria": {
            "sSortAscending":  ": Activar para ordenar la columna de manera ascendente",
            "sSortDescending": ": Activar para ordenar la columna de manera descendente"
        }
    }
});

Also using a cdn:

//cdn.datatables.net/plug-ins/a5734b29083/i18n/Spanish.json

More options: http://www.datatables.net/plug-ins/i18n/English [| Spanish | etc]

How do I set cell value to Date and apply default Excel date format?

To know the format string used by Excel without having to guess it: create an excel file, write a date in cell A1 and format it as you want. Then run the following lines:

FileInputStream fileIn = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(fileIn);
CellStyle cellStyle = workbook.getSheetAt(0).getRow(0).getCell(0).getCellStyle();
String styleString = cellStyle.getDataFormatString();
System.out.println(styleString);

Then copy-paste the resulting string, remove the backslashes (for example d/m/yy\ h\.mm;@ becomes d/m/yy h.mm;@) and use it in the http://poi.apache.org/spreadsheet/quick-guide.html#CreateDateCells code:

CellStyle cellStyle = wb.createCellStyle();
CreationHelper createHelper = wb.getCreationHelper();
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("d/m/yy h.mm;@"));
cell = row.createCell(1);
cell.setCellValue(new Date());
cell.setCellStyle(cellStyle);

How to see what privileges are granted to schema of another user

Login into the database. then run the below query

select * from dba_role_privs where grantee = 'SCHEMA_NAME';

All the role granted to the schema will be listed.

Thanks Szilagyi Donat for the answer. This one is taken from same and just where clause added.

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

I solved this issue by redirecting the user to the FQDN of the server hosting the intranet.

IE probably uses the world's worst algorithm for detecting "intranet" sites ... indeed, specifying server.domain.tld solves the problem for me.

Yes, you read that correctly, IE detects intranet sites not by private IP address, like any dev who has heard of TCP/IP would do, no, by the "host" part of the URL, if it has no domain part, must be internal.

Scary to know the IE devs do not understand the most basic TCP/IP concepts.

Note that this was at a BIG enterprise customer, getting them to change GPO for you is like trying to move the Alps east by 4 meters, not gonna happen.

How to delete row in gridview using rowdeleting event?

Make sure to create a static DataTable object and then use the following code:

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
{
    dt.Rows.RemoveAt(e.RowIndex); 
    GridView1.DataSource = dt;
    GridView1.DataBind();
}

GitHub README.md center image

It works for me on github

<p align="center"> 
<img src="...">
</p>

How to run certain task every day at a particular time using ScheduledExecutorService?

You can use below class to schedule your task every day particular time

package interfaces;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class CronDemo implements Runnable{

    public static void main(String[] args) {

        Long delayTime;

        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);

        final Long initialDelay = LocalDateTime.now().until(LocalDate.now().plusDays(1).atTime(12, 30), ChronoUnit.MINUTES);

        if (initialDelay > TimeUnit.DAYS.toMinutes(1)) {
            delayTime = LocalDateTime.now().until(LocalDate.now().atTime(12, 30), ChronoUnit.MINUTES);
        } else {
            delayTime = initialDelay;
        }

        scheduler.scheduleAtFixedRate(new CronDemo(), delayTime, TimeUnit.DAYS.toMinutes(1), TimeUnit.MINUTES);

    }

    @Override
    public void run() {
        System.out.println("I am your job executin at:" + new Date());
    }
}

ASP.NET email validator regex

For regex, I first look at this web site: RegExLib.com

Compile Views in ASP.NET MVC

Next release of ASP.NET MVC (available in January or so) should have MSBuild task that compiles views, so you might want to wait.

See announcement

How do I sleep for a millisecond in Perl?

Time::HiRes:

  use Time::HiRes;
  Time::HiRes::sleep(0.1); #.1 seconds
  Time::HiRes::usleep(1); # 1 microsecond.

http://perldoc.perl.org/Time/HiRes.html

How to play .mp4 video in videoview in android?

MP4 is just a container - the video and audio stream inside it will both be encoded in different formats.

Android natively only supports certain types of formats. This is the list here.

Make sure the video and audio encoding type is supported. Just because it says "mp4" doesn't automatically mean it should be playable.

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

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

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

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

href image link download on click

Image download with using image clicking!

I did this simple code!:)

<html>
<head>
<title> Download-Button </title>
</head>
<body>
<p> Click the image ! You can download! </p>
<a download="logo.png" href="http://localhost/folder/img/logo.png" title="Logo title">
<img alt="logo" src="http://localhost/folder/img/logo.png">
</a>
</body>
</html>

How do I format a number to a dollar amount in PHP

In PHP and C++ you can use the printf() function

printf("$%01.2f", $money);

How do I compare two columns for equality in SQL Server?

What's wrong with CASE for this? In order to see the result, you'll need at least a byte, and that's what you get with a single character.

CASE WHEN COLUMN1 = COLUMN2 THEN '1' ELSE '0' END AS MyDesiredResult

should work fine, and for all intents and purposes accomplishes the same thing as using a bit field.

Specifying a custom DateTime format when serializing with Json.Net

You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the JsonConverter attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-in IsoDateTimeConverter that lets you specify the date format. Unfortunately, you can't set the format via the JsonConverter attribute, since the attribute's sole argument is a type. However, there is a simple solution: subclass the IsoDateTimeConverter, then specify the date format in the constructor of the subclass. Apply the JsonConverter attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:

class CustomDateTimeConverter : IsoDateTimeConverter
{
    public CustomDateTimeConverter()
    {
        base.DateTimeFormat = "yyyy-MM-dd";
    }
}

If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK (as seen in the source code).

Is `shouldOverrideUrlLoading` really deprecated? What can I use instead?

Documenting in detail for future readers:

The short answer is you need to override both the methods. The shouldOverrideUrlLoading(WebView view, String url) method is deprecated in API 24 and the shouldOverrideUrlLoading(WebView view, WebResourceRequest request) method is added in API 24. If you are targeting older versions of android, you need the former method, and if you are targeting 24 (or later, if someone is reading this in distant future) it's advisable to override the latter method as well.

The below is the skeleton on how you would accomplish this:

class CustomWebViewClient extends WebViewClient {

    @SuppressWarnings("deprecation")
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        final Uri uri = Uri.parse(url);
        return handleUri(uri);
    }

    @TargetApi(Build.VERSION_CODES.N)
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
        final Uri uri = request.getUrl();
        return handleUri(uri);
    }

    private boolean handleUri(final Uri uri) {
        Log.i(TAG, "Uri =" + uri);
        final String host = uri.getHost();
        final String scheme = uri.getScheme();
        // Based on some condition you need to determine if you are going to load the url 
        // in your web view itself or in a browser. 
        // You can use `host` or `scheme` or any part of the `uri` to decide.
        if (/* any condition */) {
            // Returning false means that you are going to load this url in the webView itself
            return false;
        } else {
            // Returning true means that you need to handle what to do with the url
            // e.g. open web page in a Browser
            final Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
            return true;
        }
    }
}

Just like shouldOverrideUrlLoading, you can come up with a similar approach for shouldInterceptRequest method.

A 'for' loop to iterate over an enum in Java

.values()

You can call the values() method on your enum.

for (Direction dir : Direction.values()) {
  // do what you want
}

This values() method is implicitly declared by the compiler. So it is not listed on Enum doc.

Error: vector does not name a type

You need to either qualify vector with its namespace (which is std), or import the namespace at the top of your CPP file:

using namespace std;

How do I print debug messages in the Google Chrome JavaScript Console?

Here's my console wrapper class. It gives me scope output as well to make life easier. Note the use of localConsole.debug.call() so that localConsole.debug runs in the scope of the calling class, providing access to its toString method.

localConsole = {

    info: function(caller, msg, args) {
        if ( window.console && window.console.info ) {
            var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
            if (args) {
                params = params.concat(args);
            }
            console.info.apply(console, params);
        }
    },

    debug: function(caller, msg, args) {
        if ( window.console && window.console.debug ) {
            var params = [(this.className) ? this.className : this.toString() + '.' + caller + '(), ' + msg];
            if (args) {
                params = params.concat(args);
            }
            console.debug.apply(console, params);
        }
    }
};

someClass = {

    toString: function(){
        return 'In scope of someClass';
    },

    someFunc: function() {

        myObj = {
            dr: 'zeus',
            cat: 'hat'
        };

        localConsole.debug.call(this, 'someFunc', 'myObj: ', myObj);
    }
};

someClass.someFunc();

This gives output like so in Firebug:

In scope of someClass.someFunc(), myObj: Object { dr="zeus", more...}

Or Chrome:

In scope of someClass.someFunc(), obj:
Object
cat: "hat"
dr: "zeus"
__proto__: Object

Freemarker iterating over hashmap keys

Since 2.3.25, do it like this:

<#list user as propName, propValue>
  ${propName} = ${propValue}
</#list>

Note that this also works with non-string keys (unlike map[key], which had to be written as map?api.get(key) then).

Before 2.3.25 the standard solution was:

<#list user?keys as prop>
  ${prop} = ${user[prop]}
</#list>

However, some really old FreeMarker integrations use a strange configuration, where the public Map methods (like getClass) appear as keys. That happens as they are using a pure BeansWrapper (instead of DefaultObjectWrapper) whose simpleMapWrapper property was left on false. You should avoid such a setup, as it mixes the methods with real Map entries. But if you run into such unfortunate setup, the way to escape the situation is using the exposed Java methods, such as user.entrySet(), user.get(key), etc., and not using the template language constructs like ?keys or user[key].

How to get a list of user accounts using the command line in MySQL?

$>  mysql -u root -p -e 'Select user from mysql.user' > allUsersOnDatabase.txt

Executing this command on linux prompt will first ask for the password of mysql root user, on providing correct password it will print all the database users to the text file.

Internet Explorer cache location

I don't know the answer for XP, but for latter:

%USERPROFILE%\AppData\Local\Microsoft\Windows\Temporary Internet Files\Low and %USERPROFILE%\AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5 - these are cache locations. Other mentioned %USERPROFILE%\AppData\Local\Microsoft\Windows\Temporary Internet Files but this not a cache in this directory there are just a reflection of files that are stored somewhere else.

But you can enum %USERPROFILE%\AppData\Local\Microsoft\Windows\Temporary Internet Files and get all files you need, but you should be frustrated that file walker do not detect everything that explorer shows.

Also if you use links I gave you may need ExpandEnvironmentStrings from WinAPI.

Extract file name from path, no matter what the os/path format

Actually, there's a function that returns exactly what you want

import os
print(os.path.basename(your_path))

WARNING: When os.path.basename() is used on a POSIX system to get the base name from a Windows styled path (e.g. "C:\\my\\file.txt"), the entire path will be returned.

Example below from interactive python shell running on a Linux host:

Python 3.8.2 (default, Mar 13 2020, 10:14:16)
[GCC 9.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> filepath = "C:\\my\\path\\to\\file.txt" # A Windows style file path.
>>> os.path.basename(filepath)
'C:\\my\\path\\to\\file.txt'

How to position a DIV in a specific coordinates?

well it depends if all you want is to position a div and then nothing else, you don't need to use java script for that. You can achieve this by CSS only. What matters is relative to what container you want to position your div, if you want to position it relative to document body then your div must be positioned absolute and its container must not be positioned relatively or absolutely, in that case your div will be positioned relative to the container.

Otherwise with Jquery if you want to position an element relative to document you can use offset() method.

$(".mydiv").offset({ top: 10, left: 30 });

if relative to offset parent position the parent relative or absolute. then use following...

var pos = $('.parent').offset();
var top = pos.top + 'no of pixel you want to give the mydiv from top relative to parent';
var left = pos.left + 'no of pixel you want to give the mydiv from left relative to parent';

$('.mydiv').css({
  position:'absolute',
  top:top,
  left:left
});

HTML5 Email input pattern attribute

In HTML5 you can use the new 'email' type: http://www.w3.org/TR/html-markup/input.email.html

For example:

<input type="email" id="email" />

If the browser implements HTML5 it will make sure that the user has entered a valid email address in the field. Note that if the browser doesn't implement HTML5, it will be treated like a 'text' type, ie:

<input type="text" id="email" />

How to break line in JavaScript?

Add %0D%0A to any place you want to encode a line break on the URL.

  • %0D is a carriage return character
  • %0A is a line break character

This is the new line sequence on windows machines, though not the same on linux and macs, should work in both.

If you want a linebreak in actual javascript, use the \n escape sequence.


onClick="parent.location='mailto:[email protected]?subject=Thanks for writing to me &body=I will get back to you soon.%0D%0AThanks and Regards%0D%0ASaurav Kumar'

Mongodb: failed to connect to server on first connect

To connect to mongodb with mongoose, you can use :

mongoose.connect('mongodb://localhost/users_test');

or

mongoose.connect('localhost/users_test');

or

mongoose.connect('localhost','users_test');

But not mongoose.connect('mongodb:localhost/users_test');, it doesnt match the right hostname (mongodb instead of localhost)

VBA Excel 2-Dimensional Arrays

In fact I would not use any REDIM, nor a loop for transferring data from sheet to array:

dim arOne()
arOne = range("A2:F1000")

or even

arOne = range("A2").CurrentRegion

and that's it, your array is filled much faster then with a loop, no redim.

jQuery disable a link

Here is an alternate css/jQuery solution that I prefer for its terseness and minimized scripting:

css:

a.disabled {
  opacity: 0.5;
  pointer-events: none;
  cursor: default;
}

jQuery:

$('.disableAfterClick').click(function (e) {
   $(this).addClass('disabled');
});

How can I make my layout scroll both horizontally and vertically?

In this post Scrollview vertical and horizontal in android they talk about a possible solution, quoting:

Matt Clark has built a custom view based on the Android source, and it seems to work perfectly: http://blog.gorges.us/2010/06/android-two-dimensional-scrollview

Beware that the class in that page has a bug calculating the view's horizonal width. A fix by Manuel Hilty is in the comments:

Solution: Replace the statement on line 808 by the following:

final int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(lp.leftMargin + lp.rightMargin, MeasureSpec.UNSPECIFIED);

MySql Inner Join with WHERE clause

Yes you are right. You have placed WHERE clause wrong. You can only use one WHERE clause in single query so try AND for multiple conditions like this:

 SELECT table1.f_id  FROM table1 
   INNER JOIN table2
     ON table2.f_id = table1.f_id
 WHERE table2.f_type = 'InProcess'
   AND f_com_id = '430'
   AND f_status = 'Submitted' 

How to import .py file from another directory?

You can add to the system-path at runtime:

import sys
sys.path.insert(0, 'path/to/your/py_file')

import py_file

This is by far the easiest way to do it.

Need a query that returns every field that contains a specified letter

where somefield like '%a%' or somefield like '%b%'

Print the data in ResultSet along with column names

ResultSet resultSet = statement.executeQuery("SELECT * from foo");
ResultSetMetaData rsmd = resultSet.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (resultSet.next()) {
    for (int i = 1; i <= columnsNumber; i++) {
        if (i > 1) System.out.print(",  ");
        String columnValue = resultSet.getString(i);
        System.out.print(columnValue + " " + rsmd.getColumnName(i));
    }
    System.out.println("");
}

Reference : Printing the result of ResultSet

Set Background cell color in PHPExcel

Here is how you do it in PHPSpreadsheet, the newest version of PHPExcel

$spreadsheet = new Spreadsheet();

$spreadsheet->getActiveSheet()->getStyle('A1:F1')->applyFromArray([
    'fill' => [
            'fillType' => Fill::FILL_SOLID,
            'startColor' => [
                'argb' => 'FFDBE2F1',
            ]           
    ],
]);

alternative approach:

$spreadsheet->getActiveSheet()
    ->getStyle('A1:F1')
    ->getFill()
    ->setFillType(Fill::FILL_SOLID)
    ->getStartColor()->setARGB('FFDBE2F1');

WPF ListView - detect when selected item is clicked

You can handle click on list view item like this:

<ListView.ItemTemplate>
  <DataTemplate>
     <Button BorderBrush="Transparent" Background="Transparent" Focusable="False">
        <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <i:InvokeCommandAction Command="{Binding DataContext.MyCommand, ElementName=ListViewName}" CommandParameter="{Binding}"/>
                </i:EventTrigger>
        </i:Interaction.Triggers>
      <Button.Template>
      <ControlTemplate>
         <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
    ...

NodeJs : TypeError: require(...) is not a function

I've faced to something like this too. in your routes file , export the function as an object like this :

 module.exports = {
     hbd: handlebar
 }

and in your app file , you can have access to the function by .hbd and there is no ptoblem ....!

Using :: in C++

You're pretty much right about cout and cin. They are objects (not functions) defined inside the std namespace. Here are their declarations as defined by the C++ standard:

Header <iostream> synopsis

#include <ios>
#include <streambuf>
#include <istream>
#include <ostream>

namespace std {
  extern istream cin;
  extern ostream cout;
  extern ostream cerr;
  extern ostream clog;

  extern wistream wcin;
  extern wostream wcout;
  extern wostream wcerr;
  extern wostream wclog;
}

:: is known as the scope resolution operator. The names cout and cin are defined within std, so we have to qualify their names with std::.

Classes behave a little like namespaces in that the names declared inside the class belong to the class. For example:

class foo
{
  public:
    foo();
    void bar();
};

The constructor named foo is a member of the class named foo. They have the same name because its the constructor. The function bar is also a member of foo.

Because they are members of foo, when referring to them from outside the class, we have to qualify their names. After all, they belong to that class. So if you're going to define the constructor and bar outside the class, you need to do it like so:

foo::foo()
{
  // Implement the constructor
}

void foo::bar()
{
  // Implement bar
}

This is because they are being defined outside the class. If you had not put the foo:: qualification on the names, you would be defining some new functions in the global scope, rather than as members of foo. For example, this is entirely different bar:

void bar()
{
  // Implement different bar
}

It's allowed to have the same name as the function in the foo class because it's in a different scope. This bar is in the global scope, whereas the other bar belonged to the foo class.

Retrieving a Foreign Key value with django-rest-framework serializers

Simple solution source='category.name' where category is foreign key and .name it's attribute.

from rest_framework.serializers import ModelSerializer, ReadOnlyField
from my_app.models import Item

class ItemSerializer(ModelSerializer):
    category_name = ReadOnlyField(source='category.name')

    class Meta:
        model = Item
        fields = "__all__"

Jetty: HTTP ERROR: 503/ Service Unavailable

I had the same problem. I solved it by removing the line break from the xml file. I did

<operationBindings>
    <OperationBinding>
        <operationType>update</operationType>
        <operationId>makePdf</operationId>
        <serverObject>
            <className>com.myclass</className>
            <lookupStyle>new</lookupStyle>
        </serverObject>
        <serverMethod>makePdf</serverMethod>
    </OperationBinding>
</operationBindings>

instead of ...

<serverObject>
            <className>com.myclass
</className>
            <lookupStyle>new</lookupStyle>
</serverObject>

JDK was not found on the computer for NetBeans 6.5

For Netbeans 9.0

1)open netbeans.conf file using notepad inside etc folder

2)Search "netbeans_jdkhome" line and uncomment it by removing '#' from start

3)locate your jdk and replace file path

For example

enter image description here

What is the difference between Dim, Global, Public, and Private as Modular Field Access Modifiers?

Dim and Private work the same, though the common convention is to use Private at the module level, and Dim at the Sub/Function level. Public and Global are nearly identical in their function, however Global can only be used in standard modules, whereas Public can be used in all contexts (modules, classes, controls, forms etc.) Global comes from older versions of VB and was likely kept for backwards compatibility, but has been wholly superseded by Public.

How do I disable a Pylint warning?

Python syntax does permit more than one statement on a line, separated by semicolon (;). However, limiting each line to one statement makes it easier for a human to follow a program's logic when reading through it.

So, another way of solving this issue, is to understand why the lint message is there and not put more than one statement on a line.

Yes, you may find it easier to write multiple statements per line, however, Pylint is for every other reader of your code not just you.

How to change credentials for SVN repository in Eclipse?

In Eclipse: Ctrl + F8 -> SVN Repository Exploring -> Right Click in the respository -> Location Properties -> Finish ;)

Vertical align text in block element

DO NOT USE THE 4th solution from top if you are using ag-grid. It will fix the issue for aligning the element in middle but it might break the thing in ag-grid (for me i was not able to select checkbox after some row). Problem is not with the solution or ag-grid but somehow the combination is not good.

DO NOT USE THIS SOLUTION FOR AG-GRID

li a {
    width: 300px;
    height: 100px;
    margin: auto 0;
    display: inline-block;
    vertical-align: middle;
    background: red;  
}

li a:after {
    content:"";
    display: inline-block;
    width: 1px solid transparent;
    height: 100%;
    vertical-align: middle;
}

What certificates are trusted in truststore?

Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

keytool -list -v -keystore truststore.jks

Why use a READ UNCOMMITTED isolation level?

This can be useful to see the progress of long insert queries, make any rough estimates (like COUNT(*) or rough SUM(*)) etc.

In other words, the results the dirty read queries return are fine as long as you treat them as estimates and don't make any critical decisions based upon them.

Display names of all constraints for a table in Oracle SQL

You need to query the data dictionary, specifically the USER_CONS_COLUMNS view to see the table columns and corresponding constraints:

SELECT *
  FROM user_cons_columns
 WHERE table_name = '<your table name>';

FYI, unless you specifically created your table with a lower case name (using double quotes) then the table name will be defaulted to upper case so ensure it is so in your query.

If you then wish to see more information about the constraint itself query the USER_CONSTRAINTS view:

SELECT *
  FROM user_constraints
 WHERE table_name = '<your table name>'
   AND constraint_name = '<your constraint name>';

If the table is held in a schema that is not your default schema then you might need to replace the views with:

all_cons_columns

and

all_constraints

adding to the where clause:

   AND owner = '<schema owner of the table>'

Way to go from recursion to iteration

Strive to make your recursive call Tail Recursion (recursion where the last statement is the recursive call). Once you have that, converting it to iteration is generally pretty easy.

Selenium webdriver click google search

public class GoogleSearch {

    public static void main(String[] args) {

        WebDriver driver=new FirefoxDriver();
        driver.get("http://www.google.com");
        driver.findElement(By.xpath("//input[@type='text']")).sendKeys("Cheese");   
        driver.findElement(By.xpath("//button[@name='btnG']")).click();
        driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); 
        driver.findElement(By.xpath("(//h3[@class='r']/a)[3]")).click();
        driver.manage().timeouts().implicitlyWait(30,TimeUnit.SECONDS); 
    }
}

how to loop through json array in jquery?

try this

var events = [];

alert(doc);
var obj = jQuery.parseJSON(doc);

     $.each(obj, function (key, value) {

    alert(value.title);

});

Enzyme - How to access and set <input> value?

I solved in a very simple way:

  1. Set the value from props:
  const wrapper: ShallowWrapper = shallow(<ProfileViewClass name: 'Sample Name' />);
  1. Html code:
  <input type='text' defaultValue={props.name} className='edituser-name' />
  1. Access the attribute from wrapper.find(element).props().attribute-name:
  it('should render user name', () => {
    expect(wrapper.find('.edituser-name').props().defaultValue).toContain(props.name);
  });

Cheers

How can I color a UIImage in Swift?

For iOS13+ there are withTintColor(__:) and withTintColor(_:renderingMode:) methods.

Example usage:

let newImage = oldImage.withTintColor(.red)

or

let newImage = oldImage.withTintColor(.red, renderingMode: .alwaysTemplate)

Date / Timestamp to record when a record was added to the table?

You can create a non-nullable DATETIME column on your table, and create a DEFAULT constraint on it to auto populate when a row is added.

e.g.

CREATE TABLE Example
(
SomeField INTEGER,
DateCreated DATETIME NOT NULL DEFAULT(GETDATE())
)

Uploading Files in ASP.net without using the FileUpload server control

As others has answer, the Request.Files is an HttpFileCollection that contains all the files that were posted, you only need to ask that object for the file like this:

Request.Files["myFile"]

But what happen when there are more than one input mark-up with the same attribute name:

Select file 1 <input type="file" name="myFiles" />
Select file 2 <input type="file" name="myFiles" />

On the server side the previous code Request.Files["myFile"] only return one HttpPostedFile object instead of the two files. I have seen on .net 4.5 an extension method called GetMultiple but for prevoious versions it doesn't exists, for that matter i propose the extension method as:

public static IEnumerable<HttpPostedFile> GetMultiple(this HttpFileCollection pCollection, string pName)
{
        for (int i = 0; i < pCollection.Count; i++)
        {
            if (pCollection.GetKey(i).Equals(pName))
            {
                yield return pCollection.Get(i);
            }
        }
}

This extension method will return all the HttpPostedFile objects that have the name "myFiles" in the HttpFileCollection if any exists.

InputStream from a URL

(a) wwww.somewebsite.com/a.txt isn't a 'file URL'. It isn't a URL at all. If you put http:// on the front of it it would be an HTTP URL, which is clearly what you intend here.

(b) FileInputStream is for files, not URLs.

(c) The way to get an input stream from any URL is via URL.openStream(), or URL.getConnection().getInputStream(), which is equivalent but you might have other reasons to get the URLConnection and play with it first.

How to fix the error "Windows SDK version 8.1" was not found?

Grep the folder tree's *.vcxproj files. Replace <WindowsTargetPlatformVersion>8.1</WindowsTargetPlatformVersion> with <WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion> or whatever SDK version you get when you update one of the projects.

What should be the sizeof(int) on a 64-bit machine?

In C++, the size of int isn't specified explicitly. It just tells you that it must be at least the size of short int, which must be at least as large as signed char. The size of char in bits isn't specified explicitly either, although sizeof(char) is defined to be 1. If you want a 64 bit int, C++11 specifies long long to be at least 64 bits.

What is the difference between 'java', 'javaw', and 'javaws'?

See Java tools documentation for:

  1. The java tool launches a Java application. It does this by starting a Java runtime environment, loading a specified class, and invoking that class's main method.
  2. The javaw command is identical to java, except that with javaw there is no associated console window. Use javaw when you don't want a command prompt window to appear.

The javaws command launches Java Web Start, which is the reference implementation of the Java Network Launching Protocol (JNLP). Java Web Start launches Java applications/applets hosted on a network.

If a JNLP file is specified, javaws will launch the Java application/applet specified in the JNLP file.

The javaws launcher has a set of options that are supported in the current release. However, the options may be removed in a future release.

See also JDK 9 Release Notes Deprecated APIs, Features, and Options:

Java Deployment Technologies are deprecated and will be removed in a future release
Java Applet and WebStart functionality, including the Applet API, the Java plug-in, the Java Applet Viewer, JNLP and Java Web Start, including the javaws tool, are all deprecated in JDK 9 and will be removed in a future release.

T-SQL Cast versus Convert

Something no one seems to have noted yet is readability. Having…

CONVERT(SomeType,
    SomeReallyLongExpression
    + ThatMayEvenSpan
    + MultipleLines
    )

…may be easier to understand than…

CAST(SomeReallyLongExpression
    + ThatMayEvenSpan
    + MultipleLines
    AS SomeType
    )

Plot data in descending order as appears in data frame

You want reorder(). Here is an example with dummy data

set.seed(42)
df <- data.frame(Category = sample(LETTERS), Count = rpois(26, 6))

require("ggplot2")

p1 <- ggplot(df, aes(x = Category, y = Count)) +
         geom_bar(stat = "identity")

p2 <- ggplot(df, aes(x = reorder(Category, -Count), y = Count)) +
         geom_bar(stat = "identity")

require("gridExtra")
grid.arrange(arrangeGrob(p1, p2))

Giving:

enter image description here

Use reorder(Category, Count) to have Category ordered from low-high.

AngularJS - How can I do a redirect with a full page load?

Try this

$window.location.href="#page-name";
$window.location.reload();

jQuery looping .each() JSON key/value not working

With a simple JSON object, you don't need jQuery:

for (var i in json) {
   for (var j in json[i]) {
     console.log(json[i][j]);
   }
}

Is there a way to make AngularJS load partials in the beginning and not at when needed?

If you use rails, you can use the asset pipeline to compile and shove all your haml/erb templates into a template module which can be appended to your application.js file. Checkout http://minhajuddin.com/2013/04/28/angularjs-templates-and-rails-with-eager-loading

'sprintf': double precision in C

You need to write it like sprintf(aa, "%9.7lf", a)

Check out http://en.wikipedia.org/wiki/Printf for some more details on format codes.

Android Service needs to run always (Never pause or stop)

Add this in manifest.

      <service
        android:name=".YourServiceName"
        android:enabled="true"
        android:exported="false" />

Add a service class.

public class YourServiceName extends Service {


    @Override
    public void onCreate() {
        super.onCreate();

      // Timer task makes your service will repeat after every 20 Sec.
       TimerTask doAsynchronousTask = new TimerTask() {
            @Override
            public void run() {
                handler.post(new Runnable() {
                    public void run() {
                       // Add your code here.

                     }

               });
            }
        };
  //Starts after 20 sec and will repeat on every 20 sec of time interval.
        timer.schedule(doAsynchronousTask, 20000,20000);  // 20 sec timer 
                              (enter your own time)
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO do something useful

      return START_STICKY;
    }

}