Programs & Examples On #Ironpython studio

IronPython Studio is a free full IDE (Integrated Development Environment) for the Python programming language.

Create a hexadecimal colour based on a string with JavaScript

I have opened a pull request to Please.js that allows generating a color from a hash.

You can map the string to a color like so:

const color = Please.make_color({
    from_hash: "any string goes here"
});

For example, "any string goes here" will return as "#47291b"
and "another!" returns as "#1f0c3d"

Graphical DIFF programs for linux

xxdiff is lightweight if that's what you're after.

Turn off iPhone/Safari input element rounding

If you use normalize.css, that stylesheet will do something like input[type="search"] { -webkit-appearance: textfield; }.

This has a higher specificity than a single class selector like .foo, so be aware that you then can't do just .my-field { -webkit-appearance: none; }. If you have no better way to achieve the right specificity, this will help:

.my-field { -webkit-appearance: none !important; }

Tooltip on image

I am set Tooltips On My Working Project That Is 100% Working

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<style>_x000D_
.tooltip {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  border-bottom: 1px dotted black;_x000D_
}_x000D_
_x000D_
.tooltip .tooltiptext {_x000D_
  visibility: hidden;_x000D_
  width: 120px;_x000D_
  background-color: black;_x000D_
  color: #fff;_x000D_
  text-align: center;_x000D_
  border-radius: 6px;_x000D_
  padding: 5px 0;_x000D_
_x000D_
  /* Position the tooltip */_x000D_
  position: absolute;_x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
  visibility: visible;_x000D_
}_x000D_
.size_of_img{_x000D_
width:90px}_x000D_
</style>_x000D_
_x000D_
<body style="text-align:center;">_x000D_
_x000D_
<p>Move the mouse over the text below:</p>_x000D_
_x000D_
<div class="tooltip"><img class="size_of_img" src="https://babeltechreviews.com/wp-content/uploads/2018/07/rendition1.img_.jpg" alt="Image 1" /><span class="tooltiptext">grewon.pdf</span></div>_x000D_
_x000D_
<p>Note that the position of the tooltip text isn't very good. Check More Position <a href="https://www.w3schools.com/css/css_tooltip.asp">GO</a></p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Using AJAX to pass variable to PHP and retrieve those using AJAX again

you have to pass values with the single quotes

$(document).ready(function() {    
    $("#raaagh").click(function(){    
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: '145'}), //variables should be pass like this
            success: function(data){
                console.log(data);
                           }
        });  
        $.ajax({
    url:'ajax.php',
    data:"",
    dataType:'json',
    success:function(data1){
            var y1=data1;
            console.log(data1);
            }
        });

    });
});

try it it may work.......

Is it possible only to declare a variable without assigning any value in Python?

I'm not sure what you're trying to do. Python is a very dynamic language; you don't usually need to declare variables until you're actually going to assign to or use them. I think what you want to do is just

foo = None

which will assign the value None to the variable foo.

EDIT: What you really seem to want to do is just this:

#note how I don't do *anything* with value here
#we can just start using it right inside the loop

for index in sequence:
   if conditionMet:
       value = index
       break

try:
    doSomething(value)
except NameError:
    print "Didn't find anything"

It's a little difficult to tell if that's really the right style to use from such a short code example, but it is a more "Pythonic" way to work.

EDIT: below is comment by JFS (posted here to show the code)

Unrelated to the OP's question but the above code can be rewritten as:

for item in sequence:
    if some_condition(item): 
       found = True
       break
else: # no break or len(sequence) == 0
    found = False

if found:
   do_something(item)

NOTE: if some_condition() raises an exception then found is unbound.
NOTE: if len(sequence) == 0 then item is unbound.

The above code is not advisable. Its purpose is to illustrate how local variables work, namely whether "variable" is "defined" could be determined only at runtime in this case. Preferable way:

for item in sequence:
    if some_condition(item):
       do_something(item)
       break

Or

found = False
for item in sequence:
    if some_condition(item):
       found = True
       break

if found:
   do_something(item)

How to hide columns in HTML table?

_x000D_
_x000D_
<style>_x000D_
.hideFullColumn tr > .hidecol_x000D_
{_x000D_
    display:none;_x000D_
}_x000D_
</style>
_x000D_
_x000D_
_x000D_

use .hideFullColumn in table and .hidecol in th.You don't need to add class in td individually as it will be problem because index may not be in mind of each td.

Total Number of Row Resultset getRow Method

The getRow() method will always yield 0 after a query:

ResultSet.getRow()

Retrieves the current row number.

Second, you output totalrec but never assign anything to it.

How to restore to a different database in sql server?

SQL Server 2008 R2:

For an existing database that you wish to "restore: from a backup of a different database follow these steps:

  1. From the toolbar, click the Activity Monitor button.
  2. Click processes. Filter by the database you want to restore. Kill all running processes by right clicking on each process and selecting "kill process".
  3. Right click on the database you wish to restore, and select Tasks-->Restore-->From Database.
  4. Select the "From Device:" radio button.
  5. Select ... and choose the backup file of the other database you wish to restore from.
  6. Select the backup set you wish to restore from by selecting the check box to the left of the backup set.
  7. Select "Options".
  8. Select Overwrite the existing database (WITH REPLACE)
  9. Important: Change the "Restore As" Rows Data file name to the file name of the existing database you wish to overwrite or just give it a new name.
  10. Do the same with the log file file name.
  11. Verify from the Activity Monitor Screen that no new processes were spawned. If they were, kill them.
  12. Click OK.

Showing all errors and warnings

PHP errors can be displayed by any of below methods:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

For more details:

Displaying PHP errors

Sending private messages to user

To send a message to a user you first need a User instance representing the user you want to send the message to.


Obtaining a User instance

  • You can obtain a User instance from a message the user sent by doing message.autor
  • You can obtain a User instance from a user id with client.fetchUser

Once you got a user instance you can send the message with .send

Examples

client.on('message', (msg) => {
 if (!msg.author.bot) msg.author.send('ok ' + msg.author.id);
});
client.fetchUser('487904509670337509', false).then((user) => {
 user.send('heloo');
});

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

I’m going to hold the unpopular on SO selenium tag opinion that XPath is preferable to CSS in the longer run.

This long post has two sections - first I'll put a back-of-the-napkin proof the performance difference between the two is 0.1-0.3 milliseconds (yes; that's 100 microseconds), and then I'll share my opinion why XPath is more powerful.


Performance difference

Let's first tackle "the elephant in the room" – that xpath is slower than css.

With the current cpu power (read: anything x86 produced since 2013), even on browserstack/saucelabs/aws VMs, and the development of the browsers (read: all the popular ones in the last 5 years) that is hardly the case. The browser's engines have developed, the support of xpath is uniform, IE is out of the picture (hopefully for most of us). This comparison in the other answer is being cited all over the place, but it is very contextual – how many are running – or care about – automation against IE8?

If there is a difference, it is in a fraction of a millisecond.

Yet, most higher-level frameworks add at least 1ms of overhead over the raw selenium call anyways (wrappers, handlers, state storing etc); my personal weapon of choice – RobotFramework – adds at least 2ms, which I am more than happy to sacrifice for what it provides. A network roundtrip from an AWS us-east-1 to BrowserStack's hub is usually 11 milliseconds.

So with remote browsers if there is a difference between xpath and css, it is overshadowed by everything else, in orders of magnitude.


The measurements

There are not that many public comparisons (I've really seen only the cited one), so – here's a rough single-case, dummy and simple one.
It will locate an element by the two strategies X times, and compare the average time for that.

The target – BrowserStack's landing page, and its "Sign Up" button; a screenshot of the html as writing this post:

enter image description here

Here's the test code (python):

from selenium import webdriver
import timeit


if __name__ == '__main__':

    xpath_locator = '//div[@class="button-section col-xs-12 row"]'
    css_locator = 'div.button-section.col-xs-12.row'

    repetitions = 1000

    driver = webdriver.Chrome()
    driver.get('https://www.browserstack.com/')

    css_time = timeit.timeit("driver.find_element_by_css_selector(css_locator)", 
                             number=repetitions, globals=globals())
    xpath_time = timeit.timeit('driver.find_element_by_xpath(xpath_locator)', 
                             number=repetitions, globals=globals())

    driver.quit()

    print("css total time {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, css_time, (css_time/repetitions)*1000))
    print("xpath total time for {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, xpath_time, (xpath_time/repetitions)*1000))

For those not familiar with Python – it opens the page, and finds the element – first with the css locator, then with the xpath; the find operation is repeated 1,000 times. The output is the total time in seconds for the 1,000 repetitions, and average time for one find in milliseconds.

The locators are:

  • for xpath – "a div element having this exact class value, somewhere in the DOM";
  • the css is similar – "a div element with this class, somewhere in the DOM".

Deliberately chosen not to be over-tuned; also, the class selector is cited for the css as "the second fastest after an id".

The environment – Chrome v66.0.3359.139, chromedriver v2.38, cpu: ULV Core M-5Y10 usually running at 1.5GHz (yes, a "word-processing" one, not even a regular i7 beast).

Here's the output:

css total time 1000 repeats: 8.84s, per find: 8.84ms

xpath total time for 1000 repeats: 8.52s, per find: 8.52ms

Obviously the per find timings are pretty close; the difference is 0.32 milliseconds. Don't jump "the xpath is faster" – sometimes it is, sometimes it's css.


Let's try with another set of locators, a tiny-bit more complicated – an attribute having a substring (common approach at least for me, going after an element's class when a part of it bears functional meaning):

xpath_locator = '//div[contains(@class, "button-section")]'
css_locator = 'div[class~=button-section]'

The two locators are again semantically the same – "find a div element having in its class attribute this substring".
Here are the results:

css total time 1000 repeats: 8.60s, per find: 8.60ms

xpath total time for 1000 repeats: 8.75s, per find: 8.75ms

Diff of 0.15ms.


As an exercise - the same test as done in the linked blog in the comments/other answer - the test page is public, and so is the testing code.

They are doing a couple of things in the code - clicking on a column to sort by it, then getting the values, and checking the UI sort is correct.
I'll cut it - just get the locators, after all - this is the root test, right?

The same code as above, with these changes in:

  • The url is now http://the-internet.herokuapp.com/tables; there are 2 tests.

  • The locators for the first one - "Finding Elements By ID and Class" - are:

css_locator = '#table2 tbody .dues'
xpath_locator = "//table[@id='table2']//tr/td[contains(@class,'dues')]"

And here is the outcome:

css total time 1000 repeats: 8.24s, per find: 8.24ms

xpath total time for 1000 repeats: 8.45s, per find: 8.45ms

Diff of 0.2 milliseconds.

The "Finding Elements By Traversing":

css_locator = '#table1 tbody tr td:nth-of-type(4)'
xpath_locator = "//table[@id='table1']//tr/td[4]"

The result:

css total time 1000 repeats: 9.29s, per find: 9.29ms

xpath total time for 1000 repeats: 8.79s, per find: 8.79ms

This time it is 0.5 ms (in reverse, xpath turned out "faster" here).

So 5 years later (better browsers engines) and focusing only on the locators performance (no actions like sorting in the UI, etc), the same testbed - there is practically no difference between CSS and XPath.


So, out of xpath and css, which of the two to choose for performance? The answer is simple – choose locating by id.

Long story short, if the id of an element is unique (as it's supposed to be according to the specs), its value plays an important role in the browser's internal representation of the DOM, and thus is usually the fastest.

Yet, unique and constant (e.g. not auto-generated) ids are not always available, which brings us to "why XPath if there's CSS?"


The XPath advantage

With the performance out of the picture, why do I think xpath is better? Simple – versatility, and power.

Xpath is a language developed for working with XML documents; as such, it allows for much more powerful constructs than css.
For example, navigation in every direction in the tree – find an element, then go to its grandparent and search for a child of it having certain properties.
It allows embedded boolean conditions – cond1 and not(cond2 or not(cond3 and cond4)); embedded selectors – "find a div having these children with these attributes, and then navigate according to it".
XPath allows searching based on a node's value (its text) – however frowned upon this practice is, it does come in handy especially in badly structured documents (no definite attributes to step on, like dynamic ids and classes - locate the element by its text content).

The stepping in css is definitely easier – one can start writing selectors in a matter of minutes; but after a couple of days of usage, the power and possibilities xpath has quickly overcomes css.
And purely subjective – a complex css is much harder to read than a complex xpath expression.

Outro ;)

Finally, again very subjective - which one to chose?

IMO, there is no right or wrong choice - they are different solutions to the same problem, and whatever is more suitable for the job should be picked.

Being "a fan" of XPath I'm not shy to use in my projects a mix of both - heck, sometimes it is much faster to just throw a CSS one, if I know it will do the work just fine.

How to reduce the image file size using PIL

The main image manager in PIL is PIL's Image module.

from PIL import Image
import math

foo = Image.open("path\\to\\image.jpg")
x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)
foo = foo.resize((x2,y2),Image.ANTIALIAS)
foo.save("path\\to\\save\\image_scaled.jpg",quality=95)

You can add optimize=True to the arguments of you want to decrease the size even more, but optimize only works for JPEG's and PNG's. For other image extensions, you could decrease the quality of the new saved image. You could change the size of the new image by just deleting a bit of code and defining the image size and you can only figure out how to do this if you look at the code carefully. I defined this size:

x, y = foo.size
x2, y2 = math.floor(x-50), math.floor(y-20)

just to show you what is (almost) normally done with horizontal images. For vertical images you might do:

x, y = foo.size
x2, y2 = math.floor(x-20), math.floor(y-50)

. Remember, you can still delete that bit of code and define a new size.

Error: Cannot find module 'gulp-sass'

I worked with Yarn and I got the same issue and I solve it doing this:

delete node_modules
yarn install
yarn upgrade

yarn install gulp-sass --save-dev

How to check that a JCheckBox is checked?

By using itemStateChanged(ItemListener) you can track selecting and deselecting checkbox (and do whatever you want based on it):

myCheckBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...
        };
    }
});

Java Swing itemStateChanged docu should help too. By using isSelected() method you can just test if actual is checkbox selected:

if(myCheckBox.isSelected()){_do_something_if_selected_}

What is the difference between '/' and '//' when used for division?

/ --> Floating point division

// --> Floor division

Lets see some examples in both python 2.7 and in Python 3.5.

Python 2.7.10 vs. Python 3.5

print (2/3)  ----> 0                   Python 2.7
print (2/3)  ----> 0.6666666666666666  Python 3.5

Python 2.7.10 vs. Python 3.5

  print (4/2)  ----> 2         Python 2.7
  print (4/2)  ----> 2.0       Python 3.5

Now if you want to have (in python 2.7) same output as in python 3.5, you can do the following:

Python 2.7.10

from __future__ import division
print (2/3)  ----> 0.6666666666666666   #Python 2.7
print (4/2)  ----> 2.0                  #Python 2.7

Where as there is no differece between Floor division in both python 2.7 and in Python 3.5

138.93//3 ---> 46.0        #Python 2.7
138.93//3 ---> 46.0        #Python 3.5
4//3      ---> 1           #Python 2.7
4//3      ---> 1           #Python 3.5

How do I include a JavaScript script file in Angular and call a function from that script?

Refer the scripts inside the angular-cli.json (angular.json when using angular 6+) file.

"scripts": [
    "../path" 
 ];

then add in typings.d.ts (create this file in src if it does not already exist)

declare var variableName:any;

Import it in your file as

import * as variable from 'variableName';

How to convert std::string to LPCSTR?

std::string myString("SomeValue");
LPSTR lpSTR = const_cast<char*>(myString.c_str());

myString is the input string and lpSTR is it's LPSTR equivalent.

Default SQL Server Port

The default port of SQL server is 1433.

Calling a function when ng-repeat has finished

The other solutions will work fine on initial page load, but calling $timeout from the controller is the only way to ensure that your function is called when the model changes. Here is a working fiddle that uses $timeout. For your example it would be:

.controller('myC', function ($scope, $timeout) {
$scope.$watch("ta", function (newValue, oldValue) {
    $timeout(function () {
       test();
    });
});

ngRepeat will only evaluate a directive when the row content is new, so if you remove items from your list, onFinishRender will not fire. For example, try entering filter values in these fiddles emit.

Get button click inside UITableViewCell

Its Work For me.

 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
     UIButton *Btn_Play = (UIButton *)[cell viewWithTag:101];
     [Btn_Play addTarget:self action:@selector(ButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
}
-(void)ButtonClicked:(UIButton*)sender {
     CGPoint buttonPosition = [sender convertPoint:CGPointZero toView:self.Tbl_Name];
     NSIndexPath *indexPath = [self.Tbl_Name indexPathForRowAtPoint:buttonPosition];
}

Show "loading" animation on button click

If you are using ajax then (making it as simple as possible)

  1. Add your loading gif image to html and make it hidden (using style in html itself now, you can add it to separate CSS):

    <img src="path\to\loading\gif" id="img" style="display:none"/ >
    
  2. Show the image when button is clicked and hide it again on success function

    $('#buttonID').click(function(){
      $('#img').show(); //<----here
      $.ajax({
        ....
       success:function(result){
           $('#img').hide();  //<--- hide again
       }
    }
    

Make sure you hide the image on ajax error callbacks too to make sure the gif hides even if the ajax fails.

image size (drawable-hdpi/ldpi/mdpi/xhdpi)

Hope this will help...

mdpi is the reference density -- that is, 1 px on an mdpi display is equal to 1 dip. The ratio for asset scaling is:

ldpi | mdpi | hdpi | xhdpi | xxhdpi | xxxhdpi
0.75 | 1    | 1.5  | 2     | 3      | 4

Although you don't really need to worry about tvdpi unless you're developing specifically for Google TV or the original Nexus 7 -- but even Google recommends simply using hdpi assets. You probably don't need to worry about xxhdpi either (although it never hurts, and at least the launcher icon should be provided at xxhdpi), and xxxhdpi is just a constant in the source code right now (no devices use it, nor do I expect any to for a while, if ever), so it's safe to ignore as well.

What this means is if you're doing a 48dip image and plan to support up to xhdpi resolution, you should start with a 96px image (144px if you want native assets for xxhdpi) and make the following images for the densities:

ldpi    | mdpi    | hdpi    | xhdpi     | xxhdpi    | xxxhdpi
36 x 36 | 48 x 48 | 72 x 72 | 96 x 96   | 144 x 144 | 192 x 192

And these should display at roughly the same size on any device, provided you've placed these in density-specific folders (e.g. drawable-xhdpi, drawable-hdpi, etc.)

For reference, the pixel densities for these are:

ldpi  | mdpi  | hdpi  | xhdpi  | xxhdpi  | xxxhdpi
120   | 160   | 240   | 320    | 480     | 640

Where/how can I download (and install) the Microsoft.Jet.OLEDB.4.0 for Windows 8, 64 bit?

On modern Windows this driver isn't available by default anymore, but you can download as Microsoft Access Database Engine 2010 Redistributable on the MS site. If your app is 32 bits be sure to download and install the 32 bits variant because to my knowledge the 32 and 64 bit variant cannot coexist.

Depending on how your app locates its db driver, that might be all that's needed. However, if you use an UDL file there's one extra step - you need to edit that file. Unfortunately, on a 64bits machine the wizard used to edit UDL files is 64 bits by default, it won't see the JET driver and just slap whatever driver it finds first in the UDL file. There are 2 ways to solve this issue:

  1. start the 32 bits UDL wizard like this: C:\Windows\syswow64\rundll32.exe "C:\Program Files (x86)\Common Files\System\Ole DB\oledb32.dll",OpenDSLFile C:\path\to\your.udl. Note that I could use this technique on a Win7 64 Pro, but it didn't work on a Server 2008R2 (could be my mistake, just mentioning)
  2. open the UDL file in Notepad or another text editor, it should more or less have this format:

[oledb] ; Everything after this line is an OLE DB initstring Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Path\To\The\database.mdb;Persist Security Info=False

That should allow your app to start correctly.

Batch script to install MSI

Here is the batch file which should work for you:

@echo off
Title HOST: Installing updates on %computername%
echo %computername%
set Server=\\SERVERNAME or PATH\msifolder

:select
cls
echo Select one of the following MSI install folders for installation task.
echo.
dir "%Server%" /AD /ON /B
echo.
set /P "MSI=Please enter the MSI folder to install: "
set "Package=%Server%\%MSI%\%MSI%.msi"

if not exist "%Package%" (
   echo.
   echo The entered folder/MSI file does not exist ^(typing mistake^).
   echo.
   setlocal EnableDelayedExpansion
   set /P "Retry=Try again [Y/N]: "
   if /I "!Retry!"=="Y" endlocal & goto select
   endlocal
   goto :EOF
)

echo.
echo Selected installation: %MSI%
echo.
echo.

:verify
echo Is This Correct?
echo.
echo.
echo    0: ABORT INSTALL
echo    1: YES
echo    2: NO, RE-SELECT
echo.
set /p "choice=Select YES, NO or ABORT? [0,1,2]: "
if [%choice%]==[0] goto :EOF
if [%choice%]==[1] goto yes
goto select

:yes
echo.
echo Running %MSI% installation ...
start "Install MSI" /wait "%SystemRoot%\system32\msiexec.exe" /i /quiet "%Package%"

The characters listed on last page output on entering in a command prompt window either help cmd or cmd /? have special meanings in batch files. Here are used parentheses and square brackets also in strings where those characters should be interpreted literally. Therefore it is necessary to either enclose the string in double quotes or escape those characters with character ^ as it can be seen in code above, otherwise command line interpreter exits batch execution because of a syntax error.

And it is not possible to call a file with extension MSI. A *.msi file is not an executable. On double clicking on a MSI file, Windows looks in registry which application is associated with this file extension for opening action. And the application to use is msiexec with the command line option /i to install the application inside MSI package.

Run msiexec.exe /? to get in a GUI window the available options or look at Msiexec (command-line options).

I have added already /quiet additionally to required option /i for a silent installation.

In batch code above command start is used with option /wait to start Windows application msiexec.exe and hold execution of batch file until installation finished (or aborted).

How to create a GUID / UUID

The UUID currently has a proposal for addition to the standard library and can be supported here https://github.com/tc39/proposal-uuid

The proposal encompasses having UUID as the following:

// We're not yet certain as to how the API will be accessed (whether it's in the global, or a
// future built-in module), and this will be part of the investigative process as we continue
// working on the proposal.
uuid(); // "52e6953d-edbe-4953-be2e-65ed3836b2f0"

This implemtation follows the same layout as the V4 random uuid generation found here: https://www.npmjs.com/package/uuid

const uuidv4 = require('uuid/v4');
uuidv4(); // ? '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'

I think it's noteworthy to understand how much bandwidth could be saved by this having an official implementation in the standard library. The authors of the proposal have also noted:

The 12 kb uuid module is downloaded from npm > 62,000,000 times a month (June 2019); making it available in the standard library eventually saves TBs of bandwidth globally. If we continue to address user needs, such as uuid, with the standard library, bandwidth savings add up.

Generating an array of letters in the alphabet

for (char letter = 'A'; letter <= 'Z'; letter++)
{
     Debug.WriteLine(letter);
}

How to terminate process from Python using pid?

I wanted to do the same thing as, but I wanted to do it in the one file.

So the logic would be:

  • if a script with my name is running, kill it, then exit
  • if a script with my name is not running, do stuff

I modified the answer by Bakuriu and came up with this:

from os import getpid
from sys import argv, exit
import psutil  ## pip install psutil

myname = argv[0]
mypid = getpid()
for process in psutil.process_iter():
    if process.pid != mypid:
        for path in process.cmdline():
            if myname in path:
                print "process found"
                process.terminate()
                exit()

## your program starts here...

Running the script will do whatever the script does. Running another instance of the script will kill any existing instance of the script.

I use this to display a little PyGTK calendar widget which runs when I click the clock. If I click and the calendar is not up, the calendar displays. If the calendar is running and I click the clock, the calendar disappears.

String.Format alternative in C++

For the sake of completeness, you may use std::stringstream:

#include <iostream>
#include <sstream>
#include <string>

int main() {
    std::string a = "a", b = "b", c = "c";
    // apply formatting
    std::stringstream s;
    s << a << " " << b << " > " << c;
    // assign to std::string
    std::string str = s.str();
    std::cout << str << "\n";
}

Or (in this case) std::string's very own string concatenation capabilities:

#include <iostream>
#include <string>

int main() {
    std::string a = "a", b = "b", c = "c";
    std::string str = a + " " + b + " > " + c;
    std::cout << str << "\n";
}

For reference:


If you really want to go the C way. Here you are:

#include <iostream>
#include <string>
#include <vector>
#include <cstdio>

int main() {
    std::string a = "a", b = "b", c = "c";
    const char fmt[] = "%s %s > %s";
    // use std::vector for memory management (to avoid memory leaks)
    std::vector<char>::size_type size = 256;
    std::vector<char> buf;
    do {
        // use snprintf instead of sprintf (to avoid buffer overflows)
        // snprintf returns the required size (without terminating null)
        // if buffer is too small initially: loop should run at most twice
        buf.resize(size+1);
        size = std::snprintf(
                &buf[0], buf.size(),
                fmt, a.c_str(), b.c_str(), c.c_str());
    } while (size+1 > buf.size());
    // assign to std::string
    std::string str(buf.begin(), buf.begin()+size);
    std::cout << str << "\n";
}

For reference:


Then, there's the Boost Format Library. For the sake of your example:

#include <iostream>
#include <string>
#include <boost/format.hpp>

int main() {
    std::string a = "a", b = "b", c = "c";
    // apply format
    boost::format fmt = boost::format("%s %s > %s") % a % b % c; 
    // assign to std::string
    std::string str = fmt.str();
    std::cout << str << "\n";
}

Joining Multiple Tables - Oracle

You are doing a cartesian join. This means that if you wouldn't have even have the single where clause, the number of results you get would be book_customer size times books size times book_order size times publisher size.

In order words, the result set gets blown up because you didn't add meaningful join clauses. Your correct query should look something like this:

SELECT bc.firstname, bc.lastname, b.title, TO_CHAR(bo.orderdate, 'MM/DD/YYYY') "Order Date", p.publishername
FROM book_customer bc, books b, book_order bo, publisher p
WHERE bc.book_id = b.book_id
AND bo.book_id = b.book_id
(etc.)
AND publishername = 'PRINTING IS US';

Note: usually it is adviced to not use the implicit joins like in this query, but use the INNER JOIN syntax. I am assuming however, that this syntax is used in your study material so I've left it in.

Import CSV file with mixed data types

Given the sample you posted, this simple code should do the job:

fid = fopen('file.csv','r');
C = textscan(fid, repmat('%s',1,10), 'delimiter',';', 'CollectOutput',true);
C = C{1};
fclose(fid);

Then you could format the columns according to their type. For example if the first column is all integers, we can format it as such:

C(:,1) = num2cell( str2double(C(:,1)) )

Similarly, if you wish to convert the 8th column from hex to decimals, you can use HEX2DEC:

C(:,8) = cellfun(@hex2dec, strrep(C(:,8),'0x',''), 'UniformOutput',false);

The resulting cell array looks as follows:

C = 
    [  4]    'abc'    'def'    'ghj'    'klm'    ''            ''                []    ''    ''
    [NaN]    ''       ''       ''       ''       'Test'        'text'        [ 255]    ''    ''
    [NaN]    ''       ''       ''       ''       'asdfhsdf'    'dsafdsag'    [3855]    ''    ''

Change connection string & reload app.config at run time

First you might want to add

using System.Configuration;

To your .cs file. If it not available add it through the Project References as it is not included by default in a new project.

This is my solution to this problem. First I made the ConnectionProperties Class that saves the items I need to change in the original connection string. The _name variable in the ConnectionProperties class is important to be the name of the connectionString The first method takes a connection string and changes the option you want with the new value.

private String changeConnStringItem(string connString,string option, string value)
    {
        String[] conItems = connString.Split(';');
        String result = "";
        foreach (String item in conItems)
        {
            if (item.StartsWith(option))
            {
                result += option + "=" + value + ";";
            }
            else
            {
                result += item + ";";
            }
        }
        return result;
    }

You can change this method to accomodate your own needs. I have both mysql and mssql connections so I needed both of them. Of course you can refine this draft code for yourself.

private void changeConnectionSettings(ConnectionProperties cp)
{
     var cnSection = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
     String connString = cnSection.ConnectionStrings.ConnectionStrings[cp.Name].ConnectionString;
     connString = changeConnStringItem(connString, "provider connection string=\"data source", cp.DataSource);
     connString = changeConnStringItem(connString, "provider connection string=\"server", cp.DataSource);
     connString = changeConnStringItem(connString, "user id", cp.Username);
     connString = changeConnStringItem(connString, "password", cp.Password);
     connString = changeConnStringItem(connString, "initial catalog", cp.InitCatalogue);
     connString = changeConnStringItem(connString, "database", cp.InitCatalogue);
           cnSection.ConnectionStrings.ConnectionStrings[cp.Name].ConnectionString = connString;
     cnSection.Save();
     ConfigurationManager.RefreshSection("connectionStrings");
}

As I didn't want to add trivial information I ommited the Properties region of my code. Please add it if you want this to work.

class ConnectionProperties
{
    private String _name;
    private String _dataSource;
    private String _username;
    private String _password;
    private String _initCatalogue;

    /// <summary>
    /// Basic Connection Properties constructor
    /// </summary>
    public ConnectionProperties()
    {

    }

    /// <summary>
    /// Constructor with the needed settings
    /// </summary>
    /// <param name="name">The name identifier of the connection</param>
    /// <param name="dataSource">The url where we connect</param>
    /// <param name="username">Username for connection</param>
    /// <param name="password">Password for connection</param>
    /// <param name="initCat">Initial catalogue</param>
    public ConnectionProperties(String name,String dataSource, String username, String password, String initCat)
    {
        _name = name;
        _dataSource = dataSource;
        _username = username;
        _password = password;
        _initCatalogue = initCat;
    }
// Enter corresponding Properties here for access to private variables
}

How to get DATE from DATETIME Column in SQL?

You can use

select * 
from transaction 
where (Card_No='123') and (transaction_date = convert(varchar(10),getdate(),101))

How to select rows that have current day's timestamp?

use DATE and CURDATE()

SELECT * FROM `table` WHERE DATE(`timestamp`) = CURDATE()

Warning! This query doesn't use an index efficiently. For the more efficient solution see the answer below

see the execution plan on the DEMO

Python: Best way to add to sys.path relative to the current running script

There is a problem with every answer provided that can be summarized as "just add this magical incantation to the beginning of your script. See what you can do with just a line or two of code." They will not work in every possible situation!

For example, one such magical incantation uses __file__. Unfortunately, if you package your script using cx_Freeze or you are using IDLE, this will result in an exception.

Another such magical incantation uses os.getcwd(). This will only work if you are running your script from the command prompt and the directory containing your script is the current working directory (that is you used the cd command to change into the directory prior to running the script). Eh gods! I hope I do not have to explain why this will not work if your Python script is in the PATH somewhere and you ran it by simply typing the name of your script file.

Fortunately, there is a magical incantation that will work in all the cases I have tested. Unfortunately, the magical incantation is more than just a line or two of code.

import inspect
import os
import sys

# Add script directory to sys.path.
# This is complicated due to the fact that __file__ is not always defined.

def GetScriptDirectory():
    if hasattr(GetScriptDirectory, "dir"):
        return GetScriptDirectory.dir
    module_path = ""
    try:
        # The easy way. Just use __file__.
        # Unfortunately, __file__ is not available when cx_Freeze is used or in IDLE.
        module_path = __file__
    except NameError:
        if len(sys.argv) > 0 and len(sys.argv[0]) > 0 and os.path.isabs(sys.argv[0]):
            module_path = sys.argv[0]
        else:
            module_path = os.path.abspath(inspect.getfile(GetScriptDirectory))
            if not os.path.exists(module_path):
                # If cx_Freeze is used the value of the module_path variable at this point is in the following format.
                # {PathToExeFile}\{NameOfPythonSourceFile}. This makes it necessary to strip off the file name to get the correct
                # path.
                module_path = os.path.dirname(module_path)
    GetScriptDirectory.dir = os.path.dirname(module_path)
    return GetScriptDirectory.dir

sys.path.append(os.path.join(GetScriptDirectory(), "lib"))
print(GetScriptDirectory())
print(sys.path)

As you can see, this is no easy task!

missing FROM-clause entry for table

SELECT 
   AcId, AcName, PldepPer, RepId, CustCatg, HardCode, BlockCust, CrPeriod, CrLimit, 
   BillLimit, Mode, PNotes, gtab82.memno 
FROM
   VCustomer AS v1
INNER JOIN   
   gtab82 ON gtab82.memacid = v1.AcId 
WHERE (AcGrCode = '204' OR CreDebt = 'True') 
AND Masked = 'false'
ORDER BY AcName

You typically only use an alias for a table name when you need to prefix a column with the table name due to duplicate column names in the joined tables and the table name is long or when the table is joined to itself. In your case you use an alias for VCustomer but only use it in the ON clause for uncertain reasons. You may want to review that aspect of your code.

How do I compare two files using Eclipse? Is there any option provided by Eclipse?

To compare two files in Eclipse, first select them in the Project Explorer / Package Explorer / Navigator with control-click. Now right-click on one of the files, and the following context menu will appear. Select Compare With / Each Other.

enter image description here

C#: how to get first char of a string?

You can use LINQ

char c = mystring.FirstOrDefault()

It will be equal to '\0' if the string is empty.

Opacity of div's background without affecting contained element in IE 8?

opacity on parent element sets it for the whole sub DOM tree

You can't really set opacity for certain element that wouldn't cascade to descendants as well. That's not how CSS opacity works I'm afraid.

What you can do is to have two sibling elements in one container and set transparent one's positioning:

<div id="container">
    <div id="transparent"></div>
    <div id="content"></div>
</div>

then you have to set transparent position: absolute/relative so its content sibling will be rendered over it.

rgba can do background transparency of coloured backgrounds

rgba colour setting on element's background-color will of course work, but it will limit you to only use colour as background. No images I'm afraid. You can of course use CSS3 gradients though if you provide gradient stop colours in rgba. That works as well.

But be advised that rgba may not be supported by your required browsers.

Alert-free modal dialog functionality

But if you're after some kind of masking the whole page, this is usually done by adding a separate div with this set of styles:

position: fixed;
width: 100%;
height: 100%;
z-index: 1000; /* some high enough value so it will render on top */
opacity: .5;
filter: alpha(opacity=50);

Then when you display the content it should have a higher z-index. But these two elements are not related in terms of siblings or anything. They're just displayed as they should be. One over the other.

How to disable Google Chrome auto update?

Just add the object yourself using regedit:

Under HKEY_LOCAL_MACHINE\SOFTWARE\Policies,

  • Create new Key, "Google"
  • In "Google", create new Key, "Update"
  • In "Update" go to that key and create Dword, "AutoUpdateCheckPeriodMinutes" which automatically value set to 0, just double check and change if needed.

All done!

Restart might be needed.

How to avoid annoying error "declared and not used"

In case others have a hard time making sense of this, I think it might help to explain it in very straightforward terms. If you have a variable that you don't use, for example a function for which you've commented out the invocation (a common use-case):

myFn := func () { }
// myFn()

You can assign a useless/blank variable to the function so that it's no longer unused:

myFn := func () { }
_ = myFn
// myFn()

Close window automatically after printing dialog closes

Just wrap window.close by onafterprint event handler, it worked for me

printWindow.print();
printWindow.onafterprint = () => printWindow.close();

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

Incrementing a date in JavaScript

Tomorrow in one line in pure JS but it's ugly !

new Date(new Date().setDate(new Date().getDate() + 1))

Here is the result :

Thu Oct 12 2017 08:53:30 GMT+0200 (Romance Summer Time)

Drop-down box dependent on the option selected in another drop-down box

    function dropdownlist(listindex)
    {
         document.getElementById("ddlCity").options.length = 0;
         switch (listindex) 
         {
             case "Karnataka":
                     document.getElementById("ddlCity").options[0] = new Option("--select--", "");
                     document.getElementById("ddlCity").options[1] = new Option("Dharawad", "Dharawad");
                     document.getElementById("ddlCity").options[2] = new Option("Haveri", "Haveri");
                     document.getElementById("ddlCity").options[3] = new Option("Belgum", "Belgum");
                     document.getElementById("ddlCity").options[4] = new Option("Bijapur", "Bijapur");

                 break;

             case "Tamilnadu":
                 document.getElementById("ddlCity").options[0] = new Option("--select--", "");
                 document.getElementById("ddlCity").options[1] = new Option("dgdf", "dgdf");
                 document.getElementById("ddlCity").options[2] = new Option("gffd", "gffd");


                 break;
         }

    }

* State: --Select-- Karnataka Tamilnadu Andra pradesh Telngana

    <div>
        <p>

            <label id="lblCt">
            <span class="red">*</span>
                City:</label>
            <select id="ddlCity">
               <!-- <option>--Select--</option>
                <option value="1">Dharawad</option>
                <option value="2">Belgum</option>
                <option value="3">Bagalkot</option>
                <option value="4">Haveri</option>
                <option>Hydrabadh</option>
                <option>Vijat vada</option>-->
            </select>
            <label id="lblCity"></label>
        </p>
    </div>

How do I send a cross-domain POST request via JavaScript?

CORS is for you. CORS is "Cross Origin Resource Sharing", is a way to send cross domain request.Now the XMLHttpRequest2 and Fetch API both support CORS, and it can send both POST and GET request

But it has its limits.Server need to specific claim the Access-Control-Allow-Origin, and it can not be set to '*'.

And if you want any origin can send request to you, you need JSONP (also need to set Access-Control-Allow-Origin, but can be '*')

For lots of request way if you don't know how to choice, I think you need a full functional component to do that.Let me introduce a simple component https://github.com/Joker-Jelly/catta


If you are using modern browser (> IE9, Chrome, FF, Edge, etc.), Very Recommend you to use a simple but beauty component https://github.com/Joker-Jelly/catta.It have no dependence, Less than 3KB, and it support Fetch, AJAX and JSONP with same deadly sample syntax and options.

catta('./data/simple.json').then(function (res) {
  console.log(res);
});

It also it support all the way to import to your project, like ES6 module, CommonJS and even <script> in HTML.

Having the output of a console application in Visual Studio instead of the console

If you need output from Console.WriteLine, and the Redirect All Output Window Text to the Immediate Window does not function and you need to know the output of Tests from the Integrated Test Explorer, using NUnit.Framework our problem is already solved at VS 2017:

Example taken from C# In Depth by Jon Skeet: Example taken from C# In Depth by Jon Skeet This produce this output at Text Explorer: Task Explorer

When we click on Blue Output, under Elapsed Time, at right, and it produces this: Standard Output

Standard Output is our desired Output, produced by Console.WriteLine.

It functions for Console and for Windows Form Applications at VS 2017, but only for Output generated for Test Explorer at Debug or Run; anyway, this is my main need of Console.WriteLine output.

Constants in Objective-C

If you want something like global constants; a quick an dirty way is to put the constant declarations into the pch file.

C# "internal" access modifier when doing unit testing

Adding to Eric's answer, you can also configure this in the csproj file:

<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
      <_Parameter1>MyTests</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>

Or if you have one test project per project to be tested, you could do something like this in your Directory.Build.props file:

<ItemGroup>
    <AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
      <_Parameter1>$(MSBuildProjectName).Test</_Parameter1>
    </AssemblyAttribute>
</ItemGroup>

See: https://stackoverflow.com/a/49978185/1678053
Example: https://github.com/gldraphael/evlog/blob/master/Directory.Build.props#L5-L12

How to run JUnit tests with Gradle?

If you created your project with Spring Initializr, everything should be configured correctly and all you need to do is run...

./gradlew clean test --info
  • Use --info if you want to see test output.
  • Use clean if you want to re-run tests that have already passed since the last change.

Dependencies required in build.gradle for testing in Spring Boot...

dependencies {
    compile('org.springframework.boot:spring-boot-starter')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

For some reason the test runner doesn't tell you this, but it produces an HTML report in build/reports/tests/test/index.html.

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

I faced the similar issue on new server that I built through automated scripts via vcenter api. Looks like the "Remote Procedure Call (RPC)" service may not be running on the remote machine. you need to wait for the service to come up to use the Get-WmiObject command. Hence I simply put the script into sleep for sometime and it worked.

Android Studio: Add jar as library?

Put the .jar files in libs folder of the Android project.

Then add this line of code in the app's gradle file:

    compile fileTree(dir: 'libs', include: ['*.jar'])

For Android gradle plugin 3.0 and later, it is better to use this instead:

    implementation fileTree(dir: 'libs', include: ['*.jar'])

Prevent HTML5 video from being downloaded (right-click saved)?

First of all realise it is impossible to completely prevent a video being downloaded, all you can do is make it more difficult. I.e. you hide the source of the video.

A web browser temporarily downloads the video in a buffer, so if could prevent download you would also be preventing the video being viewed as well.

You should also know that <1% of the total population of the world will be able to understand the source code making it rather safe anyway. That does not mean you should not hide it in the source as well - you should.

You should not disable right click, and even less you should display a message saying "You cannot save this video for copyright reasons. Sorry about that.". As suggested in this answer.

This can be very annoying and confusing for the user. Apart from that; if they disable JavaScript on their browser they will be able to right click and save anyway.

Here is a CSS trick you could use:

video {
    pointer-events: none;
}

CSS cannot be turned off in browser, protecting your video without actually disabling right click. However one problem is that controls cannot be enabled either, in other words they must be set to false. If you are going to inplament your own Play/Pause function or use an API that has buttons separate to the video tag then this is a feasible option.

controls also has a download button so using it is not such a good idea either.

Here is a JSFiddle example.


If you are going to disable right click using JavaScript then also store the source of the video in JavaScript as well. That way if the user disables JavaScript (allowing right click) the video will not load (it also hides the video source a little better).

From TxRegex answer:

<video oncontextmenu="return false;" controls>
    <source type="video/mp4" id="video">
</video>

Now add the video via JavaScript:

document.getElementById("video").src = "https://www.w3schools.com/html/mov_bbb.mp4";

Functional JSFiddle


Another way to prevent right click involves using the embed tag. This is does not however provide the controls to run the video so they would need to be inplamented in JavaScript:

<embed src="https://www.w3schools.com/html/mov_bbb.mp4"></embed>

Cast received object to a List<object> or IEnumerable<object>

Problem is, you're trying to upcast to a richer object. You simply need to add the items to a new list:

if (myObject is IEnumerable)
{
   List<object> list = new List<object>();
   var enumerator = ((IEnumerable) myObject).GetEnumerator();
   while (enumerator.MoveNext())
   {
      list.Add(enumerator.Current);
   }
}

Xcode 4: create IPA file instead of .xcarchive

I had the same problem... Had to recreate the project from scratch.

Note: my project was created in XCode 3.1 and was linking against a static library that was being built as a subproject (to a common destination). I changed this to build the source instead when I recreated the XCode project in XCode 4.

Now doing a Product/Archive/Share... gets the option of "iOS App Store Package (.ipa)" directly above "Application" (which is now greyed out) and "Archive" (which exports the .xcarchive).

How to get the first line of a file in a bash script?

Just echo the first list of your source file into your target file.

echo $(head -n 1 source.txt) > target.txt

How do I parse command line arguments in Bash?

Use module "arguments" from bash-modules

Example:

#!/bin/bash
. import.sh log arguments

NAME="world"

parse_arguments "-n|--name)NAME;S" -- "$@" || {
  error "Cannot parse command line."
  exit 1
}

info "Hello, $NAME!"

Get most recent row for given ID

Simple Way To Achieve

I know it's an old question You can also do something like

SELECT * FROM Table WHERE id=1 ORDER BY signin DESC

In above, query the first record will be the most recent record.

For only one record you can use something like

SELECT top(1) * FROM Table WHERE id=1 ORDER BY signin DESC

Above query will only return one latest record.

Cheers!

Retrieve data from a ReadableStream object?

Note that you can only read a stream once, so in some cases, you may need to clone the response in order to repeatedly read it:

fetch('example.json')
  .then(res=>res.clone().json())
  .then( json => console.log(json))

fetch('url_that_returns_text')
  .then(res=>res.clone().text())
  .then( text => console.log(text))

Parse JSON from HttpURLConnection object

The JSON string will just be the body of the response you get back from the URL you have called. So add this code

...
BufferedReader in = new BufferedReader(new InputStreamReader(
                            conn.getInputStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) 
    System.out.println(inputLine);
in.close();

That will allow you to see the JSON being returned to the console. The only missing piece you then have is using a JSON library to read that data and provide you with a Java representation.

Here's an example using JSON-LIB

How to get a random number between a float range?

random.uniform(a, b) appears to be what your looking for. From the docs:

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

See here.

How can I keep my branch up to date with master with git?

You can use the cherry-pick to get the particular bug fix commit(s)

$ git checkout branch
$ git cherry-pick bugfix

Does List<T> guarantee insertion order?

As Bevan said, but keep in mind, that the list-index is 0-based. If you want to move an element to the front of the list, you have to insert it at index 0 (not 1 as shown in your example).

1052: Column 'id' in field list is ambiguous

What you are probably really wanting to do here is use the union operator like this:

(select ID from Logo where AccountID = 1 and Rendered = 'True')
  union
  (select ID from Design where AccountID = 1 and Rendered = 'True')
  order by ID limit 0, 51

Here's the docs for it https://dev.mysql.com/doc/refman/5.0/en/union.html

Has anyone gotten HTML emails working with Twitter Bootstrap?

The trick here is that you don't want to include the whole bootstrap. The issue is that email clients will ignore the media queries and process all the print styles which have a lot of !important statements.

Instead, you need to only include the specific parts of bootstrap that you need. My email.css.scss file looks like this:

@import "bootstrap-sprockets";
@import "bootstrap/variables";
@import "bootstrap/mixins";
@import "bootstrap/scaffolding";
@import "bootstrap/type";
@import "bootstrap/buttons";
@import "bootstrap/alerts";

@import 'bootstrap/normalize';
@import 'bootstrap/tables';

How can I check if character in a string is a letter? (Python)

str.isalpha()

Return true if all characters in the string are alphabetic and there is at least one character, false otherwise. Alphabetic characters are those characters defined in the Unicode character database as “Letter”, i.e., those with general category property being one of “Lm”, “Lt”, “Lu”, “Ll”, or “Lo”. Note that this is different from the “Alphabetic” property defined in the Unicode Standard.

In python2.x:

>>> s = u'a1??'
>>> for char in s: print char, char.isalpha()
...
a True
1 False
? True
? True
>>> s = 'a1??'
>>> for char in s: print char, char.isalpha()
...
a True
1 False
? False
? False
? False
? False
? False
? False
>>>

In python3.x:

>>> s = 'a1??'
>>> for char in s: print(char, char.isalpha())
...
a True
1 False
? True
? True
>>>

This code work:

>>> def is_alpha(word):
...     try:
...         return word.encode('ascii').isalpha()
...     except:
...         return False
...
>>> is_alpha('??')
False
>>> is_alpha(u'??')
False
>>>

>>> a = 'a'
>>> b = 'a'
>>> ord(a), ord(b)
(65345, 97)
>>> a.isalpha(), b.isalpha()
(True, True)
>>> is_alpha(a), is_alpha(b)
(False, True)
>>>

Webdriver Unable to connect to host 127.0.0.1 on port 7055 after 45000 ms

This issue has haunted me for long time and I have seen one working solution in case of Firefox was to use the upgraded firefox driver.

  • If your firefox upgrades are happening automatically than you may face this problem once in a while. Looks like Firefox guys are developing too fast, or they do not care about backward compatibility.

  • Every time I see this issue on my old scripts I check if the firefox version has changed since - most of the times it is.

  • Then I go to maven repo for selenium firefox driver repo - http://mvnrepository.com/artifact/org.seleniumhq.selenium/selenium-firefox-driver and download the latest version.

  • or update my pom.xml (if maven is used) with new version of firefox driver right now its - 2.40.0

  • There is no easy way to avoid this issue unless you really explicitly block the automatied update from firefox (You can do this (On Mac) in preferences - Advanced - Update - Select "Check for updates, but let me choose whether to install them")

  • If your scripts are running on a automated mode then you may want to disable updates. However this may create other issues. Since most people/user may have firefox updates enabled by default. So your application is not really being tested on any later versions.

Why is January month 0 in Java Calendar?

There has been a lot of answers to this, but I will give my view on the subject anyway. The reason behind this odd behavior, as stated previously, comes from the POSIX C time.h where the months were stored in an int with the range 0-11. To explain why, look at it like this; years and days are considered numbers in spoken language, but months have their own names. So because January is the first month it will be stored as offset 0, the first array element. monthname[JANUARY] would be "January". The first month in the year is the first month array element.

The day numbers on the other hand, since they do not have names, storing them in an int as 0-30 would be confusing, add a lot of day+1 instructions for outputting and, of course, be prone to alot of bugs.

That being said, the inconsistency is confusing, especially in javascript (which also has inherited this "feature"), a scripting language where this should be abstracted far away from the langague.

TL;DR: Because months have names and days of the month do not.

Java Program to test if a character is uppercase/lowercase/number/vowel

You don't need a for loop in your code.

Here is how you can re implement your method

  • If input is between 'A' and 'Z' its uppercase
  • If input is between 'a' and 'z' its lowercase
  • If input is one of 'a,e,i,o,u,A,E,I,O,U' its Vowel
  • Else Consonant

Edit:

Here is hint for you to proceed, Following code snippet gives int values for chars

System.out.println("a="+(int)'a');
System.out.println("z="+(int)'z');
System.out.println("A="+(int)'A');
System.out.println("Z="+(int)'Z');

Output

a=97
z=122
A=65
Z=90

Here is how you can check if a number x exists between two numbers say a and b

// x greater than or equal to a and x less than or equal to b
if ( x >= a && x <= b ) 

During comparisons chars can be treated as numbers

If you can combine these hints, you should be able to find what you want ;)

Is a Python list guaranteed to have its elements stay in the order they are inserted in?

Yes, the order of elements in a python list is persistent.

8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE

This is a typical startup failure due to the embedded servlet container’s port being in use.

Your embedded tomcat container failed to start because Port 8080 was already in use.

Just Identify and stop the process that's listening on port 8080 or configure (in you application.properties file )this application to listen on another port.

How display only years in input Bootstrap Datepicker?

format: "YYYY" 

Should be capital instead of "yyyy"

#define macro for debug printing in C?

I would do something like

#ifdef DEBUG
#define debug_print(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)
#else
#define debug_print(fmt, ...) do {} while (0)
#endif

I think this is cleaner.

Set up adb on Mac OS X

Here's a detailed manual:
http://codexpi.com/add-android-adb-path-mac-os-x-mavericks/

To sum this up:

  1. Create and open the bash_profile file

    touch .bash_profile
    open -e .bash_profile

  2. Add the path of the platform-tools folder (within the Android SDK)

    export PATH="$PATH:/Users/USERNAME/PATH TO ANDROID SDK/platform-tools/

  3. Run the command . .bash_profile to update (no need to restart the terminal)

How to set DateTime to null

You can write DateTime? newdate = null;

Installing ADB on macOS

Note that if you use Android Studio and download through its SDK Manager, the SDK is downloaded to ~/Library/Android/sdk by default, not ~/.android-sdk-macosx.

I would rather add this as a comment to @brismuth's excellent answer, but it seems I don't have enough reputation points yet.

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

How to convert Java String into byte[]?

You can use String.getBytes() which returns the byte[] array.

How to secure database passwords in PHP?

if it is possible to create the database connection in the same file where the credentials are stored. Inline the credentials in the connect statement.

mysql_connect("localhost", "me", "mypass");

Otherwise it is best to unset the credentials after the connect statement, because credentials that are not in memory, can't be read from memory ;)

include("/outside-webroot/db_settings.php");  
mysql_connect("localhost", $db_user, $db_pass);  
unset ($db_user, $db_pass);  

How to get a list of all valid IP addresses in a local network?

Install nmap,

sudo apt-get install nmap

then

nmap -sP 192.168.1.*

or more commonly

nmap -sn 192.168.1.0/24

will scan the entire .1 to .254 range

This does a simple ping scan in the entire subnet to see which hosts are online.

How can I merge two MySQL tables?

You can also try:

INSERT IGNORE
  INTO table_1 
SELECT *
  FROM table_2
     ;

which allows those rows in table_1 to supersede those in table_2 that have a matching primary key, while still inserting rows with new primary keys.

Alternatively,

REPLACE
   INTO table_1
 SELECT *
   FROM table_2
      ;

will update those rows already in table_1 with the corresponding row from table_2, while inserting rows with new primary keys.

How to improve performance of ngRepeat over a huge dataset (angular.js)?

Rule No.1: Never let the user wait for anything.

That in mind a life growing page that needs 10seconds appears way faster than waiting 3 seconds on before a blank screen and get all at once.

So instead of make the page fast, just let the page appear to be fast, even if the final result is slower:

function applyItemlist(items){
    var item = items.shift();
    if(item){
        $timeout(function(){
            $scope.items.push(item);
            applyItemlist(items);
        }, 0); // <-- try a little gap of 10ms
    }
}

The code above let appear the list to be growing row-by-row, and is always slower than render all at once. But for the user it appears to be faster.

AngularJS : How do I switch views from a controller function?

There are two ways for this:

If you are using ui-router or $stateProvider, do it as:

$state.go('stateName'); //remember to add $state service in the controller

if you are using angular-router or $routeProvider, do it as:

$location.path('routeName'); //similarily include $location service in your controller

When should you NOT use a Rules Engine?

That's certainly a good start. The other thing with rules engines is that some things are well-understood, deterministic, and straight-forward. Payroll withholding is (or use to be) like that. You could express it as rules that would be resolved by a rules engine, but you could express the same rules as a fairly simple table of values.

So, workflow engines are good when you're expressing a longer-term process that will have persistent data. Rules engines can do a similar thing, but you have to do a lot of added complexity.

Rules engines are good when you have complicated knowledge bases and need search. Rules engines can resolve complicated issues, and can be adapted quickly to changing situations, but impose a lot of complexity on the base implementation.

Many decision algorithms are simple enough to express as a simple table-driven program without the complexity implied by a real rules engine.

Get selected element's outer HTML

Extend jQuery:

(function($) {
  $.fn.outerHTML = function() {
    return $(this).clone().wrap('<div></div>').parent().html();
  };
})(jQuery);

And use it like this: $("#myTableRow").outerHTML();

Add values to app.config and retrieve them

Try adding a Reference to System.Configuration, you get some of the configuration namespace by referencing the System namespace, adding the reference to System.Configuration should allow you to access ConfigurationManager.

iOS change navigation bar title font and color

Add this extension

extension UINavigationBar {
    func changeFont() {
        self.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.white, NSAttributedStringKey.font: UIFont(name:"Poppins-Medium", size: 17)!]
    }
}

Add the following line in viewDidLoad()

self.navigationController?.navigationBar.changeFont()

Save attachments to a folder and rename them

This is my Save Attachments script. You select all the messages that you want the attachments saved from, and it will save a copy there. It also adds text to the message body indicating where the attachment is saved. You could easily change the folder name to include the date, but you would need to make sure the folder existed before starting to save files.

Public Sub SaveAttachments()
Dim objOL As Outlook.Application
Dim objMsg As Outlook.MailItem 'Object
Dim objAttachments As Outlook.Attachments
Dim objSelection As Outlook.Selection
Dim i As Long
Dim lngCount As Long
Dim strFile As String
Dim strFolderpath As String
Dim strDeletedFiles As String

' Get the path to your My Documents folder
strFolderpath = CreateObject("WScript.Shell").SpecialFolders(16)
On Error Resume Next

' Instantiate an Outlook Application object.
Set objOL = CreateObject("Outlook.Application")

' Get the collection of selected objects.
Set objSelection = objOL.ActiveExplorer.Selection

' Set the Attachment folder.
strFolderpath = strFolderpath & "\Attachments\"

' Check each selected item for attachments. If attachments exist,
' save them to the strFolderPath folder and strip them from the item.
For Each objMsg In objSelection

    ' This code only strips attachments from mail items.
    ' If objMsg.class=olMail Then
    ' Get the Attachments collection of the item.
    Set objAttachments = objMsg.Attachments
    lngCount = objAttachments.Count
    strDeletedFiles = ""

    If lngCount > 0 Then

        ' We need to use a count down loop for removing items
        ' from a collection. Otherwise, the loop counter gets
        ' confused and only every other item is removed.

        For i = lngCount To 1 Step -1

            ' Save attachment before deleting from item.
            ' Get the file name.
            strFile = objAttachments.Item(i).FileName

            ' Combine with the path to the Temp folder.
            strFile = strFolderpath & strFile

            ' Save the attachment as a file.
            objAttachments.Item(i).SaveAsFile strFile

            ' Delete the attachment.
            objAttachments.Item(i).Delete

            'write the save as path to a string to add to the message
            'check for html and use html tags in link
            If objMsg.BodyFormat <> olFormatHTML Then
                strDeletedFiles = strDeletedFiles & vbCrLf & "<file://" & strFile & ">"
            Else
                strDeletedFiles = strDeletedFiles & "<br>" & "<a href='file://" & _
                strFile & "'>" & strFile & "</a>"
            End If

            'Use the MsgBox command to troubleshoot. Remove it from the final code.
            'MsgBox strDeletedFiles

        Next i

        ' Adds the filename string to the message body and save it
        ' Check for HTML body
        If objMsg.BodyFormat <> olFormatHTML Then
            objMsg.Body = vbCrLf & "The file(s) were saved to " & strDeletedFiles & vbCrLf & objMsg.Body
        Else
            objMsg.HTMLBody = "<p>" & "The file(s) were saved to " & strDeletedFiles & "</p>" & objMsg.HTMLBody
        End If
        objMsg.Save
    End If
Next

ExitSub:

Set objAttachments = Nothing
Set objMsg = Nothing
Set objSelection = Nothing
Set objOL = Nothing
End Sub

Identifying country by IP address

You could use ipdata.co to perform the lookup

This answer uses a 'test' API Key that is very limited and only meant for testing a few calls. Signup for your own Free API Key and get up to 1500 requests daily for development.

curl https://api.ipdata.co/23.221.76.66?api-key=test

Ipdata has 10 endpoints globally each able to handle >10,000 requests per second!

Gives

{
    "ip": "23.221.76.66",
    "city": "Cambridge",
    "region": "Massachusetts",
    "region_code": "MA",
    "country_name": "United States",
    "country_code": "US",
    "continent_name": "North America",
    "continent_code": "NA",
    "latitude": 42.3626,
    "longitude": -71.0843,
    "asn": "AS20940",
    "organisation": "Akamai International B.V.",
    "postal": "02142",
    "calling_code": "1",
    "flag": "https://ipdata.co/flags/us.png",
    "emoji_flag": "\ud83c\uddfa\ud83c\uddf8",
    "emoji_unicode": "U+1F1FA U+1F1F8",
    "is_eu": false,
    "languages": [
        {
            "name": "English",
            "native": "English"
        }
    ],
    "currency": {
        "name": "US Dollar",
        "code": "USD",
        "symbol": "$",
        "native": "$",
        "plural": "US dollars"
    },
    "time_zone": {
        "name": "America/New_York",
        "abbr": "EDT",
        "offset": "-0400",
        "is_dst": true,
        "current_time": "2018-04-19T06:32:30.690963-04:00"
    },
    "threat": {
        "is_tor": false,
        "is_proxy": false,
        "is_anonymous": false,
        "is_known_attacker": false,
        "is_known_abuser": false,
        "is_threat": false,
        "is_bogon": false
    }
}? 

Remove quotes from a character vector in R

Here is one combining noquote and paste:

noquote(paste("Argument is of length zero",sQuote("!"),"and",dQuote("double")))


#[1] Argument is of length zero ‘!’ and “double”

How to tell if JRE or JDK is installed

the computer in question is a Mac.

A macOS-only solution:

/usr/libexec/java_home -v 1.8+ --exec javac -version

Where 1.8+ is Java 1.8 or higher.

Unfortunately, the java_home helper does not set the proper return code, so checking for failure requires parsing the output (e.g. 2>&1 |grep -v "Unable") which varies based on locale.

Note, Java may also exist in /Library/Internet Plug-Ins/JavaAppletPlugin.plugin/Contents/Home/bin, but at time of writing this, I'm unaware of a JRE that installs there which contains javac as well.

Read text file into string. C++ ifstream

getline(fin, buffer, '\n')
where fin is opened file(ifstream object) and buffer is of string/char type where you want to copy line.

Selecting element by data attribute with jQuery

For this to work in Chrome the value must not have another pair of quotes.

It only works, for example, like this:

$('a[data-customerID=22]');

Couldn't connect to server 127.0.0.1:27017

so first you have to remove the mongod.lock file by below command

sudo rm /var/lib/mongodb/mongod.lock

and then restart the mongo service by issuing below command

sudo service mongod restart 

If you can decode JWT, how are they secure?

Let's discuss from the very beginning:

JWT is a very modern, simple and secure approach which extends for Json Web Tokens. Json Web Tokens are a stateless solution for authentication. So there is no need to store any session state on the server, which of course is perfect for restful APIs. Restful APIs should always be stateless, and the most widely used alternative to authentication with JWTs is to just store the user's log-in state on the server using sessions. But then of course does not follow the principle that says that restful APIs should be stateless and that's why solutions like JWT became popular and effective.

So now let's know how authentication actually works with Json Web Tokens. Assuming we already have a registered user in our database. So the user's client starts by making a post request with the username and the password, the application then checks if the user exists and if the password is correct, then the application will generate a unique Json Web Token for only that user.

The token is created using a secret string that is stored on a server. Next, the server then sends that JWT back to the client which will store it either in a cookie or in local storage. enter image description here

Just like this, the user is authenticated and basically logged into our application without leaving any state on the server.

So the server does in fact not know which user is actually logged in, but of course, the user knows that he's logged in because he has a valid Json Web Token which is a bit like a passport to access protected parts of the application.

So again, just to make sure you got the idea. A user is logged in as soon as he gets back his unique valid Json Web Token which is not saved anywhere on the server. And so this process is therefore completely stateless.

Then, each time a user wants to access a protected route like his user profile data, for example. He sends his Json Web Token along with a request, so it's a bit like showing his passport to get access to that route.

Once the request hits the server, our app will then verify if the Json Web Token is actually valid and if the user is really who he says he is, well then the requested data will be sent to the client and if not, then there will be an error telling the user that he's not allowed to access that resource. enter image description here

All this communication must happen over https, so secure encrypted Http in order to prevent that anyone can get access to passwords or Json Web Tokens. Only then we have a really secure system.

enter image description here

So a Json Web Token looks like left part of this screenshot which was taken from the JWT debugger at jwt.io. So essentially, it's an encoding string made up of three parts. The header, the payload and the signature Now the header is just some metadata about the token itself and the payload is the data that we can encode into the token, any data really that we want. So the more data we want to encode here the bigger the JWT. Anyway, these two parts are just plain text that will get encoded, but not encrypted.

So anyone will be able to decode them and to read them, we cannot store any sensitive data in here. But that's not a problem at all because in the third part, so in the signature, is where things really get interesting. The signature is created using the header, the payload, and the secret that is saved on the server.

And this whole process is then called signing the Json Web Token. The signing algorithm takes the header, the payload, and the secret to create a unique signature. So only this data plus the secret can create this signature, all right? Then together with the header and the payload, these signature forms the JWT, which then gets sent to the client. enter image description here

Once the server receives a JWT to grant access to a protected route, it needs to verify it in order to determine if the user really is who he claims to be. In other words, it will verify if no one changed the header and the payload data of the token. So again, this verification step will check if no third party actually altered either the header or the payload of the Json Web Token.

So, how does this verification actually work? Well, it is actually quite straightforward. Once the JWT is received, the verification will take its header and payload, and together with the secret that is still saved on the server, basically create a test signature.

But the original signature that was generated when the JWT was first created is still in the token, right? And that's the key to this verification. Because now all we have to do is to compare the test signature with the original signature. And if the test signature is the same as the original signature, then it means that the payload and the header have not been modified. enter image description here

Because if they had been modified, then the test signature would have to be different. Therefore in this case where there has been no alteration of the data, we can then authenticate the user. And of course, if the two signatures are actually different, well, then it means that someone tampered with the data. Usually by trying to change the payload. But that third party manipulating the payload does of course not have access to the secret, so they cannot sign the JWT. So the original signature will never correspond to the manipulated data. And therefore, the verification will always fail in this case. And that's the key to making this whole system work. It's the magic that makes JWT so simple, but also extremely powerful.

Error: Segmentation fault (core dumped)

There is one more reason for such failure which I came to know when mine failed

  • You might be working with a lot of data and your RAM is full

This might not apply in this case but it also throws the same error and since this question comes up on top for this error, I have added this answer here.

Rounding float in Ruby

what about (2.3465*100).round()/100.0?

Python read JSON file and modify

There is really quite a number of ways to do this and all of the above are in one way or another valid approaches... Let me add a straightforward proposition. So assuming your current existing json file looks is this....

{
     "name":"myname"
}

And you want to bring in this new json content (adding key "id")

{
     "id": "134",
     "name": "myname"
 }

My approach has always been to keep the code extremely readable with easily traceable logic. So first, we read the entire existing json file into memory, assuming you are very well aware of your json's existing key(s).

import json 

# first, get the absolute path to json file
PATH_TO_JSON = 'data.json' #  assuming same directory (but you can work your magic here with os.)

# read existing json to memory. you do this to preserve whatever existing data. 
with open(PATH_TO_JSON,'r') as jsonfile:
    json_content = json.load(jsonfile) # this is now in memory! you can use it outside 'open'

Next, we use the 'with open()' syntax again, with the 'w' option. 'w' is a write mode which lets us edit and write new information to the file. Here s the catch that works for us ::: any existing json with the same target write name will be erased automatically.

So what we can do now, is simply write to the same filename with the new data

# add the id key-value pair (rmbr that it already has the "name" key value)
json_content["id"] = "134"

with open(PATH_TO_JSON,'w') as jsonfile:
    json.dump(json_content, jsonfile, indent=4) # you decide the indentation level

And there you go! data.json should be good to go for an good old POST request

How can I update npm on Windows?

This works fine for me

  1. Run Command Prompt as Administrator

  2. Navigate to the folder containing nodejs (eg. C:\Program Files\nodejs)
  3. Run Powershell -ExecutionPolicy Unrestricted

  4. Run npm-windows-upgrade

  5. This will show list of versions available to install. Just select your desired version by moving up/down key & Press Enter.

    This'll update your npm
  6. To check the current version of npm

    Run npm --version

Command Prompt Screenshot

Extracting the last n characters from a string in R

Try this:

x <- "some text in a string"
n <- 5
substr(x, nchar(x)-n, nchar(x))

It shoudl give:

[1] "string"

How to hide underbar in EditText

android:inputType="textVisiblePassword|textMultiLine" android:background="@android:color/transparent"

...its not the optimal solution but it works.

Spark - Error "A master URL must be set in your configuration" when submitting an app

just add .setMaster("local") to your code as shown below:

val conf = new SparkConf().setAppName("Second").setMaster("local") 

It worked for me ! Happy coding !

Convert integer value to matching Java Enum

You would need to do this manually, by adding a a static map in the class that maps Integers to enums, such as

private static final Map<Integer, PcapLinkType> intToTypeMap = new HashMap<Integer, PcapLinkType>();
static {
    for (PcapLinkType type : PcapLinkType.values()) {
        intToTypeMap.put(type.value, type);
    }
}

public static PcapLinkType fromInt(int i) {
    PcapLinkType type = intToTypeMap.get(Integer.valueOf(i));
    if (type == null) 
        return PcapLinkType.DLT_UNKNOWN;
    return type;
}

Android camera android.hardware.Camera deprecated

Faced with the same issue, supporting older devices via the deprecated camera API and needing the new Camera2 API for both current devices and moving into the future; I ran into the same issues -- and have not found a 3rd party library that bridges the 2 APIs, likely because they are very different, I turned to basic OOP principals.

The 2 APIs are markedly different making interchanging them problematic for client objects expecting the interfaces presented in the old API. The new API has different objects with different methods, built using a different architecture. Got love for Google, but ragnabbit! that's frustrating.

So I created an interface focussing on only the camera functionality my app needs, and created a simple wrapper for both APIs that implements that interface. That way my camera activity doesn't have to care about which platform its running on...

I also set up a Singleton to manage the API(s); instancing the older API's wrapper with my interface for older Android OS devices, and the new API's wrapper class for newer devices using the new API. The singleton has typical code to get the API level and then instances the correct object.

The same interface is used by both wrapper classes, so it doesn't matter if the App runs on Jellybean or Marshmallow--as long as the interface provides my app with what it needs from either Camera API, using the same method signatures; the camera runs in the App the same way for both newer and older versions of Android.

The Singleton can also do some related things not tied to the APIs--like detecting that there is indeed a camera on the device, and saving to the media library.

I hope the idea helps you out.

Get started with Latex on Linux

It depends on your Linux distibution and your preference of editors etc. but I would recommend to start with Kile (a KDE app) as it is easy to learn and installing it should install most of the needed packages for LaTex and PDF generation. Just have a look at the screenshots.

Limit to 2 decimal places with a simple pipe

Currency pipe uses the number one internally for number formatting. So you can use it like this:

{{ number | number : '1.2-2'}}

How do I get the type of a variable?

You can use the typeid operator:

#include <typeinfo>
...
cout << typeid(variable).name() << endl;

How to append one DataTable to another DataTable

Merge takes a DataTable, Load requires an IDataReader - so depending on what your data layer gives you access to, use the required method. My understanding is that Load will internally call Merge, but not 100% sure about that.

If you have two DataTables, use Merge.

Remove Item in Dictionary based on Value

In my case I use this

  var key=dict.FirstOrDefault(m => m.Value == s).Key;
            dict.Remove(key);

Converting a year from 4 digit to 2 digit and back again in C#

I've seen some systems decide that the cutoff is 75; 75+ is 19xx and below is 20xx.

Using the passwd command from within a shell script

Read the wise words from:

I quote:

Nothing you can do in bash can possibly work. passwd(1) does not read from standard input. This is intentional. It is for your protection. Passwords were never intended to be put into programs, or generated by programs. They were intended to be entered only by the fingers of an actual human being, with a functional brain, and never, ever written down anywhere.

Nonetheless, we get hordes of users asking how they can circumvent 35 years of Unix security.

It goes on to explain how you can set your shadow(5) password properly, and shows you the GNU-I-only-care-about-security-if-it-doesn't-make-me-think-too-much-way of abusing passwd(1).

Lastly, if you ARE going to use the silly GNU passwd(1) extension --stdin, do not pass the password putting it on the command line.

echo $mypassword | passwd --stdin # Eternal Sin.
echo "$mypassword" | passwd --stdin # Eternal Sin, but at least you remembered to quote your PE.
passwd --stdin <<< "$mypassword" # A little less insecure, still pretty insecure, though.
passwd --stdin < "passwordfile" # With a password file that was created with a secure `umask(1)`, a little bit secure.

The last is the best you can do with GNU passwd. Though I still wouldn't recommend it.

Putting the password on the command line means anyone with even the remotest hint of access to the box can be monitoring ps or such and steal the password. Even if you think your box is safe; it's something you should really get in the habit of avoiding at all cost (yes, even the cost of doing a bit more trouble getting the job done).

Entry point for Java applications: main(), init(), or run()?

This is a peculiar question because it's not supposed to be a matter of choice.

When you launch the JVM, you specify a class to run, and it is the main() of this class where your program starts.

By init(), I assume you mean the JApplet method. When an applet is launched in the browser, the init() method of the specified applet is executed as the first order of business.

By run(), I assume you mean the method of Runnable. This is the method invoked when a new thread is started.

  • main: program start
  • init: applet start
  • run: thread start

If Eclipse is running your run() method even though you have no main(), then it is doing something peculiar and non-standard, but not infeasible. Perhaps you should post a sample class that you've been running this way.

Tab separated values in awk

Make sure they're really tabs! In bash, you can insert a tab using C-v TAB

$ echo "LOAD_SETTLED    LOAD_INIT       2011-01-13 03:50:01" | awk -F$'\t' '{print $1}'
LOAD_SETTLED

How to clear Tkinter Canvas?

Yes, I believe you are creating thousands of objects. If you're looking for an easy way to delete a bunch of them at once, use canvas tags described here. This lets you perform the same operation (such as deletion) on a large number of objects.

Convert comma separated string of ints to int array

Let us assume that you will be reading the string from the console. Import System.Linq and try this one:

int[] input = Console.ReadLine()
            .Split(',', StringSplitOptions.RemoveEmptyEntries)
            .Select(int.Parse)
            .ToArray();

removing table border

border-spacing: 0; should work as well

Accessing members of items in a JSONArray with Java

In case it helps someone else, I was able to convert to an array by doing something like this,

JSONObject jsonObject = (JSONObject)new JSONParser().parse(jsonString);
((JSONArray) jsonObject).toArray()

...or you should be able to get the length

((JSONArray) myJsonArray).toArray().length

Set margins in a LinearLayout programmatically

 MarginLayoutParams layoutParams = (MarginLayoutParams) getLayoutParams();
 layoutParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);

os.walk without digging into directories below

I think the solution is actually very simple.

use

break

to only do first iteration of the for loop, there must be a more elegant way.

for root, dirs, files in os.walk(dir_name):
    for f in files:
        ...
        ...
    break
...

The first time you call os.walk, it returns tulips for the current directory, then on next loop the contents of the next directory.

Take original script and just add a break.

def _dir_list(self, dir_name, whitelist):
    outputList = []
    for root, dirs, files in os.walk(dir_name):
        for f in files:
            if os.path.splitext(f)[1] in whitelist:
                outputList.append(os.path.join(root, f))
            else:
                self._email_to_("ignore")
        break
    return outputList

while ($row = mysql_fetch_array($result)) - how many loops are being performed?

For the first one: your program will go through the loop once for every row in the result set returned by the query. You can know in advance how many results there are by using mysql_num_rows().

For the second one: this time you are only using one row of the result set and you are doing something for each of the columns. That's what the foreach language construct does: it goes through the body of the loop for each entry in the array $row. The number of times the program will go through the loop is knowable in advance: it will go through once for every column in the result set (which presumably you know, but if you need to determine it you can use count($row)).

How to push changes to github after jenkins build completes?

Found an answer myself, this blog helped: http://thingsyoudidntknowaboutjenkins.tumblr.com/post/23596855946/git-plugin-part-3

Basically need to execute:

git checkout master

before modifying any files

then

git commit -am "Updated version number"

after modified files

and then use post build action of Git Publisher with an option of Merge Results which will push changes to github on successful build.

Confirm deletion in modal / dialog using Twitter Bootstrap?

Following solution is better than bootbox.js, because

  • It can do everything bootbox.js can do;
  • The use syntax is simpler
  • It allows you to elegantly control the color of your message using "error", "warning" or "info"
  • Bootbox is 986 lines long, mine only 110 lines long

digimango.messagebox.js:

_x000D_
_x000D_
const dialogTemplate = '\_x000D_
    <div class ="modal" id="digimango_messageBox" role="dialog">\_x000D_
        <div class ="modal-dialog">\_x000D_
            <div class ="modal-content">\_x000D_
                <div class ="modal-body">\_x000D_
                    <p class ="text-success" id="digimango_messageBoxMessage">Some text in the modal.</p>\_x000D_
                    <p><textarea id="digimango_messageBoxTextArea" cols="70" rows="5"></textarea></p>\_x000D_
                </div>\_x000D_
                <div class ="modal-footer">\_x000D_
                    <button type="button" class ="btn btn-primary" id="digimango_messageBoxOkButton">OK</button>\_x000D_
                    <button type="button" class ="btn btn-default" data-dismiss="modal" id="digimango_messageBoxCancelButton">Cancel</button>\_x000D_
                </div>\_x000D_
            </div>\_x000D_
        </div>\_x000D_
    </div>';_x000D_
_x000D_
_x000D_
// See the comment inside function digimango_onOkClick(event) {_x000D_
var digimango_numOfDialogsOpened = 0;_x000D_
_x000D_
_x000D_
function messageBox(msg, significance, options, actionConfirmedCallback) {_x000D_
    if ($('#digimango_MessageBoxContainer').length == 0) {_x000D_
        var iDiv = document.createElement('div');_x000D_
        iDiv.id = 'digimango_MessageBoxContainer';_x000D_
        document.getElementsByTagName('body')[0].appendChild(iDiv);_x000D_
        $("#digimango_MessageBoxContainer").html(dialogTemplate);_x000D_
    }_x000D_
_x000D_
    var okButtonName, cancelButtonName, showTextBox, textBoxDefaultText;_x000D_
_x000D_
    if (options == null) {_x000D_
        okButtonName = 'OK';_x000D_
        cancelButtonName = null;_x000D_
        showTextBox = null;_x000D_
        textBoxDefaultText = null;_x000D_
    } else {_x000D_
        okButtonName = options.okButtonName;_x000D_
        cancelButtonName = options.cancelButtonName;_x000D_
        showTextBox = options.showTextBox;_x000D_
        textBoxDefaultText = options.textBoxDefaultText;_x000D_
    }_x000D_
_x000D_
    if (showTextBox == true) {_x000D_
        if (textBoxDefaultText == null)_x000D_
            $('#digimango_messageBoxTextArea').val('');_x000D_
        else_x000D_
            $('#digimango_messageBoxTextArea').val(textBoxDefaultText);_x000D_
_x000D_
        $('#digimango_messageBoxTextArea').show();_x000D_
    }_x000D_
    else_x000D_
        $('#digimango_messageBoxTextArea').hide();_x000D_
_x000D_
    if (okButtonName != null)_x000D_
        $('#digimango_messageBoxOkButton').html(okButtonName);_x000D_
    else_x000D_
        $('#digimango_messageBoxOkButton').html('OK');_x000D_
_x000D_
    if (cancelButtonName == null)_x000D_
        $('#digimango_messageBoxCancelButton').hide();_x000D_
    else {_x000D_
        $('#digimango_messageBoxCancelButton').show();_x000D_
        $('#digimango_messageBoxCancelButton').html(cancelButtonName);_x000D_
    }_x000D_
_x000D_
    $('#digimango_messageBoxOkButton').unbind('click');_x000D_
    $('#digimango_messageBoxOkButton').on('click', { callback: actionConfirmedCallback }, digimango_onOkClick);_x000D_
_x000D_
    $('#digimango_messageBoxCancelButton').unbind('click');_x000D_
    $('#digimango_messageBoxCancelButton').on('click', digimango_onCancelClick);_x000D_
_x000D_
    var content = $("#digimango_messageBoxMessage");_x000D_
_x000D_
    if (significance == 'error')_x000D_
        content.attr('class', 'text-danger');_x000D_
    else if (significance == 'warning')_x000D_
        content.attr('class', 'text-warning');_x000D_
    else_x000D_
        content.attr('class', 'text-success');_x000D_
_x000D_
    content.html(msg);_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $("#digimango_messageBox").modal();_x000D_
_x000D_
    digimango_numOfDialogsOpened++;_x000D_
}_x000D_
_x000D_
function digimango_onOkClick(event) {_x000D_
    // JavaScript's nature is unblocking. So the function call in the following line will not block,_x000D_
    // thus the last line of this function, which is to hide the dialog, is executed before user_x000D_
    // clicks the "OK" button on the second dialog shown in the callback. Therefore we need to count_x000D_
    // how many dialogs is currently showing. If we know there is still a dialog being shown, we do_x000D_
    // not execute the last line in this function._x000D_
    if (typeof (event.data.callback) != 'undefined')_x000D_
        event.data.callback($('#digimango_messageBoxTextArea').val());_x000D_
_x000D_
    digimango_numOfDialogsOpened--;_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $('#digimango_messageBox').modal('hide');_x000D_
}_x000D_
_x000D_
function digimango_onCancelClick() {_x000D_
    digimango_numOfDialogsOpened--;_x000D_
_x000D_
    if (digimango_numOfDialogsOpened == 0)_x000D_
        $('#digimango_messageBox').modal('hide');_x000D_
}
_x000D_
_x000D_
_x000D_

To use digimango.messagebox.js:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
    <title>A useful generic message box</title>_x000D_
    <meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />_x000D_
_x000D_
    <link rel="stylesheet" type="text/css" href="~/Content/bootstrap.min.css" media="screen" />_x000D_
    <script src="~/Scripts/jquery-1.10.2.min.js" type="text/javascript"></script>_x000D_
    <script src="~/Scripts/bootstrap.js" type="text/javascript"></script>_x000D_
    <script src="~/Scripts/bootbox.js" type="text/javascript"></script>_x000D_
_x000D_
    <script src="~/Scripts/digimango.messagebox.js" type="text/javascript"></script>_x000D_
_x000D_
_x000D_
    <script type="text/javascript">_x000D_
        function testAlert() {_x000D_
            messageBox('Something went wrong!', 'error');_x000D_
        }_x000D_
_x000D_
        function testAlertWithCallback() {_x000D_
            messageBox('Something went wrong!', 'error', null, function () {_x000D_
                messageBox('OK clicked.');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testConfirm() {_x000D_
            messageBox('Do you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' }, function () {_x000D_
                messageBox('Are you sure you want to proceed?', 'warning', { okButtonName: 'Yes', cancelButtonName: 'No' });_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testPrompt() {_x000D_
            messageBox('How do you feel now?', 'normal', { showTextBox: true }, function (userInput) {_x000D_
                messageBox('User entered "' + userInput + '".');_x000D_
            });_x000D_
        }_x000D_
_x000D_
        function testPromptWithDefault() {_x000D_
            messageBox('How do you feel now?', 'normal', { showTextBox: true, textBoxDefaultText: 'I am good!' }, function (userInput) {_x000D_
                messageBox('User entered "' + userInput + '".');_x000D_
            });_x000D_
        }_x000D_
_x000D_
    </script>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
    <a href="#" onclick="testAlert();">Test alert</a> <br/>_x000D_
    <a href="#" onclick="testAlertWithCallback();">Test alert with callback</a> <br />_x000D_
    <a href="#" onclick="testConfirm();">Test confirm</a> <br/>_x000D_
    <a href="#" onclick="testPrompt();">Test prompt</a><br />_x000D_
    <a href="#" onclick="testPromptWithDefault();">Test prompt with default text</a> <br />_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_ enter image description here

How to grep a text file which contains some binary data?

You can use "strings" to extract strings from a binary file, for example

strings binary.file | grep foo

How can I remove an entry in global configuration with git config?

Try these commands to remove all users' usernames and emails.

git config --global --unset-all user.name
git config --global --unset-all user.email

How to count digits, letters, spaces for a string in Python?

Ignoring anything else that may or may not be correct with your "revised code", the issue causing the error currently quoted in your question is caused by calling the "count" function with an undefined variable because your didn't quote the string.

  • count(thisisastring222) looks for a variable called thisisastring222 to pass to the function called count. For this to work you would have to have defined the variable earlier (e.g. with thisisastring222 = "AStringWith1NumberInIt.") then your function will do what you want with the contents of the value stored in the variable, not the name of the variable.
  • count("thisisastring222") hardcodes the string "thisisastring222" into the call, meaning that the count function will work with the exact string passed to it.

To fix your call to your function, just add quotes around asdfkasdflasdfl222 changing count(asdfkasdflasdfl222) to count("asdfkasdflasdfl222").

As far as the actual question "How to count digits, letters, spaces for a string in Python", at a glance the rest of the "revised code" looks OK except that the return line is not returning the same variables you've used in the rest of the code. To fix it without changing anything else in the code, change number and word to digit and letters, making return number,word,space,other into return digit,letters,space,other, or better yet return (digit, letters, space, other) to match current behavior while also using better coding style and being explicit as to what type of value is returned (in this case, a tuple).

Docker: Multiple Dockerfiles in project

Use docker-compose and multiple Dockerfile in separate directories

Don't rename your Dockerfile to Dockerfile.db or Dockerfile.web, it may not be supported by your IDE and you will lose syntax highlighting.

As Kingsley Uchnor said, you can have multiple Dockerfile, one per directory, which represent something you want to build.

I like to have a docker folder which holds each applications and their configuration. Here's an example project folder hierarchy for a web application that has a database.

docker-compose.yml
docker
+-- web
¦   +-- Dockerfile
+-- db
    +-- Dockerfile

docker-compose.yml example:

version: '3'
services:
  web:
    # will build ./docker/web/Dockerfile
    build: ./docker/web
    ports:
     - "5000:5000"
    volumes:
     - .:/code
  db:
    # will build ./docker/db/Dockerfile
    build: ./docker/db
    ports:
      - "3306:3306"
  redis:
    # will use docker hub's redis prebuilt image from here:
    # https://hub.docker.com/_/redis/
    image: "redis:alpine"

docker-compose command line usage example:

# The following command will create and start all containers in the background
# using docker-compose.yml from current directory
docker-compose up -d

# get help
docker-compose --help

In case you need files from previous folders when building your Dockerfile

You can still use the above solution and place your Dockerfile in a directory such as docker/web/Dockerfile, all you need is to set the build context in your docker-compose.yml like this:

version: '3'
services:
  web:
    build:
      context: .
      dockerfile: ./docker/web/Dockerfile
    ports:
     - "5000:5000"
    volumes:
     - .:/code

This way, you'll be able to have things like this:

config-on-root.ini
docker-compose.yml
docker
+-- web
    +-- Dockerfile
    +-- some-other-config.ini

and a ./docker/web/Dockerfile like this:

FROM alpine:latest

COPY config-on-root.ini /
COPY docker/web/some-other-config.ini /

Here are some quick commands from tldr docker-compose. Make sure you refer to official documentation for more details.

Email validation using jQuery

I take this code from jqvalidate version 1.11.0 and implemented in the version 1.16.0 as aditional method. It works

            jQuery.validator.addMethod("strictemail", function(value, element) {
                    var valid = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i.test(value);
                    return valid;
                }, "Escribe un correo v\u00e1lido"
            );

And and in the email rule

            'correo': {
                required: 'Por favor ingresa tu correo',
                email: 'Escribe un correo v\u00e1lido',
                strictemail:'Escribe un correo v\u00e1lido'
            }

How to create an Excel File with Nodejs?

install exceljs

npm i exceljs --save

import exceljs

var Excel = require('exceljs');
var workbook = new Excel.Workbook();

create workbook

var options = {
                filename: __dirname+'/Reports/'+reportName,
                useStyles: true,
                useSharedStrings: true
            };

            var workbook = new Excel.stream.xlsx.WorkbookWriter(options);

after create worksheet

var worksheet = workbook.addWorksheet('Rate Sheet',{properties:{tabColor:{argb:'FFC0000'}}});

in worksheet.column array you pass column name in header and array key pass in key

worksheet.columns = [
            { header: 'column name', key: 'array key', width: 35},
            { header: 'column name', key: 'array key', width: 35},
            { header: 'column name', key: 'array key', width: 20},

            ];

after using forEach loop append row one by one in exel file

array.forEach(function(row){ worksheet.addRow(row); })

you can also perfome loop on each exel row and cell

worksheet.eachRow(function(row, rowNumber) {
    console.log('Row ' + rowNumber + ' = ' + JSON.stringify(row.values));
});
row.eachCell(function(cell, colNumber) {
    console.log('Cell ' + colNumber + ' = ' + cell.value);
});

Create a custom View by inflating a layout?

A bit old, but I thought sharing how I'd do it, based on chubbsondubs' answer: I use FrameLayout (see Documentation), since it is used to contain a single view, and inflate into it the view from the xml.

Code following:

public class MyView extends FrameLayout {
    public MyView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        initView();
    }

    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public MyView(Context context) {
        super(context);
        initView();
    }

    private void initView() {
        inflate(getContext(), R.layout.my_view_layout, this);
    }
}

How can I debug a Perl script?

To run your script under the Perl debugger you should use the -d switch:

perl -d script.pl

But Perl is flexible. It supplies some hooks, and you may force the debugger to work as you want

So to use different debuggers you may do:

perl -d:DebugHooks::Terminal script.pl
# OR
perl -d:Trepan script.pl

Look these modules here and here.

There are several most interesting Perl modules that hook into Perl debugger internals: Devel::NYTProf and Devel::Cover

And many others.

Why can't I use the 'await' operator within the body of a lock statement?

I assume this is either difficult or impossible for the compiler team to implement for some reason.

No, it is not at all difficult or impossible to implement -- the fact that you implemented it yourself is a testament to that fact. Rather, it is an incredibly bad idea and so we don't allow it, so as to protect you from making this mistake.

call to Monitor.Exit within ExitDisposable.Dispose seems to block indefinitely (most of the time) causing deadlocks as other threads attempt to acquire the lock. I suspect the unreliability of my work around and the reason await statements are not allowed in lock statement are somehow related.

Correct, you have discovered why we made it illegal. Awaiting inside a lock is a recipe for producing deadlocks.

I'm sure you can see why: arbitrary code runs between the time the await returns control to the caller and the method resumes. That arbitrary code could be taking out locks that produce lock ordering inversions, and therefore deadlocks.

Worse, the code could resume on another thread (in advanced scenarios; normally you pick up again on the thread that did the await, but not necessarily) in which case the unlock would be unlocking a lock on a different thread than the thread that took out the lock. Is that a good idea? No.

I note that it is also a "worst practice" to do a yield return inside a lock, for the same reason. It is legal to do so, but I wish we had made it illegal. We're not going to make the same mistake for "await".

How to get first item from a java.util.Set?

To Access the element you need to get an iterator . But Iterator does not guarantee in a particular order unless it is some Exceptional case. so it is not sure to get the first Element.

Sorting a set of values

From a comment:

I want to sort each set.

That's easy. For any set s (or anything else iterable), sorted(s) returns a list of the elements of s in sorted order:

>>> s = set(['0.000000000', '0.009518000', '10.277200999', '0.030810999', '0.018384000', '4.918560000'])
>>> sorted(s)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '10.277200999', '4.918560000']

Note that sorted is giving you a list, not a set. That's because the whole point of a set, both in mathematics and in almost every programming language,* is that it's not ordered: the sets {1, 2} and {2, 1} are the same set.


You probably don't really want to sort those elements as strings, but as numbers (so 4.918560000 will come before 10.277200999 rather than after).

The best solution is most likely to store the numbers as numbers rather than strings in the first place. But if not, you just need to use a key function:

>>> sorted(s, key=float)
['0.000000000', '0.009518000', '0.018384000', '0.030810999', '4.918560000', '10.277200999']

For more information, see the Sorting HOWTO in the official docs.


* See the comments for exceptions.

How to execute an .SQL script file using c#

I managed to work out the answer by reading the manual :)

This extract from the MSDN

The code example avoids a deadlock condition by calling p.StandardOutput.ReadToEnd before p.WaitForExit. A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardOutput stream.

There is a similar issue when you read all text from both the standard output and standard error streams. For example, the following C# code performs a read operation on both streams.

Turns the code into this;

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "sqlplus";
p.StartInfo.Arguments = string.Format("xxx/xxx@{0} @{1}", in_database, s);

bool started = p.Start();
// important ... read stream input before waiting for exit.
// this avoids deadlock.
string output = p.StandardOutput.ReadToEnd();

p.WaitForExit();

Console.WriteLine(output);

if (p.ExitCode != 0)
{
    Console.WriteLine( string.Format("*** Failed : {0} - {1}",s,p.ExitCode));
    break;
}

Which now exits correctly.

Differences between Emacs and Vim

Benefits of Emacs

  • Emacs has both non-modal interface (by default) and modal one (e.g. it can emulate vim and vi through Evil, Viper, or Vimpulse).

  • One of the most ported computer programs. It runs in text mode and under graphical user interfaces on a wide variety of operating systems, including most Unix-like systems (Linux, the various BSDs, Solaris, AIX, IRIX, macOSetc.), MS-DOS, Microsoft Windows, AmigaOS, and OpenVMS. Unix systems, both free and proprietary, frequently provide Emacs bundled with the operating system.

  • Emacs server architecture allows multiple clients to attach to the same Emacs instance and share the buffer list, kill ring, undo history and other state.

  • Pervasive online help system with keybindings, functions and commands documented on the fly.

  • Extensible and customizable Lisp programming language variant (Emacs Lisp), with features that include:

  • A powerful and extensible file manager (dired), integrated debugger, and a large set of development and other tools.

  • Having every command be an Emacs Lisp function enables commands to DWIM (Do What I Mean) by programmatically responding to past actions and document state. For example, a switch-or-split-window command could switch to another window if one exists, or create one if needed. This cuts down on the number of keystrokes and commands a user must remember.

  • "An OS inside an OS". Emacs Lisp enables Emacs to be programmed far beyond editing features. Even a base install contains several dozen applications, including two web browsers, news readers, several mail agents, four IRC clients, a version of ELIZA, and a variety of games. All of these applications are available anywhere Emacs runs, with the same user interface and functionality. Starting with version 24, Emacs includes a package manager, making it easy to install additional applications including alternate web browsers, EMMS (Emacs Multimedia System), and more. Also available are numerous packages for programming, including some targeted at specific language/library combinations or coding styles.

Benefits of vi-like editors

  • Edit commands are composable
  • Vi has a modal interface (which Emacs can emulate)
  • Historically, vi loads faster than Emacs.
  • While deeply associated with UNIX tradition, it runs on all systems that can implement the standard C library, including UNIX, Linux, AmigaOS, DOS, Windows, Mac, BeOS, OpenVMS, IRIX, AIX, HP-UX, BSD and POSIX-compliant systems.
  • Extensible and customizable through Vim script or APIs for interpreted languages such as Python, Ruby, Perl, and Lua
  • Ubiquitous. Essentially all Unix and Unix-like systems come with vi (or a variant) built-in. Vi (and ex, but not vim) is specified in the POSIX standard.
  • System rescue environments, embedded systems (notably those with busybox) and other constrained environments often include vi, but not emacs.

Source: https://en.wikipedia.org/wiki/Editor_war

Where is HttpContent.ReadAsAsync?

Just right click in your project go Manage NuGet Packages search for Microsoft.AspNet.WebApi.Client install it and you will have access to the extension method.

Select Tag Helper in ASP.NET Core MVC

You can also use IHtmlHelper.GetEnumSelectList.

    // Summary:
    //     Returns a select list for the given TEnum.
    //
    // Type parameters:
    //   TEnum:
    //     Type to generate a select list for.
    //
    // Returns:
    //     An System.Collections.Generic.IEnumerable`1 containing the select list for the
    //     given TEnum.
    //
    // Exceptions:
    //   T:System.ArgumentException:
    //     Thrown if TEnum is not an System.Enum or if it has a System.FlagsAttribute.
    IEnumerable<SelectListItem> GetEnumSelectList<TEnum>() where TEnum : struct;

How to keep the local file or the remote file during merge using Git and the command line?

For the line-end thingie, refer to man git-merge:

--ignore-space-change 
--ignore-all-space 
--ignore-space-at-eol

Be sure to add autocrlf = false and/or safecrlf = false to the windows clone (.git/config)

Using git mergetool

If you configure a mergetool like this:

git config mergetool.cp.cmd '/bin/cp -v "$REMOTE" "$MERGED"'
git config mergetool.cp.trustExitCode true

Then a simple

git mergetool --tool=cp
git mergetool --tool=cp -- paths/to/files.txt
git mergetool --tool=cp -y -- paths/to/files.txt # without prompting

Will do the job

Using simple git commands

In other cases, I assume

git checkout HEAD -- path/to/myfile.txt

should do the trick

Edit to do the reverse (because you screwed up):

git checkout remote/branch_to_merge -- path/to/myfile.txt

What is "android.R.layout.simple_list_item_1"?

Per Arvand:
Eclipse: Simply type android.R.layout.simple_list_item_1 somewhere in code, hold Ctrl, hover over simple_list_item_1, and from the dropdown that appears select Open declaration in layout/simple_list_item_1.xml. It'll direct you to the contents of the XML.

From there, if you then hover over the resulting simple_list_item_1.xml tab in the Editor, you'll see the file is located at C:\Data\applications\Android\android-sdk\platforms\android-19\data\res\layout\simple_list_item_1.xml (or equivalent location for your installation).

"The page you are requesting cannot be served because of the extension configuration." error message

I fixed my issue on Windows 2012 server by Installing ALL WCF Features.

A) Server Manager > Manage[link top left] > Add Roles and Features

B) In Features > .Net Framework 4.5 Features > WCF Services

C) Check (enable) the features. I checked all.

D) Install

Splitting a string at every n-th character

I recently encountered this issue, and here is the solution I came up with

final int LENGTH = 10;
String test = "Here is a very long description, it is going to be past 10";

Map<Integer,StringBuilder> stringBuilderMap = new HashMap<>();
for ( int i = 0; i < test.length(); i++ ) {
    int position = i / LENGTH; // i<10 then 0, 10<=i<19 then 1, 20<=i<30 then 2, etc.

    StringBuilder currentSb = stringBuilderMap.computeIfAbsent( position, pos -> new StringBuilder() ); // find sb, or create one if not present
    currentSb.append( test.charAt( i ) ); // add the current char to our sb
}

List<String> comments = stringBuilderMap.entrySet().stream()
        .sorted( Comparator.comparing( Map.Entry::getKey ) )
        .map( entrySet -> entrySet.getValue().toString() )
        .collect( Collectors.toList() );
//done



// here you can see the data
comments.forEach( cmt -> System.out.println( String.format( "'%s' ... length= %d", cmt, cmt.length() ) ) );
// PRINTS:
// 'Here is a ' ... length= 10
// 'very long ' ... length= 10
// 'descriptio' ... length= 10
// 'n, it is g' ... length= 10
// 'oing to be' ... length= 10
// ' past 10' ... length= 8

// make sure they are equal
String joinedString = String.join( "", comments );
System.out.println( "\nOriginal strings are equal " + joinedString.equals( test ) );
// PRINTS: Original strings are equal true

Operation is not valid due to the current state of the object, when I select a dropdown list

I know an answer has already been accepted for this problem but someone asked in the comments if there was a solution that could be done outside the web.config. I had a ListView producing the exact same error and setting EnableViewState to false resolved this problem for me.

Count the number of commits on a Git branch

To see total no of commits you can do as Peter suggested above

git rev-list --count HEAD

And if you want to see number of commits made by each person try this line

git shortlog -s -n

will generate output like this

135  Tom Preston-Werner
15  Jack Danger Canty
10  Chris Van Pelt
7  Mark Reid
6  remi

Why does my Eclipse keep not responding?

This may help

In your eclipse,

1) Go to Help

2) Click Eclipse marketplace

3) search - optimizer

install "optimizer for eclipse"

enter image description here

MVC which submit button has been pressed

you can identify your button from there name tag like below, You need to check like this in you controller

if (Request.Form["submit"] != null)
{
//Write your code here
}
else if (Request.Form["process"] != null)
{
//Write your code here
}

ImportError: No module named - Python

For the Python module import to work, you must have "src" in your path, not "gen_py/lib".

When processing an import like import gen_py.lib, it looks for a module gen_py, then looks for a submodule lib.

As the module gen_py won't be in "../gen_py/lib" (it'll be in ".."), the path you added will do nothing to help the import process.

Depending on where you're running it from, try adding the relative path to the "src" folder. Perhaps it's sys.path.append('..'). You might also have success running the script while inside the src folder directly, via relative paths like python main/MyServer.py

How to change the background color on a Java panel?

I am assuming that we are dealing with a JFrame? The visible portion in the content pane - you have to use jframe.getContentPane().setBackground(...);

Flutter Circle Design

you can use decoration like this :

   Container(
                    width: 60,
                    height: 60,
                    child: Icon(CustomIcons.option, size: 20,),
                    decoration: BoxDecoration(
                        shape: BoxShape.circle,
                        color: Color(0xFFe0f2f1)),
                  )

Now you have circle shape and Icon on it.

enter image description here

numpy max vs amax vs maximum

np.max is just an alias for np.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis argument and will find the maximum value along an axis of the input array (returning a new array).

>>> a = np.array([[0, 1, 6],
                  [2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])

The default behaviour of np.maximum is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:

>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])

But np.maximum is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):

>>> d = np.array([2, 0, 3, -4, -2, 7, 9])
>>> np.maximum.accumulate(d)
array([2, 2, 3, 3, 3, 7, 9])

This is not possible with np.max.

You can make np.maximum imitate np.max to a certain extent when using np.maximum.reduce:

>>> np.maximum.reduce(d)
9
>>> np.max(d)
9

Basic testing suggests the two approaches are comparable in performance; and they should be, as np.max() actually calls np.maximum.reduce to do the computation.

`&mdash;` or `&#8212;` is there any difference in HTML output?

They are exactly the same character. See: http://en.wikipedia.org/wiki/Dash

Barring browser bugs they will display the same in all cases, so the only difference would be concerning code readability, which would point to &mdash;.

Or, if you are using UTF-8 as a charset in your HTML document, you could enter the character directly. That would also display exactly the same.

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

Resize svg when window is resized in d3.js

_x000D_
_x000D_
d3.select("div#chartId")
   .append("div")
   // Container class to make it responsive.
   .classed("svg-container", true) 
   .append("svg")
   // Responsive SVG needs these 2 attributes and no width and height attr.
   .attr("preserveAspectRatio", "xMinYMin meet")
   .attr("viewBox", "0 0 600 400")
   // Class to make it responsive.
   .classed("svg-content-responsive", true)
   // Fill with a rectangle for visualization.
   .append("rect")
   .classed("rect", true)
   .attr("width", 600)
   .attr("height", 400);
_x000D_
.svg-container {
  display: inline-block;
  position: relative;
  width: 100%;
  padding-bottom: 100%; /* aspect ratio */
  vertical-align: top;
  overflow: hidden;
}
.svg-content-responsive {
  display: inline-block;
  position: absolute;
  top: 10px;
  left: 0;
}

svg .rect {
  fill: gold;
  stroke: steelblue;
  stroke-width: 5px;
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<div id="chartId"></div>
_x000D_
_x000D_
_x000D_

What is the best way to access redux store outside a react component?

export my store variable

export const store = createStore(rootReducer, applyMiddleware(ReduxThunk));

in action file or your file need them import this (store)

import {store} from "./path...";

this step get sate from store variable with function

const state = store.getState();

and get all of state your app

How to check if a file exists in Documents folder?

NSURL.h provided - (BOOL)checkResourceIsReachableAndReturnError:(NSError **)error to do so

NSURL *fileURL = [NSURL fileURLWithPath:NSHomeDirectory()];
NSError * __autoreleasing error = nil;
if ([fileURL checkResourceIsReachableAndReturnError:&error]) {
    NSLog(@"%@ exists", fileURL);
} else {
    NSLog(@"%@ existence checking error: %@", fileURL, error);
}

Or using Swift

if let url = URL(fileURLWithPath: NSHomeDirectory()) {
    do {
        let result = try url.checkResourceIsReachable()
    } catch {
        print(error)
    }
}

Angular2 change detection: ngOnChanges not firing for nested object

If the data comes from an external library you might need to run the data upate statement within zone.run(...). Inject zone: NgZone for this. If you can run the instantiation of the external library within zone.run() already, then you might not need zone.run() later.

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

Nothing built in, my solution would be as follows :

function tConvert (time) {
  // Check correct time format and split into components
  time = time.toString ().match (/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];

  if (time.length > 1) { // If time format correct
    time = time.slice (1);  // Remove full string match value
    time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM
    time[0] = +time[0] % 12 || 12; // Adjust hours
  }
  return time.join (''); // return adjusted time or original string
}

tConvert ('18:00:00');

This function uses a regular expression to validate the time string and to split it into its component parts. Note also that the seconds in the time may optionally be omitted. If a valid time was presented, it is adjusted by adding the AM/PM indication and adjusting the hours.

The return value is the adjusted time if a valid time was presented or the original string.

Working example

_x000D_
_x000D_
(function() {_x000D_
_x000D_
  function tConvert(time) {_x000D_
    // Check correct time format and split into components_x000D_
    time = time.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [time];_x000D_
_x000D_
    if (time.length > 1) { // If time format correct_x000D_
      time = time.slice(1); // Remove full string match value_x000D_
      time[5] = +time[0] < 12 ? 'AM' : 'PM'; // Set AM/PM_x000D_
      time[0] = +time[0] % 12 || 12; // Adjust hours_x000D_
    }_x000D_
    return time.join(''); // return adjusted time or original string_x000D_
  }_x000D_
_x000D_
  var tel = document.getElementById('tests');_x000D_
_x000D_
  tel.innerHTML = tel.innerHTML.split(/\r*\n|\n\r*|\r/).map(function(v) {_x000D_
    return v ? v + ' => "' + tConvert(v.trim()) + '"' : v;_x000D_
  }).join('\n');_x000D_
})();
_x000D_
<h3>tConvert tests : </h3>_x000D_
<pre id="tests">_x000D_
  18:00:00_x000D_
  18:00_x000D_
  00:00_x000D_
  11:59:01_x000D_
  12:00:00_x000D_
  13:01:57_x000D_
  24:00_x000D_
  sdfsdf_x000D_
  12:61:54_x000D_
</pre>
_x000D_
_x000D_
_x000D_

What do Clustered and Non clustered index actually mean?

Clustered Index: Primary Key constraint creates clustered Index automatically if no clustered Index already exists on the table. Actual data of clustered index can be stored at leaf level of Index.

Non Clustered Index: Actual data of non clustered index is not directly found at leaf node, instead it has to take an additional step to find because it has only values of row locators pointing towards actual data. Non clustered Index can't be sorted as clustered index. There can be multiple non clustered indexes per table, actually it depends on the sql server version we are using. Basically Sql server 2005 allows 249 Non Clustered Indexes and for above versions like 2008, 2016 it allows 999 Non Clustered Indexes per table.

Razor View Engine : An expression tree may not contain a dynamic operation

In this link explain about @model, see a excerpt:

@model (lowercase "m") is a reserved keyword in Razor views to declare the model type at the top of your view. You have put the namespace too, e.g.: @model MyNamespace.Models.MyModel

Later in the file, you can reference the attribute you want with @Model.Attribute (uppercase "M").

Undo git pull, how to bring repos to old state

it works first use: git reflog

find your SHA of your previus state and make (HEAD@{1} is an example)

git reset --hard HEAD@{1}

bash string equality

There's no difference, == is a synonym for = (for the C/C++ people, I assume). See here, for example.

You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.

What are the differences between a HashMap and a Hashtable in Java?

Based on the info here, I'd recommend going with HashMap. I think the biggest advantage is that Java will prevent you from modifying it while you are iterating over it, unless you do it through the iterator.

Required attribute HTML5

Note that

<input type="text" id="car" required="true" />

is wrong, it should be one of

<input type="text" id="car" required />
<input type="text" id="car" required="" />
<input type="text" id="car" required='' />
<input type="text" id="car" required=required />
<input type="text" id="car" required="required" />
<input type="text" id="car" required='required' />

This is because the true value suggests that the false value will make the form control optional, which is not the case.

Verify ImageMagick installation

Remember that after installing Imagick (or indeed any PHP module) you need to restart your web server and/or php-fpm if you're using it, for the module to appear in phpinfo().

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

No, there should be an .exe file (vs_Community_xxxxx.exe) directly in you f:\vs2017c directory !

Just start from the this directory, not from a longer path. the packages downloaded are partly having very long path names, it fails if you start from a longer path.

Remove the title bar in Windows Forms

You can set the Property FormBorderStyle to none in the designer, or in code:

this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;

Convert base64 string to ArrayBuffer

Just found base64-arraybuffer, a small npm package with incredibly high usage, 5M downloads last month (2017-08).

https://www.npmjs.com/package/base64-arraybuffer

For anyone looking for something of a best standard solution, this may be it.

Default property value in React component using TypeScript

For those having optional props that need default values. Credit here :)

interface Props {
  firstName: string;
  lastName?: string;
}

interface DefaultProps {
  lastName: string;
}

type PropsWithDefaults = Props & DefaultProps;

export class User extends React.Component<Props> {
  public static defaultProps: DefaultProps = {
    lastName: 'None',
  }

  public render () {
    const { firstName, lastName } = this.props as PropsWithDefaults;

    return (
      <div>{firstName} {lastName}</div>
    )
  }
}

jquery clone div and append it after specific div

try this out

$("div[id^='car']:last").after($('#car2').clone());

What are the ways to sum matrix elements in MATLAB?

Another answer for the first question is to use one for loop and perform linear indexing into the array using the function NUMEL to get the total number of elements:

total = 0;
for i = 1:numel(A)
  total = total+A(i);
end

Select info from table where row has max date

You can use a window MAX() like this:

SELECT
  *, 
  max_date = MAX(date) OVER (PARTITION BY group)
FROM table

to get max dates per group alongside other data:

group  date      cash  checks  max_date
-----  --------  ----  ------  --------
1      1/1/2013  0     0       1/3/2013
2      1/1/2013  0     800     1/1/2013
1      1/3/2013  0     700     1/3/2013
3      1/1/2013  0     600     1/5/2013
1      1/2/2013  0     400     1/3/2013
3      1/5/2013  0     200     1/5/2013

Using the above output as a derived table, you can then get only rows where date matches max_date:

SELECT
  group,
  date,
  checks
FROM (
  SELECT
    *, 
    max_date = MAX(date) OVER (PARTITION BY group)
  FROM table
) AS s
WHERE date = max_date
;

to get the desired result.

Basically, this is similar to @Twelfth's suggestion but avoids a join and may thus be more efficient.

You can try the method at SQL Fiddle.

Return 0 if field is null in MySQL

You can use coalesce(column_name,0) instead of just column_name. The coalesce function returns the first non-NULL value in the list.

I should mention that per-row functions like this are usually problematic for scalability. If you think your database may get to be a decent size, it's often better to use extra columns and triggers to move the cost from the select to the insert/update.

This amortises the cost assuming your database is read more often than written (and most of them are).

How do I prevent mails sent through PHP mail() from going to spam?

Try PHP Mailer library.
Or Send mail through SMTP filter it before sending it.
Also Try to give all details like FROM, return-path.

How to insert strings containing slashes with sed?

Great answer from Anonymous. \ solved my problem when I tried to escape quotes in HTML strings.

So if you use sed to return some HTML templates (on a server), use double backslash instead of single:

var htmlTemplate = "<div style=\\"color:green;\\"></div>";

Parse HTML in Android

String tmpHtml = "<html>a whole bunch of html stuff</html>";
String htmlTextStr = Html.fromHtml(tmpHtml).toString();

PHP regular expressions: No ending delimiter '^' found in

You can use T-Regx library, that doesn't need delimiters

pattern('^([0-9]+)$')->match($input);

Convert string to JSON array

If having following JSON from web service, Json Array as a response :

       [3]
 0:  {
 id: 2
 name: "a561137"
 password: "test"
 firstName: "abhishek"
 lastName: "ringsia"
 organization: "bbb"
    }-
1:  {
 id: 3
 name: "a561023"
 password: "hello"
 firstName: "hello"
  lastName: "hello"
  organization: "hello"
 }-
 2:  {
  id: 4
  name: "a541234"
  password: "hello"
  firstName: "hello"
  lastName: "hello"
  organization: "hello"
    }

have To Accept it first as a Json Array ,then while reading its Object have to use Object Mapper.readValue ,because Json Object Still in String .

      List<User> list = new ArrayList<User>();
      JSONArray jsonArr = new JSONArray(response);


      for (int i = 0; i < jsonArr.length(); i++) {
        JSONObject jsonObj = jsonArr.getJSONObject(i);
         ObjectMapper mapper = new ObjectMapper();
        User usr = mapper.readValue(jsonObj.toString(), User.class);      
        list.add(usr);

    }

mapper.read is correct function ,if u use mapper.convert(param,param) . It will give u error .

Printing Batch file results to a text file

There's nothing wrong with your redirection of standard out to a file. Move and mkdir commands do not output anything. If you really need to have a log trail of those commands, then you'll need to explicitly echo to standard out indicating what you just executed.

The batch file, example:

@ECHO OFF
cd bob
ECHO I just did this: cd bob

Run from command line:

myfile.bat >> out.txt

or

myfile.bat > out.txt

Deleting all pending tasks in celery / rabbitmq

In Celery 3+:

CLI:

$ celery -A proj purge

Programatically:

>>> from proj.celery import app
>>> app.control.purge()

http://docs.celeryproject.org/en/latest/faq.html#how-do-i-purge-all-waiting-tasks

Why is HttpClient BaseAddress not working?

It turns out that, out of the four possible permutations of including or excluding trailing or leading forward slashes on the BaseAddress and the relative URI passed to the GetAsync method -- or whichever other method of HttpClient -- only one permutation works. You must place a slash at the end of the BaseAddress, and you must not place a slash at the beginning of your relative URI, as in the following example.

using (var handler = new HttpClientHandler())
using (var client = new HttpClient(handler))
{
    client.BaseAddress = new Uri("http://something.com/api/");
    var response = await client.GetAsync("resource/7");
}

Even though I answered my own question, I figured I'd contribute the solution here since, again, this unfriendly behavior is undocumented. My colleague and I spent most of the day trying to fix a problem that was ultimately caused by this oddity of HttpClient.

How do I drop a function if it already exists?

Here's my take on this:

if(object_id(N'[dbo].[fn_Nth_Pos]', N'FN')) is not null
    drop function [dbo].[fn_Nth_Pos];
GO
CREATE FUNCTION [dbo].[fn_Nth_Pos]
(
    @find char, --char to find
    @search varchar(max), --string to process   
    @nth int --occurrence   
)
RETURNS int
AS
BEGIN
    declare @pos int --position of nth occurrence
    --init
    set @pos = 0

    while(@nth > 0)
    begin       
        set @pos = charindex(@find,@search,@pos+1)
        set @nth = @nth - 1
    end 

    return @pos
END
GO

--EXAMPLE
declare @files table(name varchar(max));

insert into @files(name) values('abc_1_2_3_4.gif');
insert into @files(name) values('zzz_12_3_3_45.gif');

select
    f.name,
    dbo.fn_Nth_Pos('_', f.name, 1) as [1st],
    dbo.fn_Nth_Pos('_', f.name, 2) as [2nd],
    dbo.fn_Nth_Pos('_', f.name, 3) as [3rd],
    dbo.fn_Nth_Pos('_', f.name, 4) as [4th]
from 
    @files f;

How to switch databases in psql?

You can connect to a database with \c <database> or \connect <database>.

Convert decimal to hexadecimal in UNIX shell script

echo "obase=16; 34" | bc

If you want to filter a whole file of integers, one per line:

( echo "obase=16" ; cat file_of_integers ) | bc

Calling a java method from c++ in Android

Solution posted by Denys S. in the question post:

I quite messed it up with c to c++ conversion (basically env variable stuff), but I got it working with the following code for C++:

#include <string.h>
#include <stdio.h>
#include <jni.h>

jstring Java_the_package_MainActivity_getJniString( JNIEnv* env, jobject obj){

    jstring jstr = (*env)->NewStringUTF(env, "This comes from jni.");
    jclass clazz = (*env)->FindClass(env, "com/inceptix/android/t3d/MainActivity");
    jmethodID messageMe = (*env)->GetMethodID(env, clazz, "messageMe", "(Ljava/lang/String;)Ljava/lang/String;");
    jobject result = (*env)->CallObjectMethod(env, obj, messageMe, jstr);

    const char* str = (*env)->GetStringUTFChars(env,(jstring) result, NULL); // should be released but what a heck, it's a tutorial :)
    printf("%s\n", str);

    return (*env)->NewStringUTF(env, str);
}

And next code for java methods:

    public class MainActivity extends Activity {
    private static String LIB_NAME = "thelib";

    static {
        System.loadLibrary(LIB_NAME);
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        TextView tv = (TextView) findViewById(R.id.textview);
        tv.setText(this.getJniString());
    }

    // please, let me live even though I used this dark programming technique
    public String messageMe(String text) {
        System.out.println(text);
        return text;
    }

    public native String getJniString();
}

ImportError: cannot import name

When this is in a python console if you update a module to be able to use it through the console does not help reset, you must use a

import importlib

and

importlib.reload (*module*)

likely to solve your problem

Installing pip packages to $HOME folder

I would use virtualenv at your HOME directory.

$ sudo easy_install -U virtualenv
$ cd ~
$ virtualenv .
$ bin/pip ...

You could then also alter ~/.(login|profile|bash_profile), whichever is right for your shell to add ~/bin to your PATH and then that pip|python|easy_install would be the one used by default.

How do I specify the exit code of a console application in .NET?

If you are going to use the method suggested by David, you should also take a look at the [Flags] Attribute.

This allows you to do bit wise operations on enums.

[Flags]
enum ExitCodes : int
{
  Success = 0,
  SignToolNotInPath = 1,
  AssemblyDirectoryBad = 2,
  PFXFilePathBad = 4,
  PasswordMissing = 8,
  SignFailed = 16,
  UnknownError = 32
}

Then

(ExitCodes.SignFailed | ExitCodes.UnknownError)

would be 16 + 32. :)

How to configure Git post commit hook

I want to add to the answers above that it becomes a little more difficult if Jenkins authorization is enabled.

After enabling it I got an error message that anonymous user needs read permission.

I saw two possible solutions:

1: Changing my hook to:

curl --user name:passwd -s http://domain?token=whatevertokenuhave

2: setting project based authorization.

The former solutions has the disadvantage that I had to expose my passwd in the hook file. Unacceptable in my case.

The second works for me. In the global auth settings I had to enable Overall>Read for Anonymous user. In the project I wanted to trigger I had to enable Job>Build and Job>Read for Anonymous.

This is still not a perfect solution because now you can see the project in Jenkins without login. There might be an even better solution using the former approach with http login but I haven't figured it out.

how can I Update top 100 records in sql server

update tb set  f1=1 where id in (select top 100 id from tb where f1=0)

How to check Oracle patches are installed?

Here is an article on how to check and or install new patches :


To find the OPatch tool setup your database enviroment variables and then issue this comand:

cd $ORACLE_HOME/OPatch 
> pwd
/oracle/app/product/10.2.0/db_1/OPatch

To list all the patches applies to your database use the lsinventory option:

[oracle@DCG023 8828328]$ opatch lsinventory
Oracle Interim Patch Installer version 11.2.0.3.4
Copyright (c) 2012, Oracle Corporation. All rights reserved.

Oracle Home : /u00/product/11.2.0/dbhome_1
Central Inventory : /u00/oraInventory
from : /u00/product/11.2.0/dbhome_1/oraInst.loc
OPatch version : 11.2.0.3.4
OUI version : 11.2.0.1.0
Log file location : /u00/product/11.2.0/dbhome_1/cfgtoollogs/opatch/opatch2013-11-13_13-55-22PM_1.log
Lsinventory Output file location : /u00/product/11.2.0/dbhome_1/cfgtoollogs/opatch/lsinv/lsinventory2013-11-13_13-55-22PM.txt


Installed Top-level Products (1):
Oracle Database 11g 11.2.0.1.0
There are 1 products installed in this Oracle Home.

Interim patches (1) :
Patch 8405205 : applied on Mon Aug 19 15:18:04 BRT 2013
Unique Patch ID: 11805160
Created on 23 Sep 2009, 02:41:32 hrs PST8PDT
Bugs fixed:
8405205

OPatch succeeded.

To list the patches using sql :

select * from registry$history;

Should you always favor xrange() over range()?

Okay, everyone here as a different opinion as to the tradeoffs and advantages of xrange versus range. They're mostly correct, xrange is an iterator, and range fleshes out and creates an actual list. For the majority of cases, you won't really notice a difference between the two. (You can use map with range but not with xrange, but it uses up more memory.)

What I think you rally want to hear, however, is that the preferred choice is xrange. Since range in Python 3 is an iterator, the code conversion tool 2to3 will correctly convert all uses of xrange to range, and will throw out an error or warning for uses of range. If you want to be sure to easily convert your code in the future, you'll use xrange only, and list(xrange) when you're sure that you want a list. I learned this during the CPython sprint at PyCon this year (2008) in Chicago.

Can I create a One-Time-Use Function in a Script or Stored Procedure?

In scripts you have more options and a better shot at rational decomposition. Look into SQLCMD mode (Query Menu -> SQLCMD mode), specifically the :setvar and :r commands.

Within a stored procedure your options are very limited. You can't create define a function directly with the body of a procedure. The best you can do is something like this, with dynamic SQL:

create proc DoStuff
as begin

  declare @sql nvarchar(max)

  /*
  define function here, within a string
  note the underscore prefix, a good convention for user-defined temporary objects
  */
  set @sql = '
    create function dbo._object_name_twopart (@object_id int)
    returns nvarchar(517) as
    begin
      return 
        quotename(object_schema_name(@object_id))+N''.''+
        quotename(object_name(@object_id))
    end
  '

  /*
  create the function by executing the string, with a conditional object drop upfront
  */
  if object_id('dbo._object_name_twopart') is not null drop function _object_name_twopart
  exec (@sql)

  /*
  use the function in a query
  */
  select object_id, dbo._object_name_twopart(object_id) 
  from sys.objects
  where type = 'U'

  /*
  clean up
  */
  drop function _object_name_twopart

end
go

This approximates a global temporary function, if such a thing existed. It's still visible to other users. You could append the @@SPID of your connection to uniqueify the name, but that would then require the rest of the procedure to use dynamic SQL too.

Search all the occurrences of a string in the entire project in Android Studio

And for all of us who use Eclipse keymaps the shortcut is Ctrl+H. Expect limited options compared to eclipse or you will be disappointed.

jQuery ajax error function

The required parameters in an Ajax error function are jqXHR, exception and you can use it like below:

$.ajax({
    url: 'some_unknown_page.html',
    success: function (response) {
        $('#post').html(response.responseText);
    },
    error: function (jqXHR, exception) {
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    },
});

DEMO FIDDLE


Parameters

jqXHR:

Its actually an error object which is looks like this

Ajax error jqXHR object

You can also view this in your own browser console, by using console.log inside the error function like:

error: function (jqXHR, exception) {
    console.log(jqXHR);
    // Your error handling logic here..
}

We are using the status property from this object to get the error code, like if we get status = 404 this means that requested page could not be found. It doesn't exists at all. Based on that status code we can redirect users to login page or whatever our business logic requires.

exception:

This is string variable which shows the exception type. So, if we are getting 404 error, exception text would be simply 'error'. Similarly, we might get 'timeout', 'abort' as other exception texts.


Deprecation Notice: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

So, in case you are using jQuery 1.8 or above we will need to update the success and error function logic like:-

// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax("some_unknown_page.html")
    .done(function (response) {
        // success logic here
        $('#post').html(response.responseText);
    })
    .fail(function (jqXHR, exception) {
        // Our error logic here
        var msg = '';
        if (jqXHR.status === 0) {
            msg = 'Not connect.\n Verify Network.';
        } else if (jqXHR.status == 404) {
            msg = 'Requested page not found. [404]';
        } else if (jqXHR.status == 500) {
            msg = 'Internal Server Error [500].';
        } else if (exception === 'parsererror') {
            msg = 'Requested JSON parse failed.';
        } else if (exception === 'timeout') {
            msg = 'Time out error.';
        } else if (exception === 'abort') {
            msg = 'Ajax request aborted.';
        } else {
            msg = 'Uncaught Error.\n' + jqXHR.responseText;
        }
        $('#post').html(msg);
    })
    .always(function () {
        alert("complete");
    });

Hope it helps!

NSURLErrorDomain error codes description

I received the error Domain=NSURLErrorDomain Code=-1011 when using Parse, and providing the wrong clientKey. As soon as I corrected that, it began working.

What are the specific differences between .msi and setup.exe file?

MSI is basically an installer from Microsoft that is built into windows. It associates components with features and contains installation control information. It is not necessary that this file contains actual user required files i.e the application programs which user expects. MSI can contain another setup.exe inside it which the MSI wraps, which actually contains the user required files.

Hope this clears you doubt.

How to order by with union in SQL?

Order By is applied after union, so just add an order by clause at the end of the statements:

Select id,name,age
From Student
Where age < 15
Union
Select id,name,age
From Student
Where Name like '%a%'
Order By name

Google maps Places API V3 autocomplete - select first option on enter

I just want to write an small enhancement for the answer of amirnissim
The script posted doesn't support IE8, because "event.which" seems to be always empty in IE8.
To solve this problem you just need to additionally check for "event.keyCode":

listener = function (event) {
  if (event.which == 13 || event.keyCode == 13) {
    var suggestion_selected = $(".pac-item.pac-selected").length > 0;
    if(!suggestion_selected){
      var simulated_downarrow = $.Event("keydown", {keyCode:40, which:40})
      orig_listener.apply(input, [simulated_downarrow]);
    }
  }
  orig_listener.apply(input, [event]);
};

JS-Fiddle: http://jsfiddle.net/QW59W/107/

How to get package name from anywhere?

You can get your package name like so:

$ /path/to/adb shell 'pm list packages -f myapp'
package:/data/app/mycompany.myapp-2.apk=mycompany.myapp

Here are the options:

$ adb
Android Debug Bridge version 1.0.32
Revision 09a0d98bebce-android

 -a                            - directs adb to listen on all interfaces for a connection
 -d                            - directs command to the only connected USB device
                                 returns an error if more than one USB device is present.
 -e                            - directs command to the only running emulator.
                                 returns an error if more than one emulator is running.
 -s <specific device>          - directs command to the device or emulator with the given
                                 serial number or qualifier. Overrides ANDROID_SERIAL
                                 environment variable.
 -p <product name or path>     - simple product name like 'sooner', or
                                 a relative/absolute path to a product
                                 out directory like 'out/target/product/sooner'.
                                 If -p is not specified, the ANDROID_PRODUCT_OUT
                                 environment variable is used, which must
                                 be an absolute path.
 -H                            - Name of adb server host (default: localhost)
 -P                            - Port of adb server (default: 5037)
 devices [-l]                  - list all connected devices
                                 ('-l' will also list device qualifiers)
 connect <host>[:<port>]       - connect to a device via TCP/IP
                                 Port 5555 is used by default if no port number is specified.
 disconnect [<host>[:<port>]]  - disconnect from a TCP/IP device.
                                 Port 5555 is used by default if no port number is specified.
                                 Using this command with no additional arguments
                                 will disconnect from all connected TCP/IP devices.

device commands:
  adb push [-p] <local> <remote>
                               - copy file/dir to device
                                 ('-p' to display the transfer progress)
  adb pull [-p] [-a] <remote> [<local>]
                               - copy file/dir from device
                                 ('-p' to display the transfer progress)
                                 ('-a' means copy timestamp and mode)
  adb sync [ <directory> ]     - copy host->device only if changed
                                 (-l means list but don't copy)
  adb shell                    - run remote shell interactively
  adb shell <command>          - run remote shell command
  adb emu <command>            - run emulator console command
  adb logcat [ <filter-spec> ] - View device log
  adb forward --list           - list all forward socket connections.
                                 the format is a list of lines with the following format:
                                    <serial> " " <local> " " <remote> "\n"
  adb forward <local> <remote> - forward socket connections
                                 forward specs are one of:
                                   tcp:<port>
                                   localabstract:<unix domain socket name>
                                   localreserved:<unix domain socket name>
                                   localfilesystem:<unix domain socket name>
                                   dev:<character device name>
                                   jdwp:<process pid> (remote only)
  adb forward --no-rebind <local> <remote>
                               - same as 'adb forward <local> <remote>' but fails
                                 if <local> is already forwarded
  adb forward --remove <local> - remove a specific forward socket connection
  adb forward --remove-all     - remove all forward socket connections
  adb reverse --list           - list all reverse socket connections from device
  adb reverse <remote> <local> - reverse socket connections
                                 reverse specs are one of:
                                   tcp:<port>
                                   localabstract:<unix domain socket name>
                                   localreserved:<unix domain socket name>
                                   localfilesystem:<unix domain socket name>
  adb reverse --norebind <remote> <local>
                               - same as 'adb reverse <remote> <local>' but fails
                                 if <remote> is already reversed.
  adb reverse --remove <remote>
                               - remove a specific reversed socket connection
  adb reverse --remove-all     - remove all reversed socket connections from device
  adb jdwp                     - list PIDs of processes hosting a JDWP transport
  adb install [-lrtsdg] <file>
                               - push this package file to the device and install it
                                 (-l: forward lock application)
                                 (-r: replace existing application)
                                 (-t: allow test packages)
                                 (-s: install application on sdcard)
                                 (-d: allow version code downgrade)
                                 (-g: grant all runtime permissions)
  adb install-multiple [-lrtsdpg] <file...>
                               - push this package file to the device and install it
                                 (-l: forward lock application)
                                 (-r: replace existing application)
                                 (-t: allow test packages)
                                 (-s: install application on sdcard)
                                 (-d: allow version code downgrade)
                                 (-p: partial application install)
                                 (-g: grant all runtime permissions)
  adb uninstall [-k] <package> - remove this app package from the device
                                 ('-k' means keep the data and cache directories)
  adb bugreport                - return all information from the device
                                 that should be included in a bug report.

  adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]
                               - write an archive of the device's data to <file>.
                                 If no -f option is supplied then the data is written
                                 to "backup.ab" in the current directory.
                                 (-apk|-noapk enable/disable backup of the .apks themselves
                                    in the archive; the default is noapk.)
                                 (-obb|-noobb enable/disable backup of any installed apk expansion
                                    (aka .obb) files associated with each application; the default
                                    is noobb.)
                                 (-shared|-noshared enable/disable backup of the device's
                                    shared storage / SD card contents; the default is noshared.)
                                 (-all means to back up all installed applications)
                                 (-system|-nosystem toggles whether -all automatically includes
                                    system applications; the default is to include system apps)
                                 (<packages...> is the list of applications to be backed up.  If
                                    the -all or -shared flags are passed, then the package
                                    list is optional.  Applications explicitly given on the
                                    command line will be included even if -nosystem would
                                    ordinarily cause them to be omitted.)

  adb restore <file>           - restore device contents from the <file> backup archive

  adb disable-verity           - disable dm-verity checking on USERDEBUG builds
  adb enable-verity            - re-enable dm-verity checking on USERDEBUG builds
  adb keygen <file>            - generate adb public/private key. The private key is stored in <file>,
                                 and the public key is stored in <file>.pub. Any existing files
                                 are overwritten.
  adb help                     - show this help message
  adb version                  - show version num

scripting:
  adb wait-for-device          - block until device is online
  adb start-server             - ensure that there is a server running
  adb kill-server              - kill the server if it is running
  adb get-state                - prints: offline | bootloader | device
  adb get-serialno             - prints: <serial-number>
  adb get-devpath              - prints: <device-path>
  adb remount                  - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write
  adb reboot [bootloader|recovery]
                               - reboots the device, optionally into the bootloader or recovery program.
  adb reboot sideload          - reboots the device into the sideload mode in recovery program (adb root required).
  adb reboot sideload-auto-reboot
                               - reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.
  adb sideload <file>          - sideloads the given package
  adb root                     - restarts the adbd daemon with root permissions
  adb unroot                   - restarts the adbd daemon without root permissions
  adb usb                      - restarts the adbd daemon listening on USB
  adb tcpip <port>             - restarts the adbd daemon listening on TCP on the specified port

networking:
  adb ppp <tty> [parameters]   - Run PPP over USB.
 Note: you should not automatically start a PPP connection.
 <tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
 [parameters] - Eg. defaultroute debug dump local notty usepeerdns

adb sync notes: adb sync [ <directory> ]
  <localdir> can be interpreted in several ways:

  - If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.

  - If it is "system", "vendor", "oem" or "data", only the corresponding partition
    is updated.

environment variables:
  ADB_TRACE                    - Print debug information. A comma separated list of the following values
                                 1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp
  ANDROID_SERIAL               - The serial number to connect to. -s takes priority over this if given.
  ANDROID_LOG_TAGS             - When used with the logcat option, only these debug tags are printed.

How is Docker different from a virtual machine?

1. Lightweight

This is probably the first impression for many docker learners.

First, docker images are usually smaller than VM images, makes it easy to build, copy, share.

Second, Docker containers can start in several milliseconds, while VM starts in seconds.

2. Layered File System

This is another key feature of Docker. Images have layers, and different images can share layers, make it even more space-saving and faster to build.

If all containers use Ubuntu as their base images, not every image has its own file system, but share the same underline ubuntu files, and only differs in their own application data.

3. Shared OS Kernel

Think of containers as processes!

All containers running on a host is indeed a bunch of processes with different file systems. They share the same OS kernel, only encapsulates system library and dependencies.

This is good for most cases(no extra OS kernel maintains) but can be a problem if strict isolations are necessary between containers.

Why it matters?

All these seem like improvements, not revolution. Well, quantitative accumulation leads to qualitative transformation.

Think about application deployment. If we want to deploy a new software(service) or upgrade one, it is better to change the config files and processes instead of creating a new VM. Because Creating a VM with updated service, testing it(share between Dev & QA), deploying to production takes hours, even days. If anything goes wrong, you got to start again, wasting even more time. So, use configuration management tool(puppet, saltstack, chef etc.) to install new software, download new files is preferred.

When it comes to docker, it's impossible to use a newly created docker container to replace the old one. Maintainance is much easier!Building a new image, share it with QA, testing it, deploying it only takes minutes(if everything is automated), hours in the worst case. This is called immutable infrastructure: do not maintain(upgrade) software, create a new one instead.

It transforms how services are delivered. We want applications, but have to maintain VMs(which is a pain and has little to do with our applications). Docker makes you focus on applications and smooths everything.

Certificate has either expired or has been revoked

If you have a host test target that you run on the device, make sure that it uses the same code signing identity that the app target uses. Otherwise you will have to clean when you switch between testing and debugging the app.

I had this issue in Xcode 11.4.1 when we turned off code signing in our host test target as a build-time enhancement. Once I turned code signing back on for the host test, I no longer experienced this issue when switching between running the host test target and the app!