Programs & Examples On #Using directives

The `using` directive, available in several languages including C# and C++, introduces members of a namespace into the current identifier search scope.

Why is "using namespace std;" considered bad practice?

The problem with putting using namespace in the header files of your classes is that it forces anyone who wants to use your classes (by including your header files) to also be 'using' (i.e. seeing everything in) those other namespaces.

However, you may feel free to put a using statement in your (private) *.cpp files.


Beware that some people disagree with my saying "feel free" like this -- because although a using statement in a cpp file is better than in a header (because it doesn't affect people who include your header file), they think it's still not good (because depending on the code it could make the implementation of the class more difficult to maintain). This C++ Super-FAQ entry says,

The using-directive exists for legacy C++ code and to ease the transition to namespaces, but you probably shouldn’t use it on a regular basis, at least not in your new C++ code.

The FAQ suggests two alternatives:

  • A using-declaration:

    using std::cout; // a using-declaration lets you use cout without qualification
    cout << "Values:";
    
  • Just typing std::

    std::cout << "Values:";
    

The type or namespace name could not be found

just changed Application's target framework to ".Net Framework 4".

And error got Disappeared.

good luck; :D

The type or namespace cannot be found (are you missing a using directive or an assembly reference?)

You don't have the namespace the Login class is in as a reference.

Add the following to the form that uses the Login class:

using FootballLeagueSystem;

When you want to use a class in another namespace, you have to tell the compiler where to find it. In this case, Login is inside the FootballLeagueSystem namespace, or : FootballLeagueSystem.Login is the fully qualified namespace.

As a commenter pointed out, you declare the Login class inside the FootballLeagueSystem namespace, but you're using it in the FootballLeague namespace.

How to embed a Facebook page's feed into my website

In new page-plugin you can do multiple tabs in your website. The Page plugin lets you easily embed and promote any Facebook Page on your website. Just like on Facebook, your visitors can like and share the Page without leaving your site.

  1. Include the JavaScript SDK on your page once, ideally right after the opening <body> tag.

_x000D_
_x000D_
<div id="fb-root"></div>_x000D_
<script>(function(d, s, id) {_x000D_
  var js, fjs = d.getElementsByTagName(s)[0];_x000D_
  if (d.getElementById(id)) return;_x000D_
  js = d.createElement(s); js.id = id;_x000D_
  js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.5&appId={APP_ID}";_x000D_
  fjs.parentNode.insertBefore(js, fjs);_x000D_
}(document, 'script', 'facebook-jssdk'));</script>
_x000D_
_x000D_
_x000D_

  1. Place the code for your plugin wherever you want the plugin to appear on your page.

_x000D_
_x000D_
<div class="fb-page" _x000D_
     data-href="https://www.facebook.com/YourPageName" _x000D_
     data-tabs="timeline" _x000D_
     data-small-header="false" _x000D_
     data-adapt-container-width="true" _x000D_
     data-hide-cover="false" _x000D_
     data-show-facepile="true">_x000D_
  <div class="fb-xfbml-parse-ignore">_x000D_
    <blockquote cite="https://www.facebook.com/facebook">_x000D_
      <a href="https://www.facebook.com/facebook">Facebook</a>_x000D_
    </blockquote>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can also change the following settings:

enter image description here

Also You can now have timeline, events and messages tabs with the new page plugin:

  • Timeline Tab: Will show the most recent posts of your Facebook Page timeline.
  • Events Tab: People can follow your page events and subscribe to events from the plugin.
  • Messages Tab: People can message your page directly from your website. People need to be logged in to use this feature.

_x000D_
_x000D_
<div class="fb-page" _x000D_
  data-tabs="timeline,events,messages"_x000D_
  data-href="https://www.facebook.com/YourPageName"_x000D_
  data-width="380" _x000D_
  data-hide-cover="false">_x000D_
</div>
_x000D_
_x000D_
_x000D_

EL access a map value by Integer key

Just another helpful hint in addition to the above comment would be when you have a string value contained in some variable such as a request parameter. In this case, passing this in will also result in JSTL keying the value of say "1" as a sting and as such no match being found in a Map hashmap.

One way to get around this is to do something like this.

<c:set var="longKey" value="${param.selectedIndex + 0}"/>

This will now be treated as a Long object and then has a chance to match an object when it is contained withing the map Map or whatever.

Then, continue as usual with something like

${map[longKey]}

Parsing json and searching through it

ObjectPath is a library that provides ability to query JSON and nested structures of dicts and lists. For example, you can search for all attributes called "foo" regardless how deep they are by using $..foo.

While the documentation focuses on the command line interface, you can perform the queries programmatically by using the package's Python internals. The example below assumes you've already loaded the data into Python data structures (dicts & lists). If you're starting with a JSON file or string you just need to use load or loads from the json module first.

import objectpath

data = [
    {'foo': 1, 'bar': 'a'},
    {'foo': 2, 'bar': 'b'},
    {'NoFooHere': 2, 'bar': 'c'},
    {'foo': 3, 'bar': 'd'},
]

tree_obj = objectpath.Tree(data)

tuple(tree_obj.execute('$..foo'))
# returns: (1, 2, 3)

Notice that it just skipped elements that lacked a "foo" attribute, such as the third item in the list. You can also do much more complex queries, which makes ObjectPath handy for deeply nested structures (e.g. finding where x has y that has z: $.x.y.z). I refer you to the documentation and tutorial for more information.

How do I convert this list of dictionaries to a csv file?

import csv
toCSV = [{'name':'bob','age':25,'weight':200},
         {'name':'jim','age':31,'weight':180}]
keys = toCSV[0].keys()
with open('people.csv', 'w', newline='')  as output_file:
    dict_writer = csv.DictWriter(output_file, keys)
    dict_writer.writeheader()
    dict_writer.writerows(toCSV)

EDIT: My prior solution doesn't handle the order. As noted by Wilduck, DictWriter is more appropriate here.

Is it possible to specify condition in Count()?

SELECT COUNT(*) FROM bla WHERE Position = 'Manager'

Can I assume (bool)true == (int)1 for any C++ compiler?

According to the standard, you should be safe with that assumption. The C++ bool type has two values - true and false with corresponding values 1 and 0.

The thing to watch about for is mixing bool expressions and variables with BOOL expression and variables. The latter is defined as FALSE = 0 and TRUE != FALSE, which quite often in practice means that any value different from 0 is considered TRUE.

A lot of modern compilers will actually issue a warning for any code that implicitly tries to cast from BOOL to bool if the BOOL value is different than 0 or 1.

How can you speed up Eclipse?

In special cases, bad performance can be due to corrupt h2 or nwire databases. Read Five tips for speeding up Eclipse PDT and nWire for more information.

Where I work, we are dependent on a VM to run Debian. I have installed another Eclipse version on the VM for testing purpouses, but this sometimes creates conflicts if I have the other Eclipse version running. There is a shared folder which both of the Eclipse versions shares. I accidentally left the Debian Eclipse installation running in the background once and that gave me corrupt database files.

How to fix the error; 'Error: Bootstrap tooltips require Tether (http://github.hubspot.com/tether/)'

For webpack I resolved this with webpack.config.js:

new webpack.ProvidePlugin({
  $: 'jquery',
  jQuery: 'jquery',
  "window.jQuery": "jquery",
  Tether: 'tether'
})

How do I deal with installing peer dependencies in Angular CLI?

I found that running the npm install command in the same directory where your Angular project is, eliminates these warnings. I do not know the reason why.

Specifically, I was trying to use ng2-completer

$ npm install ng2-completer --save
npm WARN saveError ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm notice created a lockfile as package-lock.json. You should commit this file.
npm WARN enoent ENOENT: no such file or directory, open 'C:\Work\foo\package.json'
npm WARN [email protected] requires a peer of @angular/common@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/core@>= 6.0.0 but noneis installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of @angular/forms@>= 6.0.0 but none is installed. You must install peer dependencies yourself.
npm WARN foo No description
npm WARN foo No repository field.
npm WARN foo No README data
npm WARN foo No license field.

I was unable to compile. When I tried again, this time in my Angular project directory which was in foo/foo_app, it worked fine.

cd foo/foo_app
$ npm install ng2-completer --save

Does WGET timeout?

The default timeout is 900 second. You can specify different timeout.

-T seconds
--timeout=seconds

The default is to retry 20 times. You can specify different tries.

-t number
--tries=number

link: wget man document

SQL like search string starts with

You need to use the wildcard % :

SELECT * from games WHERE (lower(title) LIKE 'age of empires III%');

DataTables fixed headers misaligned with columns in wide tables

For bootstrap users, this fixed it for me:

   $($.fn.dataTable.tables(true)).DataTable()
      .columns.adjust()
      .fixedColumns().relayout();

See article here

Adding attribute in jQuery

You can do this with jQuery's .attr function, which will set attributes. Removing them is done via the .removeAttr function.

//.attr()
$("element").attr("id", "newId");
$("element").attr("disabled", true);

//.removeAttr()
$("element").removeAttr("id");
$("element").removeAttr("disabled");

How to detect when an @Input() value changes in Angular?

Use the ngOnChanges() lifecycle method in your component.

ngOnChanges is called right after the data-bound properties have been checked and before view and content children are checked if at least one of them has changed.

Here are the Docs.

.war vs .ear file

Refer: http://www.wellho.net/mouth/754_tar-jar-war-ear-sar-files.html

tar (tape archives) - Format used is file written in serial units of fileName, fileSize, fileData - no compression. can be huge

Jar (java archive) - compression techniques used - generally contains java information like class/java files. But can contain any files and directory structure

war (web application archives) - similar like jar files only have specific directory structure as per JSP/Servlet spec for deployment purposes

ear (enterprise archives) - similar like jar files. have directory structure following J2EE requirements so that it can be deployed on J2EE application servers. - can contain multiple JAR and WAR files

PHP, Get tomorrows date from date

First, coming up with correct abstractions is always a key. key to readability, maintainability, and extendability.

Here, quite obvious candidate is an ISO8601DateTime. There are at least two implementations: first one is a parsed datetime from a string, and the second one is tomorrow. Hence, there are two classes that can be used, and their combination results in (almost) desired outcome:

new Tomorrow(new FromISO8601('2013-01-22'));

Both objects are an ISO8601 datetime, so their textual representation is not exactly what you need. So the final stroke is to make them take a date-form:

new Date(
    new Tomorrow(
        new FromISO8601('2013-01-22')
    )
);

Since you need a textual representation, not just an object, you invoke a value() method.

For more about this approach, take a look at this post.

Run .php file in Windows Command Prompt (cmd)

If running Windows 10:

  1. Open the start menu
  2. Type path
  3. Click Edit the system environment variables (usually, it's the top search result) and continue on step 6 below.

If on older Windows:

  1. Show Desktop.

  2. Right Click My Computer shortcut in the desktop.

  3. Click Properties.

  4. You should see a section of control Panel - Control Panel\System and Security\System.

  5. Click Advanced System Settings on the Left menu.

  6. Click Enviornment Variables towards the bottom of the System Properties window.

  7. Select PATH in the user variables list.

  8. Append your PHP Path (C:\myfolder\php) to your PATH variable, separated from the already existing string by a semi colon.

  9. Click OK

  10. Open your "cmd"

  11. Type PATH, press enter

  12. Make sure that you see your PHP folder among the list.

That should work.

Note: Make sure that your PHP folder has the php.exe. It should have the file type CLI. If you do not have the php.exe, go ahead and check the installation guidelines at - http://www.php.net/manual/en/install.windows.manual.php - and download the installation file from there.

How do I change tab size in Vim?

To make the change for one session, use this command:

:set tabstop=4

To make the change permanent, add it to ~/.vimrc or ~/.vim/vimrc:

set tabstop=4

This will affect all files, not just css. To only affect css files:

autocmd Filetype css setlocal tabstop=4

as stated in Michal's answer.

Ansible: deploy on multiple hosts in the same time

As mentioned before: By default Ansible will attempt to run on all hosts in parallel, but task after Task(serial).

If you also want to run Tasks in parallel you have to start different instances of ansible. Here are some ways to to it.

1. Groups

If you already have different groups you can run one ansible instance for each group:

shell-1 #> ansible-playbook site.yml --limit webservers
shell-2 #> ansible-playbook site.yml --limit dbservers
shell-3 #> ansible-playbook site.yml --limit load_balancers

2. Multiple shells

Playbooks

If your playbooks work standalone you can although do this:

shell-1 #> ansible-playbook load_balancers.yml
shell-2 #> ansible-playbook webservers.yml
shell-3 #> ansible-playbook dbservers.yml

Limit

If not, you can let ansible do the fragmentation. When you have 6 hosts and want to run 3 instances with 2 host each, you can do something like this:

shell-1 #> ansible-playbook site.yml --limit all[0-2]
shell-2 #> ansible-playbook site.yml --limit all[2-4]
shell-3 #> ansible-playbook site.yml --limit all[4-6]

3. Background

Of course you can use one shell and put the tasks in background, an simple example would be:

shell-1 #> ansible-playbook site.yml --limit all[0-2] &
shell-1 #> ansible-playbook site.yml --limit all[2-4] &
shell-1 #> ansible-playbook site.yml --limit all[4-6] &

With this method you get all output mixed together in one terminal. To avoid this you can write the output to different files.

ansible-playbook site.yml --limit all[0-2] > log1 &
ansible-playbook site.yml --limit all[2-4] > log2 &
ansible-playbook site.yml --limit all[4-6] > log3 &

4. Better Solutions

Maybe it's better to use a tool like tmux / screen to start the instances in virtual shells.

Or have a look at the "fireball mode": http://jpmens.net/2012/10/01/dramatically-speeding-up-ansible-runs/

If you want to know more about limits, look here: https://docs.ansible.com/playbooks_best_practices.html#what-this-organization-enables-examples

how to stop a for loop

There are several ways to do it:

The simple Way: a sentinel variable

n = L[0][0]
m = len(A)
found = False
for i in range(m):
   if found:
      break
   for j in range(m):
     if L[i][j] != n: 
       found = True
       break

Pros: easy to understand Cons: additional conditional statement for every loop

The hacky Way: raising an exception

n = L[0][0]
m = len(A)

try:
  for x in range(3):
    for z in range(3):
     if L[i][j] != n: 
       raise StopIteration
except StopIteration:
   pass

Pros: very straightforward Cons: you use Exception outside of their semantic

The clean Way: make a function

def is_different_value(l, elem, size):
  for x in range(size):
    for z in range(size):
     if l[i][j] != elem: 
       return True
  return False

if is_different_value(L, L[0][0], len(A)):
  print "Doh"

pros: much cleaner and still efficient cons: yet feels like C

The pythonic way: use iteration as it should be

def is_different_value(iterable):
  first = iterable[0][0]
  for l in iterable:
    for elem in l:
       if elem != first: 
          return True
  return False

if is_different_value(L):
  print "Doh"

pros: still clean and efficient cons: you reinvdent the wheel

The guru way: use any():

def is_different_value(iterable):
  first = iterable[0][0]
  return  any(any((cell != first for cell in col)) for elem in iterable)):

if is_different_value(L):
  print "Doh"

pros: you'll feel empowered with dark powers cons: people that will read you code may start to dislike you

How do I use Join-Path to combine more than two strings into a file path?

Or you could write your own function for it (which is what I ended up doing).

function Join-Path-Recursively($PathParts) {
    $NumberOfPathParts = $PathParts.Length;

    if ($NumberOfPathParts -eq 0) {
        return $null
    } elseif ($NumberOfPathParts -eq 1) {
        return $PathParts[0]
    } else {
        return Join-Path -Path $PathParts[0] -ChildPath $(Join-Path-Recursively -PathParts $PathParts[1..($NumberOfPathParts-1)])
    }
}

You could then call the function like this:

Join-Path-Recursively -PathParts  @("C:", "Program Files", "Microsoft Office")
Join-Path-Recursively  @("C:", "Program Files", "Microsoft Office")

This has the advantage of having the exact same behaviour as the normal Join-Path function and not depending on the .NET Framework.

Web-scraping JavaScript page with Python

EDIT 30/Dec/2017: This answer appears in top results of Google searches, so I decided to update it. The old answer is still at the end.

dryscape isn't maintained anymore and the library dryscape developers recommend is Python 2 only. I have found using Selenium's python library with Phantom JS as a web driver fast enough and easy to get the work done.

Once you have installed Phantom JS, make sure the phantomjs binary is available in the current path:

phantomjs --version
# result:
2.1.1

Example

To give an example, I created a sample page with following HTML code. (link):

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>Javascript scraping test</title>
</head>
<body>
  <p id='intro-text'>No javascript support</p>
  <script>
     document.getElementById('intro-text').innerHTML = 'Yay! Supports javascript';
  </script> 
</body>
</html>

without javascript it says: No javascript support and with javascript: Yay! Supports javascript

Scraping without JS support:

import requests
from bs4 import BeautifulSoup
response = requests.get(my_url)
soup = BeautifulSoup(response.text)
soup.find(id="intro-text")
# Result:
<p id="intro-text">No javascript support</p>

Scraping with JS support:

from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get(my_url)
p_element = driver.find_element_by_id(id_='intro-text')
print(p_element.text)
# result:
'Yay! Supports javascript'

You can also use Python library dryscrape to scrape javascript driven websites.

Scraping with JS support:

import dryscrape
from bs4 import BeautifulSoup
session = dryscrape.Session()
session.visit(my_url)
response = session.body()
soup = BeautifulSoup(response)
soup.find(id="intro-text")
# Result:
<p id="intro-text">Yay! Supports javascript</p>

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

How to prevent form from submitting multiple times from client side?

On the client side, you should disable the submit button once the form is submitted with javascript code like as the method provided by @vanstee and @chaos.

But there is a problem for network lag or javascript-disabled situation where you shouldn't rely on the JS to prevent this from happening.

So, on the server-side, you should check the repeated submission from the same clients and omit the repeated one which seems a false attempt from the user.

How to fix System.NullReferenceException: Object reference not set to an instance of an object

If the problem is 100% here

EffectSelectorForm effectSelectorForm = new EffectSelectorForm(Effects);

There's only one possible explanation: property/variable "Effects" is not initialized properly... Debug your code to see what you pass to your objects.

EDIT after several hours

There were some problems:

  • MEF attribute [Import] didn't work as expected, so we replaced it for the time being with a manually populated List<>. While the collection was null, it was causing exceptions later in the code, when the method tried to get the type of the selected item and there was none.

  • several event handlers weren't wired up to control events

Some problems are still present, but I believe OP's original problem has been fixed. Other problems are not related to this one.

Concatenating strings in Razor

You can give like this....

<a href="@(IsProduction.IsProductionUrl)Index/LogOut">

Filtering array of objects with lodash based on property value

lodash also has a remove method

var myArr = [
    { name: "john", age: 23 },
    { name: "john", age: 43 },
    { name: "jim", age: 101 },
    { name: "bob", age: 67 }
];

var onlyJohn = myArr.remove( person => { return person.name == "john" })

How to load images dynamically (or lazily) when users scrolls them into view

Some of the answers here are for infinite page. What Salman is asking is lazy loading of images.

Plugin

Demo

EDIT: How do these plugins work?

This is a simplified explanation:

  1. Find window size and find the position of all images and their sizes
  2. If the image is not within the window size, replace it with a placeholder of same size
  3. When user scrolls down, and position of image < scroll + window height, the image is loaded

Where will log4net create this log file?

I was developing for .NET core 2.1 using log4net 2.0.8 and found NealWalters code moans about 0 arguments for XmlConfigurator.Configure(). I found a solution by Matt Watson here

        log4net.GlobalContext.Properties["LogFileName"] = @"E:\\file1"; //log file path
        var logRepository = LogManager.GetRepository(Assembly.GetEntryAssembly());
        XmlConfigurator.Configure(logRepository, new FileInfo("log4net.config"));

jQuery checkbox change and click event

$(document).ready(function() {
    //set initial state.
    $('#textbox1').val($(this).is(':checked'));

    $('#checkbox1').change(function() {
        $('#textbox1').val($(this).is(':checked'));
    });

    $('#checkbox1').click(function() {
        if (!$(this).is(':checked')) {
            if(!confirm("Are you sure?"))
            {
                $("#checkbox1").prop("checked", true);
                $('#textbox1').val($(this).is(':checked'));
            }
        }
    });
});

How to avoid the "Circular view path" exception with Spring MVC test

I use the annotation to configure spring web app, the problem solved by adding a InternalResourceViewResolver bean to the configuration. Hope it would be helpful.

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = { "com.example.springmvc" })
public class WebMvcConfig extends WebMvcConfigurerAdapter {

    @Bean
    public InternalResourceViewResolver internalResourceViewResolver() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/jsp/");
        resolver.setSuffix(".jsp");
        return resolver;
    }
}

Extract data from log file in specified range of time

You can use sed for this. For example:

$ sed -n '/Feb 23 13:55/,/Feb 23 14:00/p' /var/log/mail.log
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: connect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: lost connection after CONNECT from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: disconnect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie pop3d: Connection, ip=[::ffff:127.0.0.1]
...

How it works

The -n switch tells sed to not output each line of the file it reads (default behaviour).

The last p after the regular expressions tells it to print lines that match the preceding expression.

The expression '/pattern1/,/pattern2/' will print everything that is between first pattern and second pattern. In this case it will print every line it finds between the string Feb 23 13:55 and the string Feb 23 14:00.

More info here.

Regular expression search replace in Sublime Text 2

Here is a visual presentation of the approved answer.

enter image description here

Image height and width not working?

You must write

<img src="theSource" style="width:30px;height:30px;" />

Inline styling will always take precedence over CSS styling. The width and height attributes are being overridden by your stylesheet, so you need to switch to this format.

To get specific part of a string in c#

You can use Substring:

string b = a.Substring(0,3);

Update multiple values in a single statement

Why are you doing a group by on an update statement? Are you sure that's not the part that's causing the query to fail? Try this:

update 
    MasterTbl
set
    TotalX = Sum(DetailTbl.X),
    TotalY = Sum(DetailTbl.Y),
    TotalZ = Sum(DetailTbl.Z)
from
    DetailTbl
where
    DetailTbl.MasterID = MasterID

CSS property to pad text inside of div

Just use div { padding: 20px; } and substract 40px from your original div width.

Like Philip Wills pointed out, you can also use box-sizing instead of substracting 40px:

div {
    padding: 20px;
    -moz-box-sizing: border-box; 
    box-sizing: border-box;
}

The -moz-box-sizing is for Firefox.

Finding height in Binary Search Tree

For people like me who like one line solutions:

public int getHeight(Node root) {
    return Math.max(root.left != null ? getHeight(root.left) : -1, 
                    root.right != null ? getHeight(root.right) : -1) 
                    + 1;
}

Wait for shell command to complete

Use the WScript.Shell instead, because it has a waitOnReturn option:

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "C:\folder\runbat.bat", windowStyle, waitOnReturn

(Idea copied from Wait for Shell to finish, then format cells - synchronously execute a command)

How to avoid soft keyboard pushing up my layout?

Solved it by setting the naughty EditText:

etSearch = (EditText) view.findViewById(R.id.etSearch);

etSearch.setInputType(InputType.TYPE_NULL);

etSearch.setOnTouchListener(new OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        etSearch.setInputType(InputType.TYPE_CLASS_TEXT);
        return false;
    }
});

Adding custom radio buttons in android

Use the same XML file format from Evan's answer, but one drawable file is all you need for formatting.

<RadioButton
    android:id="@+id/radio0"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/custom_button_background"
    android:button="@android:color/transparent"
    android:checked="true"
    android:text="RadioButton1" />

And your separate drawable file:

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

    <item android:state_pressed="true" >
         <shape android:shape="rectangle" >
             <corners android:radius="3dip" />
             <stroke android:width="1dip" android:color="#333333" />
             <solid android:color="#cccccc" />            
         </shape>
    </item>

    <item android:state_checked="true">
         <shape android:shape="rectangle" >
             <corners android:radius="3dip" />
             <stroke android:width="1dip" android:color="#333333" />
             <solid android:color="#cccccc" /> 
         </shape>
    </item>  

    <item>
         <shape android:shape="rectangle"  >
             <corners android:radius="3dip" />
             <stroke android:width="1dip" android:color="#cccccc" />
             <solid android:color="#ffffff" />            
         </shape>
    </item>
</selector>

Count Vowels in String Python

What you want can be done quite simply like so:

>>> mystr = input("Please type a sentence: ")
Please type a sentence: abcdE
>>> print(*map(mystr.lower().count, "aeiou"))
1 1 0 0 0
>>>

In case you don't know them, here is a reference on map and one on the *.

How to enable zoom controls and pinch zoom in a WebView?

Use these:

webview.getSettings().setBuiltInZoomControls(true);
webview.getSettings().setDisplayZoomControls(false);

Parse query string in JavaScript

Here's my version based loosely on Braceyard's version above but parsing into a 'dictionary' and support for search args without '='. In use it in my JQuery $(document).ready() function. The arguments are stored as key/value pairs in argsParsed, which you might want to save somewhere...

'use strict';

function parseQuery(search) {

    var args = search.substring(1).split('&');

    var argsParsed = {};

    var i, arg, kvp, key, value;

    for (i=0; i < args.length; i++) {

        arg = args[i];

        if (-1 === arg.indexOf('=')) {

            argsParsed[decodeURIComponent(arg).trim()] = true;
        }
        else {

            kvp = arg.split('=');

            key = decodeURIComponent(kvp[0]).trim();

            value = decodeURIComponent(kvp[1]).trim();

            argsParsed[key] = value;
        }
    }

    return argsParsed;
}

parseQuery(document.location.search);

How to redirect docker container logs to a single file?

Since Docker merges stdout and stderr for us, we can treat the log output like any other shell stream. To redirect the current logs to a file, use a redirection operator

$ docker logs test_container > output.log
docker logs -f test_container > output.log

Instead of sending output to stderr and stdout, redirect your application’s output to a file and map the file to permanent storage outside of the container.

$ docker logs test_container> /tmp/output.log

Docker will not accept relative paths on the command line, so if you want to use a different directory, you’ll need to use the complete path.

How can I convert a DateTime to an int?

I think you want (this won't fit in a int though, you'll need to store it as a long):

long result = dateDate.Year * 10000000000 + dateDate.Month * 100000000 + dateDate.Day * 1000000 + dateDate.Hour * 10000 + dateDate.Minute * 100 + dateDate.Second;

Alternatively, storing the ticks is a better idea.

Is it a good practice to place C++ definitions in header files?

As Tuomas said, your header should be minimal. To be complete I will expand a bit.

I personally use 4 types of files in my C++ projects:

  • Public:
  • Forwarding header: in case of templates etc, this file get the forwarding declarations that will appear in the header.
  • Header: this file includes the forwarding header, if any, and declare everything that I wish to be public (and defines the classes...)
  • Private:
  • Private header: this file is a header reserved for implementation, it includes the header and declares the helper functions / structures (for Pimpl for example or predicates). Skip if unnecessary.
  • Source file: it includes the private header (or header if no private header) and defines everything (non-template...)

Furthermore, I couple this with another rule: Do not define what you can forward declare. Though of course I am reasonable there (using Pimpl everywhere is quite a hassle).

It means that I prefer a forward declaration over an #include directive in my headers whenever I can get away with them.

Finally, I also use a visibility rule: I limit the scopes of my symbols as much as possible so that they do not pollute the outer scopes.

Putting it altogether:

// example_fwd.hpp
// Here necessary to forward declare the template class,
// you don't want people to declare them in case you wish to add
// another template symbol (with a default) later on
class MyClass;
template <class T> class MyClassT;

// example.hpp
#include "project/example_fwd.hpp"

// Those can't really be skipped
#include <string>
#include <vector>

#include "project/pimpl.hpp"

// Those can be forward declared easily
#include "project/foo_fwd.hpp"

namespace project { class Bar; }

namespace project
{
  class MyClass
  {
  public:
    struct Color // Limiting scope of enum
    {
      enum type { Red, Orange, Green };
    };
    typedef Color::type Color_t;

  public:
    MyClass(); // because of pimpl, I need to define the constructor

  private:
    struct Impl;
    pimpl<Impl> mImpl; // I won't describe pimpl here :p
  };

  template <class T> class MyClassT: public MyClass {};
} // namespace project

// example_impl.hpp (not visible to clients)
#include "project/example.hpp"
#include "project/bar.hpp"

template <class T> void check(MyClass<T> const& c) { }

// example.cpp
#include "example_impl.hpp"

// MyClass definition

The lifesaver here is that most of the times the forward header is useless: only necessary in case of typedef or template and so is the implementation header ;)

How to find the length of a string in R

See ?nchar. For example:

> nchar("foo")
[1] 3
> set.seed(10)
> strn <- paste(sample(LETTERS, 10), collapse = "")
> strn
[1] "NHKPBEFTLY"
> nchar(strn)
[1] 10

PLS-00428: an INTO clause is expected in this SELECT statement

In PLSQL block, columns of select statements must be assigned to variables, which is not the case in SQL statements.

The second BEGIN's SQL statement doesn't have INTO clause and that caused the error.

DECLARE
   PROD_ROW_ID   VARCHAR (10) := NULL;
   VIS_ROW_ID    NUMBER;
   DSC           VARCHAR (512);
BEGIN
   SELECT ROW_ID
     INTO VIS_ROW_ID
     FROM SIEBEL.S_PROD_INT
    WHERE PART_NUM = 'S0146404';

   BEGIN
      SELECT    RTRIM (VIS.SERIAL_NUM)
             || ','
             || RTRIM (PLANID.DESC_TEXT)
             || ','
             || CASE
                   WHEN PLANID.HIGH = 'TEST123'
                   THEN
                      CASE
                         WHEN TO_DATE (PROD.START_DATE) + 30 > SYSDATE
                         THEN
                            'Y'
                         ELSE
                            'N'
                      END
                   ELSE
                      'N'
                END
             || ','
             || 'GB'
             || ','
             || RTRIM (TO_CHAR (PROD.START_DATE, 'YYYY-MM-DD'))
        INTO DSC
        FROM SIEBEL.S_LST_OF_VAL PLANID
             INNER JOIN SIEBEL.S_PROD_INT PROD
                ON PROD.PART_NUM = PLANID.VAL
             INNER JOIN SIEBEL.S_ASSET NETFLIX
                ON PROD.PROD_ID = PROD.ROW_ID
             INNER JOIN SIEBEL.S_ASSET VIS
                ON VIS.PROM_INTEG_ID = PROD.PROM_INTEG_ID
             INNER JOIN SIEBEL.S_PROD_INT VISPROD
                ON VIS.PROD_ID = VISPROD.ROW_ID
       WHERE     PLANID.TYPE = 'Test Plan'
             AND PLANID.ACTIVE_FLG = 'Y'
             AND VISPROD.PART_NUM = VIS_ROW_ID
             AND PROD.STATUS_CD = 'Active'
             AND VIS.SERIAL_NUM IS NOT NULL;
   END;
END;
/

References

http://docs.oracle.com/cd/E11882_01/appdev.112/e25519/static.htm#LNPLS00601 http://docs.oracle.com/cd/B19306_01/appdev.102/b14261/selectinto_statement.htm#CJAJAAIG http://pls-00428.ora-code.com/

Difference between virtual and abstract methods

an abstract method must be call override in derived class other wise it will give compile-time error and in virtual you may or may not override it's depend if it's good enough use it

Example:

abstract class twodshape
{
    public abstract void area(); // no body in base class
}

class twodshape2 : twodshape
{
    public virtual double area()
    {
        Console.WriteLine("AREA() may be or may not be override");
    }
}

.map() a Javascript ES6 Map?

_x000D_
_x000D_
const mapMap = (callback, map) => new Map(Array.from(map).map(callback))_x000D_
_x000D_
var myMap = new Map([["thing1", 1], ["thing2", 2], ["thing3", 3]]);_x000D_
_x000D_
var newMap = mapMap((pair) => [pair[0], pair[1] + 1], myMap); // Map { 'thing1' => 2, 'thing2' => 3, 'thing3' => 4 }
_x000D_
_x000D_
_x000D_

How to set opacity to the background color of a div?

You can use CSS3 RGBA in this way:

rgba(255, 0, 0, 0.7);

0.7 means 70% opacity.

Convert pyspark string to date format

The strptime() approach does not work for me. I get another cleaner solution, using cast:

from pyspark.sql.types import DateType
spark_df1 = spark_df.withColumn("record_date",spark_df['order_submitted_date'].cast(DateType()))
#below is the result
spark_df1.select('order_submitted_date','record_date').show(10,False)

+---------------------+-----------+
|order_submitted_date |record_date|
+---------------------+-----------+
|2015-08-19 12:54:16.0|2015-08-19 |
|2016-04-14 13:55:50.0|2016-04-14 |
|2013-10-11 18:23:36.0|2013-10-11 |
|2015-08-19 20:18:55.0|2015-08-19 |
|2015-08-20 12:07:40.0|2015-08-20 |
|2013-10-11 21:24:12.0|2013-10-11 |
|2013-10-11 23:29:28.0|2013-10-11 |
|2015-08-20 16:59:35.0|2015-08-20 |
|2015-08-20 17:32:03.0|2015-08-20 |
|2016-04-13 16:56:21.0|2016-04-13 |

Intellij IDEA Java classes not auto compiling on save

I ended up recording a Macro to save and compile in one step, and keymap Ctrl+s to it.

Adding files to a GitHub repository

The general idea is to add, commit and push your files to the GitHub repo.

First you need to clone your GitHub repo.
Then, you would git add all the files from your other folder: one trick is to specify an alternate working tree when git add'ing your files.

git --work-tree=yourSrcFolder add .

(done from the root directory of your cloned Git repo, then git commit -m "a msg", and git push origin master)

That way, you keep separate your initial source folder, from your Git working tree.


Note that since early December 2012, you can create new files directly from GitHub:

Create new File

ProTip™: You can pre-fill the filename field using just the URL.
Typing ?filename=yournewfile.txt at the end of the URL will pre-fill the filename field with the name yournewfile.txt.

d

$(document).click() not working correctly on iPhone. jquery

try this, applies only to iPhone and iPod so you're not making everything turn blue on chrome or firefox mobile;

/iP/i.test(navigator.userAgent) && $('*').css('cursor', 'pointer');

basically, on iOS, things aren't "clickable" by default -- they're "touchable" (pfffff) so you make them "clickable" by giving them a pointer cursor. makes total sense, right??

Declaring functions in JSP?

You need to enclose that in <%! %> as follows:

<%!

public String getQuarter(int i){
String quarter;
switch(i){
        case 1: quarter = "Winter";
        break;

        case 2: quarter = "Spring";
        break;

        case 3: quarter = "Summer I";
        break;

        case 4: quarter = "Summer II";
        break;

        case 5: quarter = "Fall";
        break;

        default: quarter = "ERROR";
}

return quarter;
}

%>

You can then invoke the function within scriptlets or expressions:

<%
     out.print(getQuarter(4));
%>

or

<%= getQuarter(17) %>

How to use pip with Python 3.x alongside Python 2.x

In Windows, first installed Python 3.7 and then Python 2.7. Then, use command prompt:

pip install python2-module-name

pip3 install python3-module-name

That's all

Round a double to 2 decimal places

I think this is easier:

double time = 200.3456;
DecimalFormat df = new DecimalFormat("#.##");      
time = Double.valueOf(df.format(time));

System.out.println(time); // 200.35

Note that this will actually do the rounding for you, not just formatting.

Populating a database in a Laravel migration file

I know this is an old post but since it comes up in a google search I thought I'd share some knowledge here. @erin-geyer pointed out that mixing migrations and seeders can create headaches and @justamartin countered that sometimes you want/need data to be populated as part of your deployment.

I'd go one step further and say that sometimes it is desirable to be able to roll out data changes consistently so that you can for example deploy to staging, see that all is well, and then deploy to production with confidence of the same results (and not have to remember to run some manual step).

However, there is still value in separating out the seed and the migration as those are two related but distinct concerns. Our team has compromised by creating migrations which call seeders. This looks like:

public function up()
{
    Artisan::call( 'db:seed', [
        '--class' => 'SomeSeeder',
        '--force' => true ]
    );
}

This allows you to execute a seed one time just like a migration. You can also implement logic that prevents or augments behavior. For example:

public function up()
{
    if ( SomeModel::count() < 10 )
    {
        Artisan::call( 'db:seed', [
            '--class' => 'SomeSeeder',
            '--force' => true ]
        );
    }
}

This would obviously conditionally execute your seeder if there are less than 10 SomeModels. This is useful if you want to include the seeder as a standard seeder that executed when you call artisan db:seed as well as when you migrate so that you don't "double up". You may also create a reverse seeder so that rollbacks works as expected, e.g.

public function down()
{
    Artisan::call( 'db:seed', [
        '--class' => 'ReverseSomeSeeder',
        '--force' => true ]
    );
}

The second parameter --force is required to enable to seeder to run in a production environment.

Using IQueryable with Linq

Marc Gravell's answer is very complete, but I thought I'd add something about this from the user's point of view, as well...


The main difference, from a user's perspective, is that, when you use IQueryable<T> (with a provider that supports things correctly), you can save a lot of resources.

For example, if you're working against a remote database, with many ORM systems, you have the option of fetching data from a table in two ways, one which returns IEnumerable<T>, and one which returns an IQueryable<T>. Say, for example, you have a Products table, and you want to get all of the products whose cost is >$25.

If you do:

 IEnumerable<Product> products = myORM.GetProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

What happens here, is the database loads all of the products, and passes them across the wire to your program. Your program then filters the data. In essence, the database does a SELECT * FROM Products, and returns EVERY product to you.

With the right IQueryable<T> provider, on the other hand, you can do:

 IQueryable<Product> products = myORM.GetQueryableProducts();
 var productsOver25 = products.Where(p => p.Cost >= 25.00);

The code looks the same, but the difference here is that the SQL executed will be SELECT * FROM Products WHERE Cost >= 25.

From your POV as a developer, this looks the same. However, from a performance standpoint, you may only return 2 records across the network instead of 20,000....

How to multiply all integers inside list

The simplest way to me is:

map((2).__mul__, [1, 2, 3])

how to make label visible/invisible?

Change visible="false" to style="visibility:hidden" on your tags..


or better use a class to show/hide the labels..

.hidden{
   visibility:hidden;
}

then on your labels add class="hidden"

and with your script remove the class

document.getElementById("endTimeLabel").className = 'hidden'; // to hide

and

document.getElementById("endTimeLabel").className = ''; // to show

How to add Python to Windows registry

You can find the Python executable with this command:

C:\> where python.exe

It should return something like:

C:\Users\<user>\AppData\Local\enthought\Canopy32\User\python.exe

Open regedit, navigate to HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\<version>\PythonPath and add or edit the default key with this the value found in the first command. Logout, login and python should be found. SciKit can now be installed.

See Additional “application paths” in https://docs.python.org/2/using/windows.html#finding-modules for more details.

Passing just a type as a parameter in C#

foo.GetColumnValues(dm.mainColumn, typeof(string))

Alternatively, you could use a generic method:

public void GetColumnValues<T>(object mainColumn)
{
    GetColumnValues(mainColumn, typeof(T));
}

and you could then use it like:

foo.GetColumnValues<string>(dm.mainColumn);

ResultSet exception - before start of result set

You have to call next() before you can start reading values from the first row. beforeFirst puts the cursor before the first row, so there's no data to read.

Return zero if no record is found

You could:

SELECT COALESCE(SUM(columnA), 0) FROM my_table WHERE columnB = 1
INTO res;

This happens to work, because your query has an aggregate function and consequently always returns a row, even if nothing is found in the underlying table.

Plain queries without aggregate would return no row in such a case. COALESCE would never be called and couldn't save you. While dealing with a single column we can wrap the whole query instead:

SELECT COALESCE( (SELECT columnA FROM my_table WHERE ID = 1), 0)
INTO res;

Works for your original query as well:

SELECT COALESCE( (SELECT SUM(columnA) FROM my_table WHERE columnB = 1), 0)
INTO res;

More about COALESCE() in the manual.
More about aggregate functions in the manual.
More alternatives in this later post:

What is the best regular expression to check if a string is a valid URL?

/^(http|HTTP)+(s|S)?:\/\/[\w.-]+(?:\.[\w\.-]+)+[\w\-\._\$\(\)/]+$/g

check demo with tests:

https://regexr.com/5cedu

Adding a month to a date in T SQL

DateAdd(m,1,reference_dt)

will add a month to the column value

How to compare two colors for similarity/difference

I used this in my android up and it seems satisfactory although RGB space is not recommended:

    public double colourDistance(int red1,int green1, int blue1, int red2, int green2, int blue2)
{
      double rmean = ( red1 + red2 )/2;
    int r = red1 - red2;
    int g = green1 - green2;
    int b = blue1 - blue2;
    double weightR = 2 + rmean/256;
    double weightG = 4.0;
    double weightB = 2 + (255-rmean)/256;
    return Math.sqrt(weightR*r*r + weightG*g*g + weightB*b*b);
}

Then I used the following to get percent of similarity:

double maxColDist = 764.8339663572415;
double d1 = colourDistance(red1,green1,blue1,red2,green2,blue2);
String s1 = (int) Math.round(((maxColDist-d1)/maxColDist)*100) + "% match";

It works well enough.

hibernate could not get next sequence value

Please use the following query and alter your table : CREATE SEQUENCE user_id_seq START 1; ALTER TABLE product.users ALTER COLUMN user_id SET DEFAULT nextval('user_id_seq'); ALTER SEQUENCE users.user_id_seq OWNED BY users.user_id;

and use the this in your entity class

@GeneratedValue(strategy = GenerationType.SEQUENCE,generator="user_id_seq")

How to convert string to double with proper cultureinfo

You need to define a single locale that you will use for the data stored in the database, the invariant culture is there for exactly this purpose.

When you display convert to the native type and then format for the user's culture.

E.g. to display:

string fromDb = "123.56";
string display = double.Parse(fromDb, CultureInfo.InvariantCulture).ToString(userCulture);

to store:

string fromUser = "132,56";
double value;
// Probably want to use a more specific NumberStyles selection here.
if (!double.TryParse(fromUser, NumberStyles.Any, userCulture, out value)) {
  // Error...
}
string forDB = value.ToString(CultureInfo.InvariantCulture);

PS. It, almost, goes without saying that using a column with a datatype that matches the data would be even better (but sometimes legacy applies).

Get protocol, domain, and port from URL

Indeed, window.location.origin works fine in browsers following standards, but guess what. IE isn't following standards.

So because of that, this is what worked for me in IE, FireFox and Chrome:

var full = location.protocol+'//'+location.hostname+(location.port ? ':'+location.port: '');

but for possible future enhancements which could cause conflicts, I specified the "window" reference before the "location" object.

var full = window.location.protocol+'//'+window.location.hostname+(window.location.port ? ':'+window.location.port: '');

JavaScript chop/slice/trim off last character in string

Be aware that String.prototype.{ split, slice, substr, substring } operate on UTF-16 encoded strings

None of the previous answers are Unicode-aware. Strings are encoded as UTF-16 in most modern JavaScript engines, but higher Unicode code points require surrogate pairs, so older, pre-existing string methods operate on UTF-16 code units, not Unicode code points.

_x000D_
_x000D_
const string = "?";

console.log(string.slice(0, -1)); // "?\ud83e"
console.log(string.substr(0, string.length - 1)); // "?\ud83e"
console.log(string.substring(0, string.length - 1)); // "?\ud83e"
console.log(string.replace(/.$/, "")); // "?\ud83e"
console.log(string.match(/(.*).$/)[1]); // "?\ud83e"

const utf16Chars = string.split("");

utf16Chars.pop();
console.log(utf16Chars.join("")); // "?\ud83e"
_x000D_
_x000D_
_x000D_

In addition, RegExp methods, as suggested in older answers, don’t match line breaks at the end:

_x000D_
_x000D_
const string = "Hello, world!\n";

console.log(string.replace(/.$/, "").endsWith("\n")); // true
console.log(string.match(/(.*).$/) === null); // true
_x000D_
_x000D_
_x000D_


Use the string iterator to iterate characters

Unicode-aware code utilizes the string’s iterator; see Array.from and ... spread. string[Symbol.iterator] can be used (e.g. instead of string) as well.

Also see How to split Unicode string to characters in JavaScript.

Examples:

_x000D_
_x000D_
const string = "?";

console.log(Array.from(string).slice(0, -1).join("")); // "?"
console.log([
  ...string
].slice(0, -1).join("")); // "?"
_x000D_
_x000D_
_x000D_

Use the s and u flags on a RegExp

The dotAll or s flag makes . match line break characters, the unicode or u flag enables certain Unicode-related features. Note that, when using the u flag, you eliminate unnecessary identity escapes, as these are invalid in a u regex, e.g. \[ is fine, as it would start a character class without the backslash, but \: isn’t, as it’s a : with or without the backslash, so you need to remove the backslash.

Examples:

_x000D_
_x000D_
const unicodeString = "?",
  lineBreakString = "Hello, world!\n";

console.log(lineBreakString.replace(/.$/s, "").endsWith("\n")); // false
console.log(lineBreakString.match(/(.*).$/s) === null); // false
console.log(unicodeString.replace(/.$/su, "")); // ?
console.log(unicodeString.match(/(.*).$/su)[1]); // ?

// Now `split` can be made Unicode-aware:

const unicodeCharacterArray = unicodeString.split(/(?:)/su),
  lineBreakCharacterArray = lineBreakString.split(/(?:)/su);

unicodeCharacterArray.pop();
lineBreakCharacterArray.pop();
console.log(unicodeCharacterArray.join("")); // "?"
console.log(lineBreakCharacterArray.join("").endsWith("\n")); // false
_x000D_
_x000D_
_x000D_


Note that some graphemes consist of more than one code point, e.g. ?? which consists of the sequence (U+1F3F3), VS16 (U+FE0F), ZWJ (U+200D), (U+1F308). Here, even Array.from will split this into four “characters”. Matching those is possible with the Unicode property escapes sequence properties proposal.

Selecting a Linux I/O Scheduler

The Linux Kernel does not automatically change the IO Scheduler at run-time. By this I mean, the Linux kernel, as of today, is not able to automatically choose an "optimal" scheduler depending on the type of secondary storage devise. During start-up, or during run-time, it is possible to change the IO scheduler manually.

The default scheduler is chosen at start-up based on the contents in the file located at /linux-2.6 /block/Kconfig.iosched. However, it is possible to change the IO scheduler during run-time by echoing a valid scheduler name into the file located at /sys/block/[DEV]/queue/scheduler. For example, echo deadline > /sys/block/hda/queue/scheduler

Swapping pointers in C (char, int)

If you have the luxury of working in C++, use this:

template<typename T>
void swapPrimitives(T& a, T& b)
{
    T c = a;
    a = b;
    b = c;
}

Granted, in the case of char*, it would only swap the pointers themselves, not the data they point to, but in most cases, that is OK, right?

How to View Oracle Stored Procedure using SQLPlus?

check your casing, the name is typically stored in upper case

SELECT * FROM all_source WHERE name = 'DAILY_UPDATE' ORDER BY TYPE, LINE;

Find a commit on GitHub given the commit hash

View single commit:
https://github.com/<user>/<project>/commit/<hash>

View log:
https://github.com/<user>/<project>/commits/<hash>

View full repo:
https://github.com/<user>/<project>/tree/<hash>

<hash> can be any length as long as it is unique.

Capturing a single image from my webcam in Java or Python

It can be done by using ecapture First, run

pip install ecapture

Then in a new python script type:

    from ecapture import ecapture as ec

    ec.capture(0,"test","img.jpg")

More information from thislink

ReactJS Two components communicating

I once was where you are right now, as a beginner you sometimes feel out of place on how the react way to do this. I'm gonna try to tackle the same way I think of it right now.

States are the cornerstone for communication

Usually what it comes down to is the way that you alter the states in this component in your case you point out three components.

<List /> : Which probably will display a list of items depending on a filter <Filters />: Filter options that will alter your data. <TopBar />: List of options.

To orchestrate all of this interaction you are going to need a higher component let's call it App, that will pass down actions and data to each one of this components so for instance can look like this

<div>
  <List items={this.state.filteredItems}/>
  <Filter filter={this.state.filter} setFilter={setFilter}/>
</div>

So when setFilter is called it will affect the filteredItem and re-render both component;. In case this is not entirely clear I made you an example with checkbox that you can check in a single file:

import React, {Component} from 'react';
import {render} from 'react-dom';

const Person  = ({person, setForDelete}) => (
          <div>
            <input type="checkbox" name="person" checked={person.checked} onChange={setForDelete.bind(this, person)} />
            {person.name}
          </div>
);


class PeopleList extends Component {

  render() {

    return(
      <div>
       {this.props.people.map((person, i) => {
         return <Person key={i} person={person} setForDelete={this.props.setForDelete} />;
       })}
       <div onClick={this.props.deleteRecords}>Delete Selected Records</div>
     </div>
    );
  }

} // end class

class App extends React.Component {

  constructor(props) {
    super(props)
    this.state = {people:[{id:1, name:'Cesar', checked:false},{id:2, name:'Jose', checked:false},{id:3, name:'Marbel', checked:false}]}
  }

  deleteRecords() {
    const people = this.state.people.filter(p => !p.checked);

    this.setState({people});
 }

  setForDelete(person) {
    const checked = !person.checked;
    const people = this.state.people.map((p)=>{
      if(p.id === person.id)
        return {name:person.name, checked};
      return p;
    });

    this.setState({people});
  }

  render () {

    return <PeopleList people={this.state.people} deleteRecords={this.deleteRecords.bind(this)} setForDelete={this.setForDelete.bind(this)}/>;
  }
}

render(<App/>, document.getElementById('app'));

The openssl extension is required for SSL/TLS protection

I just add this because it worked for me, i install composer with the developer option activate (just check the box in the installer)

https://getcomposer.org/Composer-Setup.exe

I think this problem may occurs when you add a new version of php to your wamp server. If you do this, you have to check if the extension_dir variable is configure to "env".

Then check if the php_openssl.dll exist in your phpx.x/ext folder. If there is not php_openssl.dll, you have to download it here : http://www.telecharger-dll.fr/dll-php_openssl.dll.html

If it still not working, check if your apache server use the good php.ini file by running the following cmd command :

php --ini

Configuration File (php.ini) Path: C:\Windows
Loaded Configuration File:         C:\wamp64\bin\php\php7.4.7x64\php.ini
Scan for additional .ini files in: (none)
Additional .ini files parsed:      (none)

If the loaded configuration file return (none), you have to check your appache/apache2.4.41/conf/httpd.conf file is configure with the proper phpIniDir and the correct module.

It must be something like this :

PHPIniDir "${APACHE_DIR}/bin"
LoadModule php7_module "${INSTALL_DIR}/bin/php/php7.4.7x64/php7apache2_4.dll"

Then restart apache and check the "apache/apache2.4.41/bin/php.ini" (wich is the one configure above by PHPIniDir) it must me like

enter image description here

Using fonts with Rails asset pipeline

I'm using Rails 4.2, and could not get the footable icons to show up. Little boxes were showing, instead of the (+) on collapsed rows and the little sorting arrows I expected. After studying the information here, I made one simple change to my code: remove the font directory in css. That is, change all the css entries like this:

src:url('fonts/footable.eot');

to look like this:

src:url('footable.eot');

It worked. I think Rails 4.2 already assumes the font directory, so specifying it again in the css code makes the font files not get found. Hope this helps.

How to add Apache HTTP API (legacy) as compile-time dependency to build.grade for Android M?

I solved this problem like so:

1.) Set classpath in top-level build file as GUG mentioned:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.3.0-beta2'
    }
    allprojects {
        repositories {
           jcenter()
        }
    }
}

2.) In build file of specific module:

android {
   useLibrary 'org.apache.http.legacy'
   compileSdkVersion 'android-MNC'
   buildToolsVersion '23.0.0 rc3'
}

How to import a csv file using python with headers intact, where first column is a non-numerical

You can use pandas library and reference the rows and columns like this:

import pandas as pd

input = pd.read_csv("path_to_file");

#for accessing ith row:
input.iloc[i]

#for accessing column named X
input.X

#for accessing ith row and column named X
input.iloc[i].X

How do I upload a file with the JS fetch API?

The problem for me was that I was using a response.blob() to populate the form data. Apparently you can't do that at least with react native so I ended up using

data.append('fileData', {
  uri : pickerResponse.uri,
  type: pickerResponse.type,
  name: pickerResponse.fileName
 });

Fetch seems to recognize that format and send the file where the uri is pointing.

Javascript Date - set just the date, ignoring time?

_x000D_
_x000D_
var today = new Date();
var year = today.getFullYear();
var mes = today.getMonth()+1;
var dia = today.getDate();
var fecha =dia+"-"+mes+"-"+year;
console.log(fecha);
_x000D_
_x000D_
_x000D_

Calling Web API from MVC controller

Its very late here but thought to share below code. If we have our WebApi as a different project altogether in the same solution then we can call the same from MVC controller like below

public class ProductsController : Controller
    {
        // GET: Products
        public async Task<ActionResult> Index()
        {
            string apiUrl = "http://localhost:58764/api/values";

            using (HttpClient client=new HttpClient())
            {
                client.BaseAddress = new Uri(apiUrl);
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));

                HttpResponseMessage response = await client.GetAsync(apiUrl);
                if (response.IsSuccessStatusCode)
                {
                    var data = await response.Content.ReadAsStringAsync();
                    var table = Newtonsoft.Json.JsonConvert.DeserializeObject<System.Data.DataTable>(data);

                }


            }
            return View();

        }
    }

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

This is what EF (DB first) generates in the DbContext class:

public ObjectResult<int> Insert_Department(string department)
{
    var departmentParameter = new ObjectParameter("department", department);

    return ((IObjectContextAdapter)this).ObjectContext.ExecuteFunction<int>("insert_department", departmentParameter);
}

How to wait in a batch script?

What about:

@echo off
set wait=%1
echo waiting %wait% s
echo wscript.sleep %wait%000 > wait.vbs
wscript.exe wait.vbs
del wait.vbs

How to use split?

Look in JavaScript split() Method

Usage:

"something -- something_else".split(" -- ") 

Convert a hexadecimal string to an integer efficiently in C?

In C you can convert a hexadecimal number to decimal in many ways. One way is to cast the hexadecimal number to an integer. I personally found this to be simple and small.

Here is an sample code for converting a Hexadecimal number to a Decimal number with the help of casting.

#include <stdio.h>

int main(){
    unsigned char Hexadecimal = 0x6D;   //example hex number
    int Decimal = 0;    //decimal number initialized to 0


        Decimal = (int) Hexadecimal;  //conversion

    printf("The decimal number is %d\n", Decimal);  //output
    return 0;
}

Call web service in excel

In Microsoft Excel Office 2007 try installing "Web Service Reference Tool" plugin. And use the WSDL and add the web-services. And use following code in module to fetch the necessary data from the web-service.

Sub Demo()
    Dim XDoc As MSXML2.DOMDocument
    Dim xEmpDetails As MSXML2.IXMLDOMNode
    Dim xParent As MSXML2.IXMLDOMNode
    Dim xChild As MSXML2.IXMLDOMNode
    Dim query As String
    Dim Col, Row As Integer
    Dim objWS As New clsws_GlobalWeather

    Set XDoc = New MSXML2.DOMDocument
    XDoc.async = False
    XDoc.validateOnParse = False
    query = objWS.wsm_GetCitiesByCountry("india")

    If Not XDoc.LoadXML(query) Then  'strXML is the string with XML'
        Err.Raise XDoc.parseError.ErrorCode, , XDoc.parseError.reason
    End If
    XDoc.LoadXML (query)

    Set xEmpDetails = XDoc.DocumentElement
    Set xParent = xEmpDetails.FirstChild
    Worksheets("Sheet3").Cells(1, 1).Value = "Country"
    Worksheets("Sheet3").Cells(1, 1).Interior.Color = RGB(65, 105, 225)
    Worksheets("Sheet3").Cells(1, 2).Value = "City"
    Worksheets("Sheet3").Cells(1, 2).Interior.Color = RGB(65, 105, 225)
    Row = 2
    Col = 1
    For Each xParent In xEmpDetails.ChildNodes
        For Each xChild In xParent.ChildNodes
            Worksheets("Sheet3").Cells(Row, Col).Value = xChild.Text
            Col = Col + 1
        Next xChild
        Row = Row + 1
        Col = 1
    Next xParent
End Sub

MySQL SELECT x FROM a WHERE NOT IN ( SELECT x FROM b ) - Unexpected result

I'm a little out of touch with the details of how MySQL deals with nulls, but here's two things to try:

SELECT * FROM match WHERE id NOT IN 
    ( SELECT id FROM email WHERE id IS NOT NULL) ;

SELECT
    m.*
FROM
    match m
    LEFT OUTER JOIN email e ON
        m.id = e.id
        AND e.id IS NOT NULL
WHERE
    e.id IS NULL

The second query looks counter intuitive, but it does the join condition and then the where condition. This is the case where joins and where clauses are not equivalent.

Position last flex item at the end of container

Flexible Box Layout Module - 8.1. Aligning with auto margins

Auto margins on flex items have an effect very similar to auto margins in block flow:

  • During calculations of flex bases and flexible lengths, auto margins are treated as 0.

  • Prior to alignment via justify-content and align-self, any positive free space is distributed to auto margins in that dimension.

Therefore you could use margin-top: auto to distribute the space between the other elements and the last element.

This will position the last element at the bottom.

p:last-of-type {
  margin-top: auto;
}

_x000D_
_x000D_
.container {
  display: flex;
  flex-direction: column;
  border: 1px solid #000;
  min-height: 200px;
  width: 100px;
}
p {
  height: 30px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-top: auto;
}
_x000D_
<div class="container">
  <p></p>
  <p></p>
  <p></p>
</div>
_x000D_
_x000D_
_x000D_

vertical example


Likewise, you can also use margin-left: auto or margin-right: auto for the same alignment horizontally.

p:last-of-type {
  margin-left: auto;
}

_x000D_
_x000D_
.container {
  display: flex;
  width: 100%;
  border: 1px solid #000;
}
p {
  height: 50px;
  width: 50px;
  background-color: blue;
  margin: 5px;
}
p:last-of-type {
  margin-left: auto;
}
_x000D_
<div class="container">
  <p></p>
  <p></p>
  <p></p>
  <p></p>
</div>
_x000D_
_x000D_
_x000D_

horizontal example

How to correctly set Http Request Header in Angular 2

The simpler and current approach for adding header to a single request is:

// Step 1

const yourHeader: HttpHeaders = new HttpHeaders({
    Authorization: 'Bearer JWT-token'
});

// POST request

this.http.post(url, body, { headers: yourHeader });

// GET request

this.http.get(url, { headers: yourHeader });

Is it possible to set UIView border properties from interface builder?

If you want to save time, just use two UIViews on top of each other, the one at the back being the border color, and the one in front smaller, giving the bordered effect. I don't think this is an elegant solution either, but if Apple cared a little more then you shouldn't have to do this.

how to set ul/li bullet point color?

A couple ways this can be done:

This will make it a square

ul
{
  list-style-type: square;
}

This will make it green

li
{
  color: #0F0;
}

This will prevent the text from being green

li p
{
  color: #000;
}

However that will require that all text within lists be in paragraphs so that the color is not overridden.

A better way is to make an image of a green square and use:

ul
{
  list-style: url(green-square.png);
}

Show "Open File" Dialog

I have a similar solution to the above and it works for opening, saving, file selecting. I paste it into its own module and use in all the Access DB's I create. As the code states it requires Microsoft Office 14.0 Object Library. Just another option I suppose:

Public Function Select_File(InitPath, ActionType, FileType)
    ' Requires reference to Microsoft Office 14.0 Object Library.

    Dim fDialog As Office.FileDialog
    Dim varFile As Variant


    If ActionType = "FilePicker" Then
        Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
        ' Set up the File Dialog.
    End If
    If ActionType = "SaveAs" Then
        Set fDialog = Application.FileDialog(msoFileDialogSaveAs)
    End If
    If ActionType = "Open" Then
        Set fDialog = Application.FileDialog(msoFileDialogOpen)
    End If
    With fDialog
        .AllowMultiSelect = False
        ' Disallow user to make multiple selections in dialog box
        .Title = "Please specify the file to save/open..."
        ' Set the title of the dialog box.
        If ActionType <> "SaveAs" Then
            .Filters.Clear
            ' Clear out the current filters, and add our own.
            .Filters.Add FileType, "*." & FileType
        End If
        .InitialFileName = InitPath
        ' Show the dialog box. If the .Show method returns True, the
        ' user picked a file. If the .Show method returns
        ' False, the user clicked Cancel.
        If .Show = True Then
        'Loop through each file selected and add it to our list box.
            For Each varFile In .SelectedItems
                'return the subroutine value as the file path & name selected
                Select_File = varFile
            Next
        End If
    End With
End Function

Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed

hope this helps someone. this worked for me on Ubuntu 18.10

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument('--no-sandbox')
driver = webdriver.Chrome('/usr/lib/chromium-browser/chromedriver', options=chrome_options)
driver.get('http://www.google.com')
print('test')
driver.close()

How to setup Tomcat server in Netbeans?

In Netbeans 8 you may have to install the Tomcat plugin manually. After you download and extract Tomcat follow these steps:

  1. Tools -> Plugins -> Available plugins, search for 'tomcat' and install the one named "Java EE Base plugin".
  2. Restart Netbeans
  3. On the project view (default left side of the screen), go to services, right click on Servers and then "Add Server"
  4. Select Apache Tomcat, enter username and password and config the rest and finish

if (boolean condition) in Java

if (turnedOn) {
    //do stuff when the condition is false or true?
}
else {
    //do else of if
}

It can be written like:

if (turnedOn == true) {
        //do stuff when the condition is false or true?
    }
else { // turnedOn == false or !turnedOn
        //do else of if
}

So if your turnedOn variable is true, if will be called, if is assigned to false, else will be called. boolean values are implicitly assigned to false if you won't assign them explicitly e.q. turnedOn = true

Parsing JSON in Java without knowing JSON format

Take a look at Jacksons built-in tree model feature.

And your code will be:

public void parse(String json)  {
       JsonFactory factory = new JsonFactory();

       ObjectMapper mapper = new ObjectMapper(factory);
       JsonNode rootNode = mapper.readTree(json);  

       Iterator<Map.Entry<String,JsonNode>> fieldsIterator = rootNode.fields();
       while (fieldsIterator.hasNext()) {

           Map.Entry<String,JsonNode> field = fieldsIterator.next();
           System.out.println("Key: " + field.getKey() + "\tValue:" + field.getValue());
       }
}

How do I remove the top margin in a web page?

_x000D_
_x000D_
body{_x000D_
margin:0;_x000D_
padding:0;_x000D_
}
_x000D_
<span>Example</span>
_x000D_
_x000D_
_x000D_

Cannot construct instance of - Jackson

For me there was no default constructor defined for the POJOs I was trying to use. creating default constructor fixed it.

public class TeamCode {

    @Expose
    private String value;

    public String getValue() {
        return value;
    }

    **public TeamCode() {
    }**

    public TeamCode(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "TeamCode{" +
                "value='" + value + '\'' +
                '}';
    }

    public void setValue(String value) {
        this.value = value;
    }

}

How to get old Value with onchange() event in text box

Maybe you can store the previous value of the textbox into a hidden textbox. Then you can get the first value from hidden and the last value from textbox itself. An alternative related to this, at onfocus event of your textbox set the value of your textbox to an hidden field and at onchange event read the previous value.

How to disable scrolling temporarily?

I had a similar animation problem on mobile screens but not on laptops, when trying to animate a div using jquery's animate command. So I decided to use a timer that restored the window's scroll position so frequently that to a naked eye the document would appear static. This solution worked perfectly on a small screen mobile device like Samsung Galaxy-2 or iphone-5.

Main Logic of this approach: The timer to set window's scroll position to original scroll position should be started before the jquery animate command, and then when animation is completed we need to clear this timer (original scroll position is the position just before animation starts).

I found to my pleasant surprise that the document actually appeared static during the animation duration if the timer interval was 1 millisecond, which is what I was aiming for.

//get window scroll position prior to animation
//so we can keep this position during animation
var xPosition = window.scrollX || window.pageXOffset || document.body.scrollLeft;
var yPosition = window.scrollY || window.pageYOffset || document.body.scrollTop;

//NOTE:restoreTimer needs to be global variable
//start the restore timer
restoreTimer = setInterval(function() {
    window.scrollTo(xPosition, yPosition);
}, 1);

//animate the element emt
emt.animate({
    left: "toggle",
    top: "toggle",
    width: "toggle",
    height: "toggle"
}, 500, function() {
    //when animation completes, we stop the timer
    clearInterval(restoreTimer);
});

ANOTHER SOLUTION that worked: Based on the answer by Mohammad Anini under this post to enable/disable scrolling, I also found that a modified version of code as below worked.

//get current scroll position
var xPosition = window.scrollX || window.pageXOffset || document.body.scrollLeft;
var yPosition = window.scrollY || window.pageYOffset || document.body.scrollTop;

//disable scrolling
window.onscroll = function() {
    window.scrollTo(xPosition, yPosition);
};

//animate and enable scrolling when animation is completed
emt.animate({
    left: "toggle",
    top: "toggle",
    width: "toggle",
    height: "toggle"
}, 500, function() {
    //enable scrolling when animation is done
    window.onscroll = function() {};
});

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

Make sure you have following configuration in your pom.xml file.

<properties>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
</properties>

XAMPP installation on Win 8.1 with UAC Warning

As ivan.sim writes in his answer

  1. Ensure that your user account has administrator privilege.
  2. Disable UAC(User Account Control) as it restricts certain administrative function needed to run a web server.
  3. Install in C://xampp.

Problem with the correct answer is in the explanation of point 2., and magicandre1981 writes more about it

Moving the slider down doesn't completely disable UAC since Windows 8. This is changed compared to Windows 7, because the new Store apps require an active UAC. With UAC off, they no longer run.


How can we then disable UAC and install XAMPP?

Easy. Go to Registry Editor and navigate to

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System

Registry Editor

Right click EnableLUA and modify the Value data to 0.

EnableLUA

Then restart your computer and you're ready to install XAMPP.

Installing XAMPP

XAMPP installed

XAMPP Control Panel

How to fill Dataset with multiple tables?

public DataSet GetDataSet()
    {
        try
        {
            DataSet dsReturn = new DataSet();
            using (SqlConnection myConnection = new SqlConnection(Core.con))
            {
                string query = "select * from table1;  select* from table2";
                SqlCommand cmd = new SqlCommand(query, myConnection);
                myConnection.Open();
                SqlDataReader reader = cmd.ExecuteReader();
                dsReturn.Load(reader, LoadOption.PreserveChanges, new string[] { "tableOne", "tableTwo" });
                return dsReturn;
            }
        }
        catch (Exception)
        {
            throw;
        }
    }

How to urlencode data for curl command?

for the sake of completeness, many solutions using sed or awk only translate a special set of characters and are hence quite large by code size and also dont translate other special characters that should be encoded.

a safe way to urlencode would be to just encode every single byte - even those that would've been allowed.

echo -ne 'some random\nbytes' | xxd -plain | tr -d '\n' | sed 's/\(..\)/%\1/g'

xxd is taking care here that the input is handled as bytes and not characters.

edit:

xxd comes with the vim-common package in Debian and I was just on a system where it was not installed and I didnt want to install it. The altornative is to use hexdump from the bsdmainutils package in Debian. According to the following graph, bsdmainutils and vim-common should have an about equal likelihood to be installed:

http://qa.debian.org/popcon-png.php?packages=vim-common%2Cbsdmainutils&show_installed=1&want_legend=1&want_ticks=1

but nevertheless here a version which uses hexdump instead of xxd and allows to avoid the tr call:

echo -ne 'some random\nbytes' | hexdump -v -e '/1 "%02x"' | sed 's/\(..\)/%\1/g'

Custom domain for GitHub project pages

Short answer

These detailed explanations are great, but the OP's (and my) confusion could be resolved with one sentence: "Direct DNS to your GitHub username or organization, ignoring the specific project, and add the appropriate CNAME files in your project repositories: GitHub will send the right DNS to the right project based on files in the respository."

How do I prevent Conda from activating the base environment by default?

If you want to keep your bashrc simple, you can remove all the conda init generated clutter, and keep only a single line:

. "/Users/geoff/anaconda2/etc/profile.d/conda.sh"

See Recommended change to enable conda in your shell.

This will make the conda command available without activating the base environment.

If you want to use your bashrc on other systems where conda is not installed in the same path, you can keep the if/fi lines as well to avoid error messages, i.e.:

if [ -f "/Users/geoff/anaconda2/etc/profile.d/conda.sh" ]; then
    . "/Users/geoff/anaconda2/etc/profile.d/conda.sh"
fi

Parsing xml using powershell

[xml]$xmlfile = '<xml> <Section name="BackendStatus"> <BEName BE="crust" Status="1" /> <BEName BE="pizza" Status="1" /> <BEName BE="pie" Status="1" /> <BEName BE="bread" Status="1" /> <BEName BE="Kulcha" Status="1" /> <BEName BE="kulfi" Status="1" /> <BEName BE="cheese" Status="1" /> </Section> </xml>'

foreach ($bename in $xmlfile.xml.Section.BEName) {
    if($bename.Status -eq 1){
        #Do something
    }
}

Use StringFormat to add a string to a WPF XAML binding

Here's an alternative that works well for readability if you have the Binding in the middle of the string or multiple bindings:

<TextBlock>
  <Run Text="Temperature is "/>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>  
</TextBlock>

<!-- displays: 0°C (32°F)-->
<TextBlock>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>
  <Run Text=" ("/>
  <Run Text="{Binding Fahrenheit}"/>
  <Run Text="°F)"/>
</TextBlock>

iTerm2 keyboard shortcut - split pane navigation

Cmd+opt+?/?/?/? navigate similarly to vim's C-w hjkl.

How can I pass a parameter to a t-sql script?

SQL*Plus uses &1, &2... &n to access the parameters.

Suppose you have the following script test.sql:

SET SERVEROUTPUT ON
SPOOL test.log
EXEC dbms_output.put_line('&1 &2');
SPOOL off

you could call this script like this for example:

$ sqlplus login/pw @test Hello World!

Edit:

In a UNIX script you would usually call a SQL script like this:

sqlplus /nolog << EOF
connect user/password@db
@test.sql Hello World!
exit
EOF

so that your login/password won't be visible with another session's ps

How can I do DNS lookups in Python, including referring to /etc/hosts?

I found this way to expand a DNS RR hostname that expands into a list of IPs, into the list of member hostnames:

#!/usr/bin/python

def expand_dnsname(dnsname):
    from socket import getaddrinfo
    from dns import reversename, resolver
    namelist = [ ]
    # expand hostname into dict of ip addresses
    iplist = dict()
    for answer in getaddrinfo(dnsname, 80):
        ipa = str(answer[4][0])
        iplist[ipa] = 0
    # run through the list of IP addresses to get hostnames
    for ipaddr in sorted(iplist):
        rev_name = reversename.from_address(ipaddr)
        # run through all the hostnames returned, ignoring the dnsname
        for answer in resolver.query(rev_name, "PTR"):
            name = str(answer)
            if name != dnsname:
                # add it to the list of answers
                namelist.append(name)
                break
    # if no other choice, return the dnsname
    if len(namelist) == 0:
        namelist.append(dnsname)
    # return the sorted namelist
    namelist = sorted(namelist)
    return namelist

namelist = expand_dnsname('google.com.')
for name in namelist:
    print name

Which, when I run it, lists a few 1e100.net hostnames:

how to change text in Android TextView

:) Your using the thread in a wrong way. Just do the following:

private void runthread()
{

splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    synchronized(this){

                        //wait 5 sec
                        wait(_splashTime);
                    }

                } catch(InterruptedException e) {}
                finally {
                    //call the handler to set the text
                }
            }
        };

        splashTread.start(); 
}

That's it.

Rails - passing parameters in link_to

Try this

link_to "+ Service", my_services_new_path(:account_id => acct.id)

it will pass the account_id as you want.

For more details on link_to use this http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

Add image to layout in ruby on rails

It's working for me:

<%= image_tag( root_url + "images/rss.jpg", size: "50x50", :alt => "rss feed") -%>

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

How to SUM parts of a column which have same text value in different column in the same row

This can be done by using SUMPRODUCT as well. Update the ranges as you see fit

=SUMPRODUCT(($A$2:$A$7=A2)*($B$2:$B$7=B2)*$C$2:$C$7)

A2:A7 = First name range

B2:B7 = Last Name Range

C2:C7 = Numbers Range

This will find all the names with the same first and last name and sum the numbers in your numbers column

Runnable with a parameter?

theView.post(new Runnable() {
    String str;
    @Override                            
    public void run() {
        par.Log(str);                              
    }
    public Runnable init(String pstr) {
        this.str=pstr;
        return(this);
    }
}.init(str));

Create init function that returns object itself and initialize parameters with it.

Failed to resolve: com.android.support:appcompat-v7:28.0

my problem was just network connection. using VPN solved the issue.

How to silence output in a Bash script?

If it outputs to stderr as well you'll want to silence that. You can do that by redirecting file descriptor 2:

# Send stdout to out.log, stderr to err.log
myprogram > out.log 2> err.log

# Send both stdout and stderr to out.log
myprogram &> out.log      # New bash syntax
myprogram > out.log 2>&1  # Older sh syntax

# Log output, hide errors.
myprogram > out.log 2> /dev/null

How to edit default dark theme for Visual Studio Code?

You cannot "edit" a default theme, they are "locked in"

However, you can copy it into your own custom theme, with the exact modifications you'd like.

For more info, see these articles: https://code.visualstudio.com/Docs/customization/themes https://code.visualstudio.com/docs/extensions/install-extension#_your-extensions-folder

If all you want to change is the colors for C++ code, you should look at overwriting the c++ support colorizer. For info about that, go here: https://code.visualstudio.com/docs/customization/colorizer

EDIT: The dark theme is found here: https://github.com/Microsoft/vscode/tree/80f8000c10b4234c7b027dccfd627442623902d2/extensions/theme-colorful-defaults

EDIT2: To clarify:

process.env.NODE_ENV is undefined

If you faced this probem in React, you need [email protected] and higher. Also for other environment variables than NODE_ENV to work in React, they need to be prefixed with REACT_APP_.

Find oldest/youngest datetime object in a list

Datetimes are comparable; so you can use max(datetimes_list) and min(datetimes_list)

error: Error parsing XML: not well-formed (invalid token) ...?

I had the same problem. In my case, even though I have not understood why, the problem was due to & in one of the elements like the following where a and b are two tokens/words:

<s> . . . a & b . . . </s>

and to resolve the issue I turned my element's text to the following:

<s> . . . a and b . . . </s>

I thought it might be the case for some of you. Generally, to make your life easier, just go and read the character at the index mentioned in the error message (line:..., col:...) and see what the character is.

What and where are the stack and heap?

Stack:

  • Stored in computer RAM just like the heap.
  • Variables created on the stack will go out of scope and are automatically deallocated.
  • Much faster to allocate in comparison to variables on the heap.
  • Implemented with an actual stack data structure.
  • Stores local data, return addresses, used for parameter passing.
  • Can have a stack overflow when too much of the stack is used (mostly from infinite or too deep recursion, very large allocations).
  • Data created on the stack can be used without pointers.
  • You would use the stack if you know exactly how much data you need to allocate before compile time and it is not too big.
  • Usually has a maximum size already determined when your program starts.

Heap:

  • Stored in computer RAM just like the stack.
  • In C++, variables on the heap must be destroyed manually and never fall out of scope. The data is freed with delete, delete[], or free.
  • Slower to allocate in comparison to variables on the stack.
  • Used on demand to allocate a block of data for use by the program.
  • Can have fragmentation when there are a lot of allocations and deallocations.
  • In C++ or C, data created on the heap will be pointed to by pointers and allocated with new or malloc respectively.
  • Can have allocation failures if too big of a buffer is requested to be allocated.
  • You would use the heap if you don't know exactly how much data you will need at run time or if you need to allocate a lot of data.
  • Responsible for memory leaks.

Example:

int foo()
{
  char *pBuffer; //<--nothing allocated yet (excluding the pointer itself, which is allocated here on the stack).
  bool b = true; // Allocated on the stack.
  if(b)
  {
    //Create 500 bytes on the stack
    char buffer[500];

    //Create 500 bytes on the heap
    pBuffer = new char[500];

   }//<-- buffer is deallocated here, pBuffer is not
}//<--- oops there's a memory leak, I should have called delete[] pBuffer;

Extracting the top 5 maximum values in excel

Given a data setup like this:

Top 5 by criteria

The formula in cell D2 and copied down is:

=INDEX($B$2:$B$28,MATCH(1,INDEX(($A$2:$A$28=LARGE($A$2:$A$28,ROWS(D$1:D1)))*(COUNTIF(D$1:D1,$B$2:$B$28)=0),),0))

This formula will work even if there are tied OPS scores among players.

AngularJs ReferenceError: angular is not defined

Well in the way this is a single page application, the solution used was:

load the content with AJAX, like any other controller, and then call:

angular.bootstrap($('#your_div_loaded_in_ajax'),["myApp","other_module"]);

Concatenating variables in Bash

Try doing this, there's no special character to concatenate in bash :

mystring="${arg1}12${arg2}endoffile"

explanations

If you don't put brackets, you will ask to concatenate $arg112 + $argendoffile (I guess that's not what you asked) like in the following example :

mystring="$arg112$arg2endoffile"

The brackets are delimiters for the variables when needed. When not needed, you can use it or not.

another solution

(less portable : require bash > 3.1)

$ arg1=foo
$ arg2=bar
$ mystring="$arg1"
$ mystring+="12"
$ mystring+="$arg2"
$ mystring+="endoffile"
$ echo "$mystring"
foo12barendoffile

See http://mywiki.wooledge.org/BashFAQ/013

How to install Laravel's Artisan?

You just have to read the laravel installation page:

  1. Install Composer if not already installed
  2. Open a command line and do:
composer global require "laravel/installer"

Inside your htdocs or www directory, use either:

laravel new appName

(this can lead to an error on windows computers while using latest Laravel (1.3.2)) or:

composer create-project --prefer-dist laravel/laravel appName

(this works also on windows) to create a project called "appName".

To use "php artisan xyz" you have to be inside your project root! as artisan is a file php is going to use... Simple as that ;)

Javascript String to int conversion

Convert by Number Class:-

Eg:

var n = Number("103");
console.log(n+1)

Output: 104

Note:- Number is class. When we pass string, then constructor of Number class will convert it.

How to kill/stop a long SQL query immediately?

You can use a keyboard shortcut ALT + Break to stop the query execution. However, this may not succeed in all cases.

How to print a string at a fixed width?

I found ljust() and rjust() very useful to print a string at a fixed width or fill out a Python string with spaces.

An example

print('123.00'.rjust(9))
print('123456.89'.rjust(9))

# expected output  
   123.00
123456.89

For your case, you case use fstring to print

for prefix in unique:
    if prefix != "":
        print(f"value  {prefix.ljust(3)} - num of occurrences = {string.count(str(prefix))}")

Expected Output

value  a   - num of occurrences = 1
value  ab  - num of occurrences = 1
value  abc - num of occurrences = 1
value  b   - num of occurrences = 1
value  bc  - num of occurrences = 1
value  bcd - num of occurrences = 1
value  c   - num of occurrences = 1
value  cd  - num of occurrences = 1
value  d   - num of occurrences = 1

You can change 3 to the highest length of your permutation string.

How to add to the end of lines containing a pattern with sed or awk?

This works for me

sed '/^all:/ s/$/ anotherthing/' file

The first part is a pattern to find and the second part is an ordinary sed's substitution using $ for the end of a line.

If you want to change the file during the process, use -i option

sed -i '/^all:/ s/$/ anotherthing/' file

Or you can redirect it to another file

sed '/^all:/ s/$/ anotherthing/' file > output

Android RelativeLayout programmatically Set "centerInParent"

Completely untested, but this should work:

View positiveButton = findViewById(R.id.positiveButton);
RelativeLayout.LayoutParams layoutParams = 
    (RelativeLayout.LayoutParams)positiveButton.getLayoutParams();
layoutParams.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);
positiveButton.setLayoutParams(layoutParams);

add android:configChanges="orientation|screenSize" inside your activity in your manifest

String was not recognized as a valid DateTime " format dd/MM/yyyy"

You need to call ParseExact, which parses a date that exactly matches a format that you supply.

For example:

DateTime date = DateTime.ParseExact(this.Text, "dd/MM/yyyy", CultureInfo.InvariantCulture);

The IFormatProvider parameter specifies the culture to use to parse the date.
Unless your string comes from the user, you should pass CultureInfo.InvariantCulture.
If the string does come from the user, you should pass CultureInfo.CurrentCulture, which will use the settings that the user specified in Regional Options in Control Panel.

Bash: Strip trailing linebreak from output

If you assign its output to a variable, bash automatically strips whitespace:

linecount=`wc -l < log.txt`

T-SQL Cast versus Convert

CAST is standard SQL, but CONVERT is only for the dialect T-SQL. We have a small advantage for convert in the case of datetime.

With CAST, you indicate the expression and the target type; with CONVERT, there’s a third argument representing the style for the conversion, which is supported for some conversions, like between character strings and date and time values. For example, CONVERT(DATE, '1/2/2012', 101) converts the literal character string to DATE using style 101 representing the United States standard.

How do I explicitly specify a Model's table-name mapping in Rails?

Rails >= 3.2 (including Rails 4+ and 5+):

class Countries < ActiveRecord::Base
  self.table_name = "cc"
end

Rails <= 3.1:

class Countries < ActiveRecord::Base
  self.set_table_name "cc"
  ...
end

How to delete a remote tag?

Seems like a lot of work for something xargs already does. Looking back through this thread, I'm guessing the slowness with xargs that you experienced is because the original answer used xargs -n 1 when it didn't really need to.

This is equivalent to your method one except that xargs automatically deals with the maximum command line length:

git tag | sorting_processing_etc | xargs git push --delete origin

xargs can run processes in parallel too. Method 2 with xargs:

git tag | sorting_processing_etc | xargs -P 5 -n 100 git push --delete origin

The above uses a maximum of 5 processes to handle a maximum of 100 arguments in each process. You can experiment with the arguments to find what works best for your needs.

Parse XML using JavaScript

I'm guessing from your last question, asked 20 minutes before this one, that you are trying to parse (read and convert) the XML found through using GeoNames' FindNearestAddress.

If your XML is in a string variable called txt and looks like this:

<address>
  <street>Roble Ave</street>
  <mtfcc>S1400</mtfcc>
  <streetNumber>649</streetNumber>
  <lat>37.45127</lat>
  <lng>-122.18032</lng>
  <distance>0.04</distance>
  <postalcode>94025</postalcode>
  <placename>Menlo Park</placename>
  <adminCode2>081</adminCode2>
  <adminName2>San Mateo</adminName2>
  <adminCode1>CA</adminCode1>
  <adminName1>California</adminName1>
  <countryCode>US</countryCode>
</address>

Then you can parse the XML with Javascript DOM like this:

if (window.DOMParser)
{
    parser = new DOMParser();
    xmlDoc = parser.parseFromString(txt, "text/xml");
}
else // Internet Explorer
{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = false;
    xmlDoc.loadXML(txt);
}

And get specific values from the nodes like this:

//Gets house address number
xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue;

//Gets Street name
xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue;

//Gets Postal Code
xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue;

JSFiddle


Feb. 2019 edit:

In response to @gaugeinvariante's concerns about xml with Namespace prefixes. Should you have a need to parse xml with Namespace prefixes, everything should work almost identically:

NOTE: this will only work in browsers that support xml namespace prefixes such as Microsoft Edge

_x000D_
_x000D_
// XML with namespace prefixes 's', 'sn', and 'p' in a variable called txt_x000D_
txt = `_x000D_
<address xmlns:p='example.com/postal' xmlns:s='example.com/street' xmlns:sn='example.com/streetNum'>_x000D_
  <s:street>Roble Ave</s:street>_x000D_
  <sn:streetNumber>649</sn:streetNumber>_x000D_
  <p:postalcode>94025</p:postalcode>_x000D_
</address>`;_x000D_
_x000D_
//Everything else the same_x000D_
if (window.DOMParser)_x000D_
{_x000D_
    parser = new DOMParser();_x000D_
    xmlDoc = parser.parseFromString(txt, "text/xml");_x000D_
}_x000D_
else // Internet Explorer_x000D_
{_x000D_
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");_x000D_
    xmlDoc.async = false;_x000D_
    xmlDoc.loadXML(txt);_x000D_
}_x000D_
_x000D_
//The prefix should not be included when you request the xml namespace_x000D_
//Gets "streetNumber" (note there is no prefix of "sn"_x000D_
console.log(xmlDoc.getElementsByTagName("streetNumber")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Street name_x000D_
console.log(xmlDoc.getElementsByTagName("street")[0].childNodes[0].nodeValue);_x000D_
_x000D_
//Gets Postal Code_x000D_
console.log(xmlDoc.getElementsByTagName("postalcode")[0].childNodes[0].nodeValue);
_x000D_
_x000D_
_x000D_

iOS Launching Settings -> Restrictions URL Scheme

As of iOS8 you can open the built-in Settings app with:

NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
if ([[UIApplication sharedApplication] canOpenURL:url]) {
   [[UIApplication sharedApplication] openURL:url];
}

The actual URL string is @"app-settings:". I tried appending different sections to the string ("Bluetooth", "GENERAL", etc.) but seems only linking to the main Settings screen works. Post a reply if you find out otherwise.

go to link on button click - jquery

$('.button1').click(function() {
   window.location = "www.example.com/index.php?id=" + this.id;
});

First of all using window.location is better as according to specification document.location value was read-only and might cause you headaches in older/different browsers. Check notes @MDC DOM document.location page

And for the second - using attr jQuery method to get id is a bad practice - you should use direct native DOM accessor this.id as the value assigned to this is normal DOM element.

CodeIgniter: Load controller within controller

Just to add more information to what Zain Abbas said:

Load the controller that way, and use it like he said:

$this->load->library('../controllers/instructor');

$this->instructor->functioname();

Or you can create an object and use it this way:

$this->load->library('../controllers/your_controller');

$obj = new $this->your_controller();

$obj->your_function();

Hope this can help.

Bootstrap 3 Slide in Menu / Navbar on Mobile

Without Plugin, we can do this; bootstrap multi-level responsive menu for mobile phone with slide toggle for mobile:

_x000D_
_x000D_
$('[data-toggle="slide-collapse"]').on('click', function() {_x000D_
  $navMenuCont = $($(this).data('target'));_x000D_
  $navMenuCont.animate({_x000D_
    'width': 'toggle'_x000D_
  }, 350);_x000D_
  $(".menu-overlay").fadeIn(500);_x000D_
});_x000D_
_x000D_
$(".menu-overlay").click(function(event) {_x000D_
  $(".navbar-toggle").trigger("click");_x000D_
  $(".menu-overlay").fadeOut(500);_x000D_
});_x000D_
_x000D_
// if ($(window).width() >= 767) {_x000D_
//     $('ul.nav li.dropdown').hover(function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//     }, function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//     });_x000D_
_x000D_
//     $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//     }, function() {_x000D_
//         $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//     });_x000D_
_x000D_
_x000D_
//     $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
//         event.preventDefault();_x000D_
//         event.stopPropagation();_x000D_
//         $(this).parent().siblings().removeClass('open');_x000D_
//         $(this).parent().toggleClass('open');_x000D_
//         $('b', this).toggleClass("caret caret-up");_x000D_
//     });_x000D_
// }_x000D_
_x000D_
// $(window).resize(function() {_x000D_
//     if( $(this).width() >= 767) {_x000D_
//         $('ul.nav li.dropdown').hover(function() {_x000D_
//             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
//         }, function() {_x000D_
//             $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
//         });_x000D_
//     }_x000D_
// });_x000D_
_x000D_
var windowWidth = $(window).width();_x000D_
if (windowWidth > 767) {_x000D_
  // $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
  //     event.preventDefault();_x000D_
  //     event.stopPropagation();_x000D_
  //     $(this).parent().siblings().removeClass('open');_x000D_
  //     $(this).parent().toggleClass('open');_x000D_
  //     $('b', this).toggleClass("caret caret-up");_x000D_
  // });_x000D_
_x000D_
  $('ul.nav li.dropdown').hover(function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
  }, function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
  });_x000D_
_x000D_
  $('ul.nav li.dropdown-submenu').hover(function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeIn(500);_x000D_
  }, function() {_x000D_
    $(this).find('>.dropdown-menu').stop(true, true).delay(200).fadeOut(500);_x000D_
  });_x000D_
_x000D_
_x000D_
  $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    $(this).parent().siblings().removeClass('open');_x000D_
    $(this).parent().toggleClass('open');_x000D_
    // $('b', this).toggleClass("caret caret-up");_x000D_
  });_x000D_
}_x000D_
if (windowWidth < 767) {_x000D_
  $('ul.dropdown-menu [data-toggle=dropdown]').on('click', function(event) {_x000D_
    event.preventDefault();_x000D_
    event.stopPropagation();_x000D_
    $(this).parent().siblings().removeClass('open');_x000D_
    $(this).parent().toggleClass('open');_x000D_
    // $('b', this).toggleClass("caret caret-up");_x000D_
  });_x000D_
}_x000D_
_x000D_
// $('.dropdown a').append('Some text');
_x000D_
@media only screen and (max-width: 767px) {_x000D_
  #slide-navbar-collapse {_x000D_
    position: fixed;_x000D_
    top: 0;_x000D_
    left: 15px;_x000D_
    z-index: 999999;_x000D_
    width: 280px;_x000D_
    height: 100%;_x000D_
    background-color: #f9f9f9;_x000D_
    overflow: auto;_x000D_
    bottom: 0;_x000D_
    max-height: inherit;_x000D_
  }_x000D_
  .menu-overlay {_x000D_
    display: none;_x000D_
    background-color: #000;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    opacity: 0.5;_x000D_
    filter: alpha(opacity=50);_x000D_
    /* IE7 & 8 */_x000D_
    position: fixed;_x000D_
    right: 0;_x000D_
    top: 0;_x000D_
    z-index: 49;_x000D_
  }_x000D_
  .navbar-fixed-top {_x000D_
    position: initial !important;_x000D_
  }_x000D_
  .navbar-nav .open .dropdown-menu {_x000D_
    background-color: #ffffff;_x000D_
  }_x000D_
  ul.nav.navbar-nav li {_x000D_
    border-bottom: 1px solid #eee;_x000D_
  }_x000D_
  .navbar-nav .open .dropdown-menu .dropdown-header,_x000D_
  .navbar-nav .open .dropdown-menu>li>a {_x000D_
    padding: 10px 20px 10px 15px;_x000D_
  }_x000D_
}_x000D_
_x000D_
.dropdown-submenu {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu .dropdown-menu {_x000D_
  top: 0;_x000D_
  left: 100%;_x000D_
  margin-top: -1px;_x000D_
}_x000D_
_x000D_
li.dropdown a {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 5px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 10px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
ul.dropdown-menu li {_x000D_
  border-bottom: 1px solid #eee;_x000D_
}_x000D_
_x000D_
.dropdown-menu {_x000D_
  padding: 0px;_x000D_
  margin: 0px;_x000D_
  border: none !important;_x000D_
}_x000D_
_x000D_
li.dropdown.open {_x000D_
  border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu.open {_x000D_
  border-bottom: 0px !important;_x000D_
}_x000D_
_x000D_
li.dropdown-submenu>a {_x000D_
  font-weight: bold !important;_x000D_
}_x000D_
_x000D_
li.dropdown>a {_x000D_
  font-weight: bold !important;_x000D_
}_x000D_
_x000D_
.navbar-default .navbar-nav>li>a {_x000D_
  font-weight: bold !important;_x000D_
  padding: 10px 20px 10px 15px;_x000D_
}_x000D_
_x000D_
li.dropdown>a:before {_x000D_
  content: "\f107";_x000D_
  font-family: FontAwesome;_x000D_
  position: absolute;_x000D_
  right: 6px;_x000D_
  top: 9px;_x000D_
  font-size: 15px;_x000D_
}_x000D_
_x000D_
@media (min-width: 767px) {_x000D_
  li.dropdown-submenu>a {_x000D_
    padding: 10px 20px 10px 15px;_x000D_
  }_x000D_
  li.dropdown>a:before {_x000D_
    content: "\f107";_x000D_
    font-family: FontAwesome;_x000D_
    position: absolute;_x000D_
    right: 3px;_x000D_
    top: 12px;_x000D_
    font-size: 15px;_x000D_
  }_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
  <head>_x000D_
    <title>Bootstrap Example</title>_x000D_
    <meta charset="utf-8">_x000D_
    <meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>_x000D_
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">_x000D_
_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <nav class="navbar navbar-default navbar-fixed-top">_x000D_
      <div class="container-fluid">_x000D_
        <!-- Brand and toggle get grouped for better mobile display -->_x000D_
        <div class="navbar-header">_x000D_
          <button type="button" class="navbar-toggle collapsed" data-toggle="slide-collapse" data-target="#slide-navbar-collapse" aria-expanded="false">_x000D_
                    <span class="sr-only">Toggle navigation</span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                    <span class="icon-bar"></span>_x000D_
                </button>_x000D_
          <a class="navbar-brand" href="#">Brand</a>_x000D_
        </div>_x000D_
        <!-- Collect the nav links, forms, and other content for toggling -->_x000D_
        <div class="collapse navbar-collapse" id="slide-navbar-collapse">_x000D_
          <ul class="nav navbar-nav">_x000D_
            <li><a href="#">Link <span class="sr-only">(current)</span></a></li>_x000D_
            <li><a href="#">Link</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#">Action</a></li>_x000D_
                <li><a href="#">Another action</a></li>_x000D_
                <li><a href="#">Something else here</a></li>_x000D_
                <li><a href="#">Separated link</a></li>_x000D_
                <li><a href="#">One more separated link</a></li>_x000D_
                <li class="dropdown-submenu">_x000D_
                  <a href="#" data-toggle="dropdown">SubMenu 1</span></a>_x000D_
                  <ul class="dropdown-menu">_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li><a href="#">3rd level dropdown</a></li>_x000D_
                    <li class="dropdown-submenu">_x000D_
                      <a href="#" data-toggle="dropdown">SubMenu 2</span></a>_x000D_
                      <ul class="dropdown-menu">_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                        <li><a href="#">3rd level dropdown</a></li>_x000D_
                      </ul>_x000D_
                    </li>_x000D_
                  </ul>_x000D_
                </li>_x000D_
              </ul>_x000D_
            </li>_x000D_
            <li><a href="#">Link</a></li>_x000D_
          </ul>_x000D_
          <ul class="nav navbar-nav navbar-right">_x000D_
            <li><a href="#">Link</a></li>_x000D_
            <li class="dropdown">_x000D_
              <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">Dropdown</span></a>_x000D_
              <ul class="dropdown-menu">_x000D_
                <li><a href="#">Action</a></li>_x000D_
                <li><a href="#">Another action</a></li>_x000D_
                <li><a href="#">Something else here</a></li>_x000D_
                <li><a href="#">Separated link</a></li>_x000D_
              </ul>_x000D_
            </li>_x000D_
          </ul>_x000D_
        </div>_x000D_
        <!-- /.navbar-collapse -->_x000D_
      </div>_x000D_
      <!-- /.container-fluid -->_x000D_
    </nav>_x000D_
    <div class="menu-overlay"></div>_x000D_
    <div class="col-md-12">_x000D_
      <h1>Resize the window to see the result</h1>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
      <p>_x000D_
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus non bibendum sem, et sodales massa. Proin quis velit vel nisl imperdiet rhoncus vitae id tortor. Praesent blandit tellus in enim sollicitudin rutrum. Integer ullamcorper, augue ut tristique_x000D_
        ultrices, augue magna placerat ex, ac varius mauris ante sed dui. Fusce ullamcorper vulputate magna, a malesuada nunc pellentesque sit amet. Donec posuere placerat erat, sed ornare enim aliquam vitae. Nullam pellentesque auctor augue, vel commodo_x000D_
        dolor porta ac. Sed libero eros, fringilla ac lorem in, blandit scelerisque lorem. Suspendisse iaculis justo velit, sit amet fringilla velit ornare a. Sed consectetur quam eget ipsum luctus bibendum. Ut nisi lectus, viverra vitae ipsum sit amet,_x000D_
        condimentum condimentum neque. In maximus suscipit eros ut eleifend. Donec venenatis mauris nulla, ac bibendum metus bibendum vel._x000D_
      </p>_x000D_
    </div>_x000D_
_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Reference JS fiddle

round a single column in pandas

No need to use for loop. It can be directly applied to a column of a dataframe

sleepstudy['Reaction'] = sleepstudy['Reaction'].round(1)

non static method cannot be referenced from a static context

You are calling nextInt statically by using Random.nextInt.

Instead, create a variable, Random r = new Random(); and then call r.nextInt(10).

It would be definitely worth while to check out:

Update:

You really should replace this line,

Random Random = new Random(); 

with something like this,

Random r = new Random();

If you use variable names as class names you'll run into a boat load of problems. Also as a Java convention, use lowercase names for variables. That might help avoid some confusion.

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

API vs Web Service

Just pasted the summary of the linked article:

Summary:

  1. All Web services are APIs but all APIs are not Web services.

  2. Web services might not perform all the operations that an API would perform.

  3. A Web service uses only three styles of use: SOAP, REST and XML-RPC for communication whereas API may use any style for communication.

  4. A Web service always needs a network for its operation whereas an API doesn’t need a network for its operation.

  5. An API facilitates interfacing directly with an application whereas a Web service is a ...

Read more: Difference Between API and Web Service | Difference Between | API vs Web Service http://www.differencebetween.net/technology/internet/difference-between-api-and-web-service/#ixzz3e3WxplAv

See the above link for the complete answer.

MySQL Error 1215: Cannot add foreign key constraint

Wooo I just got it ! It was a mix of a lot of already posted answers (innoDB, unsigned, etc). One thing I didn't see here though is : if your FK is pointing on a PK, ensure the source column has a value that makes sense. For example, if the PK is a mediumint(8), make sure the source column also contains a mediumint(8). That was part of the problem for me.

Eclipse Build Path Nesting Errors

Make two folders: final/src/ to store the source java code, and final/WebRoot/.

You cannot put the source and the webroot together. I think you may misunderstand your teacher.

How to Automatically Close Alerts using Twitter Bootstrap

Calling window.setTimeout(function, delay) will allow you to accomplish this. Here's an example that will automatically close the alert 2 seconds (or 2000 milliseconds) after it is displayed.

$(".alert-message").alert();
window.setTimeout(function() { $(".alert-message").alert('close'); }, 2000);

If you want to wrap it in a nifty function you could do this.

function createAutoClosingAlert(selector, delay) {
   var alert = $(selector).alert();
   window.setTimeout(function() { alert.alert('close') }, delay);
}

Then you could use it like so...

createAutoClosingAlert(".alert-message", 2000);

I am certain there are more elegant ways to accomplish this.

Pagination using MySQL LIMIT, OFFSET

First off, don't have a separate server script for each page, that is just madness. Most applications implement pagination via use of a pagination parameter in the URL. Something like:

http://yoursite.com/itempage.php?page=2

You can access the requested page number via $_GET['page'].

This makes your SQL formulation really easy:

// determine page number from $_GET
$page = 1;
if(!empty($_GET['page'])) {
    $page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
    if(false === $page) {
        $page = 1;
    }
}

// set the number of items to display per page
$items_per_page = 4;

// build query
$offset = ($page - 1) * $items_per_page;
$sql = "SELECT * FROM menuitem LIMIT " . $offset . "," . $items_per_page;

So for example if input here was page=2, with 4 rows per page, your query would be"

SELECT * FROM menuitem LIMIT 4,4

So that is the basic problem of pagination. Now, you have the added requirement that you want to understand the total number of pages (so that you can determine if "NEXT PAGE" should be shown or if you wanted to allow direct access to page X via a link).

In order to do this, you must understand the number of rows in the table.

You can simply do this with a DB call before trying to return your actual limited record set (I say BEFORE since you obviously want to validate that the requested page exists).

This is actually quite simple:

$sql = "SELECT your_primary_key_field FROM menuitem";
$result = mysqli_query($con, $sql);
if(false === $result) {
   throw new Exception('Query failed with: ' . mysqli_error());
} else {
   $row_count = mysqli_num_rows($result);
   // free the result set as you don't need it anymore
   mysqli_free_result($result);
}

$page_count = 0;
if (0 === $row_count) {  
    // maybe show some error since there is nothing in your table
} else {
   // determine page_count
   $page_count = (int)ceil($row_count / $items_per_page);
   // double check that request page is in range
   if($page > $page_count) {
        // error to user, maybe set page to 1
        $page = 1;
   }
}

// make your LIMIT query here as shown above


// later when outputting page, you can simply work with $page and $page_count to output links
// for example
for ($i = 1; $i <= $page_count; $i++) {
   if ($i === $page) { // this is current page
       echo 'Page ' . $i . '<br>';
   } else { // show link to other page   
       echo '<a href="/menuitem.php?page=' . $i . '">Page ' . $i . '</a><br>';
   }
}

Declaring multiple variables in JavaScript

var variable1 = "Hello, World!";
var variable2 = "Testing...";
var variable3 = 42;

is more readable than:

var variable1 = "Hello, World!",
    variable2 = "Testing...",
    variable3 = 42;

But they do the same thing.

Failed to serialize the response in Web API with Json

In my case I have had similar error message:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.

But when I dig deeper in it, the issue was:

Type 'name.SomeSubRootType' with data contract name 'SomeSubRootType://schemas.datacontract.org/2004/07/WhatEverService' is not expected. Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer.

The way I solved by adding KnownType.

[KnownType(typeof(SomeSubRootType))]
public partial class SomeRootStructureType

This was solved inspired from this answer.

Reference: https://msdn.microsoft.com/en-us/library/ms730167(v=vs.100).aspx

How do you get the current text contents of a QComboBox?

PyQt4 can be forced to use a new API in which QString is automatically converted to and from a Python object:

import sip
sip.setapi('QString', 2)

With this API, QtCore.QString class is no longer available and self.ui.comboBox.currentText() will return a Python string or unicode object.

See Selecting Incompatible APIs from the doc.

When to use throws in a Java method declaration?

The code you posted is wrong, it should throw an Exception if is catching a specific exception in order to handler IOException but throwing not catched exceptions.

Something like:

public void method() throws Exception{
   try{
           BufferedReader br = new BufferedReader(new FileReader("file.txt"));
   }catch(IOException e){
           System.out.println(e.getMessage());
   }
}

or

public void method(){
   try{
           BufferedReader br = new BufferedReader(new FileReader("file.txt"));
   }catch(IOException e){
           System.out.println("Catching IOException");
           System.out.println(e.getMessage());
   }catch(Exception e){
           System.out.println("Catching any other Exceptions like NullPontException, FileNotFoundExceptioon, etc.");
           System.out.println(e.getMessage());
   }

}

IndexError: tuple index out of range ----- Python

A tuple consists of a number of values separated by commas. like

>>> t = 12345, 54321, 'hello!'
>>> t[0]
12345

tuple are index based (and also immutable) in Python.

Here in this case x = rows[1][1] + " " + rows[1][2] have only two index 0, 1 available but you are trying to access the 3rd index.

Web.Config Debug/Release

If your are going to replace all of the connection strings with news ones for production environment, you can simply replace all connection strings with production ones using this syntax:

<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">

<connectionStrings xdt:Transform="Replace">
    <!-- production environment config --->
    <add name="ApplicationServices" connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\aspnetdb.mdf;User Instance=true"
      providerName="System.Data.SqlClient" />
    <add name="Testing1" connectionString="Data Source=test;Initial Catalog=TestDatabase;Integrated Security=True"
      providerName="System.Data.SqlClient" />
</connectionStrings>
....

Information for this answer are brought from this answer and this blog post.

notice: As others explained already, this setting will apply only when application publishes not when running/debugging it (by hitting F5).

ImportError: No module named 'Queue'

import queue is lowercase q in Python 3.

Change Q to q and it will be fine.

(See code in https://stackoverflow.com/a/29688081/632951 for smart switching.)

How to restore the permissions of files and directories within git if they have been modified?

i know this is old, but i came from google and i didn't find an answer

i have a simple solution if you have no change you want to keep :

git config core.fileMode true
git reset --hard HEAD

Daemon not running. Starting it now on port 5037

This worked for me: Open task manager (of your OS) and kill adb.exe process. Now start adb again, now adb should start normally.

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'demoRestController'

To me it happened in DogController that autowired DogService that autowired DogRepository. Dog class used to have field name but I changed it to coolName, but didn't change methods in DogRepository: Dog findDogByName(String name). I change that method to Dog findDogByCoolName(String name) and now it works.

Using Pip to install packages to Anaconda Environment

If you didn't add pip when creating conda environment

conda create -n env_name pip

and also didn't install pip inside the environment

source activate env_name
conda install pip

then the only pip you got is the system pip, which will install packages globally.

Bus as you can see in this issue, even if you did either of the procedure mentioned above, the behavior of pip inside conda environment is still kind of undefined.

To ensure using the pip installed inside conda environment without having to type the lengthy /home/username/anaconda/envs/env_name/bin/pip, I wrote a shell function:

# Using pip to install packages inside conda environments.
cpip() {
    ERROR_MSG="Not in a conda environment."
    ERROR_MSG="$ERROR_MSG\nUse \`source activate ENV\`"
    ERROR_MSG="$ERROR_MSG to enter a conda environment."

    [ -z "$CONDA_DEFAULT_ENV" ] && echo "$ERROR_MSG" && return 1

    ERROR_MSG='Pip not installed in current conda environment.'
    ERROR_MSG="$ERROR_MSG\nUse \`conda install pip\`"
    ERROR_MSG="$ERROR_MSG to install pip in current conda environment."

    [ -e "$CONDA_PREFIX/bin/pip" ] || (echo "$ERROR_MSG" && return 2)

    PIP="$CONDA_PREFIX/bin/pip"
    "$PIP" "$@"
}

Hope this is helpful to you.

What is the equivalent of ngShow and ngHide in Angular 2+?

<div [hidden]="flagValue">
---content---
</div>

How do I split a string on a delimiter in Bash?

In Bash, a bullet proof way, that will work even if your variable contains newlines:

IFS=';' read -d '' -ra array < <(printf '%s;\0' "$in")

Look:

$ in=$'one;two three;*;there is\na newline\nin this field'
$ IFS=';' read -d '' -ra array < <(printf '%s;\0' "$in")
$ declare -p array
declare -a array='([0]="one" [1]="two three" [2]="*" [3]="there is
a newline
in this field")'

The trick for this to work is to use the -d option of read (delimiter) with an empty delimiter, so that read is forced to read everything it's fed. And we feed read with exactly the content of the variable in, with no trailing newline thanks to printf. Note that's we're also putting the delimiter in printf to ensure that the string passed to read has a trailing delimiter. Without it, read would trim potential trailing empty fields:

$ in='one;two;three;'    # there's an empty field
$ IFS=';' read -d '' -ra array < <(printf '%s;\0' "$in")
$ declare -p array
declare -a array='([0]="one" [1]="two" [2]="three" [3]="")'

the trailing empty field is preserved.


Update for Bash=4.4

Since Bash 4.4, the builtin mapfile (aka readarray) supports the -d option to specify a delimiter. Hence another canonical way is:

mapfile -d ';' -t array < <(printf '%s;' "$in")

HTML: Changing colors of specific words in a string of text

<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">
    Enter the competition by <span style="color:#FF0000">January 30, 2011</span> and you could win up to $$$$ — including amazing <span style="color:#0000A0">summer</span> trips!
</p>

The span elements are inline an thus don't break the flow of the paragraph, only style in between the tags.

How to get current html page title with javascript

One option from DOM directly:

$(document).find("title").text();

Tested only on chrome & IE9, but logically should work on all browsers.

Or more generic

var title = document.getElementsByTagName("title")[0].innerHTML;

How do you install Google frameworks (Play, Accounts, etc.) on a Genymotion virtual device?

Now there is official FAQ for using Google Play in How do I install Google Play Services?, here the FAQ text:

For intellectual property reasons, Google Play Services are not included by default in Genymotion virtual devices. However, if you really need them, you can use the packages provided by OpenGapps. Simply follow these steps:

  1. Visit opengapps.org
  2. Select x86 as platform
  3. Choose the Android version corresponding to your virtual device
  4. Select nano as variant
  5. Download the zip file
  6. Drag & Drop the zip installer in new Genymotion virtual device (2.7.2 and above only)
  7. Follow the pop-up instructions

Please note Genymobile Inc. and Genymotion assume no liability whatsoever resulting from the download, install and use of Google Play Services within your virtual devices. You are solely responsible for the use and assume all liability related thereto. Moreover, we disclaim any warranties of any kind for a particular purpose regarding the compatibility of the OpenGapps packages with any version of Genymotion.

How to disable SSL certificate checking with Spring RestTemplate?

Iknow It is too old to answer, but I couldn't find solution like this.

The code that worked for me with the jersey client:

import org.glassfish.jersey.client.ClientConfig;
import org.glassfish.jersey.client.ClientProperties;

import javax.net.ssl.*;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.Form;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;

public class Testi {

static {
    disableSslVerification();
}
private static void disableSslVerification() {
    // Create all-trusting host name verifier
    HostnameVerifier allHostsValid = new HostnameVerifier() {
        public boolean verify(String hostname, SSLSession session) {
            return true;
        }
    };
    // Install the all-trusting host verifier
    HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);
}

public Testi() {
    MultivaluedHashMap<String, Object> headers = new MultivaluedHashMap<>();
    //... initialize headers

    Form form = new Form();
    Entity<Form> entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
    // initialize entity ...

    WebTarget target = getWebTarget();
    Object responseResult = target.path("api/test/path...").request()
            .headers(headers).post(entity, Object.class);

}

public static void main(String args[]) {
    new Testi();
}

private WebTarget getWebTarget() {
    ClientConfig clientConfig = new ClientConfig();
    clientConfig.property(ClientProperties.CONNECT_TIMEOUT, 30000);
    clientConfig.property(ClientProperties.READ_TIMEOUT, 30000);

    SSLContext sc = getSSLContext();
    Client client = ClientBuilder.newBuilder().sslContext(sc).withConfig(clientConfig).build();
    WebTarget target = client.target("...url...");
    return target;
}

private SSLContext getSSLContext() {
    try {
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
            @Override
            public void checkClientTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }
        }
        };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        return sc;
    } catch (NoSuchAlgorithmException | KeyManagementException e) {
        e.printStackTrace();
    }
    return null;
}
}

Java "lambda expressions not supported at this language level"

Actually, Eclipse support for Java 8 is available: see here and here.

  • For Kepler, it is available as a "feature patch" against SR2 (i.e. Eclipse 4.3.2)
  • For Luna (Eclipse 4.4) it will be in the standard release. (release schedule)

What method in the String class returns only the first N characters?

string.Substring(0,n); // 0 - start index and n - number of characters

How to solve time out in phpmyadmin?

To increase the phpMyAdmin Session Timeout, open config.inc.php in the root phpMyAdmin directory and add this setting (anywhere).

$cfg['LoginCookieValidity'] = <your_new_timeout>;

Where is some number larger than 1800.

Note:

Always keep on mind that a short cookie lifetime is all well and good for the development server. So do not do this on your production server.

Reference

Difference between an API and SDK

Application Programming Interface is a set of routines/data structures/classes which specifies a way to interact with the target platform/software like OS X, Android, project management application, virtualization software etc.

While Software Development Kit is a wrapper around API/s that makes the job easy for developers.

For example, Android SDK facilitates developers to interact with the Android platform as a whole while the platform itself is built by composite software components communicating via APIs.

Also, sometimes SDKs are built to facilitate development in a specific programming language. For example, Selenium web driver (built in Java) provides APIs to drive any browser natively, while capybara can be considered an an SDK that facilitates Ruby developers to use Selenium web driver. However, Selenium web driver is also an SDK by itself as it combines interaction with various native browser drivers into one package.

Difference between $.ajax() and $.get() and $.load()

Very basic but

  • $.load(): Load a piece of html into a container DOM.
  • $.get(): Use this if you want to make a GET call and play extensively with the response.
  • $.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
  • $.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the fly.

How to do parallel programming in Python?

CPython uses the Global Interpreter Lock which makes parallel programing a bit more interesting than C++

This topic has several useful examples and descriptions of the challenge:

Python Global Interpreter Lock (GIL) workaround on multi-core systems using taskset on Linux?

How to truncate milliseconds off of a .NET DateTime

2 Extension methods for the solutions mentioned above

    public static bool LiesAfterIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
    {
        DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
        compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);

        return thisDate > compareDate;
    }


    public static bool LiesAfterOrEqualsIgnoringMilliseconds(this DateTime theDate, DateTime compareDate, DateTimeKind kind)
    {
        DateTime thisDate = new DateTime(theDate.Year, theDate.Month, theDate.Day, theDate.Hour, theDate.Minute, theDate.Second, kind);
        compareDate = new DateTime(compareDate.Year, compareDate.Month, compareDate.Day, compareDate.Hour, compareDate.Minute, compareDate.Second, kind);

        return thisDate >= compareDate;
    }

usage:

bool liesAfter = myObject.DateProperty.LiesAfterOrEqualsIgnoringMilliseconds(startDateTime, DateTimeKind.Utc);

How to choose multiple files using File Upload Control?

step 1: add

<asp:FileUpload runat="server" id="fileUpload1" Multiple="Multiple">
    </asp:FileUpload>

step 2: add

Protected Sub uploadBtn_Click(sender As Object, e As System.EventArgs) Handles uploadBtn.Click
    Dim ImageFiles As HttpFileCollection = Request.Files
    For i As Integer = 0 To ImageFiles.Count - 1
        Dim file As HttpPostedFile = ImageFiles(i)
        file.SaveAs(Server.MapPath("Uploads/") & ImageFiles(i).FileName)
    Next

End Sub

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

import-module Microsoft.Exchange.Management.PowerShell.E2010aTry with some implementation like:

$exchangeser = "MTLServer01"
$session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionURI http://${exchangeserver}/powershell/ -Authentication kerberos
import-PSSession $session 

or

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

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

You can use these queries:

select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;

Each of these tables have a grantee column, you can filter on that in the where criteria:

where grantee = 'A'

To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs, it also has a table_schema column.

If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs, user_sys_privs, user_role_privs. They can be queried by a normal non-dba user.

How to run a program in Atom Editor?

For C/C++ programs there's very good package gpp-compiler.

Shortcuts:

  • To compile and run: F5
  • To debug: F6

How to use Apple's new San Francisco font on a webpage

Basically, this is what worked for me:

-apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif 

P.S. This works on all systems.

How does the bitwise complement operator (~ tilde) work?

~ flips the bits in the value.

Why ~2 is -3 has to do with how numbers are represented bitwise. Numbers are represented as two's complement.

So, 2 is the binary value

00000010

And ~2 flips the bits so the value is now:

11111101

Which, is the binary representation of -3.

What is the difference between encode/decode?

anUnicode.encode('encoding') results in a string object and can be called on a unicode object

aString.decode('encoding') results in an unicode object and can be called on a string, encoded in given encoding.


Some more explanations:

You can create some unicode object, which doesn't have any encoding set. The way it is stored by Python in memory is none of your concern. You can search it, split it and call any string manipulating function you like.

But there comes a time, when you'd like to print your unicode object to console or into some text file. So you have to encode it (for example - in UTF-8), you call encode('utf-8') and you get a string with '\u<someNumber>' inside, which is perfectly printable.

Then, again - you'd like to do the opposite - read string encoded in UTF-8 and treat it as an Unicode, so the \u360 would be one character, not 5. Then you decode a string (with selected encoding) and get brand new object of the unicode type.

Just as a side note - you can select some pervert encoding, like 'zip', 'base64', 'rot' and some of them will convert from string to string, but I believe the most common case is one that involves UTF-8/UTF-16 and string.

ORACLE and TRIGGERS (inserted, updated, deleted)

From Using Triggers:

Detecting the DML Operation That Fired a Trigger

If more than one type of DML operation can fire a trigger (for example, ON INSERT OR DELETE OR UPDATE OF Emp_tab), the trigger body can use the conditional predicates INSERTING, DELETING, and UPDATING to check which type of statement fire the trigger.

So

IF DELETING THEN ... END IF;

should work for your case.

How to initialize a variable of date type in java?

tl;dr

Use Instant, replacement for java.util.Date.

Instant.now()  // Capture current moment as seen in UTC.

If you must have a Date, convert.

java.util.Date.from( Instant.now() ) 

java.time

The java.util.Date & .Calendar classes have been supplanted by the java.time framework built into Java 8 and later. The new classes are a tremendous improvement, inspired by the successful Joda-Time library.

The java.time classes tend to use static factory methods rather than constructors for instantiating objects.

To get the current moment in UTC time zone:

Instant instant = Instant.now();

To get the current moment in a particular time zone:

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );

If you must have a java.util.Date for use with other classes not yet updated for the java.time types, convert from Instant.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

Table of date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to change node.js's console font color?

There are multiple packages available for formatting console text in Node.js. The most popular are:

Usage:

CHALK:

const chalk = require('chalk');
console.log(chalk.red('Text in red'));

COLORS:

const colors = require('colors');
console.log('Text in red'.red);

CLI-COLOR:

const clc = require('cli-color');
console.log(clc.red('Text in red'));

Many people have noted their disapproval of colors altering the String prototype. If you prefer your prototypes to be left alone, use the following code instead:

const colors = require('colors/safe');
console.log(colors.red('Text in red'));

Execute multiple command lines with the same process using .NET

const string strCmdText = "/C command1&command2";
Process.Start("CMD.exe", strCmdText);

Java method: Finding object in array list given a known attribute value

If you have to get an attribute that is not the ID. I would use CollectionUtils.

Dog someDog = new Dog();
Dog dog = CollectionUtils(dogList, new Predicate() {

@Override
public boolean evaluate(Object o)
{
    Dog d = (Dog)o;
    return someDog.getName().equals(d.getName());
}
});

When to use Common Table Expression (CTE)

One of the scenarios I found useful to use CTE is when you want to get DISTINCT rows of data based on one or more columns but return all columns in the table. With a standard query you might first have to dump the distinct values into a temp table and then try to join them back to the original table to retrieve the rest of the columns or you might write an extremely complex partition query that can return the results in one run but in most likelihood, it will be unreadable and cause performance issue.

But by using CTE (as answered by Tim Schmelter on Select the first instance of a record)

WITH CTE AS(
    SELECT myTable.*
    , RN = ROW_NUMBER()OVER(PARTITION BY patientID ORDER BY ID)
    FROM myTable 
)
SELECT * FROM CTE
WHERE RN = 1

As you can see, this is much easier to read and maintain. And in comparison to other queries, is much better at performance.

How can I run a PHP script in the background after a form is submitted?

In my case I have 3 params, one of them is string (mensaje):

exec("C:\wamp\bin\php\php5.5.12\php.exe C:/test/N/trunk/api/v1/Process.php $idTest2 $idTest3 \"$mensaje\" >> c:/log.log &");

In my Process.php I have this code:

if (!isset($argv[1]) || !isset($argv[2]) || !isset($argv[3]))
{   
    die("Error.");
} 

$idCurso = $argv[1];
$idDestino = $argv[2];
$mensaje = $argv[3];

c++ array - expression must have a constant value

No it doesn't need to be constant, the reason why his code above is wrong is because he needs to include a variable name before the declaration.

int row = 8;
int col= 8;
int x[row][col];

In Xcode that will compile and run without any issues, in M$ C++ compiler in .NET it won't compile, it will complain that you cannot use a non const literal to initialize array, the size needs to be known at compile time

Run a Command Prompt command from Desktop Shortcut

  1. Create new text file on desktop;

  2. Enter desired commands in text file;

  3. Rename extension of text file from ".txt" --> ".bat"

python selenium click on button

try this:

download firefox, add the plugin "firebug" and "firepath"; after install them go to your webpage, start firebug and find the xpath of the element, it unique in the page so you can't make any mistake.

See picture: instruction

browser.find_element_by_xpath('just copy and paste the Xpath').click()

Unique constraint violation during insert: why? (Oracle)

Presumably, since you're not providing a value for the DB_ID column, that value is being populated by a row-level before insert trigger defined on the table. That trigger, presumably, is selecting the value from a sequence.

Since the data was moved (presumably recently) from the production database, my wager would be that when the data was copied, the sequence was not modified as well. I would guess that the sequence is generating values that are much lower than the largest DB_ID that is currently in the table leading to the error.

You could confirm this suspicion by looking at the trigger to determine which sequence is being used and doing a

SELECT <<sequence name>>.nextval
  FROM dual

and comparing that to

SELECT MAX(db_id)
  FROM cmdb_db

If, as I suspect, the sequence is generating values that already exist in the database, you could increment the sequence until it was generating unused values or you could alter it to set the INCREMENT to something very large, get the nextval once, and set the INCREMENT back to 1.