Programs & Examples On #Tablespace

A tablespace is a database concept and refers to a storage location where the actual data underlying database objects can be kept.

Find out free space on tablespace

This is one of the simplest query for the same that I came across and we use it for monitoring as well:

SELECT TABLESPACE_NAME,SUM(BYTES)/1024/1024/1024 "FREE SPACE(GB)"
FROM DBA_FREE_SPACE GROUP BY TABLESPACE_NAME;

A complete article about Oracle Tablespace: Tablespace

Error: Tablespace for table xxx exists. Please DISCARD the tablespace before IMPORT

if you have this problem and you don't have another option change the engine to any other engine like 'myisam', then try to create the table.

disclaimer: it is not the valid answer as you may have foreign key constraints which will not be supported by another storage engine. Every storage engine has their own specialty to store and access data, these points also to be taken in account.

ORA-01950: no privileges on tablespace 'USERS'

You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run

ALTER USER <user> quota unlimited on <tablespace name>;

or

ALTER USER <user> quota 100M on <tablespace name>;

as a DBA user (depending on how much space you need / want to grant).

ORA-01652 Unable to extend temp segment by in tablespace

Create a new datafile by running the following command:

alter tablespace TABLE_SPACE_NAME add datafile 'D:\oracle\Oradata\TEMP04.dbf'            
   size 2000M autoextend on;

ORA-01653: unable to extend table by in tablespace ORA-06512

Just add a new datafile for the existing tablespace

ALTER TABLESPACE LEGAL_DATA ADD DATAFILE '/u01/oradata/userdata03.dbf' SIZE 200M;

To find out the location and size of your data files:

SELECT FILE_NAME, BYTES FROM DBA_DATA_FILES WHERE TABLESPACE_NAME = 'LEGAL_DATA';

how to determine size of tablespace oracle 11g

The following query can be used to detemine tablespace and other params:

select df.tablespace_name "Tablespace",
       totalusedspace "Used MB",
       (df.totalspace - tu.totalusedspace) "Free MB",
       df.totalspace "Total MB",
       round(100 * ( (df.totalspace - tu.totalusedspace)/ df.totalspace)) "Pct. Free"
  from (select tablespace_name,
               round(sum(bytes) / 1048576) TotalSpace
          from dba_data_files 
         group by tablespace_name) df,
       (select round(sum(bytes)/(1024*1024)) totalusedspace,
               tablespace_name
          from dba_segments 
         group by tablespace_name) tu
 where df.tablespace_name = tu.tablespace_name 
   and df.totalspace <> 0;

Source: https://community.oracle.com/message/1832920

For your case if you want to know the partition name and it's size just run this query:

select owner,
       segment_name,
       partition_name,
       segment_type,
       bytes / 1024/1024 "MB" 
  from dba_segments 
 where owner = <owner_name>;

element not interactable exception in selenium web automation

Please try selecting the password field like this.

    WebDriverWait wait = new WebDriverWait(driver, 10);
    WebElement passwordElement = wait.until(ExpectedConditions.elementToBeClickable(By.cssSelector("#Passwd")));
    passwordElement.click();
  passwordElement.clear();
     passwordElement.sendKeys("123");

Get json value from response

Normally you could access it by its property name:

var foo = {"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"};
alert(foo.id);

or perhaps you've got a JSON string that needs to be turned into an object:

var foo = jQuery.parseJSON(data);
alert(foo.id);

http://api.jquery.com/jQuery.parseJSON/

android listview item height

Here is my solutions; It is my getView() in BaseAdapter subclass:

public View getView(int position, View convertView, ViewGroup parent)
{
    if(convertView==null)
    {
        convertView=inflater.inflate(R.layout.list_view, parent,false);
        System.out.println("In");
    }
    convertView.setMinimumHeight(100);
    return convertView;
}

Here i have set ListItem's minimum height to 100;

How do I rename all folders and files to lowercase on Linux?

Smaller still I quite like:

rename 'y/A-Z/a-z/' *

On case insensitive filesystems such as OS X's HFS+, you will want to add the -f flag:

rename -f 'y/A-Z/a-z/' *

How should we manage jdk8 stream for null values

Stuart's answer provides a great explanation, but I'd like to provide another example.

I ran into this issue when attempting to perform a reduce on a Stream containing null values (actually it was LongStream.average(), which is a type of reduction). Since average() returns OptionalDouble, I assumed the Stream could contain nulls but instead a NullPointerException was thrown. This is due to Stuart's explanation of null v. empty.

So, as the OP suggests, I added a filter like so:

list.stream()
    .filter(o -> o != null)
    .reduce(..);

Or as tangens pointed out below, use the predicate provided by the Java API:

list.stream()
    .filter(Objects::nonNull)
    .reduce(..);

From the mailing list discussion Stuart linked: Brian Goetz on nulls in Streams

How to create JSON object using jQuery

How to get append input field value as json like

temp:[
        {
           test:'test 1',
           testData:  [ 
                       {testName: 'do',testId:''}
                         ],
           testRcd:'value'                             
        },
        {
            test:'test 2',
           testData:  [
                            {testName: 'do1',testId:''}
                         ],
           testRcd:'value'                           
        }
      ],

How to make custom error pages work in ASP.NET MVC 4

I've done pablo solution and I always had the error (MVC4)

The view 'Error' or its master was not found or no view engine supports the searched location.

To get rid of this, remove the line

 filters.Add(new HandleErrorAttribute());

in FilterConfig.cs

Declaring an HTMLElement Typescript

Okay: weird syntax!

var el: HTMLElement = document.getElementById('content');

fixes the problem. I wonder why the example didn't do this in the first place?

complete code:

class Greeter {
    element: HTMLElement;
    span: HTMLElement;
    timerToken: number;

    constructor (element: HTMLElement) { 
        this.element = element;
        this.element.innerText += "The time is: ";
        this.span = document.createElement('span');
        this.element.appendChild(this.span);
        this.span.innerText = new Date().toUTCString();
    }

    start() {
        this.timerToken = setInterval(() => this.span.innerText = new Date().toUTCString(), 500);
    }

    stop() {
        clearTimeout(this.timerToken);
    }

}

window.onload = () => {
    var el: HTMLElement = document.getElementById('content');
    var greeter = new Greeter(el);
    greeter.start();
};

What is a good pattern for using a Global Mutex in C#?

Neither Mutex nor WinApi CreateMutex() works for me.

An alternate solution:

static class Program
{
    [STAThread]
    static void Main()
    {
        if (SingleApplicationDetector.IsRunning()) {
            return;
        }

        Application.Run(new MainForm());

        SingleApplicationDetector.Close();
    }
}

And the SingleApplicationDetector:

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Threading;

public static class SingleApplicationDetector
{
    public static bool IsRunning()
    {
        string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
        var semaphoreName = @"Global\" + guid;
        try {
            __semaphore = Semaphore.OpenExisting(semaphoreName, SemaphoreRights.Synchronize);

            Close();
            return true;
        }
        catch (Exception ex) {
            __semaphore = new Semaphore(0, 1, semaphoreName);
            return false;
        }
    }

    public static void Close()
    {
        if (__semaphore != null) {
            __semaphore.Close();
            __semaphore = null;
        }
    }

    private static Semaphore __semaphore;
}

Reason to use Semaphore instead of Mutex:

The Mutex class enforces thread identity, so a mutex can be released only by the thread that acquired it. By contrast, the Semaphore class does not enforce thread identity.

<< System.Threading.Mutex

Ref: Semaphore.OpenExisting()

make image( not background img) in div repeat?

It would probably be easier to just fake it by using a div. Just make sure you set the height if its empty so that it can actually appear. Say for instance you want it to be 50px tall set the div height to 50px.

<div id="rightflower">
<div id="divImg"></div> 
</div>

And in your style sheet just add the background and its properties, height and width, and what ever positioning you had in mind.

Difference between checkout and export in SVN

Are you re-running your checkout or export into an existing directory?

Because if you are, checkout will update the working copy, including deleting any files.

But export will simply transfer all the files from the reporsitory to the destination - if the destination is the same directory, this means any files deleted in the repository will NOT be deleted.

So you export copy may only work because it is relying on a file which has been deleted in the repository?

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

This method works for me. It's checking if the person has had their birthday this year and subtracts one year otherwise.

// date is the moment you're calculating the age of
var now = moment().unix();
var then = date.unix();
var diff = (now - then) / (60 * 60 * 24 * 365);
var years = Math.floor(diff);

Edit: First version didn't quite work perfectly. The updated one should

How to select Python version in PyCharm?

File -> Settings

Preferences->Project Interpreter->Python Interpreters

If it's not listed add it.

enter image description here

Does C# support multiple inheritance?

Actually, it depends on your definition of inheritance:

  • you can inherit implementation (members, i.e. data and behavior) from a single class, but
  • you can inherit interfaces from multiple, well, interfaces.

This is not what is usually meant by the term "inheritance", but it is also not entirely unreasonable to define it this way.

Adding Google Play services version to your app's manifest?

It is probably that your library is not linked to project properly or that you have older google-play-services library version so conflict appears and Eclipse got stupid.. :S

No you don't need to add anything in integers.xml. When you link properly Google-play-services library to your project reference android:value="@integer/google_play_services_version" will be found and you are ready to go. When you add library to your project just do one more clean so funny Eclipse environment sweep-out things properly.

If you hardcode somewhere this number when next play version come you would need to update it. And if you forget that, you will spend time again looking for bug.. :S

Hope it helped. ;)

How to "crop" a rectangular image into a square with CSS?

I actually came across this same problem recently and ended up with a slightly different approach (I wasn't able to use background images). It does require a tiny bit of jQuery though to determine the orientation of the images (I' sure you could use plain JS instead though).

I wrote a blog post about it if you are interested in more explaination but the code is pretty simple:

HTML:

<ul class="cropped-images">
  <li><img src="http://fredparke.com/sites/default/files/cat-portrait.jpg" /></li>
  <li><img src="http://fredparke.com/sites/default/files/cat-landscape.jpg" /></li>
</ul>

CSS:

li {
  width: 150px; // Or whatever you want.
  height: 150px; // Or whatever you want.
  overflow: hidden;
  margin: 10px;
  display: inline-block;
  vertical-align: top;
}
li img {
  max-width: 100%;
  height: auto;
  width: auto;
}
li img.landscape {
  max-width: none;
  max-height: 100%;
}

jQuery:

$( document ).ready(function() {

    $('.cropped-images img').each(function() {
      if ($(this).width() > $(this).height()) {
        $(this).addClass('landscape');        
      }
    });

});

Removing Conda environment

Use source deactivate to deactivate the environment before removing it, replace ENV_NAME with the environment you wish to remove:

source deactivate
conda env remove -n ENV_NAME

SQL order string as number

If you are using AdonisJS and have mixed IDs such as ABC-202, ABC-201..., you can combine raw queries with Query Builder and implement the solution above (https://stackoverflow.com/a/25061144/4040835) as follows:

const sortField =
  'membership_id'
const sortDirection =
  'asc'
const subquery = UserProfile.query()
  .select(
    'user_profiles.id',
    'user_profiles.user_id',
    'user_profiles.membership_id',
    'user_profiles.first_name',
    'user_profiles.middle_name',
    'user_profiles.last_name',
    'user_profiles.mobile_number',
    'countries.citizenship',
    'states.name as state_of_origin',
    'user_profiles.gender',
    'user_profiles.created_at',
    'user_profiles.updated_at'
  )
  .leftJoin(
    'users',
    'user_profiles.user_id',
    'users.id'
  )
  .leftJoin(
    'countries',
    'user_profiles.nationality',
    'countries.id'
  )
  .leftJoin(
    'states',
    'user_profiles.state_of_origin',
    'states.id'
  )
  .orderByRaw(
    `SUBSTRING(:sortField:,3,15)*1 ${sortDirection}`,
    {
      sortField: sortField,
    }
  )
  .paginate(
    page,
    per_page
  )

NOTES: In this line: SUBSTRING(:sortField:,3,15)*1 ${sortDirection},

  1. '3' stands for the index number of the last non-numerical character before the digits. If your mixed ID is "ABC-123," your index number will be 4.
  2. '15' is used to catch as any number of digits as possible after the hyphen.
  3. '1' performs a mathematical operation on the substring which effectively casts the substring to a number.

Ref 1: You can read more about parameter bindings in raw queries here: https://knexjs.org/#Raw-Bindings Ref 2: Adonis Raw Queries: https://adonisjs.com/docs/4.1/query-builder#_raw_queries

Object passed as parameter to another class, by value or reference?

"Objects" are NEVER passed in C# -- "objects" are not values in the language. The only types in the language are primitive types, struct types, etc. and reference types. No "object types".

The types Object, MyClass, etc. are reference types. Their values are "references" -- pointers to objects. Objects can only be manipulated through references -- when you do new on them, you get a reference, the . operator operates on a reference; etc. There is no way to get a variable whose value "is" an object, because there are no object types.

All types, including reference types, can be passed by value or by reference. A parameter is passed by reference if it has a keyword like ref or out. The SetObject method's obj parameter (which is of a reference type) does not have such a keyword, so it is passed by value -- the reference is passed by value.

Resource blocked due to MIME type mismatch (X-Content-Type-Options: nosniff)

I've solved this problem by changing charset in js-files from UTF-8 without BOM to simple UTF-8 in Notepad++

Align div right in Bootstrap 3

Add offset8 to your class, for example:

<div class="offset8">aligns to the right</div>

What is the difference between document.location.href and document.location?

typeof document.location; // 'object'
typeof document.location.href; // 'string'

The href property is a string, while document.location itself is an object.

Re-order columns of table in Oracle

Since the release of Oracle 12c it is now easier to rearrange columns logically.

Oracle 12c added support for making columns invisible and that feature can be used to rearrange columns logically.

Quote from the documentation on invisible columns:

When you make an invisible column visible, the column is included in the table's column order as the last column.

Example

Create a table:

CREATE TABLE t (
    a INT,
    b INT,
    d INT,
    e INT
);

Add a column:

ALTER TABLE t ADD (c INT);

Move the column to the middle:

ALTER TABLE t MODIFY (d INVISIBLE, e INVISIBLE);
ALTER TABLE t MODIFY (d VISIBLE, e VISIBLE);

DESCRIBE t;

Name
----
A
B
C
D
E

Credits

I learned about this from an article by Tom Kyte on new features in Oracle 12c.

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

the problem is in url pattern of servlet-mapping.

 <url-pattern>/DispatcherServlet</url-pattern>

let's say our controller is

@Controller
public class HomeController {
    @RequestMapping("/home")
    public String home(){
        return "home";
    }
}

when we hit some URL on our browser. the dispatcher servlet will try to map this url.

the url pattern of our serlvet currently is /Dispatcher which means resources are served from {contextpath}/Dispatcher

but when we request http://localhost:8080/home we are actually asking resources from / which is not available. so either we need to say dispatcher servlet to serve from / by doing

<url-pattern>/</url-pattern>

our make it serve from /Dispatcher by doing /Dispatcher/*

E.g

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xmlns="http://xmlns.jcp.org/xml/ns/javaee" 
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" 
version="3.1">
  <display-name>springsecuritydemo</display-name>

  <servlet>
    <description></description>
    <display-name>offers</display-name>
    <servlet-name>offers</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>offers</servlet-name>
    <url-pattern>/Dispatcher/*</url-pattern>
  </servlet-mapping>

</web-app>

and request it with http://localhost:8080/Dispatcher/home or put just / to request like

http://localhost:8080/home

How to add a boolean datatype column to an existing table in sql?

In SQL SERVER it is BIT, though it allows NULL to be stored

ALTER TABLE person add  [AdminApproved] BIT default 'FALSE';

Also there are other mistakes in your query

  1. When you alter a table to add column no need to mention column keyword in alter statement

  2. For adding default constraint no need to use SET keyword

  3. Default value for a BIT column can be ('TRUE' or '1') / ('FALSE' or 0). TRUE or FALSE needs to mentioned as string not as Identifier

PHP ternary operator vs null coalescing operator

The major difference is that

  1. Ternary Operator expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE but on the other hand Null Coalescing Operator expression (expr1) ?? (expr2) evaluates to expr1 if expr1 is not NULL

  2. Ternary Operator expr1 ?: expr3 emit a notice if the left-hand side value (expr1) does not exist but on the other hand Null Coalescing Operator (expr1) ?? (expr2) In particular, does not emit a notice if the left-hand side value (expr1) does not exist, just like isset().

  3. TernaryOperator is left associative

    ((true ? 'true' : false) ? 't' : 'f');
    

    Null Coalescing Operator is right associative

    ($a ?? ($b ?? $c));
    

Now lets explain the difference between by example :

Ternary Operator (?:)

$x='';
$value=($x)?:'default';
var_dump($value);

// The above is identical to this if/else statement
if($x){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

Null Coalescing Operator (??)

$value=($x)??'default';
var_dump($value);

// The above is identical to this if/else statement
if(isset($x)){
  $value=$x;
}
else{
  $value='default';
}
var_dump($value);

Here is the table that explain the difference and similarity between '??' and ?:

enter image description here

Special Note : null coalescing operator and ternary operator is an expression, and that it doesn't evaluate to a variable, but to the result of an expression. This is important to know if you want to return a variable by reference. The statement return $foo ?? $bar; and return $var == 42 ? $a : $b; in a return-by-reference function will therefore not work and a warning is issued.

How to add smooth scrolling to Bootstrap's scroll spy function

with this code, the id will not appear on the link

    document.querySelectorAll('a[href^="#"]').forEach(anchor => {
        anchor.addEventListener('click', function (e) {
            e.preventDefault();

            document.querySelector(this.getAttribute('href')).scrollIntoView({
                behavior: 'smooth'
            });
        });
    });

How to delete a file via PHP?

$files = [
    './first.jpg',
    './second.jpg',
    './third.jpg'
];

foreach ($files as $file) {
    if (file_exists($file)) {
        unlink($file);
    } else {
        // File not found.
    }
}

Can I use DIV class and ID together in CSS?

#y.x should work. And it's convenient too. You can make a page with different kinds of output. You can give a certain element an id, but give it different classes depending on the look you want.

Starting of Tomcat failed from Netbeans

Also, it is very likely, that problem with proxy settings.

Any who didn't overcome Tomact starting problrem, - try in NetBeans choose No Proxy in the Tools -> Options -> General tab.

It helped me.

List of Timezone IDs for use with FindTimeZoneById() in C#?

This is the code fully tested and working for me. You can use it just copy and paste in your aspx page and cs page.

This is my blog you can download full code here. thanks.

http://www.c-sharpcorner.com/blogs/display-all-the-timezone-information-in-dropdown-list-of-a-local-system-using-c-sharp-with-asp-net

_x000D_
_x000D_
<form id="form1" runat="server">_x000D_
    <div style="font-size: 30px; padding: 25px; text-align: center;">_x000D_
        Get Current Date And Time Of All TimeZones_x000D_
    </div>_x000D_
    <hr />_x000D_
    <div style="font-size: 18px; padding: 25px; text-align: center;">_x000D_
        <div class="clsLeft">_x000D_
            Select TimeZone :-_x000D_
        </div>_x000D_
        <div class="clsRight">_x000D_
            <asp:DropDownList ID="ddlTimeZone" runat="server" AutoPostBack="True" OnSelectedIndexChanged="ddlTimeZone_SelectedIndexChanged"_x000D_
                Font-Size="18px">_x000D_
            </asp:DropDownList>_x000D_
        </div>_x000D_
        <div class="clearspace">_x000D_
        </div>_x000D_
        <div class="clsLeft">_x000D_
            Selected TimeZone :-_x000D_
        </div>_x000D_
        <div class="clsRight">_x000D_
            <asp:Label ID="lblTimeZone" runat="server" Text="" />_x000D_
        </div>_x000D_
        <div class="clearspace">_x000D_
        </div>_x000D_
        <div class="clsLeft">_x000D_
            Current Date And Time :-_x000D_
        </div>_x000D_
        <div class="clsRight">_x000D_
            <asp:Label ID="lblCurrentDateTime" runat="server" Text="" />_x000D_
        </div>_x000D_
    </div>_x000D_
    <p>_x000D_
        &nbsp;</p>_x000D_
    <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Button" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

 protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindTimeZone();
            GetSelectedTimeZone();
        }
    }

    protected void ddlTimeZone_SelectedIndexChanged(object sender, EventArgs e)
    {
        GetSelectedTimeZone();
    }

    /// <summary>
    /// Get all timezone from local system and bind it in dropdownlist
    /// </summary>
    private void BindTimeZone()
    {
        foreach (TimeZoneInfo z in TimeZoneInfo.GetSystemTimeZones())
        {
            ddlTimeZone.Items.Add(new ListItem(z.DisplayName, z.Id));
        }
    }

    /// <summary>
    /// Get selected timezone and current date & time
    /// </summary>
    private void GetSelectedTimeZone()
    {
        DateTimeOffset newTime = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(ddlTimeZone.SelectedValue));
        //DateTimeOffset newTime2 = TimeZoneInfo.ConvertTime(DateTimeOffset.UtcNow, TimeZoneInfo.FindSystemTimeZoneById(ddlTimeZone.SelectedValue));
        lblTimeZone.Text = ddlTimeZone.SelectedItem.Text;
        lblCurrentDateTime.Text = newTime.ToString();
        string str;
        str = lblCurrentDateTime.Text;
        string s=str.Substring(0, 10);
        DateTime dt = new DateTime();
        dt = Convert.ToDateTime(s);
       // Response.Write(dt.ToString());
        Response.Write(ddlTimeZone.SelectedValue);

    }

How to use format() on a moment.js duration?

You don't need .format. Use durations like this:

const duration = moment.duration(83, 'seconds');
console.log(duration.minutes() + ':' +duration.seconds());
// output: 1:23

I found this solution here: https://github.com/moment/moment/issues/463

EDIT:

And with padding for seconds, minutes and hours:

const withPadding = (duration) => {
    if (duration.asDays() > 0) {
        return 'at least one day';
    } else {
        return [
            ('0' + duration.hours()).slice(-2),
            ('0' + duration.minutes()).slice(-2),
            ('0' + duration.seconds()).slice(-2),
        ].join(':')
    }
}

withPadding(moment.duration(83, 'seconds'))
// 00:01:23

withPadding(moment.duration(6048000, 'seconds'))
// at least one day

C#: easiest way to populate a ListBox from a List

You can also use the AddRange method

listBox1.Items.AddRange(myList.ToArray());

What is the difference between char array and char pointer in C?

char p[3] = "hello" ? should be char p[6] = "hello" remember there is a '\0' char in the end of a "string" in C.

anyway, array in C is just a pointer to the first object of an adjust objects in the memory. the only different s are in semantics. while you can change the value of a pointer to point to a different location in the memory an array, after created, will always point to the same location.
also when using array the "new" and "delete" is automatically done for you.

ASP.NET strange compilation error

If you are still struggling to solve this issue, even after all options, then try to find application which is running and taking huge memory.

In my case it was an application which was having more than 100 instances running due to some error and that was taking at least 20 MB per application so around 2 GB.

After I killed the few applications and memory was released my site was back online.

Selecting option by text content with jQuery

If your <option> elements don't have value attributes, then you can just use .val:

$selectElement.val("text_you're_looking_for")

However, if your <option> elements have value attributes, or might do in future, then this won't work, because whenever possible .val will select an option by its value attribute instead of by its text content. There's no built-in jQuery method that will select an option by its text content if the options have value attributes, so we'll have to add one ourselves with a simple plugin:

/*
  Source: https://stackoverflow.com/a/16887276/1709587

  Usage instructions:

  Call

      jQuery('#mySelectElement').selectOptionWithText('target_text');

  to select the <option> element from within #mySelectElement whose text content
  is 'target_text' (or do nothing if no such <option> element exists).
*/
jQuery.fn.selectOptionWithText = function selectOptionWithText(targetText) {
    return this.each(function () {
        var $selectElement, $options, $targetOption;

        $selectElement = jQuery(this);
        $options = $selectElement.find('option');
        $targetOption = $options.filter(
            function () {return jQuery(this).text() == targetText}
        );

        // We use `.prop` if it's available (which it should be for any jQuery
        // versions above and including 1.6), and fall back on `.attr` (which
        // was used for changing DOM properties in pre-1.6) otherwise.
        if ($targetOption.prop) {
            $targetOption.prop('selected', true);
        } 
        else {
            $targetOption.attr('selected', 'true');
        }
    });
}

Just include this plugin somewhere after you add jQuery onto the page, and then do

jQuery('#someSelectElement').selectOptionWithText('Some Target Text');

to select options.

The plugin method uses filter to pick out only the option matching the targetText, and selects it using either .attr or .prop, depending upon jQuery version (see .prop() vs .attr() for explanation).

Here's a JSFiddle you can use to play with all three answers given to this question, which demonstrates that this one is the only one to reliably work: http://jsfiddle.net/3cLm5/1/

Is there a label/goto in Python?

Python offers you the ability to do some of the things you could do with a goto using first class functions. For example:

void somefunc(int a)
{
    if (a == 1)
        goto label1;
    if (a == 2)
        goto label2;

    label1:
        ...
    label2:
        ...
}

Could be done in python like this:

def func1():
    ...

def func2():
    ...

funcmap = {1 : func1, 2 : func2}

def somefunc(a):
    funcmap[a]()  #Ugly!  But it works.

Granted, that isn't the best way to substitute for goto. But without knowing exactly what you're trying to do with the goto, it's hard to give specific advice.

@ascobol:

Your best bet is to either enclose it in a function or use an exception. For the function:

def loopfunc():
    while 1:
        while 1:
            if condition:
                return

For the exception:

try:
    while 1:
        while 1:
            raise BreakoutException #Not a real exception, invent your own
except BreakoutException:
    pass

Using exceptions to do stuff like this may feel a bit awkward if you come from another programming language. But I would argue that if you dislike using exceptions, Python isn't the language for you. :-)

Converting HTML to Excel?

So long as Excel can open the file, the functionality to change the format of the opened file is built in.

To convert an .html file, open it using Excel (File - Open) and then save it as a .xlsx file from Excel (File - Save as).

To do it using VBA, the code would look like this:

Sub Open_HTML_Save_XLSX()

    Workbooks.Open Filename:="C:\Temp\Example.html"
    ActiveWorkbook.SaveAs Filename:= _
        "C:\Temp\Example.xlsx", FileFormat:= _
        xlOpenXMLWorkbook

End Sub

Spring profiles and testing

@EnableConfigurationProperties needs to be there (you also can annotate your test class), the application-localtest.yml from test/resources will be loaded. A sample with jUnit5

@ExtendWith(SpringExtension.class)
@EnableConfigurationProperties
@ContextConfiguration(classes = {YourClasses}, initializers = ConfigFileApplicationContextInitializer.class)
@ActiveProfiles(profiles = "localtest")
class TestActiveProfile {

    @Test
    void testActiveProfile(){

    }
}

Case Insensitive String comp in C

static int ignoreCaseComp (const char *str1, const char *str2, int length)
{
    int k;
    for (k = 0; k < length; k++)
    {

        if ((str1[k] | 32) != (str2[k] | 32))
            break;
    }

    if (k != length)
        return 1;
    return 0;
}

Reference

Does it make sense to use Require.js with Angular.js?

Yes, it does, specially for very large SPA.

In some scenario, RequireJS is a must. For example, I develop PhoneGap applications using AngularJS that also uses Google Map API. Without AMD loader like RequireJS, the app would simply crash upon launch when offline as it cannot source the Google Map API scripts. An AMD loader gives me a chance to display an error message to the user.

However, integration between AngularJS and RequireJS is a bit tricky. I created angularAMD to make this a less painful process:

http://marcoslin.github.io/angularAMD/

Bootstrap Modal sitting behind backdrop

In my case one of parents of my modal was animated and had this

.animated {
    -webkit-animation-duration: 1s;
    animation-duration: 1s;
    -webkit-animation-fill-mode: both;
    animation-fill-mode: both;
    z-index: 100;
}

The blocker here is animation-fill-mode: both;. I could not just move modal outside, so the solution was to override 'animation-fill-mode' to animation-fill-mode: none;. Animation still worked fine.

Catching FULL exception message

Errors and exceptions in PowerShell are structured objects. The error message you see printed on the console is actually a formatted message with information from several elements of the error/exception object. You can (re-)construct it yourself like this:

$formatstring = "{0} : {1}`n{2}`n" +
                "    + CategoryInfo          : {3}`n" +
                "    + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
          $_.ErrorDetails.Message,
          $_.InvocationInfo.PositionMessage,
          $_.CategoryInfo.ToString(),
          $_.FullyQualifiedErrorId

$formatstring -f $fields

If you just want the error message displayed in your catch block you can simply echo the current object variable (which holds the error at that point):

try {
  ...
} catch {
  $_
}

If you need colored output use Write-Host with a formatted string as described above:

try {
  ...
} catch {
  ...
  Write-Host -Foreground Red -Background Black ($formatstring -f $fields)
}

With that said, usually you don't want to just display the error message as-is in an exception handler (otherwise the -ErrorAction Stop would be pointless). The structured error/exception objects provide you with additional information that you can use for better error control. For instance you have $_.Exception.HResult with the actual error number. $_.ScriptStackTrace and $_.Exception.StackTrace, so you can display stacktraces when debugging. $_.Exception.InnerException gives you access to nested exceptions that often contain additional information about the error (top level PowerShell errors can be somewhat generic). You can unroll these nested exceptions with something like this:

$e = $_.Exception
$msg = $e.Message
while ($e.InnerException) {
  $e = $e.InnerException
  $msg += "`n" + $e.Message
}
$msg

In your case the information you want to extract seems to be in $_.ErrorDetails.Message. It's not quite clear to me if you have an object or a JSON string there, but you should be able to get information about the types and values of the members of $_.ErrorDetails by running

$_.ErrorDetails | Get-Member
$_.ErrorDetails | Format-List *

If $_.ErrorDetails.Message is an object you should be able to obtain the message string like this:

$_.ErrorDetails.Message.message

otherwise you need to convert the JSON string to an object first:

$_.ErrorDetails.Message | ConvertFrom-Json | Select-Object -Expand message

Depending what kind of error you're handling, exceptions of particular types might also include more specific information about the problem at hand. In your case for instance you have a WebException which in addition to the error message ($_.Exception.Message) contains the actual response from the server:

PS C:\> $e.Exception | Get-Member

   TypeName: System.Net.WebException

Name             MemberType Definition
----             ---------- ----------
Equals           Method     bool Equals(System.Object obj), bool _Exception.E...
GetBaseException Method     System.Exception GetBaseException(), System.Excep...
GetHashCode      Method     int GetHashCode(), int _Exception.GetHashCode()
GetObjectData    Method     void GetObjectData(System.Runtime.Serialization.S...
GetType          Method     type GetType(), type _Exception.GetType()
ToString         Method     string ToString(), string _Exception.ToString()
Data             Property   System.Collections.IDictionary Data {get;}
HelpLink         Property   string HelpLink {get;set;}
HResult          Property   int HResult {get;}
InnerException   Property   System.Exception InnerException {get;}
Message          Property   string Message {get;}
Response         Property   System.Net.WebResponse Response {get;}
Source           Property   string Source {get;set;}
StackTrace       Property   string StackTrace {get;}
Status           Property   System.Net.WebExceptionStatus Status {get;}
TargetSite       Property   System.Reflection.MethodBase TargetSite {get;}

which provides you with information like this:

PS C:\> $e.Exception.Response

IsMutuallyAuthenticated : False
Cookies                 : {}
Headers                 : {Keep-Alive, Connection, Content-Length, Content-T...}
SupportsHeaders         : True
ContentLength           : 198
ContentEncoding         :
ContentType             : text/html; charset=iso-8859-1
CharacterSet            : iso-8859-1
Server                  : Apache/2.4.10
LastModified            : 17.07.2016 14:39:29
StatusCode              : NotFound
StatusDescription       : Not Found
ProtocolVersion         : 1.1
ResponseUri             : http://www.example.com/
Method                  : POST
IsFromCache             : False

Since not all exceptions have the exact same set of properties you may want to use specific handlers for particular exceptions:

try {
  ...
} catch [System.ArgumentException] {
  # handle argument exceptions
} catch [System.Net.WebException] {
  # handle web exceptions
} catch {
  # handle all other exceptions
}

If you have operations that need to be done regardless of whether an error occured or not (cleanup tasks like closing a socket or a database connection) you can put them in a finally block after the exception handling:

try {
  ...
} catch {
  ...
} finally {
  # cleanup operations go here
}

Javascript Get Element by Id and set the value

try like below it will work...

<html>
<head>
<script>
function displayResult(element)
{
document.getElementById(element).value = 'hi';
}
</script>
</head>
<body>

<textarea id="myTextarea" cols="20">
BYE
</textarea>
<br>

<button type="button" onclick="displayResult('myTextarea')">Change</button>

</body>
</html>

Ruby - test for array

You probably want to use kind_of().

>> s = "something"
=> "something"
>> s.kind_of?(Array)
=> false
>> s = ["something", "else"]
=> ["something", "else"]
>> s.kind_of?(Array)
=> true

Multiple left-hand assignment with JavaScript

It is clear by now, that they are not the same. The way to code that is

var var1, var2, var3
var1 = var2 = var3 = 1

And, what about let assigment? Exactly the same as var, don't let the let assigment confuse you because of block scope.

let var1 = var2 = 1 // here var2 belong to the global scope

We could do the following:

let v1, v2, v3
v1 = v2 = v3 = 2

Note: btw, I do not recommend use multiple assignments, not even multiple declarations in the same line.

How to control the width of select tag?

USE style="max-width:90%;"

<select name=countries  style="max-width:90%;">
 <option value=af>Afghanistan</option>
 <option value=ax>Åland Islands</option>
 ...
 <option value=gs>South Georgia and the South Sandwich Islands</option>
 ...
</select>  

LIVE DEMO

Insert Unicode character into JavaScript

I'm guessing that you actually want Omega to be a string containing an uppercase omega? In that case, you can write:

var Omega = '\u03A9';

(Because Ω is the Unicode character with codepoint U+03A9; that is, 03A9 is 937, except written as four hexadecimal digits.)

Windows batch: sleep

timeout /t 10 /nobreak > NUL

/t specifies the time to wait in seconds

/nobreak won't interrupt the timeout if you press a key (except CTRL-C)

> NUL will suppress the output of the command

MySql export schema without data

shell> mysqldump --no-data --routines --events test > dump-defs.sql

Embedding Base64 Images

Update: 2017-01-10

Data URIs are now supported by all major browsers. IE supports embedding images since version 8 as well.

http://caniuse.com/#feat=datauri


Data URIs are now supported by the following web browsers:

  • Gecko-based, such as Firefox, SeaMonkey, XeroBank, Camino, Fennec and K-Meleon
  • Konqueror, via KDE's KIO slaves input/output system
  • Opera (including devices such as the Nintendo DSi or Wii)
  • WebKit-based, such as Safari (including on iOS), Android's browser, Epiphany and Midori (WebKit is a derivative of Konqueror's KHTML engine, but Mac OS X does not share the KIO architecture so the implementations are different), as well as Webkit/Chromium-based, such as Chrome
  • Trident
    • Internet Explorer 8: Microsoft has limited its support to certain "non-navigable" content for security reasons, including concerns that JavaScript embedded in a data URI may not be interpretable by script filters such as those used by web-based email clients. Data URIs must be smaller than 32 KiB in Version 8[3].
    • Data URIs are supported only for the following elements and/or attributes[4]:
      • object (images only)
      • img
      • input type=image
      • link
    • CSS declarations that accept a URL, such as background-image, background, list-style-type, list-style and similar.
    • Internet Explorer 9: Internet Explorer 9 does not have 32KiB limitation and allowed in broader elements.
    • TheWorld Browser: An IE shell browser which has a built-in support for Data URI scheme

http://en.wikipedia.org/wiki/Data_URI_scheme#Web_browser_support

Changing Shell Text Color (Windows)

Try to look at the following link: Python | change text color in shell

Or read here: http://bytes.com/topic/python/answers/21877-coloring-print-lines

In general solution is to use ANSI codes while printing your string.

There is a solution that performs exactly what you need.

The Web Application Project [...] is configured to use IIS. The Web server [...] could not be found.

You can load the project without setting the value of attribute UseIIS to true. Simply follow the below steps:

In the mywebproject.csproj file--

Delete the tag < IISUrl>http://localhost/MyWebApp/< /IISUrl> and save the file. The application will automatically assign the default port to it.

How to Delete Session Cookie?

Deleting a jQuery cookie:

$(function() {
    var COOKIE_NAME = 'test_cookie';
    var options = { path: '/', expires: 10 };
    $.cookie(COOKIE_NAME, 'test', options); // sets the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns test
    $.cookie(COOKIE_NAME, null, options);   // deletes the cookie
    console.log( $.cookie( COOKIE_NAME)); // check the value // returns null
});

Pass a list to a function to act as multiple arguments

Since Python 3.5 you can unpack unlimited amount of lists.

PEP 448 - Additional Unpacking Generalizations

So this will work:

a = ['1', '2', '3', '4']
b = ['5', '6']
function_that_needs_strings(*a, *b)

How can we run a test method with multiple parameters in MSTest?

EDIT 4: Looks like this is completed in MSTest V2 June 17, 2016: https://blogs.msdn.microsoft.com/visualstudioalm/2016/06/17/taking-the-mstest-framework-forward-with-mstest-v2/

Original Answer:

As of about a week ago in Visual Studio 2012 Update 1 something similar is now possible:

[DataTestMethod]
[DataRow(12,3,4)]
[DataRow(12,2,6)]
[DataRow(12,4,3)]
public void DivideTest(int n, int d, int q)
{
  Assert.AreEqual( q, n / d );
}

EDIT: It appears this is only available within the unit testing project for WinRT/Metro. Bummer

EDIT 2: The following is the metadata found using "Go To Definition" within Visual Studio:

#region Assembly Microsoft.VisualStudio.TestPlatform.UnitTestFramework.dll, v11.0.0.0
// C:\Program Files (x86)\Microsoft SDKs\Windows\v8.0\ExtensionSDKs\MSTestFramework\11.0\References\CommonConfiguration\neutral\Microsoft.VisualStudio.TestPlatform.UnitTestFramework.dll
#endregion

using System;

namespace Microsoft.VisualStudio.TestPlatform.UnitTestFramework
{
    [AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
    public class DataTestMethodAttribute : TestMethodAttribute
    {
        public DataTestMethodAttribute();

        public override TestResult[] Execute(ITestMethod testMethod);
    }
}

EDIT 3: This issue was brought up in Visual Studio's UserVoice forums. Last Update states:

STARTED · Visual Studio Team ADMIN Visual Studio Team (Product Team, Microsoft Visual Studio) responded · April 25, 2016 Thank you for the feedback. We have started working on this.

Pratap Lakshman Visual Studio

https://visualstudio.uservoice.com/forums/330519-team-services/suggestions/3865310-allow-use-of-datatestmethod-datarow-in-all-unit

Ignore invalid self-signed ssl certificate in node.js with https.request?

So, my company just switched to Node.js v12.x. I was using NODE_TLS_REJECT_UNAUTHORIZED, and it stopped working. After some digging, I started using NODE_EXTRA_CA_CERTS=A_FILE_IN_OUR_PROJECT that has a PEM format of our self signed cert and all my scripts are working again.

So, if your project has self signed certs, perhaps this env var will help you.

Ref: https://nodejs.org/api/cli.html#cli_node_extra_ca_certs_file

Setting the number of map tasks and reduce tasks

In your example, the -D parts are not picked up:

hadoop jar Test_Parallel_for.jar Test_Parallel_for Matrix/test4.txt Result 3 \ -D mapred.map.tasks = 20 \ -D mapred.reduce.tasks =0

They should come after the classname part like this:

hadoop jar Test_Parallel_for.jar Test_Parallel_for -Dmapred.map.tasks=20 -Dmapred.reduce.tasks=0 Matrix/test4.txt Result 3

A space after -D is allowed though.

Also note that changing the number of mappers is probably a bad idea as other people have mentioned here.

The first day of the current month in php using date_modify as DateTime object

Requires PHP 5.3 to work ("first day of" is introduced in PHP 5.3). Otherwise the example above is the only way to do it:

<?php
    // First day of this month
    $d = new DateTime('first day of this month');
    echo $d->format('jS, F Y');

    // First day of a specific month
    $d = new DateTime('2010-01-19');
    $d->modify('first day of this month');
    echo $d->format('jS, F Y');

    // alternatively...
    echo date_create('2010-01-19')
      ->modify('first day of this month')
      ->format('jS, F Y');

In PHP 5.4+ you can do this:

<?php
    // First day of this month
    echo (new DateTime('first day of this month'))->format('jS, F Y');

    echo (new DateTime('2010-01-19'))
      ->modify('first day of this month')
      ->format('jS, F Y');

If you prefer a concise way to do this, and already have the year and month in numerical values, you can use date():

<?php
    echo date('Y-m-01'); // first day of this month
    echo date("$year-$month-01"); // first day of a month chosen by you

Chrome violation : [Violation] Handler took 83ms of runtime

It seems you have found your solution, but still it will be helpful to others, on this page on point based on Chrome 59.

4.Note the red triangle in the top-right of the Animation Frame Fired event. Whenever you see a red triangle, it's a warning that there may be an issue related to this event.

If you hover on these triangle you can see those are the violation handler errors and as per point 4. yes there is some issue related to that event.

How can I change the thickness of my <hr> tag

height attribute has been deprecated in html 5. What I would do is create a border around the hr and increase the thickness of the border as such: hr style="border:solid 2px black;"

How do you declare an interface in C++?

A little addition to what's written up there:

First, make sure your destructor is also pure virtual

Second, you may want to inherit virtually (rather than normally) when you do implement, just for good measures.

hadoop No FileSystem for scheme: file

For SBT use below mergeStrategy in build.sbt

mergeStrategy in assembly <<= (mergeStrategy in assembly) { (old) => {
    case PathList("META-INF", "services", "org.apache.hadoop.fs.FileSystem") => MergeStrategy.filterDistinctLines
    case s => old(s)
  }
}

How to unzip files programmatically in Android?

The Kotlin way

//FileExt.kt

data class ZipIO (val entry: ZipEntry, val output: File)

fun File.unzip(unzipLocationRoot: File? = null) {

    val rootFolder = unzipLocationRoot ?: File(parentFile.absolutePath + File.separator + nameWithoutExtension)
    if (!rootFolder.exists()) {
       rootFolder.mkdirs()
    }

    ZipFile(this).use { zip ->
        zip
        .entries()
        .asSequence()
        .map {
            val outputFile = File(rootFolder.absolutePath + File.separator + it.name)
            ZipIO(it, outputFile)
        }
        .map {
            it.output.parentFile?.run{
                if (!exists()) mkdirs()
            }
            it
        }
        .filter { !it.entry.isDirectory }
        .forEach { (entry, output) ->
            zip.getInputStream(entry).use { input ->
                output.outputStream().use { output ->
                    input.copyTo(output)
                }
            }
        }
    }

}

Usage

val zipFile = File("path_to_your_zip_file")
file.unzip()

Why is it not advisable to have the database and web server on the same machine?

I can speak from first hand experience that it is often a good idea to place the web server and database on different machines. If you have an application that is resource intensive, it can easily cause the CPU cycles on the machine to peak, essentially bringing the machine to a halt. However, if your application has limited use of the database, it would probably be no big deal to have them share a server.

Rename multiple files by replacing a particular pattern in the filenames using a shell script

this example, I am assuming that all your image files begin with "IMG" and you want to replace "IMG" with "VACATION"

solution : first identified all jpg files and then replace keyword

find . -name '*jpg' -exec bash -c 'echo mv $0 ${0/IMG/VACATION}' {} \; 

What exactly is an instance in Java?

An object and an instance are the same thing.

Personally I prefer to use the word "instance" when referring to a specific object of a specific type, for example "an instance of type Foo". But when talking about objects in general I would say "objects" rather than "instances".

A reference either refers to a specific object or else it can be a null reference.


They say that they have to create an instance to their application. What does it mean?

They probably mean you have to write something like this:

Foo foo = new Foo();

If you are unsure what type you should instantiate you should contact the developers of the application and ask for a more complete example.

How to get the current location in Google Maps Android API v2?

Try This

public class MyLocationListener implements LocationListener
{

 @Override

public void onLocationChanged(Location loc)
{

loc.getLatitude();

loc.getLongitude();

String Text = “My current location is: ” +

“Latitud = ” + loc.getLatitude() +

“Longitud = ” + loc.getLongitude();

Toast.makeText( getApplicationContext(),Text,   Toast.LENGTH_SHORT).show();



tvlat.setText(“”+loc.getLatitude());

tvlong.setText(“”+loc.getLongitude());

this.gpsCurrentLocation();

}

how to set textbox value in jquery

Note that the .value attribute is a JavaScript feature. If you want to use jQuery, use:

$('#pid').val()

to get the value, and:

$('#pid').val('value')

to set it.

http://api.jquery.com/val/

Regarding your second issue, I have never tried automatically setting the HTML value using the load method. For sure, you can do something like this:

$('#subtotal').load( 'compz.php?prodid=' + x + '&qbuys=' + y, function(response){ $('#subtotal').val(response);
});

Note that the code above is untested.

http://api.jquery.com/load/

What's the difference between Visual Studio Community and other, paid versions?

There are 2 major differences.

  1. Technical
  2. Licensing

Technical, there are 3 major differences:

First and foremost, Community doesn't have TFS support.
You'll just have to use git (arguable whether this constitutes a disadvantage or whether this actually is a good thing).
Note: This is what MS wrote. Actually, you can check-in&out with TFS as normal, if you have a TFS server in the network. You just cannot use Visual Studio as TFS SERVER.

Second, VS Community is severely limited in its testing capability.
Only unit tests. No Performance tests, no load tests, no performance profiling.

Third, VS Community's ability to create Virtual Environments has been severely cut.

On the other hand, syntax highlighting, IntelliSense, Step-Through debugging, GoTo-Definition, Git-Integration and Build/Publish are really all the features I need, and I guess that applies to a lot of developers.

For all other things, there are tools that do the same job faster, better and cheaper.

If you, like me, anyway use git, do unit testing with NUnit, and use Java-Tools to do Load-Testing on Linux plus TeamCity for CI, VS Community is more than sufficient, technically speaking.

Licensing:

A) If you're an individual developer (no enterprise, no organization), no difference (AFAIK), you can use CommunityEdition like you'd use the paid edition (as long as you don't do subcontracting)
B) You can use CommunityEdition freely for OpenSource (OSI) projects
C) If you're an educational insitution, you can use CommunityEdition freely (for education/classroom use)
D) If you're an enterprise with 250 PCs or users or more than one million US dollars in revenue (including subsidiaries), you are NOT ALLOWED to use CommunityEdition.
E) If you're not an enterprise as defined above, and don't do OSI or education, but are an "enterprise"/organization, with 5 or less concurrent (VS) developers, you can use VS Community freely (but only if you're the owner of the software and sell it, not if you're a subcontractor creating software for a larger enterprise, software which in the end the enterprise will own), otherwise you need a paid edition.

The above does not consitute legal advise.
See also:
https://softwareengineering.stackexchange.com/questions/262916/understanding-visual-studio-community-edition-license

Entity Framework - Generating Classes

  1. Open the EDMX model
  2. Right click -> Update Model from Browser -> Stored Procedure -> Select your stored procedure -> Finish
  3. See the Model Browser popping up next to Solution Explorer.
  4. Go to Function Imports -> Right click on your Stored Procedure -> Add Function Import
  5. Select the Entities under Return a Collection of -> Select your Entity name from the drop down
  6. Build your Solution.

How to get the excel file name / path in VBA

   strScriptFullname = WScript.ScriptFullName 
   strScriptPath = Left(strScriptFullname, InStrRev(strScriptFullname,"\")) 

Why is document.write considered a "bad practice"?

A few of the more serious problems:

  • document.write (henceforth DW) does not work in XHTML

  • DW does not directly modify the DOM, preventing further manipulation (trying to find evidence of this, but it's at best situational)

  • DW executed after the page has finished loading will overwrite the page, or write a new page, or not work

  • DW executes where encountered: it cannot inject at a given node point

  • DW is effectively writing serialised text which is not the way the DOM works conceptually, and is an easy way to create bugs (.innerHTML has the same problem)

Far better to use the safe and DOM friendly DOM manipulation methods

Try-Catch-End Try in VBScript doesn't seem to work

Handling Errors

A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:

On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear      ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
    WScript.Echo "Error: " & Err.Number
    WScript.Echo "Error (Hex): " & Hex(Err.Number)
    WScript.Echo "Source: " &  Err.Source
    WScript.Echo "Description: " &  Err.Description
    Err.Clear             ' Clear the Error
End If
On Error Goto 0           ' Don't resume on Error
WScript.Echo "This text will always print."

Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).

Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.

If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.

The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.


Raising Errors

If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.

If MyValue <> 42 Then
    Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If

You could then handle the raised error as discussed above.


Change Log

  • Edit #1: Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
  • Edit #2: Clarified.
  • Edit #3: Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
  • Using the "start" command with parameters passed to the started program

    You can use quotes by using the [/D"Path"] use /D only for specifying the path and not the path+program. It appears that all code on the same line that follows goes back to normal meaning you don't need to separate path and file.

        start  /D "C:\Program Files\Internet Explorer\" IEXPLORE.EXE
    

    or:

        start  /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE
    

    will start IE with default web page.

        start  /D "TITLE" "C:\Program Files\Internet Explorer\" IEXPLORE.EXE www.bing.com
    

    starts with Bing, but does not reset your home page.

    /D stands for "directory" and using quotes is OK!

    WRONG EXAMPLE:

        start  /D "TITLE" "C:\Program Files\Internet Explorer\IEXPLORE.EXE"
    

    gives:

    ERROR "The current directory is invalid."

    /D must only be followed by a directory path. Then space and the batchfile or program you wish to start/run

    Tested and works under XP but windows Vista/7/8 may need some adjustments to UAC.

    -Mrbios

    Best way to do multiple constructors in PHP

    As has already been shown here, there are many ways of declaring multiple constructors in PHP, but none of them are the correct way of doing so (since PHP technically doesn't allow it). But it doesn't stop us from hacking this functionality... Here's another example:

    <?php
    
    class myClass {
        public function __construct() {
            $get_arguments       = func_get_args();
            $number_of_arguments = func_num_args();
    
            if (method_exists($this, $method_name = '__construct'.$number_of_arguments)) {
                call_user_func_array(array($this, $method_name), $get_arguments);
            }
        }
    
        public function __construct1($argument1) {
            echo 'constructor with 1 parameter ' . $argument1 . "\n";
        }
    
        public function __construct2($argument1, $argument2) {
            echo 'constructor with 2 parameter ' . $argument1 . ' ' . $argument2 . "\n";
        }
    
        public function __construct3($argument1, $argument2, $argument3) {
            echo 'constructor with 3 parameter ' . $argument1 . ' ' . $argument2 . ' ' . $argument3 . "\n";
        }
    }
    
    $object1 = new myClass('BUET');
    $object2 = new myClass('BUET', 'is');
    $object3 = new myClass('BUET', 'is', 'Best.');
    

    Source: The easiest way to use and understand multiple constructors:

    Hope this helps. :)

    How schedule build in Jenkins?

    The steps for schedule jobs in Jenkins:

    1. click on "Configure" of the job requirement
    2. scroll down to "Build Triggers" - subtitle
    3. Click on the checkBox of Build periodically
    4. Add time schedule in the Schedule field, for example, @midnight

    enter image description here

    Note: under the schedule field, can see the last and the next date-time run.

    Jenkins also supports predefined aliases to schedule build:

    @hourly, @daily, @weekly, @monthly, @midnight

    @hourly --> Build every hour at the beginning of the hour --> 0 * * * *

    @daily, @midnight --> Build every day at midnight --> 0 0 * * *

    @weekly --> Build every week at midnight on Sunday morning --> 0 0 * * 0

    @monthly --> Build every month at midnight of the first day of the month --> 0 0 1 * *

    Set background color of WPF Textbox in C# code

    You can convert hex to RGB:

    string ccode = "#00FFFF00";
    int argb = Int32.Parse(ccode.Replace("#", ""), NumberStyles.HexNumber);
    Color clr = Color.FromArgb(argb);
    

    Compare two files and write it to "match" and "nomatch" files

    I had used JCL about 2 years back so cannot write a code for you but here is the idea;

    1. Have 2 steps
    2. First step will have ICETOOl where you can write the matching records to matched file.
    3. Second you can write a file for mismatched by using SORT/ICETOOl or by just file operations.

    again i apologize for solution without code, but i am out of touch by 2 yrs+

    Change hover color on a button with Bootstrap customization

    I had to add !important to get it to work. I also made my own class button-primary-override.

    .button-primary-override:hover, 
    .button-primary-override:active,
    .button-primary-override:focus,
    .button-primary-override:visited{
        background-color: #42A5F5 !important;
        border-color: #42A5F5 !important;
        background-image: none !important;
        border: 0 !important;
    }
    

    How do I list loaded plugins in Vim?

    Not a VIM user myself, so forgive me if this is totally offbase. But according to what I gather from the following VIM Tips site:

    " where was an option set  
    :scriptnames            : list all plugins, _vimrcs loaded (super)  
    :verbose set history?   : reveals value of history and where set  
    :function               : list functions  
    :func SearchCompl       : List particular function
    

    How to make several plots on a single page using matplotlib?

    @doug & FS.'s answer are very good solutions. I want to share the solution for iteration on pandas.dataframe.

    import pandas as pd
    df=pd.DataFrame([[1, 2], [3, 4], [4, 3], [2, 3]])
    fig = plt.figure(figsize=(14,8))
    for i in df.columns:
        ax=plt.subplot(2,1,i+1) 
        df[[i]].plot(ax=ax)
        print(i)
    plt.show()
    

    ASP.NET MVC Custom Error Handling Application_Error Global.asax?

    This may not be the best way for MVC ( https://stackoverflow.com/a/9461386/5869805 )

    Below is how you render a view in Application_Error and write it to http response. You do not need to use redirect. This will prevent a second request to server, so the link in browser's address bar will stay same. This may be good or bad, it depends on what you want.

    Global.asax.cs

    protected void Application_Error()
    {
        var exception = Server.GetLastError();
        // TODO do whatever you want with exception, such as logging, set errorMessage, etc.
        var errorMessage = "SOME FRIENDLY MESSAGE";
    
        // TODO: UPDATE BELOW FOUR PARAMETERS ACCORDING TO YOUR ERROR HANDLING ACTION
        var errorArea = "AREA";
        var errorController = "CONTROLLER";
        var errorAction = "ACTION";
        var pathToViewFile = $"~/Areas/{errorArea}/Views/{errorController}/{errorAction}.cshtml"; // THIS SHOULD BE THE PATH IN FILESYSTEM RELATIVE TO WHERE YOUR CSPROJ FILE IS!
    
        var requestControllerName = Convert.ToString(HttpContext.Current.Request.RequestContext?.RouteData?.Values["controller"]);
        var requestActionName = Convert.ToString(HttpContext.Current.Request.RequestContext?.RouteData?.Values["action"]);
    
        var controller = new BaseController(); // REPLACE THIS WITH YOUR BASE CONTROLLER CLASS
        var routeData = new RouteData { DataTokens = { { "area", errorArea } }, Values = { { "controller", errorController }, {"action", errorAction} } };
        var controllerContext = new ControllerContext(new HttpContextWrapper(HttpContext.Current), routeData, controller);
        controller.ControllerContext = controllerContext;
    
        var sw = new StringWriter();
        var razorView = new RazorView(controller.ControllerContext, pathToViewFile, "", false, null);
        var model = new ViewDataDictionary(new HandleErrorInfo(exception, requestControllerName, requestActionName));
        var viewContext = new ViewContext(controller.ControllerContext, razorView, model, new TempDataDictionary(), sw);
        viewContext.ViewBag.ErrorMessage = errorMessage;
        //TODO: add to ViewBag what you need
        razorView.Render(viewContext, sw);
        HttpContext.Current.Response.Write(sw);
        Server.ClearError();
        HttpContext.Current.Response.End(); // No more processing needed (ex: by default controller/action routing), flush the response out and raise EndRequest event.
    }
    

    View

    @model HandleErrorInfo
    @{
        ViewBag.Title = "Error";
        // TODO: SET YOUR LAYOUT
    }
    <div class="">
        ViewBag.ErrorMessage
    </div>
    @if(Model != null && HttpContext.Current.IsDebuggingEnabled)
    {
        <div class="" style="background:khaki">
            <p>
                <b>Exception:</b> @Model.Exception.Message <br/>
                <b>Controller:</b> @Model.ControllerName <br/>
                <b>Action:</b> @Model.ActionName <br/>
            </p>
            <div>
                <pre>
                    @Model.Exception.StackTrace
                </pre>
            </div>
        </div>
    }
    

    fs: how do I locate a parent folder?

    Try this:

    fs.readFile(__dirname + '/../../foo.bar');
    

    Note the forward slash at the beginning of the relative path.

    Passing arguments to an interactive program non-interactively

    For more complex tasks there is expect ( http://en.wikipedia.org/wiki/Expect ). It basically simulates a user, you can code a script how to react to specific program outputs and related stuff.

    This also works in cases like ssh that prohibits piping passwords to it.

    Change Tomcat Server's timeout in Eclipse

    Windows->Preferences->Server

    Server Timeout can be specified there.

    or another method via the Servers tab here:

    http://henneberke.wordpress.com/2009/09/28/fixing-eclipse-tomcat-timeout/

    In an array of objects, fastest way to find the index of an object whose attributes match a search

    The simplest and easiest way to find element index in array.

    ES5 syntax: [{id:1},{id:2},{id:3},{id:4}].findIndex(function(obj){return obj.id == 3})

    ES6 syntax: [{id:1},{id:2},{id:3},{id:4}].findIndex(obj => obj.id == 3)

    Class constructor type in typescript?

    How can I declare a class type, so that I ensure the object is a constructor of a general class?

    A Constructor type could be defined as:

     type AConstructorTypeOf<T> = new (...args:any[]) => T;
    
     class A { ... }
    
     function factory(Ctor: AConstructorTypeOf<A>){
       return new Ctor();
     }
    
    const aInstance = factory(A);
    

    How to check if a subclass is an instance of a class at runtime?

    You have to read the API carefully for this methods. Sometimes you can get confused very easily.

    It is either:

    if (B.class.isInstance(view))
    

    API says: Determines if the specified Object (the parameter) is assignment-compatible with the object represented by this Class (The class object you are calling the method at)

    or:

    if (B.class.isAssignableFrom(view.getClass()))
    

    API says: Determines if the class or interface represented by this Class object is either the same as, or is a superclass or superinterface of, the class or interface represented by the specified Class parameter

    or (without reflection and the recommended one):

    if (view instanceof B)
    

    Fastest way to check if a file exist using standard C++/C++11/C?

    Same as suggested by PherricOxide but in C

    #include <sys/stat.h>
    int exist(const char *name)
    {
      struct stat   buffer;
      return (stat (name, &buffer) == 0);
    }
    

    Detect key input in Python

    Key input is a predefined event. You can catch events by attaching event_sequence(s) to event_handle(s) by using one or multiple of the existing binding methods(bind, bind_class, tag_bind, bind_all). In order to do that:

    1. define an event_handle method
    2. pick an event(event_sequence) that fits your case from an events list

    When an event happens, all of those binding methods implicitly calls the event_handle method while passing an Event object, which includes information about specifics of the event that happened, as the argument.

    In order to detect the key input, one could first catch all the '<KeyPress>' or '<KeyRelease>' events and then find out the particular key used by making use of event.keysym attribute.

    Below is an example using bind to catch both '<KeyPress>' and '<KeyRelease>' events on a particular widget(root):

    try:                        # In order to be able to import tkinter for
        import tkinter as tk    # either in python 2 or in python 3
    except ImportError:
        import Tkinter as tk
    
    
    def event_handle(event):
        # Replace the window's title with event.type: input key
        root.title("{}: {}".format(str(event.type), event.keysym))
    
    
    if __name__ == '__main__':
        root = tk.Tk()
        event_sequence = '<KeyPress>'
        root.bind(event_sequence, event_handle)
        root.bind('<KeyRelease>', event_handle)
        root.mainloop()
    

    How to create local notifications?

    Updated with Swift 5 Generally we use three type of Local Notifications

    1. Simple Local Notification
    2. Local Notification with Action
    3. Local Notification with Content

    Where you can send simple text notification or with action button and attachment.

    Using UserNotifications package in your app, the following example Request for notification permission, prepare and send notification as per user action AppDelegate itself, and use view controller listing different type of local notification test.

    AppDelegate

    import UIKit
    import UserNotifications
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
    
        let notificationCenter = UNUserNotificationCenter.current()
        var window: UIWindow?
    
    
        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
    
            //Confirm Delegete and request for permission
            notificationCenter.delegate = self
            let options: UNAuthorizationOptions = [.alert, .sound, .badge]
            notificationCenter.requestAuthorization(options: options) {
                (didAllow, error) in
                if !didAllow {
                    print("User has declined notifications")
                }
            }
    
            return true
        }
    
        func applicationWillResignActive(_ application: UIApplication) {
        }
        func applicationDidEnterBackground(_ application: UIApplication) {
        }
        func applicationWillEnterForeground(_ application: UIApplication) {
        }
        func applicationWillTerminate(_ application: UIApplication) {
        }
        func applicationDidBecomeActive(_ application: UIApplication) {
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
    
    
        //MARK: Local Notification Methods Starts here
    
        //Prepare New Notificaion with deatils and trigger
        func scheduleNotification(notificationType: String) {
    
            //Compose New Notificaion
            let content = UNMutableNotificationContent()
            let categoryIdentifire = "Delete Notification Type"
            content.sound = UNNotificationSound.default
            content.body = "This is example how to send " + notificationType
            content.badge = 1
            content.categoryIdentifier = categoryIdentifire
    
            //Add attachment for Notification with more content
            if (notificationType == "Local Notification with Content")
            {
                let imageName = "Apple"
                guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else { return }
                let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
                content.attachments = [attachment]
            }
    
            let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
            let identifier = "Local Notification"
            let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
    
            notificationCenter.add(request) { (error) in
                if let error = error {
                    print("Error \(error.localizedDescription)")
                }
            }
    
            //Add Action button the Notification
            if (notificationType == "Local Notification with Action")
            {
                let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
                let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
                let category = UNNotificationCategory(identifier: categoryIdentifire,
                                                      actions: [snoozeAction, deleteAction],
                                                      intentIdentifiers: [],
                                                      options: [])
                notificationCenter.setNotificationCategories([category])
            }
        }
    
        //Handle Notification Center Delegate methods
        func userNotificationCenter(_ center: UNUserNotificationCenter,
                                    willPresent notification: UNNotification,
                                    withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
            completionHandler([.alert, .sound])
        }
    
        func userNotificationCenter(_ center: UNUserNotificationCenter,
                                    didReceive response: UNNotificationResponse,
                                    withCompletionHandler completionHandler: @escaping () -> Void) {
            if response.notification.request.identifier == "Local Notification" {
                print("Handling notifications with the Local Notification Identifier")
            }
            completionHandler()
        }
    }
    

    and ViewController

    import UIKit
    
    class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
        var appDelegate = UIApplication.shared.delegate as? AppDelegate
        let notifications = ["Simple Local Notification",
                             "Local Notification with Action",
                             "Local Notification with Content",]
    
        override func viewDidLoad() {
            super.viewDidLoad()
        }
    
        // MARK: - Table view data source
    
         func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return notifications.count
        }
    
         func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
            cell.textLabel?.text = notifications[indexPath.row]
            return cell
        }
    
         func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
            let notificationType = notifications[indexPath.row]
            let alert = UIAlertController(title: "",
                                          message: "After 5 seconds " + notificationType + " will appear",
                                          preferredStyle: .alert)
            let okAction = UIAlertAction(title: "Okay, I will wait", style: .default) { (action) in
                self.appDelegate?.scheduleNotification(notificationType: notificationType)
            }
            alert.addAction(okAction)
            present(alert, animated: true, completion: nil)
        }
    }
    

    jQuery exclude elements with certain class in selector

    To add some info that helped me today, a jQuery object/this can also be passed in to the .not() selector.

    _x000D_
    _x000D_
    $(document).ready(function(){_x000D_
        $(".navitem").click(function(){_x000D_
            $(".navitem").removeClass("active");_x000D_
            $(".navitem").not($(this)).addClass("active");_x000D_
        });_x000D_
    });
    _x000D_
    .navitem_x000D_
    {_x000D_
        width: 100px;_x000D_
        background: red;_x000D_
        color: white;_x000D_
        display: inline-block;_x000D_
        position: relative;_x000D_
        text-align: center;_x000D_
    }_x000D_
    .navitem.active_x000D_
    {_x000D_
        background:green;_x000D_
    }
    _x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
    _x000D_
    <div class="navitem">Home</div>_x000D_
    <div class="navitem">About</div>_x000D_
    <div class="navitem">Pricing</div>
    _x000D_
    _x000D_
    _x000D_

    The above example can be simplified, but wanted to show the usage of this in the not() selector.

    How does one Display a Hyperlink in React Native App?

    Use React Native Hyperlink (Native <A> tag):

    Install:

    npm i react-native-a
    

    import:

    import A from 'react-native-a'
    

    Usage:

    1. <A>Example.com</A>
    2. <A href="example.com">Example</A>
    3. <A href="https://example.com">Example</A>
    4. <A href="example.com" style={{fontWeight: 'bold'}}>Example</A>

    How to efficiently calculate a running standard deviation?

    I like to express the update this way:

    def running_update(x, N, mu, var):
        '''
            @arg x: the current data sample
            @arg N : the number of previous samples
            @arg mu: the mean of the previous samples
            @arg var : the variance over the previous samples
            @retval (N+1, mu', var') -- updated mean, variance and count
        '''
        N = N + 1
        rho = 1.0/N
        d = x - mu
        mu += rho*d
        var += rho*((1-rho)*d**2 - var)
        return (N, mu, var)
    

    so that a one-pass function would look like this:

    def one_pass(data):
        N = 0
        mu = 0.0
        var = 0.0
        for x in data:
            N = N + 1
            rho = 1.0/N
            d = x - mu
            mu += rho*d
            var += rho*((1-rho)*d**2 - var)
            # could yield here if you want partial results
       return (N, mu, var)
    

    note that this is calculating the sample variance (1/N), not the unbiased estimate of the population variance (which uses a 1/(N-1) normalzation factor). Unlike the other answers, the variable, var, that is tracking the running variance does not grow in proportion to the number of samples. At all times it is just the variance of the set of samples seen so far (there is no final "dividing by n" in getting the variance).

    In a class it would look like this:

    class RunningMeanVar(object):
        def __init__(self):
            self.N = 0
            self.mu = 0.0
            self.var = 0.0
        def push(self, x):
            self.N = self.N + 1
            rho = 1.0/N
            d = x-self.mu
            self.mu += rho*d
            self.var += + rho*((1-rho)*d**2-self.var)
        # reset, accessors etc. can be setup as you see fit
    

    This also works for weighted samples:

    def running_update(w, x, N, mu, var):
        '''
            @arg w: the weight of the current sample
            @arg x: the current data sample
            @arg mu: the mean of the previous N sample
            @arg var : the variance over the previous N samples
            @arg N : the number of previous samples
            @retval (N+w, mu', var') -- updated mean, variance and count
        '''
        N = N + w
        rho = w/N
        d = x - mu
        mu += rho*d
        var += rho*((1-rho)*d**2 - var)
        return (N, mu, var)
    

    Merge two Excel tables Based on matching data in Columns

    Put the table in the second image on Sheet2, columns D to F.

    In Sheet1, cell D2 use the formula

    =iferror(vlookup($A2,Sheet2!$D$1:$F$100,column(A1),false),"")
    

    copy across and down.

    Edit: here is a picture. The data is in two sheets. On Sheet1, enter the formula into cell D2. Then copy the formula across to F2 and then down as many rows as you need.

    enter image description here

    Deleting rows with MySQL LEFT JOIN

    This script worked for me:

    DELETE t
    FROM table t
    INNER JOIN join_table jt ON t.fk_column = jt.id
    WHERE jt.comdition_column…;
    

    Sorted collection in Java

    Use TreeSet which gives elements in sorted order. OR use Collection.sort() for external sorting with Comparator().

    python pandas dataframe to dictionary

    Simplest solution:

    df.set_index('id').T.to_dict('records')
    

    Example:

    df= pd.DataFrame([['a',1],['a',2],['b',3]], columns=['id','value'])
    df.set_index('id').T.to_dict('records')
    

    If you have multiple values, like val1, val2, val3,etc and u want them as lists, then use the below code:

    df.set_index('id').T.to_dict('list')
    

    How can I use tabs for indentation in IntelliJ IDEA?

    File > Settings > Editor > Code Style > Java > Tabs and Indents > Use tab character

    Substitute weapon of choice for Java as required.

    Bash checking if string does not contain other string

    Use !=.

    if [[ ${testmystring} != *"c0"* ]];then
        # testmystring does not contain c0
    fi
    

    See help [[ for more information.

    Should I use SVN or Git?

    If your team is already familiar with version and source control softwares like cvs or svn, then, for a simple and small project (such as you claim it is), I would recommend you stick to SVN. I am really comfortable with svn, but for the current e-commerce project I am doing on django, I decided to work on git (I am using git in svn-mode, that is, with a centralised repo that I push to and pull from in order to collaborate with at least one other developer). The other developer is comfortable with SVN, and while others' experiences may differ, both of us are having a really bad time embracing git for this small project. (We are both hardcore Linux users, if it matters at all.)

    Your mileage may vary, of course.

    What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

    The best way I have found to get a feel for things like this is to try them out:

    import java.io.File;
    public class PathTesting {
        public static void main(String [] args) {
            File f = new File("test/.././file.txt");
            System.out.println(f.getPath());
            System.out.println(f.getAbsolutePath());
            try {
                System.out.println(f.getCanonicalPath());
            }
            catch(Exception e) {}
        }
    }
    

    Your output will be something like:

    test\..\.\file.txt
    C:\projects\sandbox\trunk\test\..\.\file.txt
    C:\projects\sandbox\trunk\file.txt
    

    So, getPath() gives you the path based on the File object, which may or may not be relative; getAbsolutePath() gives you an absolute path to the file; and getCanonicalPath() gives you the unique absolute path to the file. Notice that there are a huge number of absolute paths that point to the same file, but only one canonical path.

    When to use each? Depends on what you're trying to accomplish, but if you were trying to see if two Files are pointing at the same file on disk, you could compare their canonical paths. Just one example.

    Encode URL in JavaScript?

    You have three options:

    • escape() will not encode: @*/+

    • encodeURI() will not encode: ~!@#$&*()=:/,;?+'

    • encodeURIComponent() will not encode: ~!*()'

    But in your case, if you want to pass a URL into a GET parameter of other page, you should use escape or encodeURIComponent, but not encodeURI.

    See Stack Overflow question Best practice: escape, or encodeURI / encodeURIComponent for further discussion.

    Role/Purpose of ContextLoaderListener in Spring?

    For a simple Spring application, you don't have to define ContextLoaderListener in your web.xml; you can just put all your Spring configuration files in <servlet>:

    <servlet>
        <servlet-name>hello</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/mvc-core-config.xml, classpath:spring/business-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    

    For a more complex Spring application, where you have multiple DispatcherServlet defined, you can have the common Spring configuration files that are shared by all the DispatcherServlet defined in the ContextLoaderListener:

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/common-config.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    
    <servlet>
        <servlet-name>mvc1</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/mvc1-config.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet>
        <servlet-name>mvc2</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/mvc2-config.xmll</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    

    Just keep in mind, ContextLoaderListener performs the actual initialization work for the root application context.

    I found this article helps a lot: Spring MVC – Application Context vs Web Application Context

    How to use hex color values

    Swift 4.0

    use this Single line of method

    override func viewDidLoad() {
        super.viewDidLoad()
    
       let color = UIColor(hexColor: "FF00A0")
       self.view.backgroundColor = color
    
    }
    

    You have to create new Class or use any controller where u need to use Hex color. This extension class provide you UIColor that will convert Hex to RGB color.

    extension UIColor {
    convenience init(hexColor: String) {
        let scannHex = Scanner(string: hexColor)
        var rgbValue: UInt64 = 0
        scannHex.scanLocation = 0
        scannHex.scanHexInt64(&rgbValue)
        let r = (rgbValue & 0xff0000) >> 16
        let g = (rgbValue & 0xff00) >> 8
        let b = rgbValue & 0xff
        self.init(
            red: CGFloat(r) / 0xff,
            green: CGFloat(g) / 0xff,
            blue: CGFloat(b) / 0xff, alpha: 1
        )
      }
    }
    

    Eclipse C++: Symbol 'std' could not be resolved

    What allowed me to fix the problem was going to: Project -> Properties -> C/C++ General -> Preprocessor Include Paths, Macros, etc. -> Providers -> CDT GCC built-in compiler settings, enabling that and disabling the CDT Cross GCC Built-in Compiler Settings

    jQuery "on create" event for dynamically-created elements

    You can on the DOMNodeInserted event to get an event for when it's added to the document by your code.

    $('body').on('DOMNodeInserted', 'select', function () {
          //$(this).combobox();
    });
    
    $('<select>').appendTo('body');
    $('<select>').appendTo('body');
    

    Fiddled here: http://jsfiddle.net/Codesleuth/qLAB2/3/

    EDIT: after reading around I just need to double check DOMNodeInserted won't cause problems across browsers. This question from 2010 suggests IE doesn't support the event, so test it if you can.

    See here: [link] Warning! the DOMNodeInserted event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type.

    Counting array elements in Python

    len is a built-in function that calls the given container object's __len__ member function to get the number of elements in the object.

    Functions encased with double underscores are usually "special methods" implementing one of the standard interfaces in Python (container, number, etc). Special methods are used via syntactic sugar (object creation, container indexing and slicing, attribute access, built-in functions, etc.).

    Using obj.__len__() wouldn't be the correct way of using the special method, but I don't see why the others were modded down so much.

    PL/SQL block problem: No data found error

    Your SELECT statement isn't finding the data you're looking for. That is, there is no record in the ENROLLMENT table with the given STUDENT_ID and SECTION_ID. You may want to try putting some DBMS_OUTPUT.PUT_LINE statements before you run the query, printing the values of v_student_id and v_section_id. They may not be containing what you expect them to contain.

    matplotlib colorbar for scatter

    Here is the OOP way of adding a colorbar:

    fig, ax = plt.subplots()
    im = ax.scatter(x, y, c=c)
    fig.colorbar(im, ax=ax)
    

    Hibernate, @SequenceGenerator and allocationSize

    allocationSize=1 It is a micro optimization before getting query Hibernate tries to assign value in the range of allocationSize and so try to avoid querying database for sequence. But this query will be executed every time if you set it to 1. This hardly makes any difference since if your data base is accessed by some other application then it will create issues if same id is used by another application meantime .

    Next generation of Sequence Id is based on allocationSize.

    By defualt it is kept as 50 which is too much. It will also only help if your going to have near about 50 records in one session which are not persisted and which will be persisted using this particular session and transation.

    So you should always use allocationSize=1 while using SequenceGenerator. As for most of underlying databases sequence is always incremented by 1.

    How do you UDP multicast in Python?

    tolomea's answer worked for me. I hacked it into socketserver.UDPServer too:

    class ThreadedMulticastServer(socketserver.ThreadingMixIn, socketserver.UDPServer):
        def __init__(self, *args):
            super().__init__(*args)
            self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
            self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            self.socket.bind((MCAST_GRP, MCAST_PORT))
            mreq = struct.pack('4sl', socket.inet_aton(MCAST_GRP), socket.INADDR_ANY)
            self.socket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mreq)
    

    How to connect to LocalDB in Visual Studio Server Explorer?

    OK, answering to my own question.

    Steps to connect LocalDB to Visual Studio Server Explorer

    1. Open command prompt
    2. Run SqlLocalDB.exe start v11.0
    3. Run SqlLocalDB.exe info v11.0
    4. Copy the Instance pipe name that starts with np:\...
    5. In Visual Studio select TOOLS > Connect to Database...
    6. For Server Name enter (localdb)\v11.0. If it didn't work, use the Instance pipe name that you copied earlier. You can also use this to connect with SQL Management Studio.
    7. Select the database on next dropdown list
    8. Click OK

    enter image description here

    Aligning textviews on the left and right edges in Android layout

    You can use the gravity property to "float" views.

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
    
        <LinearLayout 
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                android:gravity="center_vertical|center_horizontal"
                android:orientation="horizontal">
    
            <TextView  
                android:layout_width="wrap_content" 
                android:layout_height="wrap_content" 
                android:gravity="left"
                android:layout_weight="1"
                android:text="Left Aligned"
                />
    
            <TextView  
                android:layout_width="wrap_content" 
                android:layout_height="wrap_content"
                android:gravity="right"
                android:layout_weight="1"
                android:text="Right Aligned"
                />
        </LinearLayout>
    
    </LinearLayout>
    

    INSERT INTO TABLE from comma separated varchar-list

    Sql Server does not (on my knowledge) have in-build Split function. Split function in general on all platforms would have comma-separated string value to be split into individual strings. In sql server, the main objective or necessary of the Split function is to convert a comma-separated string value (‘abc,cde,fgh’) into a temp table with each string as rows.

    The below Split function is Table-valued function which would help us splitting comma-separated (or any other delimiter value) string to individual string.

    CREATE FUNCTION dbo.Split(@String varchar(8000), @Delimiter char(1))       
    returns @temptable TABLE (items varchar(8000))       
    as       
    begin       
        declare @idx int       
        declare @slice varchar(8000)       
    
        select @idx = 1       
            if len(@String)<1 or @String is null  return       
    
        while @idx!= 0       
        begin       
            set @idx = charindex(@Delimiter,@String)       
            if @idx!=0       
                set @slice = left(@String,@idx - 1)       
            else       
                set @slice = @String       
    
            if(len(@slice)>0)  
                insert into @temptable(Items) values(@slice)       
    
            set @String = right(@String,len(@String) - @idx)       
            if len(@String) = 0 break       
        end   
    return       
    end  
    

    select top 10 * from dbo.split('Chennai,Bangalore,Mumbai',',')

    the complete can be found at follownig link http://www.logiclabz.com/sql-server/split-function-in-sql-server-to-break-comma-separated-strings-into-table.aspx

    How to access child's state in React?

    Now You can access the InputField's state which is the child of FormEditor .

    Basically whenever there is a change in the state of the input field(child) we are getting the value from the event object and then passing this value to the Parent where in the state in the Parent is set.

    On button click we are just printing the state of the Input fields.

    The key point here is that we are using the props to get the Input Field's id/value and also to call the functions which are set as attributes on the Input Field while we generate the reusable child Input fields.

    class InputField extends React.Component{
      handleChange = (event)=> {
        const val = event.target.value;
        this.props.onChange(this.props.id , val);
      }
    
      render() {
        return(
          <div>
            <input type="text" onChange={this.handleChange} value={this.props.value}/>
            <br/><br/>
          </div>
        );
      }
    }       
    
    
    class FormEditorParent extends React.Component {
      state = {};
      handleFieldChange = (inputFieldId , inputFieldValue) => {
        this.setState({[inputFieldId]:inputFieldValue});
      }
      //on Button click simply get the state of the input field
      handleClick = ()=>{
        console.log(JSON.stringify(this.state));
      }
    
      render() {
        const fields = this.props.fields.map(field => (
          <InputField
            key={field}
            id={field}
            onChange={this.handleFieldChange}
            value={this.state[field]}
          />
        ));
    
        return (
          <div>
            <div>
              <button onClick={this.handleClick}>Click Me</button>
            </div>
            <div>
              {fields}
            </div>
          </div>
        );
      }
    }
    
    const App = () => {
      const fields = ["field1", "field2", "anotherField"];
      return <FormEditorParent fields={fields} />;
    };
    
    ReactDOM.render(<App/>, mountNode);
    

    Struct inheritance in C++

    Yes. The inheritance is public by default.

    Syntax (example):

    struct A { };
    struct B : A { };
    struct C : B { };
    

    How to get value at a specific index of array In JavaScript?

    Array indexes in JavaScript start at zero for the first item, so try this:

    var firstArrayItem = myValues[0]
    

    Of course, if you actually want the second item in the array at index 1, then it's myValues[1].

    See Accessing array elements for more info.

    Python - Module Not Found

    After trying to add the path using:

    pip show
    

    on command prompt and using

    sys.path.insert(0, "/home/myname/pythonfiles")
    

    and didn't work. Also got SSL error when trying to install the module again using conda this time instead of pip.

    I simply copied the module that wasn't found from the path "Mine was in

    C:\Users\user\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.7_qbz5n2kfra8p0\LocalCache\local-packages\Python37\site-packages 
    

    so I copied it to 'C:\Users\user\Anaconda3\Lib\site-packages'

    Naming threads and thread-pools of ExecutorService

    Using the existing functionality of Executors.defaultThreadFactory() but just setting the name:

    import java.util.concurrent.Executors;
    import java.util.concurrent.ThreadFactory;
    
    public class NamingThreadFactory implements ThreadFactory {
        private final String prefix;
        private int threadNuber = 0;
    
        public NamingThreadFactory(String prefix){
            this.prefix = prefix;
        }
    
        @Override
        public Thread newThread(Runnable r) {
            Thread t = Executors.defaultThreadFactory().newThread(r);
            t.setName(prefix + threadNuber);
            return t;
        }
    }
    

    Converting pixels to dp

    private fun toDP(context: Context,value: Int): Int {
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
            value.toFloat(),context.resources.displayMetrics).toInt()
    }
    

    Text not wrapping inside a div element

    That's because there are no spaces in that long string so it has to break out of its container. Add word-break:break-all; to your .title rules to force a break.

    #calendar_container > #events_container > .event_block > .title {
        width:400px;
        font-size:12px;
        word-break:break-all;
    }
    

    jsFiddle example

    Entity Framework Code First - two Foreign Keys from same table

    This is because Cascade Deletes are enabled by default. The problem is that when you call a delete on the entity, it will delete each of the f-key referenced entities as well. You should not make 'required' values nullable to fix this problem. A better option would be to remove EF Code First's Cascade delete convention:

    modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>(); 
    

    It's probably safer to explicitly indicate when to do a cascade delete for each of the children when mapping/config. the entity.

    How to return HTTP 500 from ASP.NET Core RC2 Web Api?

    From what I can see there are helper methods inside the ControllerBase class. Just use the StatusCode method:

    [HttpPost]
    public IActionResult Post([FromBody] string something)
    {    
        //...
        try
        {
            DoSomething();
        }
        catch(Exception e)
        {
             LogException(e);
             return StatusCode(500);
        }
    }
    

    You may also use the StatusCode(int statusCode, object value) overload which also negotiates the content.

    applying css to specific li class

    I only see one color being specified (albeit you specify it in two different places.) Either you've omitted some of your style rules, or you simply didn't specify another color.

    How to declare 2D array in bash

    Bash doesn't have multi-dimensional array. But you can simulate a somewhat similar effect with associative arrays. The following is an example of associative array pretending to be used as multi-dimensional array:

    declare -A arr
    arr[0,0]=0
    arr[0,1]=1
    arr[1,0]=2
    arr[1,1]=3
    echo "${arr[0,0]} ${arr[0,1]}" # will print 0 1
    

    If you don't declare the array as associative (with -A), the above won't work. For example, if you omit the declare -A arr line, the echo will print 2 3 instead of 0 1, because 0,0, 1,0 and such will be taken as arithmetic expression and evaluated to 0 (the value to the right of the comma operator).

    multiple axis in matplotlib with different scales

    If I understand the question, you may interested in this example in the Matplotlib gallery.

    enter image description here

    Yann's comment above provides a similar example.


    Edit - Link above fixed. Corresponding code copied from the Matplotlib gallery:

    from mpl_toolkits.axes_grid1 import host_subplot
    import mpl_toolkits.axisartist as AA
    import matplotlib.pyplot as plt
    
    host = host_subplot(111, axes_class=AA.Axes)
    plt.subplots_adjust(right=0.75)
    
    par1 = host.twinx()
    par2 = host.twinx()
    
    offset = 60
    new_fixed_axis = par2.get_grid_helper().new_fixed_axis
    par2.axis["right"] = new_fixed_axis(loc="right", axes=par2,
                                            offset=(offset, 0))
    
    par2.axis["right"].toggle(all=True)
    
    host.set_xlim(0, 2)
    host.set_ylim(0, 2)
    
    host.set_xlabel("Distance")
    host.set_ylabel("Density")
    par1.set_ylabel("Temperature")
    par2.set_ylabel("Velocity")
    
    p1, = host.plot([0, 1, 2], [0, 1, 2], label="Density")
    p2, = par1.plot([0, 1, 2], [0, 3, 2], label="Temperature")
    p3, = par2.plot([0, 1, 2], [50, 30, 15], label="Velocity")
    
    par1.set_ylim(0, 4)
    par2.set_ylim(1, 65)
    
    host.legend()
    
    host.axis["left"].label.set_color(p1.get_color())
    par1.axis["right"].label.set_color(p2.get_color())
    par2.axis["right"].label.set_color(p3.get_color())
    
    plt.draw()
    plt.show()
    
    #plt.savefig("Test")
    

    Python 3.6 install win32api?

    Information provided by @Gord

    As of September 2019 pywin32 is now available from PyPI and installs the latest version (currently version 224). This is done via the pip command

    pip install pywin32
    

    If you wish to get an older version the sourceforge link below would probably have the desired version, if not you can use the command, where xxx is the version you require, e.g. 224

    pip install pywin32==xxx
    

    This differs to the pip command below as that one uses pypiwin32 which currently installs an older (namely 223)

    Browsing the docs I see no reason for these commands to work for all python3.x versions, I am unsure on python2.7 and below so you would have to try them and if they do not work then the solutions below will work.


    Probably now undesirable solutions but certainly still valid as of September 2019

    There is no version of specific version ofwin32api. You have to get the pywin32module which currently cannot be installed via pip. It is only available from this link at the moment.

    https://sourceforge.net/projects/pywin32/files/pywin32/Build%20220/

    The install does not take long and it pretty much all done for you. Just make sure to get the right version of it depending on your python version :)


    EDIT

    Since I posted my answer there are other alternatives to downloading the win32api module.

    It is now available to download through pip using this command;

    pip install pypiwin32
    

    Also it can be installed from this GitHub repository as provided in comments by @Heath

    Styling mat-select in Angular Material

    Put your class name on the mat-form-field element. This works for all inputs.

    "Thinking in AngularJS" if I have a jQuery background?

    Actually, if you're using AngularJS, you don't need jQuery anymore. AngularJS itself has the binding and directive, which is a very good "replacement" for most things you can do with jQuery.

    I usually develop mobile applications using AngularJS and Cordova. The ONLY thing from jQuery I needed is the Selector.

    By googling, I see that there is a standalone jQuery selector module out there. It's Sizzle.

    And I decided to make a tiny code snippet that help me quickly start a website using AngularJS with the power of jQuery Selector (using Sizzle).

    I shared my code here: https://github.com/huytd/Sizzular

    How to do case insensitive string comparison?

    With the help of regular expression also we can achieve.

    (/keyword/i).test(source)
    

    /i is for ignore case. If not necessary we can ignore and test for NOT case sensitive match like

    (/keyword/).test(source)
    

    How do you set the Content-Type header for an HttpClient request?

    I end up having similar issue. So I discovered that the Software PostMan can generate code when clicking the "Code" button at upper/left corner. From that we can see what going on "under the hood" and the HTTP call is generated in many code language; curl command, C# RestShart, java, nodeJs, ...

    That helped me a lot and instead of using .Net base HttpClient I ended up using RestSharp nuget package.

    Hope that can help someone else!

    Only get hash value using md5sum (without filename)

    Well another way :)

    md5=`md5sum ${my_iso_file} | awk '{ print $1 }'`
    

    Downloading jQuery UI CSS from Google's CDN

    I would think so. Why not? Wouldn't be much of a CDN w/o offering the CSS to support the script files

    This link suggests that they are:

    We find it particularly exciting that the jQuery UI CSS themes are now hosted on Google's Ajax Libraries CDN.

    How to close a web page on a button click, a hyperlink or a link button click?

    To close a windows form (System.Windows.Forms.Form) when one of its button is clicked: in Visual Studio, open the form in the designer, right click on the button and open its property page, then select the field DialogResult an set it to OK or the appropriate value.

    grep a tab in UNIX

    On ksh I used

    grep "[^I]" testfile
    

    Error 'LINK : fatal error LNK1123: failure during conversion to COFF: file invalid or corrupt' after installing Visual Studio 2012 Release Preview

    Reinstalling CMake worked for me. The new copy of CMake figured out that it should use Visual Studio 11 instead of 10.

    chart.js load totally new data

    Not is necesary destroy the chart. Try with this

    function removeData(chart) {
    
            let total = chart.data.labels.length;
    
            while (total >= 0) {
                chart.data.labels.pop();
                chart.data.datasets[0].data.pop();
                total--;
            }
    
            chart.update();
        }
    

    Password encryption/decryption code in .NET

    This question will answer how to encrypt/decrypt: Encrypt and decrypt a string in C#?

    You didn't specify a database, but you will want to base-64 encode it, using Convert.toBase64String. For an example you can use: http://www.opinionatedgeek.com/Blog/blogentry=000361/BlogEntry.aspx

    You'll then either save it in a varchar or a blob, depending on how long your encrypted message is, but for a password varchar should work.

    The examples above will also cover decryption after decoding the base64.

    UPDATE:

    In actuality you may not need to use base64 encoding, but I found it helpful, in case I wanted to print it, or send it over the web. If the message is long enough it's best to compress it first, then encrypt, as it is harder to use brute-force when the message was already in a binary form, so it would be hard to tell when you successfully broke the encryption.

    How to check ASP.NET Version loaded on a system?

    open a new command prompt and run the following command: dotnet --info

    "ORA-01438: value larger than specified precision allowed for this column" when inserting 3

    NUMBER (precision, scale) means precision number of total digits, of which scale digits are right of the decimal point.

    NUMBER(2,2) in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2) to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.

    More info at the Oracle docs.

    Submit form on pressing Enter with AngularJS

    FWIW - Here's a directive I've used for a basic confirm/alert bootstrap modal, without the need for a <form>

    (just switch out the jQuery click action for whatever you like, and add data-easy-dismiss to your modal tag)

    app.directive('easyDismiss', function() {
        return {
            restrict: 'A',
            link: function ($scope, $element) {
    
                var clickSubmit = function (e) {
                    if (e.which == 13) {
                        $element.find('[type="submit"]').click();
                    }
                };
    
                $element.on('show.bs.modal', function() {
                    $(document).on('keypress', clickSubmit);
                });
    
                $element.on('hide.bs.modal', function() {
                    $(document).off('keypress', clickSubmit);
                });
            }
        };
    });
    

    How to convert answer into two decimal point

    Try using the Format function:

    Private Sub btncalc_Click(ByVal sender As System.Object,
                              ByVal e As System.EventArgs) Handles btncalc.Click
      txtA.Text = Format(Val(txtD.Text) / Val(txtC.Text) * 
                         Val(txtF.Text) / Val(txtE.Text), "0.00")
      txtB.Text = Format(Val(txtA.Text) * 1000 / Val(txtG.Text), "0.00")
    End Sub
    

    SQL variable to hold list of integers

    You are right, there is no datatype in SQL-Server which can hold a list of integers. But what you can do is store a list of integers as a string.

    DECLARE @listOfIDs varchar(8000);
    SET @listOfIDs = '1,2,3,4';
    

    You can then split the string into separate integer values and put them into a table. Your procedure might already do this.

    You can also use a dynamic query to achieve the same outcome:

    DECLARE @SQL nvarchar(8000);
    
    SET @SQL = 'SELECT * FROM TabA WHERE TabA.ID IN (' + @listOfIDs + ')';
    EXECUTE (@SQL);
    

    Makefile If-Then Else and Loops

    Conditional Forms

    Simple

    conditional-directive
    text-if-true
    endif
    

    Moderately Complex

    conditional-directive
    text-if-true
    else
    text-if-false
    endif
    

    More Complex

    conditional-directive
    text-if-one-is-true
    else
    conditional-directive
    text-if-true
    else
    text-if-false
    endif
    endif
    

    Conditional Directives

    If Equal Syntax

    ifeq (arg1, arg2)
    ifeq 'arg1' 'arg2'
    ifeq "arg1" "arg2"
    ifeq "arg1" 'arg2'
    ifeq 'arg1' "arg2"
    

    If Not Equal Syntax

    ifneq (arg1, arg2)
    ifneq 'arg1' 'arg2'
    ifneq "arg1" "arg2"
    ifneq "arg1" 'arg2'
    ifneq 'arg1' "arg2"
    

    If Defined Syntax

    ifdef variable-name
    

    If Not Defined Syntax

    ifndef variable-name  
    

    foreach Function

    foreach Function Syntax

    $(foreach var, list, text)  
    

    foreach Semantics
    For each whitespace separated word in "list", the variable named by "var" is set to that word and text is executed.

    How do I use sudo to redirect output to a location I don't have permission to write to?

    I would do it this way:

    sudo su -c 'ls -hal /root/ > /root/test.out'
    

    How to store phone numbers on MySQL databases?

    You should never store values with format. Formatting should be done in the view depending on user preferences.

    Searching for phone nunbers with mixed formatting is near impossible.

    For this case I would split into fields and store as integer. Numbers are faster than texts and splitting them and putting index on them makes all kind of queries ran fast.

    Leading 0 could be a problem but probably not. In Sweden all area codes start with 0 and that is removed if also a country code is dialed. But the 0 isn't really a part of the number, it's a indicator used to tell that I'm adding an area code. Same for country code, you add 00 to say that you use a county code.

    Leading 0 shouldn't be stored, they should be added when needed. Say you store 00 in the database and you use a server that only works with + they you have to replace 00 with + for that application.

    So, store numbers as numbers.

    Convert List<DerivedClass> to List<BaseClass>

    Because C# doesn't allow that type of inheritance conversion at the moment.

    HTTP GET with request body

    I'm upset that REST as protocol doesn't support OOP and Get method is proof. As a solution, you can serialize your a DTO to JSON and then create a query string. On server side you'll able to deserialize the query string to the DTO.

    Take a look on:

    Message based approach can help you to solve Get method restriction. You'll able to send any DTO as with request body

    Nelibur web service framework provides functionality which you can use

    var client = new JsonServiceClient(Settings.Default.ServiceAddress);
    var request = new GetClientRequest
        {
            Id = new Guid("2217239b0e-b35b-4d32-95c7-5db43e2bd573")
        };
    var response = client.Get<GetClientRequest, ClientResponse>(request);
    
    as you can see, the GetClientRequest was encoded to the following query string
    
    http://localhost/clients/GetWithResponse?type=GetClientRequest&data=%7B%22Id%22:%2217239b0e-b35b-4d32-95c7-5db43e2bd573%22%7D
    

    Node.js/Express.js App Only Works on Port 3000

    Just a note for Mac OS X and Linux users:

    If you want to run your Node / Express app on a port number lower than 1024, you have to run as the superuser: sudo PORT=80 node app.js

    Delete specific values from column with where condition?

    UPDATE myTable 
       SET myColumn = NULL 
     WHERE myCondition
    

    How can I center text (horizontally and vertically) inside a div block?

    Try the following example. I have added examples for each category: horizontal and vertical

    <!DOCTYPE html>
    <html>
        <head>
            <style>
                #horizontal
                {
                    text-align: center;
                }
                #vertical
                {
                    position: absolute;
                    top: 50%;
                    left: 50%;
                    transform: translateX(-50%) translateY(-50%);
                }
             </style>
        </head>
        <body>
             <div id ="horizontal">Center horizontal text</div>
             <div id ="vertical">Center vertical text</div>
        </body>
    </html> 
    

    Head and tail in one line

    Building on the Python 2 solution from @GarethLatty, the following is a way to get a single line equivalent without intermediate variables in Python 2.

    t=iter([1, 1, 2, 3, 5, 8, 13, 21, 34, 55]);h,t = [(h,list(t)) for h in t][0]
    

    If you need it to be exception-proof (i.e. supporting empty list), then add:

    t=iter([]);h,t = ([(h,list(t)) for h in t]+[(None,[])])[0]
    

    If you want to do it without the semicolon, use:

    h,t = ([(h,list(t)) for t in [iter([1,2,3,4])] for h in t]+[(None,[])])[0]
    

    Angular 5 Scroll to top on every Route click

    Although @Vega provides the direct answer to your question, there are issues. It breaks the browser's back/forward button. If you're user clicks the browser back or forward button, they lose their place and gets scrolled way at the top. This can be a bit of a pain for your users if they had to scroll way down to get to a link and decided to click back only to find the scrollbar had been reset to the top.

    Here's my solution to the problem.

    export class AppComponent implements OnInit {
      isPopState = false;
    
      constructor(private router: Router, private locStrat: LocationStrategy) { }
    
      ngOnInit(): void {
        this.locStrat.onPopState(() => {
          this.isPopState = true;
        });
    
        this.router.events.subscribe(event => {
          // Scroll to top if accessing a page, not via browser history stack
          if (event instanceof NavigationEnd && !this.isPopState) {
            window.scrollTo(0, 0);
            this.isPopState = false;
          }
    
          // Ensures that isPopState is reset
          if (event instanceof NavigationEnd) {
            this.isPopState = false;
          }
        });
      }
    }
    

    Convert UTF-8 to base64 string

    It's a little difficult to tell what you're trying to achieve, but assuming you're trying to get a Base64 string that when decoded is abcdef==, the following should work:

    byte[] bytes = Encoding.UTF8.GetBytes("abcdef==");
    string base64 = Convert.ToBase64String(bytes);
    Console.WriteLine(base64);
    

    This will output: YWJjZGVmPT0= which is abcdef== encoded in Base64.

    Edit:

    To decode a Base64 string, simply use Convert.FromBase64String(). E.g.

    string base64 = "YWJjZGVmPT0=";
    byte[] bytes = Convert.FromBase64String(base64);
    

    At this point, bytes will be a byte[] (not a string). If we know that the byte array represents a string in UTF8, then it can be converted back to the string form using:

    string str = Encoding.UTF8.GetString(bytes);
    Console.WriteLine(str);
    

    This will output the original input string, abcdef== in this case.

    PHP Session data not being saved

    Check the value of "views" when before you increment it. If, for some bizarre reason, it's getting set to a string, then when you add 1 to it, it'll always return 1.

    if (isset($_SESSION['views'])) {
        if (!is_numeric($_SESSION['views'])) {
            echo "CRAP!";
        }
        ++$_SESSION['views'];
    } else {
        $_SESSION['views'] = 1;
    }
    

    PowerShell says "execution of scripts is disabled on this system."

    1. Open PowerShell as Administrator and run Set-ExecutionPolicy -Scope CurrentUser
    2. Provide RemoteSigned and press Enter
    3. Run Set-ExecutionPolicy -Scope CurrentUser
    4. Provide Unrestricted and press Enter

    Can Javascript read the source of any web page?

    If you absolutely need to use javascript, you could load the page source with an ajax request.

    Note that with javascript, you can only retrieve pages that are located under the same domain with the requesting page.

    How do I set the timeout for a JAX-WS webservice client?

    the easiest way to avoid slow retrieval of the remote WSDL when you instantiate your SEI is to not retrieve the WSDL from the remote service endpoint at runtime.

    this means that you have to update your local WSDL copy any time the service provider makes an impacting change, but it also means that you have to update your local copy any time the service provider makes an impacting change.

    When I generate my client stubs, I tell the JAX-WS runtime to annotate the SEI in such a way that it will read the WSDL from a pre-determined location on the classpath. by default the location is relative to the package location of the Service SEI


    <wsimport
        sourcedestdir="${dao.helter.dir}/build/generated"
        destdir="${dao.helter.dir}/build/bin/generated"
        wsdl="${dao.helter.dir}/src/resources/schema/helter/helterHttpServices.wsdl"
        wsdlLocation="./wsdl/helterHttpServices.wsdl"
        package="com.helter.esp.dao.helter.jaxws"
        >
        <binding dir="${dao.helter.dir}/src/resources/schema/helter" includes="*.xsd"/>
    </wsimport>
    <copy todir="${dao.helter.dir}/build/bin/generated/com/helter/esp/dao/helter/jaxws/wsdl">
        <fileset dir="${dao.helter.dir}/src/resources/schema/helter" includes="*" />
    </copy>
    

    the wsldLocation attribute tells the SEI where is can find the WSDL, and the copy makes sure that the wsdl (and supporting xsd.. etc..) is in the correct location.

    since the location is relative to the SEI's package location, we create a new sub-package (directory) called wsdl, and copy all the wsdl artifacts there.

    all you have to do at this point is make sure you include all *.wsdl, *.xsd in addition to all *.class when you create your client-stub artifact jar file.

    (in case your curious, the @webserviceClient annotation is where this wsdl location is actually set in the java code

    @WebServiceClient(name = "httpServices", targetNamespace = "http://www.helter.com/schema/helter/httpServices", wsdlLocation = "./wsdl/helterHttpServices.wsdl")
    

    JSONP call showing "Uncaught SyntaxError: Unexpected token : "

    You're trying to access a JSON, not JSONP.

    Notice the difference between your source:

    https://api.flightstats.com/flex/schedules/rest/v1/json/flight/AA/100/departing/2013/10/4?appId=19d57e69&appKey=e0ea60854c1205af43fd7b1203005d59&callback=?

    And actual JSONP (a wrapping function):

    http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=processJSON&tags=monkey&tagmode=any&format=json

    Search for JSON + CORS/Cross-domain policy and you will find hundreds of SO threads on this very topic.

    Moving x-axis to the top of a plot in matplotlib

    You've got to do some extra massaging if you want the ticks (not labels) to show up on the top and bottom (not just the top). The only way I could do this is with a minor change to unutbu's code:

    import matplotlib.pyplot as plt
    import numpy as np
    column_labels = list('ABCD')
    row_labels = list('WXYZ')
    data = np.random.rand(4, 4)
    fig, ax = plt.subplots()
    heatmap = ax.pcolor(data, cmap=plt.cm.Blues)
    
    # put the major ticks at the middle of each cell
    ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
    ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
    
    # want a more natural, table-like display
    ax.invert_yaxis()
    ax.xaxis.tick_top()
    ax.xaxis.set_ticks_position('both') # THIS IS THE ONLY CHANGE
    
    ax.set_xticklabels(column_labels, minor=False)
    ax.set_yticklabels(row_labels, minor=False)
    plt.show()
    

    Output:

    enter image description here

    How to tell CRAN to install package dependencies automatically?

    Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:

    enter image description here

    HTTP 415 unsupported media type error when calling Web API 2 endpoint

    SOLVED
    After banging my head on the wall for a couple days with this issue, it was looking like the problem had something to do with the content type negotiation between the client and server. I dug deeper into that using Fiddler to check the request details coming from the client app, here's a screenshot of the raw request as captured by fiddler:

    Fiddler capture of http request from client app

    What's obviously missing there is the Content-Type header, even though I was setting it as seen in the code sample in my original post. I thought it was strange that the Content-Type never came through even though I was setting it, so I had another look at my other (working) code calling a different Web API service, the only difference was that I happened to be setting the req.ContentType property prior to writing to the request body in that case. I made that change to this new code and that did it, the Content-Type was now showing up and I got the expected success response from the web service. The new code from my .NET client now looks like this:

    req.Method = "POST"
    req.ContentType = "application/json"
    lstrPagingJSON = JsonSerializer(Of Paging)(lPaging)
    bytData = Encoding.UTF8.GetBytes(lstrPagingJSON)
    req.ContentLength = bytData.Length
    reqStream = req.GetRequestStream()
    reqStream.Write(bytData, 0, bytData.Length)
    reqStream.Close()
    '// Content-Type was being set here, causing the problem
    'req.ContentType = "application/json"
    

    That's all it was, the ContentType property just needed to be set prior to writing to the request body

    I believe this behavior is because once content is written to the body it is streamed to the service endpoint being called, any other attributes pertaining to the request need to be set prior to that. Please correct me if I'm wrong or if this needs more detail.

    How to get the client IP address in PHP

    Like the following?

    if (($ip=filter_input(INPUT_SERVER, 'REMOTE_ADDR', validate_ip)) === false or empty($ip)) {
        exit;
    }
    echo $ip;
    

    PS

    if (($ip=filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP|FILTER_FLAG_NO_PRIV_RANGE|FILTER_FLAG_NO_RES_RANGE)) === false) {
        header('HTTP/1.0 400 Bad Request');
        exit;
    }
    

    All headers beginning with 'HTTP_' or 'X-' may be spoofed, respectively is user defined. If you want to keep track, use cookies, etc.

    How to check if a char is equal to an empty space?

    My suggestion would be:

    if (c == ' ')
    

    handling DATETIME values 0000-00-00 00:00:00 in JDBC

    I wrestled with this problem and implemented the 'convertToNull' solutions discussed above. It worked in my local MySql instance. But when I deployed my Play/Scala app to Heroku it no longer would work. Heroku also concatenates several args to the DB URL that they provide users, and this solution, because of Heroku's use concatenation of "?" before their own set of args, will not work. However I found a different solution which seems to work equally well.

    SET sql_mode = 'NO_ZERO_DATE';

    I put this in my table descriptions and it solved the problem of '0000-00-00 00:00:00' can not be represented as java.sql.Timestamp

    Android Stop Emulator from Command Line

    adb kill-server will kill all emulators and restart the server clean.

    What is the most efficient way to store tags in a database?

    Actually I believe de-normalising the tags table might be a better way forward, depending on scale.

    This way, the tags table simply has tagid, itemid, tagname.

    You'll get duplicate tagnames, but it makes adding/removing/editing tags for specific items MUCH more simple. You don't have to create a new tag, remove the allocation of the old one and re-allocate a new one, you just edit the tagname.

    For displaying a list of tags, you simply use DISTINCT or GROUP BY, and of course you can count how many times a tag is used easily, too.

    Max tcp/ip connections on Windows Server 2008

    How many thousands of users?

    I've run some TCP/IP client/server connection tests in the past on Windows 2003 Server and managed more than 70,000 connections on a reasonably low spec VM. (see here for details: http://www.lenholgate.com/blog/2005/10/the-64000-connection-question.html). I would be extremely surprised if Windows 2008 Server is limited to less than 2003 Server and, IMHO, the posting that Cloud links to is too vague to be much use. This kind of question comes up a lot, I blogged about why I don't really think that it's something that you should actually worry about here: http://www.serverframework.com/asynchronousevents/2010/12/one-million-tcp-connections.html.

    Personally I'd test it and see. Even if there is no inherent limit in the Windows 2008 Server version that you intend to use there will still be practical limits based on memory, processor speed and server design.

    If you want to run some 'generic' tests you can use my multi-client connection test and the associated echo server. Detailed here: http://www.lenholgate.com/blog/2005/11/windows-tcpip-server-performance.html and here: http://www.lenholgate.com/blog/2005/11/simple-echo-servers.html. These are what I used to run my own tests for my server framework and these are what allowed me to create 70,000 active connections on a Windows 2003 Server VM with 760MB of memory.

    Edited to add details from the comment below...

    If you're already thinking of multiple servers I'd take the following approach.

    1. Use the free tools that I link to and prove to yourself that you can create a reasonable number of connections onto your target OS (beware of the Windows limits on dynamic ports which may cause your client connections to fail, search for MAX_USER_PORT).

    2. during development regularly test your actual server with test clients that can create connections and actually 'do something' on the server. This will help to prevent you building the server in ways that restrict its scalability. See here: http://www.serverframework.com/asynchronousevents/2010/10/how-to-support-10000-or-more-concurrent-tcp-connections-part-2-perf-tests-from-day-0.html

    How exactly does the python any() function work?

    >>> names = ['King', 'Queen', 'Joker']
    >>> any(n in 'King and john' for n in names)
    True
    
    >>> all(n in 'King and Queen' for n in names)
    False
    

    It just reduce several line of code into one. You don't have to write lengthy code like:

    for n in names:
        if n in 'King and john':
           print True
        else:
           print False
    

    Multiple returns from a function

    I had a similar problem - so I tried around and googled a bit (finding this thread). After 5 minutes of try and error I found out that you can simply use "AND" to return two (maybe more - not tested yet) in one line of return.

    My code:

      function get_id(){
        global $b_id, $f_id;
        // stuff happens
        return $b_id AND $f_id;
      }
      //later in the code:
      get_id();
      var_dump($b_id);
      var_dump($f_id); // tested output by var_dump
    

    it works. I got both the values I expected to get/should get. I hope I could help anybody reading this thread :)

    change background image in body

    If you're page has an Open Graph image, commonly used for social sharing, you can use it to set the background image at runtime with vanilla JavaScript like so:

    <script>
      const meta = document.querySelector('[property="og:image"]');
      const body = document.querySelector("body");
      body.style.background = `url(${meta.content})`;
    </script>
    

    The above uses document.querySelector and Attribute Selectors to assign meta the first Open Graph image it selects. A similar task is performed to get the body. Finally, string interpolation is used to assign body the background.style the value of the path to the Open Graph image.

    If you want the image to cover the entire viewport and stay fixed set background-size like so:

    body.style.background = `url(${meta.content}) center center no-repeat fixed`;
    body.style.backgroundSize = 'cover';
    

    Using this approach you can set a low-quality background image placeholder using CSS and swap with a high-fidelity image later using an image onload event, thereby reducing perceived latency.

    Using Font Awesome icon for bullet points, with a single list item element

    In Font Awesome 5 it can be done using pure CSS as in some of the above answers with some modifications.

    ul {
      list-style-type: none;
    }
    
    li:before {
      position: absolute;
      font-family: 'Font Awesome 5 free';
              /*  Use the Name of the Font Awesome free font, e.g.:
               - 'Font Awesome 5 Free' for Regular and Solid symbols;
               - 'Font Awesome 5 Brand' for Brands symbols.
               - 'Font Awesome 5 Pro' for Regular and Solid symbols (Professional License);
              */
      content: "\f1fc"; /* Unicode value of the icon to use: */
      font-weight: 900; /* This is important, change the value according to the font family name
                           used above. See the link below  */
      color: red;
    }
    

    Without the correct font-weight, it will only show a blank square.

    https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements#define

    How do I find numeric columns in Pandas?

    Adapting this answer, you could do

    df.ix[:,df.applymap(np.isreal).all(axis=0)]
    

    Here, np.applymap(np.isreal) shows whether every cell in the data frame is numeric, and .axis(all=0) checks if all values in a column are True and returns a series of Booleans that can be used to index the desired columns.

    How do I split a string so I can access item x?

    declare @strng varchar(max)='hello john smith'
    select (
        substring(
            @strng,
            charindex(' ', @strng) + 1,
            (
              (charindex(' ', @strng, charindex(' ', @strng) + 1))
              - charindex(' ',@strng)
            )
        ))
    

    wp-admin shows blank page, how to fix it?

    Just reset the password, this will work.

    Fastest way to write huge data in text file Java

    Only for the sake of statistics:

    The machine is old Dell with new SSD

    CPU: Intel Pentium D 2,8 Ghz

    SSD: Patriot Inferno 120GB SSD

    4000000 'records'
    175.47607421875 MB
    
    Iteration 0
    Writing raw... 3.547 seconds
    Writing buffered (buffer size: 8192)... 2.625 seconds
    Writing buffered (buffer size: 1048576)... 2.203 seconds
    Writing buffered (buffer size: 4194304)... 2.312 seconds
    
    Iteration 1
    Writing raw... 2.922 seconds
    Writing buffered (buffer size: 8192)... 2.406 seconds
    Writing buffered (buffer size: 1048576)... 2.015 seconds
    Writing buffered (buffer size: 4194304)... 2.282 seconds
    
    Iteration 2
    Writing raw... 2.828 seconds
    Writing buffered (buffer size: 8192)... 2.109 seconds
    Writing buffered (buffer size: 1048576)... 2.078 seconds
    Writing buffered (buffer size: 4194304)... 2.015 seconds
    
    Iteration 3
    Writing raw... 3.187 seconds
    Writing buffered (buffer size: 8192)... 2.109 seconds
    Writing buffered (buffer size: 1048576)... 2.094 seconds
    Writing buffered (buffer size: 4194304)... 2.031 seconds
    
    Iteration 4
    Writing raw... 3.093 seconds
    Writing buffered (buffer size: 8192)... 2.141 seconds
    Writing buffered (buffer size: 1048576)... 2.063 seconds
    Writing buffered (buffer size: 4194304)... 2.016 seconds
    

    As we can see the raw method is slower the buffered.

    Share data between html pages

    I know this is an old post, but figured I'd share my two cents. @Neji is correct in that you can use sessionStorage.getItem('label'), and sessionStorage.setItem('label', 'value') (although he had the setItem parameters backwards, not a big deal). I much more prefer the following, I think it's more succinct:

    var val = sessionStorage.myValue
    

    in place of getItem and

    sessionStorage.myValue = 'value'
    

    in place of setItem.

    Also, it should be noted that in order to store JavaScript objects, they must be stringified to set them, and parsed to get them, like so:

    sessionStorage.myObject = JSON.stringify(myObject); //will set object to the stringified myObject
    var myObject = JSON.parse(sessionStorage.myObject); //will parse JSON string back to object
    

    The reason is that sessionStorage stores everything as a string, so if you just say sessionStorage.object = myObject all you get is [object Object], which doesn't help you too much.

    What is `git push origin master`? Help with git's refs, heads and remotes

    Git has two types of branches: local and remote. To use git pull and git push as you'd like, you have to tell your local branch (my_test) which remote branch it's tracking. In typical Git fashion this can be done in both the config file and with commands.

    Commands

    Make sure you're on your master branch with

    1)git checkout master

    then create the new branch with

    2)git branch --track my_test origin/my_test

    and check it out with

    3)git checkout my_test.

    You can then push and pull without specifying which local and remote.

    However if you've already created the branch then you can use the -u switch to tell git's push and pull you'd like to use the specified local and remote branches from now on, like so:

    git pull -u my_test origin/my_test
    git push -u my_test origin/my_test
    

    Config

    The commands to setup remote branch tracking are fairly straight forward but I'm listing the config way as well as I find it easier if I'm setting up a bunch of tracking branches. Using your favourite editor open up your project's .git/config and add the following to the bottom.

    [remote "origin"]
        url = [email protected]:username/repo.git
        fetch = +refs/heads/*:refs/remotes/origin/*
    [branch "my_test"]
        remote = origin
        merge = refs/heads/my_test
    

    This specifies a remote called origin, in this case a GitHub style one, and then tells the branch my_test to use it as it's remote.

    You can find something very similar to this in the config after running the commands above.

    Some useful resources:

    Tool to generate JSON schema from JSON data

    json-schema-generator is a neat Ruby based JSON schema generator. It supports both draft 3 and 4 of the JSON schema. It can be run as a standalone executable, or it can be embedded inside of a Ruby script.

    Then you can use json-schema to validate JSON samples against your newly generated schema if you want.

    Cannot invoke an expression whose type lacks a call signature

    Perhaps create a shared Fruit interface that provides isDecayed. fruits is now of type Fruit[] so the type can be explicit. Like this:

    interface Fruit {
        isDecayed: boolean;
    }
    
    interface Apple extends Fruit {
        color: string;
    }
    
    interface Pear extends Fruit {
        weight: number;
    }
    
    interface FruitBasket {
        apples: Apple[];
        pears: Pear[];
    }
    
    
    const fruitBasket: FruitBasket = { apples: [], pears: [] };
    const key: keyof FruitBasket = Math.random() > 0.5 ? 'apples': 'pears'; 
    const fruits: Fruit[] = fruitBasket[key];
    
    const freshFruits = fruits.filter((fruit) => !fruit.isDecayed);
    

    What does ON [PRIMARY] mean?

    When you create a database in Microsoft SQL Server you can have multiple file groups, where storage is created in multiple places, directories or disks. Each file group can be named. The PRIMARY file group is the default one, which is always created, and so the SQL you've given creates your table ON the PRIMARY file group.

    See MSDN for the full syntax.

    How to upgrade rubygems

    I wouldn't use the debian packages, have a look at RVM or Rbenv.

    HTML/CSS: how to put text both right and left aligned in a paragraph

    Ok what you probably want will be provide to you by result of:

    1. in CSS:

      div { column-count: 2; }

    2. in html:

      <div> some text, bla bla bla </div>

    In CSS you make div to split your paragraph on to column, you can make them 3, 4...

    If you want to have many differend paragraf like that, then put id or class in your div:

    SVN icon overlays not showing properly

    Tortoise SVN on Windows happens to lose sync quite often with the real file status. In that case try doing an svn cleanup.

    Another thing, it may also depend where your source files are located, different drive, network drive, etc. There's an option in Tortoise to allow icon overlay or not, on remote drives.

    Check this out in: TortoiseSVN / Settings / Icon Overlays / Drive types

    Difference and uses of onCreate(), onCreateView() and onActivityCreated() in fragments

    UPDATE:

    onActivityCreated() is deprecated from API Level 28.


    onCreate():

    The onCreate() method in a Fragment is called after the Activity's onAttachFragment() but before that Fragment's onCreateView().
    In this method, you can assign variables, get Intent extras, and anything else that doesn't involve the View hierarchy (i.e. non-graphical initialisations). This is because this method can be called when the Activity's onCreate() is not finished, and so trying to access the View hierarchy here may result in a crash.

    onCreateView():

    After the onCreate() is called (in the Fragment), the Fragment's onCreateView() is called. You can assign your View variables and do any graphical initialisations. You are expected to return a View from this method, and this is the main UI view, but if your Fragment does not use any layouts or graphics, you can return null (happens by default if you don't override).

    onActivityCreated():

    As the name states, this is called after the Activity's onCreate() has completed. It is called after onCreateView(), and is mainly used for final initialisations (for example, modifying UI elements). This is deprecated from API level 28.


    To sum up...
    ... they are all called in the Fragment but are called at different times.
    The onCreate() is called first, for doing any non-graphical initialisations. Next, you can assign and declare any View variables you want to use in onCreateView(). Afterwards, use onActivityCreated() to do any final initialisations you want to do once everything has completed.


    If you want to view the official Android documentation, it can be found here:

    There are also some slightly different, but less developed questions/answers here on Stack Overflow:

    Javascript receipt printing using POS Printer

    If you are talking about a browser based POS app then it basically can't be done out of the box. There are a number of alternatives.

    1. Use an applet like Scott Selby says
    2. Print from the server. If this is a cloud server, ie not connectable to the receipt printer then what you can do is
      • From the server generate it as a pdf which can be made to popup a print dialog in the browser
      • Use something like Google Cloud Print which will allow connecting printers to a cloud service

    Converting a generic list to a CSV string

    I like a nice simple extension method

     public static string ToCsv(this List<string> itemList)
             {
                 return string.Join(",", itemList);
             }
    

    Then you can just call the method on the original list:

    string CsvString = myList.ToCsv();
    

    Cleaner and easier to read than some of the other suggestions.

    Verify a method call using Moq

    You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.

    You should be doing something more like this:

    class MyClassTest
    {
        [TestMethod]
        public void MyMethodTest()
        {
            string action = "test";
            Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
    
            mockSomeClass.Setup(mock => mock.DoSomething());
    
            MyClass myClass = new MyClass(mockSomeClass.Object);
            myClass.MyMethod(action);
    
            // Explicitly verify each expectation...
            mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
    
            // ...or verify everything.
            // mockSomeClass.VerifyAll();
        }
    }
    

    In other words, you are verifying that calling MyClass#MyMethod, your class will definitely call SomeClass#DoSomething once in that process. Note that you don't need the Times argument; I was just demonstrating its value.

    Send file using POST from a Python script

    You may also want to have a look at httplib2, with examples. I find using httplib2 is more concise than using the built-in HTTP modules.

    Copy the entire contents of a directory in C#

    Better than any code (extension method to DirectoryInfo with recursion)

    public static bool CopyTo(this DirectoryInfo source, string destination)
        {
            try
            {
                foreach (string dirPath in Directory.GetDirectories(source.FullName))
                {
                    var newDirPath = dirPath.Replace(source.FullName, destination);
                    Directory.CreateDirectory(newDirPath);
                    new DirectoryInfo(dirPath).CopyTo(newDirPath);
                }
                //Copy all the files & Replaces any files with the same name
                foreach (string filePath in Directory.GetFiles(source.FullName))
                {
                    File.Copy(filePath, filePath.Replace(source.FullName,destination), true);
                }
                return true;
            }
            catch (IOException exp)
            {
                return false;
            }
        }
    

    How do I run a single test using Jest?

    npm test __tests__/filename.test.ts - to run a single file.

    test.only('check single test', () => { expect(true).toBe(true)}); - to run a single test case

    test.skip('to skip testcase, () => {expect(false).toBe(false_}); - to skip a test case

    How do I order my SQLITE database in descending order, for an android app?

    return database.rawQuery("SELECT * FROM " + DbHandler.TABLE_ORDER_DETAIL +
                             " ORDER BY "+DbHandler.KEY_ORDER_CREATED_AT + " DESC"
                             , new String[] {});
    

    Retrieving the output of subprocess.call()

    For python 3.5+ it is recommended that you use the run function from the subprocess module. This returns a CompletedProcess object, from which you can easily obtain the output as well as return code.

    from subprocess import PIPE, run
    
    command = ['echo', 'hello']
    result = run(command, stdout=PIPE, stderr=PIPE, universal_newlines=True)
    print(result.returncode, result.stdout, result.stderr)