Programs & Examples On #Quilt

Markdown `native` text alignment

For Markdown Extra you can use custom attributes:

# Example text {style=text-align:center}

This works for headers and blockquotes, but not for paragraphs, inline elements and code blocks.

A shorter version (but not supported in HTML 5):

# Example text {align=center}

Close Window from ViewModel

My proffered way is Declare event in ViewModel and use blend InvokeMethodAction as below.

Sample ViewModel

public class MainWindowViewModel : BindableBase, ICloseable
{
    public DelegateCommand SomeCommand { get; private set; }
    #region ICloseable Implementation
    public event EventHandler CloseRequested;        

    public void RaiseCloseNotification()
    {
        var handler = CloseRequested;
        if (handler != null)
        {
            handler.Invoke(this, EventArgs.Empty);
        }
    }
    #endregion

    public MainWindowViewModel()
    {
        SomeCommand = new DelegateCommand(() =>
        {
            //when you decide to close window
            RaiseCloseNotification();
        });
    }
}

I Closeable interface is as below but don't require to perform this action. ICloseable will help in creating generic view service, so if you construct view and ViewModel by dependency injection then what you can do is

internal interface ICloseable
{
    event EventHandler CloseRequested;
}

Use of ICloseable

var viewModel = new MainWindowViewModel();
        // As service is generic and don't know whether it can request close event
        var window = new Window() { Content = new MainView() };
        var closeable = viewModel as ICloseable;
        if (closeable != null)
        {
            closeable.CloseRequested += (s, e) => window.Close();
        }

And Below is Xaml, You can use this xaml even if you don't implement interface, it will only need your view model to raise CloseRquested.

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:WPFRx"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" 
xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" 
xmlns:ViewModels="clr-namespace:WPFRx.ViewModels" x:Name="window" x:Class="WPFRx.MainWindow"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525" 
d:DataContext="{d:DesignInstance {x:Type ViewModels:MainWindowViewModel}}">

<i:Interaction.Triggers>
    <i:EventTrigger SourceObject="{Binding Mode=OneWay}" EventName="CloseRequested" >
        <ei:CallMethodAction TargetObject="{Binding ElementName=window}" MethodName="Close"/>
    </i:EventTrigger>
</i:Interaction.Triggers>

<Grid>
    <Button Content="Some Content" Command="{Binding SomeCommand}" Width="100" Height="25"/>
</Grid>

Aligning textviews on the left and right edges in Android layout

enter image description here

This Code will Divide the control into two equal sides.

    <LinearLayout
    android:orientation="horizontal"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/linearLayout">
    <TextView
        android:text = "Left Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtLeft"/>

    <TextView android:text = "Right Side"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight = "1"
        android:id = "@+id/txtRight"/>
    </LinearLayout>

Conversion failed when converting date and/or time from character string while inserting datetime

There are many formats supported by SQL Server - see the MSDN Books Online on CAST and CONVERT. Most of those formats are dependent on what settings you have - therefore, these settings might work some times - and sometimes not.

The way to solve this is to use the (slightly adapted) ISO-8601 date format that is supported by SQL Server - this format works always - regardless of your SQL Server language and dateformat settings.

The ISO-8601 format is supported by SQL Server comes in two flavors:

  • YYYYMMDD for just dates (no time portion); note here: no dashes!, that's very important! YYYY-MM-DD is NOT independent of the dateformat settings in your SQL Server and will NOT work in all situations!

or:

  • YYYY-MM-DDTHH:MM:SS for dates and times - note here: this format has dashes (but they can be omitted), and a fixed T as delimiter between the date and time portion of your DATETIME.

This is valid for SQL Server 2000 and newer.

So in your concrete case - use these strings:

insert into table1 values('2012-02-21T18:10:00', '2012-01-01T00:00:00');

and you should be fine (note: you need to use the international 24-hour format rather than 12-hour AM/PM format for this).

Alternatively: if you're on SQL Server 2008 or newer, you could also use the DATETIME2 datatype (instead of plain DATETIME) and your current INSERT would just work without any problems! :-) DATETIME2 is a lot better and a lot less picky on conversions - and it's the recommend date/time data types for SQL Server 2008 or newer anyway.

SELECT
   CAST('02-21-2012 6:10:00 PM' AS DATETIME2),     -- works just fine
   CAST('01-01-2012 12:00:00 AM' AS DATETIME2)   -- works just fine  

Don't ask me why this whole topic is so tricky and somewhat confusing - that's just the way it is. But with the YYYYMMDD format, you should be fine for any version of SQL Server and for any language and dateformat setting in your SQL Server.

support FragmentPagerAdapter holds reference to old fragments

Just so you know...

Adding to the litany of woes with these classes, there is a rather interesting bug that's worth sharing.

I'm using a ViewPager to navigate a tree of items (select an item and the view pager animates scrolling to the right, and the next branch appears, navigate back, and the ViewPager scrolls in the opposite direction to return to the previous node).

The problem arises when I push and pop fragments off the end of the FragmentStatePagerAdapter. It's smart enough to notice that the items change, and smart enough to create and replace a fragment when the item has changed. But not smart enough to discard the fragment state, or smart enough to trim the internally saved fragment states when the adapter size changes. So when you pop an item, and push a new one onto the end, the fragment for the new item gets the saved state of the fragment for the old item, which caused absolute havoc in my code. My fragments carry data that may require a lot of work to refetch from the internet, so not saving state really wasn't an option.

I don't have a clean workaround. I used something like this:

  public void onSaveInstanceState(Bundle outState) {
    IFragmentListener listener = (IFragmentListener)getActivity();
    if (listener!= null)
    {
        if (!listener.isStillInTheAdapter(this.getAdapterItem()))
        {
            return; // return empty state.
        }

    }
    super.onSaveInstanceState(outState);

    // normal saving of state for flips and 
    // paging out of the activity follows
    ....
  }

An imperfect solution because the new fragment instance still gets a savedState Bundle, but at least it doesn't carry stale data.

How to implement debounce in Vue2?

In case you need to apply a dynamic delay with the lodash's debounce function:

props: {
  delay: String
},

data: () => ({
  search: null
}),

created () {
     this.valueChanged = debounce(function (event) {
      // Here you have access to `this`
      this.makeAPIrequest(event.target.value)
    }.bind(this), this.delay)

},

methods: {
  makeAPIrequest (newVal) {
    // ...
  }
}

And the template:

<template>
  //...

   <input type="text" v-model="search" @input="valueChanged" />

  //...
</template>

NOTE: in the example above I made an example of search input which can call the API with a custom delay which is provided in props

Passing bash variable to jq

Another way to accomplish this is with the jq "--arg" flag. Using the original example:

#!/bin/sh

#this works ***
projectID=$(cat file.json | jq -r '.resource[] | 
select(.username=="[email protected]") | .id')
echo "$projectID"

[email protected]

# Use --arg to pass the variable to jq. This should work:
projectID=$(cat file.json | jq --arg EMAILID $EMAILID -r '.resource[] 
| select(.username=="$EMAILID") | .id')
echo "$projectID"

See here, which is where I found this solution: https://github.com/stedolan/jq/issues/626

Using an index to get an item, Python

You can use _ _getitem__(key) function.

>>> iterable = ('A', 'B', 'C', 'D', 'E')
>>> key = 4
>>> iterable.__getitem__(key)
'E'

How to extract multiple JSON objects from one file?

Use a json array, in the format:

[
{"ID":"12345","Timestamp":"20140101", "Usefulness":"Yes",
  "Code":[{"event1":"A","result":"1"},…]},
{"ID":"1A35B","Timestamp":"20140102", "Usefulness":"No",
  "Code":[{"event1":"B","result":"1"},…]},
{"ID":"AA356","Timestamp":"20140103", "Usefulness":"No",
  "Code":[{"event1":"B","result":"0"},…]},
...
]

Then import it into your python code

import json

with open('file.json') as json_file:

    data = json.load(json_file)

Now the content of data is an array with dictionaries representing each of the elements.

You can access it easily, i.e:

data[0]["ID"]

Locate the nginx.conf file my nginx is actually using

In addition to @Daniel Li's answer, the nginx installation with Valet would use the Velet configuration as well, this is found in "/usr/local/etc/nginx/valet/valet.conf". The nginx.conf file would have imported this Valet conf file. The settings you need may be in the Valet file.

How do you do a ‘Pause’ with PowerShell 2.0?

In addition to Michael Sorens' answer:

<6> ReadKey in a new process

Start-Process PowerShell {[void][System.Console]::ReadKey($true)} -Wait -NoNewWindow
  • Advantage: Accepts any key but properly excludes Shift, Alt, Ctrl modifier keys.
  • Advantage: Works in PS-ISE.

Modulo operation with negative numbers

In Mathematics, where these conventions stem from, there is no assertion that modulo arithmetic should yield a positive result.

Eg.

1 mod 5 = 1, but it can also equal -4. That is, 1/5 yields a remainder 1 from 0 or -4 from 5. (Both factors of 5)

Similarly, -1 mod 5 = -1, but it can also equal 4. That is, -1/5 yields a remainder -1 from 0 or 4 from -5. (Both factors of 5)

For further reading look into equivalence classes in Mathematics.

Break or return from Java 8 stream forEach?

int valueToMatch = 7;
Stream.of(1,2,3,4,5,6,7,8).anyMatch(val->{
   boolean isMatch = val == valueToMatch;
   if(isMatch) {
      /*Do whatever you want...*/
       System.out.println(val);
   }
   return isMatch;
});

It will do only operation where it find match, and after find match it stop it's iteration.

Log4j, configuring a Web App to use a relative path

Tomcat sets a catalina.home system property. You can use this in your log4j properties file. Something like this:

log4j.rootCategory=DEBUG,errorfile

log4j.appender.errorfile.File=${catalina.home}/logs/LogFilename.log

On Debian (including Ubuntu), ${catalina.home} will not work because that points at /usr/share/tomcat6 which has no link to /var/log/tomcat6. Here just use ${catalina.base}.

If your using another container, try to find a similar system property, or define your own. Setting the system property will vary by platform, and container. But for Tomcat on Linux/Unix I would create a setenv.sh in the CATALINA_HOME/bin directory. It would contain:

export JAVA_OPTS="-Dcustom.logging.root=/var/log/webapps"

Then your log4j.properties would be:

log4j.rootCategory=DEBUG,errorfile

log4j.appender.errorfile.File=${custom.logging.root}/LogFilename.log

Using a PagedList with a ViewModel ASP.Net MVC

The fact that you're using a view model has no bearing. The standard way of using PagedList is to store "one page of items" as a ViewBag variable. All you have to determine is what collection constitutes what you'll be paging over. You can't logically page multiple collections at the same time, so assuming you chose Instructors:

ViewBag.OnePageOfItems = myViewModelInstance.Instructors.ToPagedList(pageNumber, 10);

Then, the rest of the standard code works as it always has.

How can I determine the direction of a jQuery scroll event?

I had problems with elastic scrolling (scroll bouncing, rubber-banding). Ignoring the down-scroll event if close to the page top worked for me.

var position = $(window).scrollTop();
$(window).scroll(function () {
    var scroll = $(window).scrollTop();
    var downScroll = scroll > position;
    var closeToTop = -120 < scroll && scroll < 120;
    if (downScroll && !closeToTop) {
        // scrolled down and not to close to top (to avoid Ipad elastic scroll-problems)
        $('.top-container').slideUp('fast');
        $('.main-header').addClass('padding-top');
    } else {
        // scrolled up
        $('.top-container').slideDown('fast');
        $('.main-header').removeClass('padding-top');
    }
    position = scroll;
});

The server encountered an internal error that prevented it from fulfilling this request - in servlet 3.0

In here:

    if (ValidationUtils.isNullOrEmpty(lastName)) {
        registrationErrors.add(ValidationErrors.LAST_NAME);
    }
    if (!ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

you check for null or empty value on lastname, but in isEmailValid you don't check for empty value. Something like this should do

    if (ValidationUtils.isNullOrEmpty(email) || !ValidationUtils.isEmailValid(email)) {
        registrationErrors.add(ValidationErrors.EMAIL);
    }

or better yet, fix your ValidationUtils.isEmailValid() to cope with null email values. It shouldn't crash, it should just return false.

httpd-xampp.conf: How to allow access to an external IP besides localhost?

In windows all you have to do is to go to windows search Allow an app through Windows Firewall.click on Allow another app select Apache and mark public and private both . Open cmd by pressing windows button+r write cmd than in cmd write ipconfig find out your ip . than open up your browser write down your ip http://172.16..x and you will be on the xampp startup page.if you want to access your local site simply put / infront of your ip e.g http://192.168.1.x/yousite. Now you are able to access your website in private network computers .

i hope this will resolve your problem

How to configure Fiddler to listen to localhost?

Rather than configure the application server and client to use another domain, you may want to configure the client application to use a proxy. Fiddler also creates a proxy you can use, logging all traffic. Rick Strahl blogged about using this in .NET Apps, I am always misplacing this blog post, so let me link it here: http://weblog.west-wind.com/posts/2008/Mar/14/Debugging-Http-or-Web-Services-Calls-from-ASPNET-with-Fiddler.

To be brief, the app.config change is:

<system.net>
  <defaultProxy>
    <proxy  proxyaddress="http://127.0.0.1:8888" />      
  </defaultProxy>
</system.net>

When is it acceptable to call GC.Collect?

One instance where it is almost necessary to call GC.Collect() is when automating Microsoft Office through Interop. COM objects for Office don't like to automatically release and can result in the instances of the Office product taking up very large amounts of memory. I'm not sure if this is an issue or by design. There's lots of posts about this topic around the internet so I won't go into too much detail.

When programming using Interop, every single COM object should be manually released, usually though the use of Marshal.ReleseComObject(). In addition, calling Garbage Collection manually can help "clean up" a bit. Calling the following code when you're done with Interop objects seems to help quite a bit:

GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()

In my personal experience, using a combination of ReleaseComObject and manually calling garbage collection greatly reduces the memory usage of Office products, specifically Excel.

Provisioning Profiles menu item missing from Xcode 5

Xcode 5 lost my Mac Provisioning Profile while the one for iOS was present. The tips elsewhere helped solve the problem; this is what I did, because I noticed the lists were too short and did not include *Mac Team Provisioning Profile: **

  1. Xcode menu => Preferences => Accounts
  2. Select the Apple ID in the left panel.
  3. Click the View Details button on the right.
  4. In the pop-over that follows click the round refresh arrow. The lists will refresh after the download from the Member Center finishes. This can take a few minutes.
  5. The provisioning profiles can then be selected in a Mac project under Build Settings => Code Signing => Provisioning Profile.

Virtual/pure virtual explained

  • Virtual functions must have a definition in base class and also in derived class but not necessary, for example ToString() or toString() function is a Virtual so you can provide your own implementation by overriding it in user-defined class(es).

  • Virtual functions are declared and defined in normal class.

  • Pure virtual function must be declared ending with "= 0" and it can only be declared in abstract class.

  • An abstract class having a pure virtual function(s) cannot have a definition(s) of that pure virtual functions, so it implies that implementation must be provided in class(es) that derived from that abstract class.

How to manually install an artifact in Maven 2?

You need to indicate the groupId, the artifactId and the version for your artifact:

mvn install:install-file \
  -DgroupId=javax.transaction \
  -DartifactId=jta \
  -Dpackaging=jar \
  -Dversion=1.0.1B \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true

Disabling Minimize & Maximize On WinForm?

public Form1()
{
InitializeComponent();
//this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
}

Converting String to "Character" array in Java

Use this:

String str = "testString";
char[] charArray = str.toCharArray();
Character[] charObjectArray = ArrayUtils.toObject(charArray);

TypeError: $ is not a function when calling jQuery function

Double check your jQuery references. It is possible that you are either referencing it more than once or you are calling your function too early (before jQuery is defined). You can try as mentioned in my comments and put any jQuery reference at the top of your file (in the head) and see if that helps.

If you use the encapsulation of jQuery it shouldn't help in this case. Please try it because I think it is prettier and more obvious, but if jQuery is not defined you will get the same errors.

In the end... jQuery is not currently defined.

Pandas group-by and sum

Both the other answers accomplish what you want.

You can use the pivot functionality to arrange the data in a nice table

df.groupby(['Fruit','Name'],as_index = False).sum().pivot('Fruit','Name').fillna(0)



Name    Bob     Mike    Steve   Tom    Tony
Fruit                   
Apples  16.0    9.0     10.0    0.0     0.0
Grapes  35.0    0.0     0.0     87.0    15.0
Oranges 67.0    57.0    0.0     15.0    1.0

"inappropriate ioctl for device"

I got the error Can't open file for reading. Inappropriate ioctl for device recently when I migrated an old UB2K forum with a DBM file-based database to a new host. Apparently there are multiple, incompatible implementations of DBM. I had a backup of the database, so I was able to load that, but it seems there are other options e.g. moving a perl script/dbm to a new server, and shifting out of dbm?.

Search for highest key/index in an array

You can get the maximum key this way:

<?php
$arr = array("a"=>"test", "b"=>"ztest");
$max = max(array_keys($arr));
?>

assign multiple variables to the same value in Javascript

Nothing stops you from doing

moveUp = moveDown = moveLeft = moveRight = mouseDown = touchDown = false;

Check this example

_x000D_
_x000D_
var a, b, c;_x000D_
a = b = c = 10;_x000D_
console.log(a + b + c)
_x000D_
_x000D_
_x000D_

C# Select elements in list as List of string

List<string> empnames = emplist.Select(e => e.Ename).ToList();

This is an example of Projection in Linq. Followed by a ToList to resolve the IEnumerable<string> into a List<string>.

Alternatively in Linq syntax (head compiled):

var empnamesEnum = from emp in emplist 
                   select emp.Ename;
List<string> empnames = empnamesEnum.ToList();

Projection is basically representing the current type of the enumerable as a new type. You can project to anonymous types, another known type by calling constructors etc, or an enumerable of one of the properties (as in your case).

For example, you can project an enumerable of Employee to an enumerable of Tuple<int, string> like so:

var tuples = emplist.Select(e => new Tuple<int, string>(e.EID, e.Ename));

How to make --no-ri --no-rdoc the default for gem install?

For Windows users, Ruby doesn't set up .gemrc file. So you have to create .gemrc file in your home directory (echo %USERPROFILE%) and put following line in it:

gem: --no-document

As already mentioned in previous answers, don't use --no-ri and --no-rdoc cause its deprecated. See it yourself:

gem help install

How to specify jdk path in eclipse.ini on windows 8 when path contains space

I have Windows 8.1 and my JDK under "Program Files" as well. What worked for me was replacing the name of the folder by the 8-digit internal MS-DOS name.

-vm
C:/PROGRA~1/Java/jdk1.8.0_40/bin/javaw.exe

I realized what was going on after running this in cmd.exe

CD \
DIR P* /X

It returned...

<DIR>          PROGRA~1     Program Files
<DIR>          PROGRA~2     Program Files (x86)

So we can find out how to use a path containing spaces

How to add a "open git-bash here..." context menu to the windows explorer?

You can install git for windows or Github for windows , both give you the choice while installing to add this feature to your windows explorer. You can find it here:

Github for Windows

https://windows.github.com/

Git for Windows

http://git-scm.com/

Keyboard shortcut to change font size in Eclipse?

In Eclipse Neon.3, as well as in the new Eclipse Photon (4.8.0), I can resize the font easily with Ctrl + Shift + + and -, without any plugin or special key binding.

At least in Editor Windows (this does not work in other Views like Console, Project Explorer etc).

python pandas dataframe to dictionary

Another (slightly shorter) solution for not losing duplicate entries:

>>> ptest = pd.DataFrame([['a',1],['a',2],['b',3]], columns=['id','value'])
>>> ptest
  id  value
0  a      1
1  a      2
2  b      3

>>> pdict = dict()
>>> for i in ptest['id'].unique().tolist():
...     ptest_slice = ptest[ptest['id'] == i]
...     pdict[i] = ptest_slice['value'].tolist()
...

>>> pdict
{'b': [3], 'a': [1, 2]}

jQuery select2 get value of select tag?

Other answers wasn't working for me so i developed solution:

I created option with class="option-item" for easy targeting

HTML :

<select id="select-test">
<option value="5-val" id="first-id" class="option-item"> First option </option>
</select>

Then for every selected option i added display none property

CSS:

option:checked {
   display: none;
}

Now we can add change to our SelectBox to find our selected option with display none property by simple :hidden attribute

JQuery:

$('#select-test').change(function(){
//value 
    $('#select-test').find('.option-item:hidden').val();
//id
    $('#select-test').find('.option-item:hidden').attr('id');
//text
    $('#select-test').find('.option-item:hidden').text();
});

Working fiddle: https://jsfiddle.net/Friiz/2dk4003j/10/

What's the difference between .NET Core, .NET Framework, and Xamarin?

This is how Microsoft explains it:

.NET Framework, .NET Core, Xamarin

.NET Framework is the "full" or "traditional" flavor of .NET that's distributed with Windows. Use this when you are building a desktop Windows or UWP app, or working with older ASP.NET 4.6+.

.NET Core is cross-platform .NET that runs on Windows, Mac, and Linux. Use this when you want to build console or web apps that can run on any platform, including inside Docker containers. This does not include UWP/desktop apps currently.

Xamarin is used for building mobile apps that can run on iOS, Android, or Windows Phone devices.

Xamarin usually runs on top of Mono, which is a version of .NET that was built for cross-platform support before Microsoft decided to officially go cross-platform with .NET Core. Like Xamarin, the Unity platform also runs on top of Mono.


A common point of confusion is where ASP.NET Core fits in. ASP.NET Core can run on top of either .NET Framework (Windows) or .NET Core (cross-platform), as detailed in this answer: Difference between ASP.NET Core (.NET Core) and ASP.NET Core (.NET Framework)

What's causing my java.net.SocketException: Connection reset?

I got this error when the text file I was trying to read contained a string that matched an antivirus signature on our firewall.

Excel formula to get ranking position

You could also use the RANK function

=RANK(C2,$C$2:$C$7,0)

It would return data like your example:

  | A       | B        | C
1 | name    | position | points
2 | person1 | 1        | 10
3 | person2 | 2        | 9
4 | person3 | 2        | 9
5 | person4 | 2        | 9
6 | person5 | 5        | 8
7 | person6 | 6        | 7

The 'Points' column needs to be sorted into descending order.

XML Schema Validation : Cannot find the declaration of element

The targetNamespace of your XML Schema does not match the namespace of the Root element (dot in Test.Namespace vs. comma in Test,Namespace)

Once you make the above agree, you have to consider that your element2 has an attribute order that is not in your XSD.

Set environment variables on Mac OS X Lion

It is recommended to check default terminal shell before setting any environment variables, via following commands:

$ echo $SHELL
/bin/zsh

If your default terminal is /bin/zsh (Z Shell) like in my case (Personally prefer Z Shell), then you should set these environment variable in ~/.zshenv file with following contents (In this example, setting JAVA_HOME environment variable, but same applies to others):

export JAVA_HOME="$(/usr/libexec/java_home)"

Similarly, any other terminal type not mentioned above, you should set environment variable in its respective terminal env file.

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

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

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

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

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

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

AngularJs event to call after content is loaded

Running after the page load should partially be satisfied by setting an event listener to the window load event

window.addEventListener("load",function()...)

Inside the module.run(function()...) of angular you will have all access to the module structure and dependencies.

You can broadcast and emit events for communications bridges.

For example:

  • module set onload event and build logic
  • module broadcast event to controllers when logic required it
  • controllers will listen and execute their own logic based on module onload processes.

Selenium WebDriver findElement(By.xpath()) not working for me

You should add the tag name in the xpath, like:

element = findElement(By.xpath("//input[@test-id='test-username']");

"Unable to get the VLookup property of the WorksheetFunction Class" error

Try below code

I will recommend to use error handler while using vlookup because error might occur when the lookup_value is not found.

Private Sub ComboBox1_Change()


    On Error Resume Next
    Ret = Application.WorksheetFunction.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)
    On Error GoTo 0

    If Ret <> "" Then MsgBox Ret


End Sub

OR

 On Error Resume Next

    Result = Application.VLookup(Me.ComboBox1.Value, Worksheets("Sheet3").Range("Names"), 2, False)

    If Result = "Error 2042" Then
        'nothing found
    ElseIf cell <> Result Then
        MsgBox cell.Value
    End If

    On Error GoTo 0

Nested iframes, AKA Iframe Inception

You should use live method for elements which are rendered later, like colorbox, hidden fields or iframe

$(".inverter-value").live("change",function() {
     elem = this
    $.ajax({
      url: '/main/invertor_attribute/',
      type: 'POST',
      aysnc: false,
      data: {id: $(this).val() },
      success: function(data){
       // code
      },
      dataType: 'html'
    });
  });

How to change identity column values programmatically?

DBCC CHECKIDENT ( ‘databasename.dbo.orders’,RESEED, 999) you can change any identity column number with this command,and also you can start that field number from every number you want.for example in my command i ask to start from 1000 (999+1) hope that it would be enough...good luck

How to ignore the first line of data when processing CSV data?

Python 2.x

csvreader.next()

Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

csv_data = csv.reader(open('sample.csv'))
csv_data.next() # skip first row
for row in csv_data:
    print(row) # should print second row

Python 3.x

csvreader.__next__()

Return the next row of the reader’s iterable object as a list (if the object was returned from reader()) or a dict (if it is a DictReader instance), parsed according to the current dialect. Usually you should call this as next(reader).

csv_data = csv.reader(open('sample.csv'))
csv_data.__next__() # skip first row
for row in csv_data:
    print(row) # should print second row

Prevent screen rotation on Android

Add

android:screenOrientation="portrait" 

or

 android:screenOrientation="landscape" 

to the <activity> element/s in the manifest and you're done.

Returning unique_ptr from functions

This is in no way specific to std::unique_ptr, but applies to any class that is movable. It's guaranteed by the language rules since you are returning by value. The compiler tries to elide copies, invokes a move constructor if it can't remove copies, calls a copy constructor if it can't move, and fails to compile if it can't copy.

If you had a function that accepts std::unique_ptr as an argument you wouldn't be able to pass p to it. You would have to explicitly invoke move constructor, but in this case you shouldn't use variable p after the call to bar().

void bar(std::unique_ptr<int> p)
{
    // ...
}

int main()
{
    unique_ptr<int> p = foo();
    bar(p); // error, can't implicitly invoke move constructor on lvalue
    bar(std::move(p)); // OK but don't use p afterwards
    return 0;
}

Proper way to declare custom exceptions in modern Python?

To define your own exceptions correctly, there are a few best practices that you should follow:

  • Define a base class inheriting from Exception. This will allow to easily catch any exceptions related to the project:

    class MyProjectError(Exception):
        """A base class for MyProject exceptions."""
    

    Organizing the exception classes in a separate module (e.g. exceptions.py) is generally a good idea.

  • To create a specific exception, subclass the base exception class.

  • To add support for extra argument(s) to a custom exception, define a custom __init__() method with a variable number of arguments. Call the base class's __init__(), passing any positional arguments to it (remember that BaseException/Exception expect any number of positional arguments):

    class CustomError(MyProjectError):
        def __init__(self, *args, **kwargs):
            super().__init__(*args)
            self.foo = kwargs.get('foo')
    

    To raise such exception with an extra argument you can use:

     raise CustomError('Something bad happened', foo='foo')
    

This design adheres to the Liskov substitution principle, since you can replace an instance of a base exception class with an instance of a derived exception class. Also, it allows you to create an instance of a derived class with the same parameters as the parent.

How to install psycopg2 with "pip" on Python?

This is what worked for me (On RHEL, CentOS:

sudo yum install postgresql postgresql-devel python-devel

And now include the path to your postgresql binary dir with you pip install:

sudo PATH=$PATH:/usr/pgsql-9.3/bin/ pip install psycopg2

Make sure to include the correct path. Thats all :)

UPDATE: For python 3, please install python3-devel instead of python-devel

Fastest Way to Find Distance Between Two Lat/Long Points

Using mysql

SET @orig_lon = 1.027125;
SET @dest_lon = 1.027125;

SET @orig_lat = 2.398441;
SET @dest_lat = 2.398441;

SET @kmormiles = 6371;-- for distance in miles set to : 3956

SELECT @kmormiles * ACOS(LEAST(COS(RADIANS(@orig_lat)) * 
 COS(RADIANS(@dest_lat)) * COS(RADIANS(@orig_lon - @dest_lon)) + 
 SIN(RADIANS(@orig_lat)) * SIN(RADIANS(@dest_lat)),1.0)) as distance;

See: https://andrew.hedges.name/experiments/haversine/

See: https://stackoverflow.com/a/24372831/5155484

See: http://www.plumislandmedia.net/mysql/haversine-mysql-nearest-loc/

NOTE: LEAST is used to avoid null values as a comment suggested on https://stackoverflow.com/a/24372831/5155484

Converting a string to a date in a cell

I was struggling with this for some time and after some help on a post I was able to come up with this formula =(DATEVALUE(LEFT(XX,10)))+(TIMEVALUE(MID(XX,12,5))) where XX is the cell in reference.

I've come across many other forums with people asking the same thing and this, to me, seems to be the simplest answer. What this will do is return text that is copied in from this format 2014/11/20 11:53 EST and turn it in to a Date/Time format so it can be sorted oldest to newest. It works with short date/long date and if you want the time just format the cell to display time and it will show. Hope this helps anyone who goes searching around like I did.

How to downgrade tensorflow, multiple versions possible?

If you have anaconda, you can just install desired version and conda will automatically downgrade the current package for you.

For example:

conda install tensorflow=1.1

C# MessageBox dialog result

If you're using WPF and the previous answers don't help, you can retrieve the result using:

var result = MessageBox.Show("Message", "caption", MessageBoxButton.YesNo, MessageBoxImage.Question);

if (result == MessageBoxResult.Yes)
{
    // Do something
}

How to use makefiles in Visual Studio?

I actually use a makefile to build any dependencies needed before invoking devenv to build a particular project as in the following:

debug: coratools_debug
    devenv coralib.vcproj /build debug

coratools_debug: nothing
    cd ../coratools
    nmake debug
    cd $(MAKEDIR)

You can also use the msbuild tool to do the same thing:

debug: coratools_debug
    msbuild coralib.vcxproj /p:Configuration=debug

coratools_debug: nothing
    cd ../coratools
    nmake debug
    cd $(MAKEDIR)

In my opinion, this is much easier than trying to figure out the overly complicated visual studio project management scheme.

How To Get The Current Year Using Vba

Year(Date)

Year(): Returns the year portion of the date argument.
Date: Current date only.

Explanation of both of these functions from here.

How do I combine 2 select statements into one?

If they are from the same table, I think UNION is the command you're looking for.

(If you'd ever need to select values from columns of different tables, you should look at JOIN instead...)

Send file via cURL from form POST in PHP

It works for me when sending an attachment to Mercadolibre, through its messaging system.

The anwswer https://stackoverflow.com/a/35227055/7656744

$target_url = "http://server:port/xxxxx.php";           
$fname = 'file.txt';   
$cfile = new CURLFile(realpath($fname));

    $post = array (
              'file' => $cfile
              );    

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $target_url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");   
curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);   
curl_setopt($ch, CURLOPT_FORBID_REUSE, 1);  
curl_setopt($ch, CURLOPT_TIMEOUT, 100);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

$result = curl_exec ($ch);

if ($result === FALSE) {
    echo "Error sending" . $fname .  " " . curl_error($ch);
    curl_close ($ch);
}else{
    curl_close ($ch);
    echo  "Result: " . $result;
}   

Sites not accepting wget user agent header

You need to set both the user-agent and the referer:

 wget  --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" --referrer  connect.wso2.com http://dist.wso2.org/products/carbon/4.2.0/wso2carbon-4.2.0.zip

How to convert .pem into .key?

I assume you want the DER encoded version of your PEM private key.

openssl rsa -outform der -in private.pem -out private.key

Define preprocessor macro through CMake?

The other solution proposed on this page are useful some versions of Cmake < 3.3.2. Here the solution for the version I am using (i.e., 3.3.2). Check the version of your Cmake by using $ cmake --version and pick the solution that fits with your needs. The cmake documentation can be found on the official page.

With CMake version 3.3.2, in order to create

#define foo

I needed to use:

add_definitions(-Dfoo)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

and, in order to have a preprocessor macro definition like this other one:

#define foo=5

the line is so modified:

add_definitions(-Dfoo=5)   # <--------HERE THE NEW CMAKE LINE inside CMakeLists.txt
add_executable( ....)
target_link_libraries(....)

Does Java have something like C#'s ref and out keywords?

Like many others, I needed to convert a C# project to Java. I did not find a complete solution on the web regarding out and ref modifiers. But, I was able to take the information I found, and expand upon it to create my own classes to fulfill the requirements. I wanted to make a distinction between ref and out parameters for code clarity. With the below classes, it is possible. May this information save others time and effort.

An example is included in the code below.

//*******************************************************************************************
//XOUT CLASS
//*******************************************************************************************
public class XOUT<T>
{
    public XOBJ<T> Obj = null;

    public XOUT(T value)
    {
        Obj = new XOBJ<T>(value);
    }

    public XOUT()
    {
      Obj = new XOBJ<T>();
    }

    public XOUT<T> Out()
    {
        return(this);
    }

    public XREF<T> Ref()
    {
        return(Obj.Ref());
    }
};

//*******************************************************************************************
//XREF CLASS
//*******************************************************************************************

public class XREF<T>
{
    public XOBJ<T> Obj = null;

    public XREF(T value)
    {
        Obj = new XOBJ<T>(value);
    }

    public XREF()
    {
      Obj = new XOBJ<T>();
    }

    public XOUT<T> Out()
    {
        return(Obj.Out());
    }

    public XREF<T> Ref()
    {
        return(this);
    }
};

//*******************************************************************************************
//XOBJ CLASS
//*******************************************************************************************
/**
 *
 * @author jsimms
 */
/*
    XOBJ is the base object that houses the value. XREF and XOUT are classes that
    internally use XOBJ. The classes XOBJ, XREF, and XOUT have methods that allow
    the object to be used as XREF or XOUT parameter; This is important, because
    objects of these types are interchangeable.

    See Method:
       XXX.Ref()
       XXX.Out()

    The below example shows how to use XOBJ, XREF, and XOUT;
    //
    // Reference parameter example
    //
    void AddToTotal(int a, XREF<Integer> Total)
    {
       Total.Obj.Value += a;
    }

    //
    // out parameter example
    //
    void Add(int a, int b, XOUT<Integer> ParmOut)
    {
       ParmOut.Obj.Value = a+b;
    }

    //
    // XOBJ example
    //
    int XObjTest()
    {
       XOBJ<Integer> Total = new XOBJ<>(0);
       Add(1, 2, Total.Out());    // Example of using out parameter
       AddToTotal(1,Total.Ref()); // Example of using ref parameter
       return(Total.Value);
    }
*/


public class XOBJ<T> {

    public T Value;

    public  XOBJ() {

    }

    public XOBJ(T value) {
        this.Value = value;
    }

    //
    // Method: Ref()
    // Purpose: returns a Reference Parameter object using the XOBJ value
    //
    public XREF<T> Ref()
    {
        XREF<T> ref = new XREF<T>();
        ref.Obj = this;
        return(ref);
    }

    //
    // Method: Out()
    // Purpose: returns an Out Parameter Object using the XOBJ value
    //
    public XOUT<T> Out()
    {
        XOUT<T> out = new XOUT<T>();
        out.Obj = this;
        return(out);
    }

    //
    // Method get()
    // Purpose: returns the value
    // Note: Because this is combersome to edit in the code,
    // the Value object has been made public
    //
    public T get() {
        return Value;
    }

    //
    // Method get()
    // Purpose: sets the value
    // Note: Because this is combersome to edit in the code,
    // the Value object has been made public
    //
    public void set(T anotherValue) {
        Value = anotherValue;
    }

    @Override
    public String toString() {
        return Value.toString();
    }

    @Override
    public boolean equals(Object obj) {
        return Value.equals(obj);
    }

    @Override
    public int hashCode() {
        return Value.hashCode();
    }
}

How/When does Execute Shell mark a build as failure in Jenkins?

In Jenkins ver. 1.635, it is impossible to show a native environment variable like this:

$BUILD_NUMBER or ${BUILD_NUMBER}

In this case, you have to set it in an other variable.

set BUILDNO = $BUILD_NUMBER
$BUILDNO

jQuery dialog popup

This HTML is fine:

<a href="#" id="contactUs">Contact Us</a>                   
<div id="dialog" title="Contact form">
  <p>appear now</p>
</div>

You need to initialize the Dialog (not sure if you are doing this):

$(function() {
  // this initializes the dialog (and uses some common options that I do)
  $("#dialog").dialog({
    autoOpen : false, modal : true, show : "blind", hide : "blind"
  });

  // next add the onclick handler
  $("#contactUs").click(function() {
    $("#dialog").dialog("open");
    return false;
  });
});

PHP, getting variable from another php-file

You can, but the variable in your last include will overwrite the variable in your first one:

myfile.php

$var = 'test';

mysecondfile.php

$var = 'tester';

test.php

include 'myfile.php';
echo $var;

include 'mysecondfile.php';
echo $var;

Output:

test

tester

I suggest using different variable names.

How can you get the first digit in an int (C#)?

start = getFirstDigit(start);   
public int getFirstDigit(final int start){
    int number = Math.abs(start);
    while(number > 10){
        number /= 10;
    }
    return number;
}

or

public int getFirstDigit(final int start){
  return getFirstDigit(Math.abs(start), true);
}
private int getFirstDigit(final int start, final boolean recurse){
  if(start < 10){
    return start;
  }
  return getFirstDigit(start / 10, recurse);
}

What is the default access specifier in Java?

Here is a quote about package level visibility from an interview with James Gosling, the creator of Java:

Bill Venners: Java has four access levels. The default is package. I have always wondered if making package access default was convenient because the three keywords that people from C++ already knew about were private, protected, and public. Or if you had some particular reason that you felt package access should be the default.

James Gosling: A package is generally a set of things that are kind of written together. So generically I could have done one of two things. One was force you always to put in a keyword that gives you the domain. Or I could have had a default value. And then the question is, what makes a sensible default? And I tend to go for what is the least dangerous thing.

So public would have been a really bad thing to make the default. Private would probably have been a bad thing to make a default, if only because people actually don't write private methods that often. And same thing with protected. And in looking at a bunch of code that I had, I decided that the most common thing that was reasonably safe was in the package. And C++ didn't have a keyword for that, because they didn't have a notion of packages.

But I liked it rather than the friends notion, because with friends you kind of have to enumerate who all of your friends are, and so if you add a new class to a package, then you generally end up having to go to all of the classes in that package and update their friends, which I had always found to be a complete pain in the butt.

But the friends list itself causes sort of a versioning problem. And so there was this notion of a friendly class. And the nice thing that I was making that the default -- I'll solve the problem so what should the keyword be?

For a while there actually was a friendly keyword. But because all the others start with "P," it was "phriendly" with a "PH." But that was only in there for maybe a day.

http://www.artima.com/intv/gosling2P.html

How to persist data in a dockerized postgres database using volumes

I think you just need to create your volume outside docker first with a docker create -v /location --name and then reuse it.

And by the time I used to use docker a lot, it wasn't possible to use a static docker volume with dockerfile definition so my suggestion is to try the command line (eventually with a script ) .

Executing <script> injected by innerHTML after AJAX call

I had a similiar post here, addEventListener load on ajax load WITHOUT jquery

How I solved it was to insert calls to functions within my stateChange function. The page I had setup was 3 buttons that would load 3 different pages into the contentArea. Because I had to know which button was being pressed to load page 1, 2 or 3, I could easily use if/else statements to determine which page is being loaded and then which function to run. What I was trying to do was register different button listeners that would only work when the specific page was loaded because of element IDs..

so...

if (page1 is being loaded, pageload = 1) run function registerListeners1

then the same for page 2 or 3.

What is the difference between concurrency and parallelism?

From the book Linux System Programming by Robert Love:

Concurrency, Parallelism, and Races

Threads create two related but distinct phenomena: concurrency and parallelism. Both are bittersweet, touching on the costs of threading as well as its benefits. Concurrency is the ability of two or more threads to execute in overlapping time periods. Parallelism is the ability to execute two or more threads simultaneously. Concurrency can occur without parallelism: for example, multitasking on a single processor system. Parallelism (sometimes emphasized as true parallelism) is a specific form of concurrency requiring multiple processors (or a single processor capable of multiple engines of execution, such as a GPU). With concurrency, multiple threads make forward progress, but not necessarily simultaneously. With parallelism, threads literally execute in parallel, allowing multithreaded programs to utilize multiple processors.

Concurrency is a programming pattern, a way of approaching problems. Parallelism is a hardware feature, achievable through concurrency. Both are useful.

This explanation is consistent with the accepted answer. Actually the concepts are far simpler than we think. Don't think them as magic. Concurrency is about a period of time, while Parallelism is about exactly at the same time, simultaneously.

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

For me, I changed class='carousel-item' to class='item' like this

<div class="item">
    <img class="img-responsive" src="..." alt="...">
</div>

Division in Python 2.7. and 3.3

In Python 3, / is float division

In Python 2, / is integer division (assuming int inputs)

In both 2 and 3, // is integer division

(To get float division in Python 2 requires either of the operands be a float, either as 20. or float(20))

BarCode Image Generator in Java

iText is a great Java PDF library. They also have an API for creating barcodes. You don't need to be creating a PDF to use it.

This page has the details on creating barcodes. Here is an example from that site:

BarcodeEAN codeEAN = new BarcodeEAN();
codeEAN.setCodeType(codeEAN.EAN13);
codeEAN.setCode("9780201615883");
Image imageEAN = codeEAN.createImageWithBarcode(cb, null, null);

The biggest thing you will need to determine is what type of barcode you need. There are many different barcode formats and iText does support a lot of them. You will need to know what format you need before you can determine if this API will work for you.

What is the printf format specifier for bool?

I prefer an answer from Best way to print the result of a bool as 'false' or 'true' in c?, just like

printf("%s\n", "false\0true"+6*x);
  • x == 0, "false\0true"+ 0" it means "false";
  • x == 1, "false\0true"+ 6" it means "true";

Invisible characters - ASCII

An invisible Character is ?, or U+200b

?

Internet Access in Ubuntu on VirtualBox

I had the same problem.

Solved by sharing internet connection (on the hosting OS).

Network Connection Properties -> advanced -> Allow other users to connect...

Python division

Make at least one of them float, then it will be float division, not integer:

>>> (20.0-10) / (100-10)
0.1111111111111111

Casting the result to float is too late.

How to split data into trainset and testset randomly?

To answer @desmond.carros question, I modified the best answer as follows,

 import random
 file=open("datafile.txt","r")
 data=list()
 for line in file:
    data.append(line.split(#your preferred delimiter))
 file.close()
 random.shuffle(data)
 train_data = data[:int((len(data)+1)*.80)] #Remaining 80% to training set
 test_data = data[int((len(data)+1)*.80):] #Splits 20% data to test set

The code splits the entire dataset to 80% train and 20% test data

Java string to date conversion

While some of the answers are technically correct, they are not advisable.

  • The java.util.Date & Calendar classes are notoriously troublesome. Because of flaws in design and implementation, avoid them. Fortunately we have our choice of two other excellent date-time libraries:
    • Joda-Time
      This popular open-source free-of-cost library can be used across several versions of Java. Many examples of its usage may be found on StackOverflow. Reading some of these will help get you up to speed quickly.
    • java.time.* package
      This new set of classes are inspired by Joda-Time and defined by JSR 310. These classes are built into Java 8. A project is underway to backport these classes to Java 7, but that backporting is not backed by Oracle.
  • As Kristopher Johnson correctly noted in his comment on the question, the other answers ignore vital issues of:
    • Time of Day
      Date has both a date portion and a time-of-day portion)
    • Time Zone
      The beginning of a day depends on the time zone. If you fail to specify a time zone, the JVM's default time zone is applied. That means the behavior of your code may change when run on other computers or with a modified time zone setting. Probably not what you want.
    • Locale
      The Locale's language specifies how to interpret the words (name of month and of day) encountered during parsing. (The answer by BalusC handles this properly.) Also, the Locale affects the output of some formatters when generating a string representation of your date-time.

Joda-Time

A few notes about Joda-Time follow.

Time Zone

In Joda-Time, a DateTime object truly knows its own assigned time zone. This contrasts the java.util.Date class which seems to have a time zone but does not.

Note in the example code below how we pass a time zone object to the formatter which parses the string. That time zone is used to interpret that date-time as having occurred in that time zone. So you need to think about and determine the time zone represented by that string input.

Since you have no time portion in your input string, Joda-Time assigns the first moment of the day of the specified time zone as the time-of-day. Usually this means 00:00:00 but not always, because of Daylight Saving Time (DST) or other anomalies. By the way, you can do the same to any DateTime instance by calling withTimeAtStartOfDay.

Formatter Pattern

The characters used in a formatter's pattern are similar in Joda-Time to those in java.util.Date/Calendar but not exactly the same. Carefully read the doc.

Immutability

We usually use the immutable classes in Joda-Time. Rather than modify an existing Date-Time object, we call methods that create a new fresh instance based on the other object with most aspects copied except where alterations were desired. An example is the call to withZone in last line below. Immutability helps to make Joda-Time very thread-safe, and can also make some work more clear.

Conversion

You will need java.util.Date objects for use with other classes/framework that do not know about Joda-Time objects. Fortunately, it is very easy to move back and forth.

Going from a java.util.Date object (here named date) to Joda-Time DateTime…

org.joda.time.DateTime dateTime = new DateTime( date, timeZone );

Going the other direction from Joda-Time to a java.util.Date object…

java.util.Date date = dateTime.toDate();

Sample Code

String input = "January 2, 2010";

java.util.Locale locale = java.util.Locale.US;
DateTimeZone timeZone = DateTimeZone.forID( "Pacific/Honolulu" ); // Arbitrarily chosen for example.
DateTimeFormatter formatter = DateTimeFormat.forPattern( "MMMM d, yyyy" ).withZone( timeZone ).withLocale( locale );
DateTime dateTime = formatter.parseDateTime( input );

System.out.println( "dateTime: " + dateTime );
System.out.println( "dateTime in UTC/GMT: " + dateTime.withZone( DateTimeZone.UTC ) );

When run…

dateTime: 2010-01-02T00:00:00.000-10:00
dateTime in UTC/GMT: 2010-01-02T10:00:00.000Z

How can I find out if an .EXE has Command-Line Options?

This is what I get from console on Windows 10:

C:\>find /?
Searches for a text string in a file or files.

FIND [/V] [/C] [/N] [/I] [/OFF[LINE]] "string" [[drive:][path]filename[ ...]]

  /V         Displays all lines NOT containing the specified string.
  /C         Displays only the count of lines containing the string.
  /N         Displays line numbers with the displayed lines.
  /I         Ignores the case of characters when searching for the string.
  /OFF[LINE] Do not skip files with offline attribute set.
  "string"   Specifies the text string to find.
  [drive:][path]filename
             Specifies a file or files to search.

If a path is not specified, FIND searches the text typed at the prompt
or piped from another command.

Generate a sequence of numbers in Python

Includes some guessing on the exact sequence you are expecting:

>>> l = list(range(1, 100, 4)) + list(range(2, 100, 4))
>>> l.sort()
>>> ','.join(map(str, l))
'1,2,5,6,9,10,13,14,17,18,21,22,25,26,29,30,33,34,37,38,41,42,45,46,49,50,53,54,57,58,61,62,65,66,69,70,73,74,77,78,81,82,85,86,89,90,93,94,97,98'

As one-liner:

>>> ','.join(map(str, sorted(list(range(1, 100, 4))) + list(range(2, 100, 4))))

(btw. this is Python 3 compatible)

How can I get a character in a string by index?

string s = "hello";
char c = s[1];
// now c == 'e'

See also Substring, to return more than one character.

Codeigniter: does $this->db->last_query(); execute a query?

For me save_queries option was turned off so,

$this->db->save_queries = TRUE; //Turn ON save_queries for temporary use.
$str = $this->db->last_query();
echo $str;

Ref: Can't get result from $this->db->last_query(); codeigniter

How to drop columns by name in a data frame

df2 <- df[!names(df) %in% c("c1", "c2")]

Why should I use a container div in HTML?

div tags are used to style the webpage so that it look visually appealing for the users or audience of the website. using container-div in html will make the website look more professional and attractive and therefore more people will want to explore your page.

What is the difference between a static and a non-static initialization code block

Uff! what is static initializer?

The static initializer is a static {} block of code inside java class, and run only one time before the constructor or main method is called.

OK! Tell me more...

  • is a block of code static { ... } inside any java class. and executed by virtual machine when class is called.
  • No return statements are supported.
  • No arguments are supported.
  • No this or super are supported.

Hmm where can I use it?

Can be used anywhere you feel ok :) that simple. But I see most of the time it is used when doing database connection, API init, Logging and etc.

Don't just bark! where is example?

package com.example.learnjava;

import java.util.ArrayList;

public class Fruit {

    static {
        System.out.println("Inside Static Initializer.");

        // fruits array
        ArrayList<String> fruits = new ArrayList<>();
        fruits.add("Apple");
        fruits.add("Orange");
        fruits.add("Pear");

        // print fruits
        for (String fruit : fruits) {
            System.out.println(fruit);
        }
        System.out.println("End Static Initializer.\n");
    }

    public static void main(String[] args) {
        System.out.println("Inside Main Method.");
    }
}

Output???

Inside Static Initializer.

Apple

Orange

Pear

End Static Initializer.

Inside Main Method.

Hope this helps!

SQLException: No suitable Driver Found for jdbc:oracle:thin:@//localhost:1521/orcl

The "ojdbc.jar" is not in the CLASSPATH of your application server.

Just tell us which application server it is and we will tell you where the driver should be placed.

Edit: I saw the tag so it has to be placed in folder "$JBOSS_HOME/server/default/lib/"

How do I profile memory usage in Python?

Since the accepted answer and also the next highest voted answer have, in my opinion, some problems, I'd like to offer one more answer that is based closely on Ihor B.'s answer with some small but important modifications.

This solution allows you to run profiling on either by wrapping a function call with the profile function and calling it, or by decorating your function/method with the @profile decorator.

The first technique is useful when you want to profile some third-party code without messing with its source, whereas the second technique is a bit "cleaner" and works better when you are don't mind modifying the source of the function/method you want to profile.

I've also modified the output, so that you get RSS, VMS, and shared memory. I don't care much about the "before" and "after" values, but only the delta, so I removed those (if you're comparing to Ihor B.'s answer).

Profiling code

# profile.py
import time
import os
import psutil
import inspect


def elapsed_since(start):
    #return time.strftime("%H:%M:%S", time.gmtime(time.time() - start))
    elapsed = time.time() - start
    if elapsed < 1:
        return str(round(elapsed*1000,2)) + "ms"
    if elapsed < 60:
        return str(round(elapsed, 2)) + "s"
    if elapsed < 3600:
        return str(round(elapsed/60, 2)) + "min"
    else:
        return str(round(elapsed / 3600, 2)) + "hrs"


def get_process_memory():
    process = psutil.Process(os.getpid())
    mi = process.memory_info()
    return mi.rss, mi.vms, mi.shared


def format_bytes(bytes):
    if abs(bytes) < 1000:
        return str(bytes)+"B"
    elif abs(bytes) < 1e6:
        return str(round(bytes/1e3,2)) + "kB"
    elif abs(bytes) < 1e9:
        return str(round(bytes / 1e6, 2)) + "MB"
    else:
        return str(round(bytes / 1e9, 2)) + "GB"


def profile(func, *args, **kwargs):
    def wrapper(*args, **kwargs):
        rss_before, vms_before, shared_before = get_process_memory()
        start = time.time()
        result = func(*args, **kwargs)
        elapsed_time = elapsed_since(start)
        rss_after, vms_after, shared_after = get_process_memory()
        print("Profiling: {:>20}  RSS: {:>8} | VMS: {:>8} | SHR {"
              ":>8} | time: {:>8}"
            .format("<" + func.__name__ + ">",
                    format_bytes(rss_after - rss_before),
                    format_bytes(vms_after - vms_before),
                    format_bytes(shared_after - shared_before),
                    elapsed_time))
        return result
    if inspect.isfunction(func):
        return wrapper
    elif inspect.ismethod(func):
        return wrapper(*args,**kwargs)

Example usage, assuming the above code is saved as profile.py:

from profile import profile
from time import sleep
from sklearn import datasets # Just an example of 3rd party function call


# Method 1
run_profiling = profile(datasets.load_digits)
data = run_profiling()

# Method 2
@profile
def my_function():
    # do some stuff
    a_list = []
    for i in range(1,100000):
        a_list.append(i)
    return a_list


res = my_function()

This should result in output similar to the below:

Profiling:        <load_digits>  RSS:   5.07MB | VMS:   4.91MB | SHR  73.73kB | time:  89.99ms
Profiling:        <my_function>  RSS:   1.06MB | VMS:   1.35MB | SHR       0B | time:   8.43ms

A couple of important final notes:

  1. Keep in mind, this method of profiling is only going to be approximate, since lots of other stuff might be happening on the machine. Due to garbage collection and other factors, the deltas might even be zero.
  2. For some unknown reason, very short function calls (e.g. 1 or 2 ms) show up with zero memory usage. I suspect this is some limitation of the hardware/OS (tested on basic laptop with Linux) on how often memory statistics are updated.
  3. To keep the examples simple, I didn't use any function arguments, but they should work as one would expect, i.e. profile(my_function, arg) to profile my_function(arg)

Exception in thread "main" java.lang.UnsupportedClassVersionError: a (Unsupported major.minor version 51.0)

I had this problem, after installing jdk7 next to Java 6. The binaries were correctly updated using update-alternatives --config java to jdk7, but the $JAVA_HOME environment variable still pointed to the old directory of Java 6.

How to throw std::exceptions with variable messages?

Here is my solution:

#include <stdexcept>
#include <sstream>

class Formatter
{
public:
    Formatter() {}
    ~Formatter() {}

    template <typename Type>
    Formatter & operator << (const Type & value)
    {
        stream_ << value;
        return *this;
    }

    std::string str() const         { return stream_.str(); }
    operator std::string () const   { return stream_.str(); }

    enum ConvertToString 
    {
        to_str
    };
    std::string operator >> (ConvertToString) { return stream_.str(); }

private:
    std::stringstream stream_;

    Formatter(const Formatter &);
    Formatter & operator = (Formatter &);
};

Example:

throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData);   // implicitly cast to std::string
throw std::runtime_error(Formatter() << foo << 13 << ", bar" << myData >> Formatter::to_str);    // explicitly cast to std::string

Converting of Uri to String

If you want to pass a Uri to another activity, try the method intent.setData(Uri uri) https://developer.android.com/reference/android/content/Intent.html#setData(android.net.Uri)

In another activity, via intent.getData() to obtain the Uri.

'xmlParseEntityRef: no name' warnings while loading xml into a php file

The XML is most probably invalid.

The problem could be the "&"

$text=preg_replace('/&(?!#?[a-z0-9]+;)/', '&amp;', $text);

will get rid of the "&" and replace it with it's HTML code version...give it a try.

What happens to a declared, uninitialized variable in C? Does it have a value?

It depends on the storage duration of the variable. A variable with static storage duration is always implicitly initialized with zero.

As for automatic (local) variables, an uninitialized variable has indeterminate value. Indeterminate value, among other things, mean that whatever "value" you might "see" in that variable is not only unpredictable, it is not even guaranteed to be stable. For example, in practice (i.e. ignoring the UB for a second) this code

int num;
int a = num;
int b = num;

does not guarantee that variables a and b will receive identical values. Interestingly, this is not some pedantic theoretical concept, this readily happens in practice as consequence of optimization.

So in general, the popular answer that "it is initialized with whatever garbage was in memory" is not even remotely correct. Uninitialized variable's behavior is different from that of a variable initialized with garbage.

whitespaces in the path of windows filepath

path = r"C:\Users\mememe\Google Drive\Programs\Python\file.csv"

Closing the path in r"string" also solved this problem very well.

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

For anyone else and just an addition to Robert, If your nav has flex display value, you can float the element that you need to the right, by adding this to its css

{
    margin-left: auto;
}

How to use Spring Boot with MySQL database and JPA?

You can move Application.java to a folder under the java.

Rename Oracle Table or View

Past 10g the current answer no longer works for renaming views. The only method that still works is dropping and recreating the view. The best way I can think of to do this would be:

SELECT TEXT FROM ALL_VIEWS WHERE owner='some_schema' and VIEW_NAME='some_view';

Add this in front of the SQL returned

Create or replace view some_schema.new_view_name as ...

Drop the old view

Drop view some_schema.some_view;

Is there any way to call a function periodically in JavaScript?

You will want to have a look at setInterval() and setTimeout().

Here is a decent tutorial article.

Android sqlite how to check if a record exists

You can use like this:

String Query = "Select * from " + TABLE_NAME + " where " + Cust_id + " = " + cust_no;

Cursor cursorr = db.rawQuery(Query, null);
if(cursor.getCount() <= 0){
cursorr.close();
}
cursor.close();

endforeach in loops?

How about this?

<ul>
<?php while ($items = array_pop($lists)) { ?>
    <ul>
    <?php foreach ($items as $item) { ?>
        <li><?= $item ?></li>
    <?php
    }//foreach
}//while ?>

We can still use the more widely-used braces and, at the same time, increase readability.

"NoClassDefFoundError: Could not initialize class" error

I had this:

 class Util {
  static boolean isNeverAsync = System.getenv().get("asyncc_exclude_redundancy").equals("yes");
}

you can probably see the problem, the env var might return null instead of string. So just to test my theory, I changed it to:

 class Util {
  static boolean isNeverAsync = false;
}

and the problem went away. Too bad that Java can't give you the exact stack trace of the error though, kinda weird.

Android Left to Right slide animation

If you want the transition work for whole application you can create a rootacivity and inherit it in the activity you need. In Root Activity's onCreate call overridePendingTransition with desired direction. And onStart call overridePendingTransition with other direction if activity is resumed. Here I am giving full running code below.Correct me if I am wrong.

create this xml file on your anim folder

anim_slide_in_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate
        android:duration="600"
        android:fromXDelta="100%"
        android:toXDelta="0%" >
    </translate>
</set>

anim_slide_in_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate
        android:duration="600"
        android:fromXDelta="-100%"
        android:toXDelta="0%" >
    </translate>
</set>

anim_slide_out_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate
        android:duration="600"
        android:fromXDelta="0%"
        android:toXDelta="-100%" >
    </translate>
</set>

anim_slide_out_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android" >
    <translate
        android:duration="600"
        android:fromXDelta="0%"
        android:toXDelta="100%" >
    </translate>
</set>

RootActivity

import android.app.Activity;
import android.os.Bundle;

public class RootActivity extends Activity {
    int onStartCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        onStartCount = 1;
        if (savedInstanceState == null) // 1st time
        {
            this.overridePendingTransition(R.anim.anim_slide_in_left,
                    R.anim.anim_slide_out_left);
        } else // already created so reverse animation
        { 
            onStartCount = 2;
        }
    }

    @Override
    protected void onStart() {
        // TODO Auto-generated method stub
        super.onStart();
        if (onStartCount > 1) {
            this.overridePendingTransition(R.anim.anim_slide_in_right,
                    R.anim.anim_slide_out_right);

        } else if (onStartCount == 1) {
            onStartCount++;
        }

    }

}

FirstActivity

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class FirstActivity extends RootActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv = (TextView) findViewById(R.id.tvTitle);
        tv.setText("First Activity");
        Button bt = (Button) findViewById(R.id.buttonNext);
        bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(FirstActivity.this, SecondActivity.class);
                startActivity(i);

            }
        });
    }

}

SecondActivity

import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class SecondActivity extends RootActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv = (TextView) findViewById(R.id.tvTitle);
        tv.setText("Second Activity");
        Button bt = (Button) findViewById(R.id.buttonNext);
        bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(SecondActivity.this, ThirdActivity.class);
                startActivity(i);

            }
        });

    }

}

ThirdActivity

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class ThirdActivity extends RootActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView tv = (TextView) findViewById(R.id.tvTitle);
        tv.setText("Third Activity");
        Button bt = (Button) findViewById(R.id.buttonNext);
        bt.setText("previous");
        bt.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();

            }
        });
    }

}

and finally Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.transitiontest"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="18" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.transitiontest.FirstActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name="com.example.transitiontest.SecondActivity"
            android:label="@string/app_name" >
        </activity>
        <activity
            android:name="com.example.transitiontest.ThirdActivity"
            android:label="@string/app_name" >
        </activity>
    </application>

</manifest>

How to install Maven 3 on Ubuntu 18.04/17.04/16.10/16.04 LTS/15.10/15.04/14.10/14.04 LTS/13.10/13.04 by using apt-get?

It's best to use miske's answer.

Properly installing natecarlson's repository

If you really want to use natecarlson's repository, the instructions just below can do any of the following:

  1. set it up from scratch
  2. repair it if apt-get update gives a 404 error after add-apt-repository
  3. repair it if apt-get update gives a NO_PUBKEY error after manually adding it to /etc/apt/sources.list

Open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

export GOOD_RELEASE='precise'
export BAD_RELEASE="`lsb_release -cs`"
cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-add-repository -y ppa:natecarlson/maven3
mv natecarlson-maven3-${BAD_RELEASE}.list natecarlson-maven3-${GOOD_RELEASE}.list
sed -i "s/${BAD_RELEASE}/${GOOD_RELEASE}/" natecarlson-maven3-${GOOD_RELEASE}.list
apt-get update
exit
echo Done!

Removing natecarlson's repository

If you installed natecarlson's repository (either using add-apt-repository or manually added to /etc/apt/sources.list) and you don't want it anymore, open a terminal and run the following:

sudo -i

Enter your password if necessary, then paste the following into the terminal:

cd /etc/apt
sed -i '/natecarlson\/maven3/d' sources.list
cd sources.list.d
rm -f natecarlson-maven3-*.list*
apt-get update
exit
echo Done!

C#/Linq: Apply a mapping function to each element in an IEnumerable?

You can just use the Select() extension method:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };
IEnumerable<string> strings = integers.Select(i => i.ToString());

Or in LINQ syntax:

IEnumerable<int> integers = new List<int>() { 1, 2, 3, 4, 5 };

var strings = from i in integers
              select i.ToString();

SQL Query - Using Order By in UNION

Here's an example from Northwind 2007:

SELECT [Product ID], [Order Date], [Company Name], [Transaction], [Quantity]
FROM [Product Orders]
UNION SELECT [Product ID], [Creation Date], [Company Name], [Transaction], [Quantity]
FROM [Product Purchases]
ORDER BY [Order Date] DESC;

The ORDER BY clause just needs to be the last statement, after you've done all your unioning. You can union several sets together, then put an ORDER BY clause after the last set.

How connect Postgres to localhost server using pgAdmin on Ubuntu?

Modify password for role postgres:

sudo -u postgres psql postgres

alter user postgres with password 'postgres';

Now connect to pgadmin using username postgres and password postgres

Now you can create roles & databases using pgAdmin

How to change PostgreSQL user password?

jQuery, simple polling example

jQuery.Deferred() can simplify management of asynchronous sequencing and error handling.

polling_active = true // set false to interrupt polling

function initiate_polling()
    {
    $.Deferred().resolve() // optional boilerplate providing the initial 'then()'
    .then( () => $.Deferred( d=>setTimeout(()=>d.resolve(),5000) ) ) // sleep
    .then( () => $.get('/my-api') ) // initiate AJAX
    .then( response =>
        {
        if ( JSON.parse(response).my_result == my_target ) polling_active = false
        if ( ...unhappy... ) return $.Deferred().reject("unhappy") // abort
        if ( polling_active ) initiate_polling() // iterative recursion
        })
    .fail( r => { polling_active=false, alert('failed: '+r) } ) // report errors
    }

This is an elegant approach, but there are some gotchas...

  • If you don't want a then() to fall through immediately, the callback should return another thenable object (probably another Deferred), which the sleep and ajax lines both do.
  • The others are too embarrassing to admit. :)

Get url parameters from a string in .NET

if you want in get your QueryString on Default page .Default page means your current page url . you can try this code :

string paramIl = HttpUtility.ParseQueryString(this.ClientQueryString).Get("city");

How to install PHP mbstring on CentOS 6.2

sudo yum install php<version>w-mbstring

ex. sudo yum install php56w-mbstring

How to break long string to multiple lines

If the long string to multiple lines confuses you. Then you may install mz-tools addin which is a freeware and has the utility which splits the line for you.

Download Mz-tools

If your string looks like below

SqlQueryString = "Insert into Employee values(" & txtEmployeeNo.Value & "','" & txtContractStartDate.Value & "','" & txtSeatNo.Value & "','" & txtFloor.Value & "','" & txtLeaves.Value & "')"

Simply select the string > right click on VBA IDE > Select MZ-tools > Split Lines

enter image description here

What is std::move(), and when should it be used?

Q: What is std::move?

A: std::move() is a function from the C++ Standard Library for casting to a rvalue reference.

Simplisticly std::move(t) is equivalent to:

static_cast<T&&>(t);

An rvalue is a temporary that does not persist beyond the expression that defines it, such as an intermediate function result which is never stored in a variable.

int a = 3; // 3 is a rvalue, does not exist after expression is evaluated
int b = a; // a is a lvalue, keeps existing after expression is evaluated

An implementation for std::move() is given in N2027: "A Brief Introduction to Rvalue References" as follows:

template <class T>
typename remove_reference<T>::type&&
std::move(T&& a)
{
    return a;
}

As you can see, std::move returns T&& no matter if called with a value (T), reference type (T&), or rvalue reference (T&&).

Q: What does it do?

A: As a cast, it does not do anything during runtime. It is only relevant at compile time to tell the compiler that you would like to continue considering the reference as an rvalue.

foo(3 * 5); // obviously, you are calling foo with a temporary (rvalue)

int a = 3 * 5;
foo(a);     // how to tell the compiler to treat `a` as an rvalue?
foo(std::move(a)); // will call `foo(int&& a)` rather than `foo(int a)` or `foo(int& a)`

What it does not do:

  • Make a copy of the argument
  • Call the copy constructor
  • Change the argument object

Q: When should it be used?

A: You should use std::move if you want to call functions that support move semantics with an argument which is not an rvalue (temporary expression).

This begs the following follow-up questions for me:

  • What is move semantics? Move semantics in contrast to copy semantics is a programming technique in which the members of an object are initialized by 'taking over' instead of copying another object's members. Such 'take over' makes only sense with pointers and resource handles, which can be cheaply transferred by copying the pointer or integer handle rather than the underlying data.

  • What kind of classes and objects support move semantics? It is up to you as a developer to implement move semantics in your own classes if these would benefit from transferring their members instead of copying them. Once you implement move semantics, you will directly benefit from work from many library programmers who have added support for handling classes with move semantics efficiently.

  • Why can't the compiler figure it out on its own? The compiler cannot just call another overload of a function unless you say so. You must help the compiler choose whether the regular or move version of the function should be called.

  • In which situations would I want to tell the compiler that it should treat a variable as an rvalue? This will most likely happen in template or library functions, where you know that an intermediate result could be salvaged.

Good tutorial for using HTML5 History API (Pushstate?)

I've written a very simple router abstraction on top of History.js, called StateRouter.js. It's in very early stages of development, but I am using it as the routing solution in a single-page application I'm writing. Like you, I found History.js very hard to grasp, especially as I'm quite new to JavaScript, until I understood that you really need (or should have) a routing abstraction on top of it, as it solves a low-level problem.

This simple example code should demonstrate how it's used:

var router = new staterouter.Router();
// Configure routes
router
  .route('/', getHome)
  .route('/persons', getPersons)
  .route('/persons/:id', getPerson);
// Perform routing of the current state
router.perform();

Here's a little fiddle I've concocted in order to demonstrate its usage.

How do I programmatically click a link with javascript?

This function works in at least Firefox, and Internet Explorer. It runs any event handlers attached to the link and loads the linked page if the event handlers don't cancel the default action.

function clickLink(link) {
    var cancelled = false;

    if (document.createEvent) {
        var event = document.createEvent("MouseEvents");
        event.initMouseEvent("click", true, true, window,
            0, 0, 0, 0, 0,
            false, false, false, false,
            0, null);
        cancelled = !link.dispatchEvent(event);
    }
    else if (link.fireEvent) {
        cancelled = !link.fireEvent("onclick");
    }

    if (!cancelled) {
        window.location = link.href;
    }
}

How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"

Visual Studio Community 2017

Go here : C:\Program Files (x86)\Windows Kits\10

and do whatever you were supposed to go in the given directory for VS 13.

in the lib folder, you will find some versions, I copied the 32-bit glut.lib files in amd and x86 and 64-bit glut.lib in arm64 and x64 directories in um folder for every version that I could find.

That worked for me.

EDIT : I tried this in windows 10, maybe you need to go to C:\Program Files (x86)\Windows Kits\8.1 folder for windows 8/8.1.

How to yum install Node.JS on Amazon Linux

https://nodejs.org/en/download/package-manager/#debian-and-ubuntu-based-linux-distributions

curl --silent --location https://rpm.nodesource.com/setup_10.x | sudo bash - sudo yum -y install nodejs

async/await - when to return a Task vs void?

The problem with calling async void is that

you don’t even get the task back. You have no way of knowing when the function’s task has completed. —— Crash course in async and await | The Old New Thing

Here are the three ways to call an async function:

async Task<T> SomethingAsync() { ... return t; }
async Task SomethingAsync() { ... }
async void SomethingAsync() { ... }

In all the cases, the function is transformed into a chain of tasks. The difference is what the function returns.

In the first case, the function returns a task that eventually produces the t.

In the second case, the function returns a task which has no product, but you can still await on it to know when it has run to completion.

The third case is the nasty one. The third case is like the second case, except that you don't even get the task back. You have no way of knowing when the function's task has completed.

The async void case is a "fire and forget": You start the task chain, but you don't care about when it's finished. When the function returns, all you know is that everything up to the first await has executed. Everything after the first await will run at some unspecified point in the future that you have no access to.

Inconsistent accessibility: property type is less accessible

Your Delivery class is internal (the default visibility for classes), however the property (and presumably the containing class) are public, so the property is more accessible than the Delivery class. You need to either make Delivery public, or restrict the visibility of the thelivery property.

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

Tomcat is not deploying my web project from Eclipse

look into org.eclipse.wst.common.component file in your web project in eclipse.

< wb-module deploy-name="PROJECT_NAME">

check the PROJECT_NAME. It might got messed up. Similarly look into .project file.

Hope this helps!!

CSS body background image fixed to full screen even when zooming in/out

You can do quite a lot with plain css...the css property background-size can be set to a number of things as well as just cover as Ranjith pointed out.

The background-size: cover setting scales the image to cover the entire screen but may mean that some of the image is off screen if the aspect ratio of the screen and image are different.

A good alternative is background-size: contain which resizes the background image to fit the smaller of width and height, ensuring that the whole image is visible but may lead to letterboxing if the aspect ratios are different.

For example:

body {
      background: url(/images/bkgd.png) no-repeat rgb(30,30,30) fixed center center;
      background-size: contain;
     }

The other options that I find less useful are: background-size: length <widthpx> <heightpx> which sets the absolute size of the background image. background-size: percentage <width> <height> background image is a percentage of the window size. (see w3schools.com's page)

What's NSLocalizedString equivalent in Swift?

Localization with default language:

extension String {
func localized() -> String {
       let defaultLanguage = "en"
       let path = Bundle.main.path(forResource: defaultLanguage, ofType: "lproj")
       let bundle = Bundle(path: path!)

       return NSLocalizedString(self, tableName: nil, bundle: bundle!, value: "", comment: "")
    }
}

Position an element relative to its container

You have to explicitly set the position of the parent container along with the position of the child container. The typical way to do that is something like this:

div.parent{
    position: relative;
    left: 0px;  /* stick it wherever it was positioned by default */
    top: 0px;
}

div.child{
    position: absolute;
    left: 10px;
    top: 10px;
}

Android appcompat v7:23

Latest published version of the Support Library is 24.1.1, So you can use it like this,

compile 'com.android.support:appcompat-v7:24.1.1'
compile 'com.android.support:design:24.1.1'

Same as for other support components.

You can see the revisions here,
https://developer.android.com/topic/libraries/support-library/revisions.html

Angular HttpPromise: difference between `success`/`error` methods and `then`'s arguments

Official Notice: success and error have been deprecated, please use the standard then method instead.

Deprecation Notice: The $http legacy promise methods success and error have been deprecated. Use the standard then method instead. If $httpProvider.useLegacyPromiseExtensions is set to false then these methods will throw $http/legacy error.

link: https://code.angularjs.org/1.5.7/docs/api/ng/service/$http

screenshot: view the screenshot

How to Save Console.WriteLine Output to Text File

Based in the answer by WhoIsNinja:

This code will output both into the Console and into a Log string that can be saved into a file, either by appending lines to it or by overwriting it.

The default name for the log file is 'Log.txt' and is saved under the Application path.

public static class Logger
{
    public static StringBuilder LogString = new StringBuilder();
    public static void WriteLine(string str)
    {
        Console.WriteLine(str);
        LogString.Append(str).Append(Environment.NewLine);
    }
    public static void Write(string str)
    {
        Console.Write(str);
        LogString.Append(str);

    }
    public static void SaveLog(bool Append = false, string Path = "./Log.txt")
    {
        if (LogString != null && LogString.Length > 0)
        {
            if (Append)
            {
                using (StreamWriter file = System.IO.File.AppendText(Path))
                {
                    file.Write(LogString.ToString());
                    file.Close();
                    file.Dispose();
                }
            }
            else
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(Path))
                {
                    file.Write(LogString.ToString());
                    file.Close();
                    file.Dispose();
                }
            }               
        }
    }
}

Then you can use it like this:

Logger.WriteLine("==========================================================");
Logger.Write("Loading 'AttendPunch'".PadRight(35, '.'));
Logger.WriteLine("OK.");

Logger.SaveLog(true); //<- default 'false', 'true' Append the log to an existing file.

Force the origin to start at 0

In the latest version of ggplot2, this can be more easy.

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))

enter image description here

See ?expansion() for more details.

Compare two List<T> objects for equality, ignoring order

As written, this question is ambigous. The statement:

... they both have the same elements, regardless of their position within the list. Each MyType object may appear multiple times on a list.

does not indicate whether you want to ensure that the two lists have the same set of objects or the same distinct set.

If you want to ensure to collections have exactly the same set of members regardless of order, you can use:

// lists should have same count of items, and set difference must be empty
var areEquivalent = (list1.Count == list2.Count) && !list1.Except(list2).Any();

If you want to ensure two collections have the same distinct set of members (where duplicates in either are ignored), you can use:

// check that [(A-B) Union (B-A)] is empty
var areEquivalent = !list1.Except(list2).Union( list2.Except(list1) ).Any();

Using the set operations (Intersect, Union, Except) is more efficient than using methods like Contains. In my opinion, it also better expresses the expectations of your query.

EDIT: Now that you've clarified your question, I can say that you want to use the first form - since duplicates matter. Here's a simple example to demonstrate that you get the result you want:

var a = new[] {1, 2, 3, 4, 4, 3, 1, 1, 2};
var b = new[] { 4, 3, 2, 3, 1, 1, 1, 4, 2 };

// result below should be true, since the two sets are equivalent...
var areEquivalent = (a.Count() == b.Count()) && !a.Except(b).Any(); 

No Multiline Lambda in Python: Why not?

Let me present to you a glorious but terrifying hack:

import types

def _obj():
  return lambda: None

def LET(bindings, body, env=None):
  '''Introduce local bindings.
  ex: LET(('a', 1,
           'b', 2),
          lambda o: [o.a, o.b])
  gives: [1, 2]

  Bindings down the chain can depend on
  the ones above them through a lambda.
  ex: LET(('a', 1,
           'b', lambda o: o.a + 1),
          lambda o: o.b)
  gives: 2
  '''
  if len(bindings) == 0:
    return body(env)

  env = env or _obj()
  k, v = bindings[:2]
  if isinstance(v, types.FunctionType):
    v = v(env)

  setattr(env, k, v)
  return LET(bindings[2:], body, env)

You can now use this LET form as such:

map(lambda x: LET(('y', x + 1,
                   'z', x - 1),
                  lambda o: o.y * o.z),
    [1, 2, 3])

which gives: [0, 3, 8]

How to convert Integer to int?

Since you say you're using Java 5, you can use setInt with an Integer due to autounboxing: pstmt.setInt(1, tempID) should work just fine. In earlier versions of Java, you would have had to call .intValue() yourself.

The opposite works as well... assigning an int to an Integer will automatically cause the int to be autoboxed using Integer.valueOf(int).

Recommended method for escaping HTML in Java

For some purposes, HtmlUtils:

import org.springframework.web.util.HtmlUtils;
[...]
HtmlUtils.htmlEscapeDecimal("&"); //gives &#38;
HtmlUtils.htmlEscape("&"); //gives &amp;

PHP remove commas from numeric strings

Not tested, but probably something like if(preg_match("/^[0-9,]+$/", $a)) $a = str_replace(...)


Do it the other way around:

$a = "1,435";
$b = str_replace( ',', '', $a );

if( is_numeric( $b ) ) {
    $a = $b;
}

The easiest would be:

$var = intval(preg_replace('/[^\d.]/', '', $var));

or if you need float:

$var = floatval(preg_replace('/[^\d.]/', '', $var));

Return multiple values from a function in swift

Swift 3

func getTime() -> (hour: Int, minute: Int,second: Int) {
        let hour = 1
        let minute = 20
        let second = 55
        return (hour, minute, second)
    }

To use :

let(hour, min,sec) = self.getTime()
print(hour,min,sec)

Android list view inside a scroll view

You should never use a ScrollView with a ListView, because ListView takes care of its own vertical scrolling. Most importantly, doing this defeats all of the important optimizations in ListView for dealing with large lists, since it effectively forces the ListView to display its entire list of items to fill up the infinite container supplied by ScrollView.

http://developer.android.com/reference/android/widget/ScrollView.html

How do you do exponentiation in C?

Similar to an earlier answer, this will handle positive and negative integer powers of a double nicely.

double intpow(double a, int b)
{
  double r = 1.0;
  if (b < 0)
  {
    a = 1.0 / a;
    b = -b;
  }
  while (b)
  {
    if (b & 1)
      r *= a;
    a *= a;
    b >>= 1;
  }
  return r;
}

How to prevent background scrolling when Bootstrap 3 modal open on mobile browsers?

Try this,

 body.modal-open {
    overflow: hidden;
    position:fixed;
    width: 100%;
}

Swap two variables without using a temporary variable

Yes, use this code:

stopAngle = Convert.ToDecimal(159.9);
startAngle = Convert.ToDecimal(355.87);

The problem is harder for arbitrary values. :-)

How to get a list of sub-folders and their files, ordered by folder-names

Command to put list of all files and folders into a text file is as below:

Eg: dir /b /s | sort > ListOfFilesFolders.txt

Print raw string from variable? (not getting the answers)

You can't turn an existing string "raw". The r prefix on literals is understood by the parser; it tells it to ignore escape sequences in the string. However, once a string literal has been parsed, there's no difference between a raw string and a "regular" one. If you have a string that contains a newline, for instance, there's no way to tell at runtime whether that newline came from the escape sequence \n, from a literal newline in a triple-quoted string (perhaps even a raw one!), from calling chr(10), by reading it from a file, or whatever else you might be able to come up with. The actual string object constructed from any of those methods looks the same.

Why are Python lambdas useful?

A lambda is part of a very important abstraction mechanism which deals with higher order functions. To get proper understanding of its value, please watch high quality lessons from Abelson and Sussman, and read the book SICP

These are relevant issues in modern software business, and becoming ever more popular.

Restoring Nuget References?

I have to agree with @Juri that the vastly popular answer by jmfenoll is not complete. In the case of broken references, I submit that most of the time you do not want to update to the latest package, but only fix your references to the current versions that you happen to be using. And Juri provided a handy function Sync-References to do just that.

But we can go just a bit further, allowing the flexibility to filter by project as well as package:

function Sync-References([string]$PackageId, [string]$ProjectName) {
    get-project -all | 
    Where-Object { $_.name -match $ProjectName } |
    ForEach-Object {
        $proj = $_ ;
        Write-Output ('Project: ' + $proj.name)
        Get-Package -project $proj.name |
        Where-Object { $_.id -match $PackageId } |
        ForEach-Object { 
            Write-Output ('Package: ' + $_.id)
            uninstall-package -projectname $proj.name -id $_.id -version $_.version -RemoveDependencies -force
            install-package -projectname $proj.name -id $_.id -version $_.version
        }
    }
}

Chrome blocks different origin requests

Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.

How can I close a browser window without receiving the "Do you want to close this window" prompt?

For security reasons, a window can only be closed in JavaScript if it was opened by JavaScript. In order to close the window, you must open a new window with _self as the target, which will overwrite your current window, and then close that one (which you can do since it was opened via JavaScript).

window.open('', '_self', '');
window.close();

How to replace all double quotes to single quotes using jquery?

You can also use replaceAll(search, replaceWith) [MDN].

Then, make sure you have a string by wrapping one type of quotes by a different type:

 'a "b" c'.replaceAll('"', "'")
 // result: "a 'b' c"
    
 'a "b" c'.replaceAll(`"`, `'`)
 // result: "a 'b' c"

 // Using RegEx. You MUST use a global RegEx(Meaning it'll match all occurrences).
 'a "b" c'.replaceAll(/\"/g, "'")
 // result: "a 'b' c"

Important(!) if you choose regex:

when using a regexp you have to set the global ("g") flag; otherwise, it will throw a TypeError: "replaceAll must be called with a global RegExp".

What's the difference between JavaScript and Java?

Take a look at the Wikipedia link

JavaScript, despite the name, is essentially unrelated to the Java programming language, although both have the common C syntax, and JavaScript copies many Java names and naming conventions. The language was originally named "LiveScript" but was renamed in a co-marketing deal between Netscape and Sun, in exchange for Netscape bundling Sun's Java runtime with their then-dominant browser. The key design principles within JavaScript are inherited from the Self and Scheme programming languages.

How to use BufferedReader in Java

Try this to read a file:

BufferedReader reader = null;

try {
    File file = new File("sample-file.dat");
    reader = new BufferedReader(new FileReader(file));

    String line;
    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }

} catch (IOException e) {
    e.printStackTrace();
} finally {
    try {
        reader.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Android background music service

@Synxmax's answer is correct when using a Service and the MediaPlayer class, however you also need to declare the Service in the Manifest for this to work, like so:

<service
    android:enabled="true"
    android:name="com.package.name.BackgroundSoundService" />

Switch php versions on commandline ubuntu 16.04

From PHP 5.6 => PHP 7.1

$ sudo a2dismod php5.6
$ sudo a2enmod php7.1

for old linux versions

 $ sudo service apache2 restart

for more recent version

$ systemctl restart apache2

How to trigger a build only if changes happen on particular set of files

The Git plugin has an option (excluded region) to use regexes to determine whether to skip building based on whether files in the commit match the excluded region regex.

Unfortunately, the stock Git plugin does not have a "included region" feature at this time (1.15). However, someone posted patches on GitHub that work on Jenkins and Hudson that implement the feature you want.

It is a little work to build, but it works as advertised and has been extremely useful since one of my Git trees has multiple independent projects.

https://github.com/jenkinsci/git-plugin/pull/49

Update: The Git plugin (1.16) now has the 'included' region feature.

Python class returning value

Use __new__ to return value from a class.

As others suggest __repr__,__str__ or even __init__ (somehow) CAN give you what you want, But __new__ will be a semantically better solution for your purpose since you want the actual object to be returned and not just the string representation of it.

Read this answer for more insights into __str__ and __repr__ https://stackoverflow.com/a/19331543/4985585

class MyClass():
    def __new__(cls):
        return list() #or anything you want

>>> MyClass()
[]   #Returns a true list not a repr or string

Chart.js v2 - hiding grid lines

The code below removes remove grid lines from chart area only not the ones in x&y axis labels

Chart.defaults.scale.gridLines.drawOnChartArea = false;

How to handle authentication popup with Selenium WebDriver using Java

I faced this issue a number of times in my application.

We can generally handle this with the below 2 approaches.

  1. Pass the username and password in url itself

  2. You can create an AutoIT Script and call script before opening the url.

Please check the below article in which I have mentioned both ways:
Handle Authentication/Login window in Selenium Webdriver

How do I select a random value from an enumeration?

Array values = Enum.GetValues(typeof(Bar));
Random random = new Random();
Bar randomBar = (Bar)values.GetValue(random.Next(values.Length));

Changing WPF title bar background color

In WPF the titlebar is part of the non-client area, which can't be modified through the WPF window class. You need to manipulate the Win32 handles (if I remember correctly).
This article could be helpful for you: Custom Window Chrome in WPF.

How to play ringtone/alarm sound in Android

For the future googlers: use RingtoneManager.getActualDefaultRingtoneUri() instead of RingtoneManager.getDefaultUri(). According to its name, it would return the actual uri, so you can freely use it. From documentation of getActualDefaultRingtoneUri():

Gets the current default sound's Uri. This will give the actual sound Uri, instead of using this, most clients can use DEFAULT_RINGTONE_URI.

Meanwhile getDefaultUri() says this:

Returns the Uri for the default ringtone of a particular type. Rather than returning the actual ringtone's sound Uri, this will return the symbolic Uri which will resolved to the actual sound when played.

How to convert string to string[]?

To convert a string with comma separated values to a string array use Split:

string strOne = "One,Two,Three,Four";
string[] strArrayOne = new string[] {""};
//somewhere in your code
strArrayOne = strOne.Split(',');

Result will be a string array with four strings:

{"One","Two","Three","Four"}

How to select a radio button by default?

This doesn't exactly answer the question but for anyone using AngularJS trying to achieve this, the answer is slightly different. And actually the normal answer won't work (at least it didn't for me).

Your html will look pretty similar to the normal radio button:

<input type='radio' name='group' ng-model='mValue' value='first' />First
<input type='radio' name='group' ng-model='mValue' value='second' /> Second

In your controller you'll have declared the mValue that is associated with the radio buttons. To have one of these radio buttons preselected, assign the $scope variable associated with the group to the desired input's value:

$scope.mValue="second"

This makes the "second" radio button selected on loading the page.

EDIT: Since AngularJS 2.x

The above approach does not work if you're using version 2.x and above. Instead use ng-checked attribute as follows:

<input type='radio' name='gender' ng-model='genderValue' value='male' ng-checked='genderValue === male'/>Male
<input type='radio' name='gender' ng-model='genderValue' value='female' ng-checked='genderValue === female'/> Female

How to take character input in java

Here is the sample program.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadFromConsole {

  public static void main(String[] args) {

    System.out.println("Enter here : ");

    try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));

        String value = bufferRead.readLine();

        System.out.println(value);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }
  }
}

You can get it easily when you search in Internet. StackExchange recommends to do some research and put some effort before reaching it.

Append value to empty vector in R?

Just for the sake of completeness, appending values to a vector in a for loop is not really the philosophy in R. R works better by operating on vectors as a whole, as @BrodieG pointed out. See if your code can't be rewritten as:

ouput <- sapply(values, function(v) return(2*v))

Output will be a vector of return values. You can also use lapply if values is a list instead of a vector.

How to get the indexpath.row when an element is activated?

USING A SINGLE TAG FOR ROWS AND SECTIONS

There is a simple way to use tags for transmitting the row/item AND the section of a TableView/CollectionView at the same time.

Encode the IndexPath for your UIView.tag in cellForRowAtIndexPath :

buttonForCell.tag = convertIndexPathToTag(with: indexPath)

Decode the IndexPath from your sender in your target selector:

    @IBAction func touchUpInsideButton(sender: UIButton, forEvent event: UIEvent) {

        var indexPathForButton = convertTagToIndexPath(from: sender)

    }

Encoder and Decoder:

func convertIndexPathToTag(indexPath: IndexPath) -> Int {
    var tag: Int = indexPath.row + (1_000_000 * indexPath.section)
    
    return tag
}

func convertTagToIndexPath(from sender: UIButton) -> IndexPath {
    var section: Int = Int((Float(sender.tag) / 1_000_000).rounded(.down))
    var row: Int = sender.tag - (1_000_000 * section)

    return IndexPath(row: row, section: section)
}

Provided that you don’t need more than 4294967296 rows/items on a 32bit device ;-) e.g.

  • 42949 sections with 100_000 items/rows
  • 4294 sections with 1_000_000 items/rows - (like in the example above)
  • 429 sections with 10_000_000 items/rows

—-

WARNING: Keep in mind that when deleting or inserting rows/items in your TableView/CollectionView you have to reload all rows/items after your insertion/deletion point in order to keep the tag numbers of your buttons in sync with your model.

—-

Add all files to a commit except a single file?

We can add all the files and exclude the file which has to be removed by git reset.

git add .
git reset -- <file_name_to_exclude>

How to redirect to Login page when Session is expired in Java web application?

When the use logs in, put its username in the session:

`session.setAttribute("USER", username);`

At the beginning of each page you can do this:

<%
String username = (String)session.getAttribute("USER");
if(username==null) 
// if session is expired, forward it to login page
%>
<jsp:forward page="Login.jsp" />
<% { } %>

How to get Domain name from URL using jquery..?

You can do this with plain js by using

  1. location.host , same as document.location.hostname
  2. document.domain Not recommended

Unable to launch the IIS Express Web server

I read all the answers herein and then, as mentioned in Mihail Shishkov answer, jumped to Project Properties > Web > Servers > Create Virtual Directory. This had the effect of getting me by the exception:

Unable to launch the IIS Express Web server. The start URL specified is not valid. http://localhost:44300/

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

Look for GSpread.NET. You can work with Google Spreadsheets by using API from Microsoft Excel. You don't need to rewrite old code with the new Google API usage. Just add a few row:

Set objExcel = CreateObject("GSpreadCOM.Application");

app.MailLogon(Name, ClientIdAndSecret, ScriptId);

It's an OpenSource project and it doesn't require Office to be installed.

The documentation available over here http://scand.com/products/gspread/index.html

Django CSRF Cookie Not Set

Problem seems that you are not handling GET requests appropriately or directly posting the data without first getting the form.

When you first access the page, client will send GET request, in that case you should send html with appropriate form.

Later, user fills up the form and sends POST request with form data.

Your view should be:

def deposit(request,account_num):
   if request.method == 'POST':
      form_=AccountForm(request.POST or None, instance=account)
      if form.is_valid(): 
          #handle form data
          return HttpResponseRedirect("/history/" + account_num + "/")
      else:
         #handle when form not valid
    else:
       #handle when request is GET (or not POST)
       form_=AccountForm(instance=account)

    return render_to_response('history.html',
                          {'account_form': form},
                          context_instance=RequestContext(request))

How to truncate text in Angular2?

Like this:

{{ data.title | slice:0:20 }}

And if you want the ellipsis, here's a workaround

{{ data.title | slice:0:20 }}...

How to get the client IP address in PHP

The following is the most advanced method I have found, and I have already tried some others in the past. It is valid to ensure to get the IP address of a visitor (but please note that any hacker could falsify the IP address easily).

function get_ip_address() {

    // Check for shared Internet/ISP IP
    if (!empty($_SERVER['HTTP_CLIENT_IP']) && validate_ip($_SERVER['HTTP_CLIENT_IP'])) {
        return $_SERVER['HTTP_CLIENT_IP'];
    }

    // Check for IP addresses passing through proxies
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {

        // Check if multiple IP addresses exist in var
        if (strpos($_SERVER['HTTP_X_FORWARDED_FOR'], ',') !== false) {
            $iplist = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
            foreach ($iplist as $ip) {
                if (validate_ip($ip))
                    return $ip;
            }
        }
        else {
            if (validate_ip($_SERVER['HTTP_X_FORWARDED_FOR']))
                return $_SERVER['HTTP_X_FORWARDED_FOR'];
        }
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED']) && validate_ip($_SERVER['HTTP_X_FORWARDED']))
        return $_SERVER['HTTP_X_FORWARDED'];
    if (!empty($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']) && validate_ip($_SERVER['HTTP_X_CLUSTER_CLIENT_IP']))
        return $_SERVER['HTTP_X_CLUSTER_CLIENT_IP'];
    if (!empty($_SERVER['HTTP_FORWARDED_FOR']) && validate_ip($_SERVER['HTTP_FORWARDED_FOR']))
        return $_SERVER['HTTP_FORWARDED_FOR'];
    if (!empty($_SERVER['HTTP_FORWARDED']) && validate_ip($_SERVER['HTTP_FORWARDED']))
        return $_SERVER['HTTP_FORWARDED'];

    // Return unreliable IP address since all else failed
    return $_SERVER['REMOTE_ADDR'];
}

/**
 * Ensures an IP address is both a valid IP address and does not fall within
 * a private network range.
 */
function validate_ip($ip) {

    if (strtolower($ip) === 'unknown')
        return false;

    // Generate IPv4 network address
    $ip = ip2long($ip);

    // If the IP address is set and not equivalent to 255.255.255.255
    if ($ip !== false && $ip !== -1) {
        // Make sure to get unsigned long representation of IP address
        // due to discrepancies between 32 and 64 bit OSes and
        // signed numbers (ints default to signed in PHP)
        $ip = sprintf('%u', $ip);

        // Do private network range checking
        if ($ip >= 0 && $ip <= 50331647)
            return false;
        if ($ip >= 167772160 && $ip <= 184549375)
            return false;
        if ($ip >= 2130706432 && $ip <= 2147483647)
            return false;
        if ($ip >= 2851995648 && $ip <= 2852061183)
            return false;
        if ($ip >= 2886729728 && $ip <= 2887778303)
            return false;
        if ($ip >= 3221225984 && $ip <= 3221226239)
            return false;
        if ($ip >= 3232235520 && $ip <= 3232301055)
            return false;
        if ($ip >= 4294967040)
            return false;
    }
    return true;
}

How to find all the tables in MySQL with specific column names in them?

To get all tables with columns columnA or ColumnB in the database YourDatabase:

SELECT DISTINCT TABLE_NAME 
    FROM INFORMATION_SCHEMA.COLUMNS
    WHERE COLUMN_NAME IN ('columnA','ColumnB')
        AND TABLE_SCHEMA='YourDatabase';

AngularJS- Login and Authentication in each route and controller

app.js

'use strict';
// Declare app level module which depends on filters, and services
var app= angular.module('myApp', ['ngRoute','angularUtils.directives.dirPagination','ngLoadingSpinner']);
app.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/login', {templateUrl: 'partials/login.html', controller: 'loginCtrl'});
  $routeProvider.when('/home', {templateUrl: 'partials/home.html', controller: 'homeCtrl'});
  $routeProvider.when('/salesnew', {templateUrl: 'partials/salesnew.html', controller: 'salesnewCtrl'});
  $routeProvider.when('/salesview', {templateUrl: 'partials/salesview.html', controller: 'salesviewCtrl'});
  $routeProvider.when('/users', {templateUrl: 'partials/users.html', controller: 'usersCtrl'});
    $routeProvider.when('/forgot', {templateUrl: 'partials/forgot.html', controller: 'forgotCtrl'});


  $routeProvider.otherwise({redirectTo: '/login'});


}]);


app.run(function($rootScope, $location, loginService){
    var routespermission=['/home'];  //route that require login
    var salesnew=['/salesnew'];
    var salesview=['/salesview'];
    var users=['/users'];
    $rootScope.$on('$routeChangeStart', function(){
        if( routespermission.indexOf($location.path()) !=-1
        || salesview.indexOf($location.path()) !=-1
        || salesnew.indexOf($location.path()) !=-1
        || users.indexOf($location.path()) !=-1)
        {
            var connected=loginService.islogged();
            connected.then(function(msg){
                if(!msg.data)
                {
                    $location.path('/login');
                }

            });
        }
    });
});

loginServices.js

'use strict';
app.factory('loginService',function($http, $location, sessionService){
    return{
        login:function(data,scope){
            var $promise=$http.post('data/user.php',data); //send data to user.php
            $promise.then(function(msg){
                var uid=msg.data;
                if(uid){
                    scope.msgtxt='Correct information';
                    sessionService.set('uid',uid);
                    $location.path('/home');
                }          
                else  {
                    scope.msgtxt='incorrect information';
                    $location.path('/login');
                }                  
            });
        },
        logout:function(){
            sessionService.destroy('uid');
            $location.path('/login');
        },
        islogged:function(){
            var $checkSessionServer=$http.post('data/check_session.php');
            return $checkSessionServer;
            /*
            if(sessionService.get('user')) return true;
            else return false;
            */
        }
    }

});

sessionServices.js

'use strict';

app.factory('sessionService', ['$http', function($http){
    return{
        set:function(key,value){
            return sessionStorage.setItem(key,value);
        },
        get:function(key){
            return sessionStorage.getItem(key);
        },
        destroy:function(key){
            $http.post('data/destroy_session.php');
            return sessionStorage.removeItem(key);
        }
    };
}])

loginCtrl.js

'use strict';

app.controller('loginCtrl', ['$scope','loginService', function ($scope,loginService) {
    $scope.msgtxt='';
    $scope.login=function(data){
        loginService.login(data,$scope); //call login service
    };

}]);

Reading InputStream as UTF-8

String file = "";

try {

    InputStream is = new FileInputStream(filename);
    String UTF8 = "utf8";
    int BUFFER_SIZE = 8192;

    BufferedReader br = new BufferedReader(new InputStreamReader(is,
            UTF8), BUFFER_SIZE);
    String str;
    while ((str = br.readLine()) != null) {
        file += str;
    }
} catch (Exception e) {

}

Try this,.. :-)

How to assign pointer address manually in C programming language?

Your code would be like this:

int *p = (int *)0x28ff44;

int needs to be the type of the object that you are referencing or it can be void.

But be careful so that you don't try to access something that doesn't belong to your program.

How would I run an async Task<T> method synchronously?

It's much simpler to run the task on the thread pool, rather than trying to trick the scheduler to run it synchronously. That way you can be sure that it won't deadlock. Performance is affected because of the context switch.

Task<MyResult> DoSomethingAsync() { ... }

// Starts the asynchronous task on a thread-pool thread.
// Returns a proxy to the original task.
Task<MyResult> task = Task.Run(() => DoSomethingAsync());

// Will block until the task is completed...
MyResult result = task.Result; 

Define make variable at rule execution time

Another possibility is to use separate lines to set up Make variables when a rule fires.

For example, here is a makefile with two rules. If a rule fires, it creates a temp dir and sets TMP to the temp dir name.

PHONY = ruleA ruleB display

all: ruleA

ruleA: TMP = $(shell mktemp -d testruleA_XXXX)
ruleA: display

ruleB: TMP = $(shell mktemp -d testruleB_XXXX)
ruleB: display

display:
    echo ${TMP}

Running the code produces the expected result:

$ ls
Makefile
$ make ruleB
echo testruleB_Y4Ow
testruleB_Y4Ow
$ ls
Makefile  testruleB_Y4Ow

How to get previous month and year relative to today, using strtotime and date?

date("m-Y", strtotime("-1 months")); 

would solve this

How can I position my jQuery dialog to center?

I had a problem with this and I finally figured this out. Until today I was using a really old version of jQuery, version 1.8.2.

Everywhere where I had used dialog I had initialised it with the following position option:

$.dialog({
    position: "center"
});

However, I found that removing position: "center" or replacing it with the correct syntax didn't do the trick, for example:

$.dialog({
    position: {
       my: "center",
       at: "center",
       of: window
    }
});

Although the above is correct, I was also using option to set the position as center when I loaded the page, in the old way, like so:

// The wrong old way of keeping a dialog centered
passwordDialogInstance.dialog("option", "position", "center");

This was causing all of my dialog windows to stick to the top left of the view port.

I had to replace all instances of this with the correct new syntax below:

passwordDialogInstance.dialog(
    "option",
    "position", 
    { my: "center", at: "center", of: window }
);

Loop Through Each HTML Table Column and Get the Data using jQuery

Using a nested .each() means that your inner loop is doing one td at a time, so you can't set the productId and product and quantity all in the inner loop.

Also using function(key, val) and then val[key].innerHTML isn't right: the .each() method passes the index (an integer) and the actual element, so you'd use function(i, element) and then element.innerHTML. Though jQuery also sets this to the element, so you can just say this.innerHTML.

Anyway, here's a way to get it to work:

    table.find('tr').each(function (i, el) {
        var $tds = $(this).find('td'),
            productId = $tds.eq(0).text(),
            product = $tds.eq(1).text(),
            Quantity = $tds.eq(2).text();
        // do something with productId, product, Quantity
    });

Demo: http://jsfiddle.net/bqX7Q/

How do I vertical center text next to an image in html/css?

Since most of the answers to this question are between 2009 and 2014 (except for a comment in 2018), there should be an update to this.

I found a solution to the wrap-text problem brought up by Spongman on Jun 11 '14 at 23:20. He has an example here: jsfiddle.net/vPpD4

If you add the following in the CSS under the div tag in the jsfiddle.net/vPpD4 example, you get the desired wrap-text effect that I think Spongman was asking about. I don't know how far back this is applicable, but this works in all of the current (as of Dec 2020/Jan 2021) browsers available for Windows computers. Note: I have not tested this on the Apple Safari browser. I have also not tested this on any mobile devices.

    div img { 
        float: left;
    }
    .clearfix::after {
        content: ""; 
        clear: both;
        display: table;
    }

I also added a border around the image, just so that the reader will understand where the edge of the image is and why the text wraps as it does. The resulting example looks is here: http://jsfiddle.net/tqg7hLzk/

How can I copy a file on Unix using C?

There is no baked-in equivalent CopyFile function in the APIs. But sendfile can be used to copy a file in kernel mode which is a faster and better solution (for numerous reasons) than opening a file, looping over it to read into a buffer, and writing the output to another file.

Update:

As of Linux kernel version 2.6.33, the limitation requiring the output of sendfile to be a socket was lifted and the original code would work on both Linux and — however, as of OS X 10.9 Mavericks, sendfile on OS X now requires the output to be a socket and the code won't work!

The following code snippet should work on the most OS X (as of 10.5), (Free)BSD, and Linux (as of 2.6.33). The implementation is "zero-copy" for all platforms, meaning all of it is done in kernelspace and there is no copying of buffers or data in and out of userspace. Pretty much the best performance you can get.

#include <fcntl.h>
#include <unistd.h>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <copyfile.h>
#else
#include <sys/sendfile.h>
#endif

int OSCopyFile(const char* source, const char* destination)
{    
    int input, output;    
    if ((input = open(source, O_RDONLY)) == -1)
    {
        return -1;
    }    
    if ((output = creat(destination, 0660)) == -1)
    {
        close(input);
        return -1;
    }

    //Here we use kernel-space copying for performance reasons
#if defined(__APPLE__) || defined(__FreeBSD__)
    //fcopyfile works on FreeBSD and OS X 10.5+ 
    int result = fcopyfile(input, output, 0, COPYFILE_ALL);
#else
    //sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
    off_t bytesCopied = 0;
    struct stat fileinfo = {0};
    fstat(input, &fileinfo);
    int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
#endif

    close(input);
    close(output);

    return result;
}

EDIT: Replaced the opening of the destination with the call to creat() as we want the flag O_TRUNC to be specified. See comment below.

Should I mix AngularJS with a PHP framework?

It seems you may be more comfortable with developing in PHP you let this hold you back from utilizing the full potential with web applications.

It is indeed possible to have PHP render partials and whole views, but I would not recommend it.

To fully utilize the possibilities of HTML and javascript to make a web application, that is, a web page that acts more like an application and relies heavily on client side rendering, you should consider letting the client maintain all responsibility of managing state and presentation. This will be easier to maintain, and will be more user friendly.

I would recommend you to get more comfortable thinking in a more API centric approach. Rather than having PHP output a pre-rendered view, and use angular for mere DOM manipulation, you should consider having the PHP backend output the data that should be acted upon RESTFully, and have Angular present it.

Using PHP to render the view:

/user/account

if($loggedIn)
{
    echo "<p>Logged in as ".$user."</p>";
}
else
{
    echo "Please log in.";
}

How the same problem can be solved with an API centric approach by outputting JSON like this:

api/auth/

{
  authorized:true,
  user: {
      username: 'Joe', 
      securityToken: 'secret'
  }
}

and in Angular you could do a get, and handle the response client side.

$http.post("http://example.com/api/auth", {})
.success(function(data) {
    $scope.isLoggedIn = data.authorized;
});

To blend both client side and server side the way you proposed may be fit for smaller projects where maintainance is not important and you are the single author, but I lean more towards the API centric way as this will be more correct separation of conserns and will be easier to maintain.

How do I use PHP to get the current year?

My super lazy version of showing a copyright line, that automatically stays updated:

&copy; <?php 
$copyYear = 2008; 
$curYear = date('Y'); 
echo $copyYear . (($copyYear != $curYear) ? '-' . $curYear : '');
?> Me, Inc.

This year (2008), it will say:

© 2008 Me, Inc.

Next year, it will say:

© 2008-2009 Me, Inc.

and forever stay updated with the current year.


Or (PHP 5.3.0+) a compact way to do it using an anonymous function so you don't have variables leaking out and don't repeat code/constants:

&copy; 
<?php call_user_func(function($y){$c=date('Y');echo $y.(($y!=$c)?'-'.$c:'');}, 2008); ?> 
Me, Inc.

List comprehension with if statement

This is not a lambda function. It is a list comprehension.

Just change the order:

[ y for y in a if y not in b]

How to build query string with Javascript

I know this is very late answer but works very well...

var obj = {
a:"a",
b:"b"
}

Object.entries(obj).map(([key, val])=>`${key}=${val}`).join("&");

note: object.entries will return key,values pairs

output from above line will be a=a&b=b

Hope its helps someone.

Happy Coding...

Simple If/Else Razor Syntax

Just use this for the closing tag:

  @:</tr>

And leave your if/else as is.

Seems like the if statement doesn't wanna' work.

It works fine. You're working in 2 language-spaces here, it seems only proper not to split open/close sandwiches over the border.

Connecting to Oracle Database through C#?

Using Nuget

  1. Right click Project, select Manage NuGet packages...
  2. Select the Browse tab, search for Oracle and install Oracle.ManagedDataAccess

Oracle NuGet package

  1. In code use the following command (Ctrl+. to automatically add the using directive).

  2. Note the different DataSource string which in comparison to Java is different.

    // create connection
    OracleConnection con = new OracleConnection();
    
    // create connection string using builder
    OracleConnectionStringBuilder ocsb = new OracleConnectionStringBuilder();
    ocsb.Password = "autumn117";
    ocsb.UserID = "john";
    ocsb.DataSource = "database.url:port/databasename";
    
    // connect
    con.ConnectionString = ocsb.ConnectionString;
    con.Open();
    Console.WriteLine("Connection established (" + con.ServerVersion + ")");
    

PHP: Call to undefined function: simplexml_load_string()

If the XML module is not installed, install it.

Current version 5.6 on ubuntu 14.04:

sudo apt-get install php5.6-xml

And don't forget to run sudo service apache2 restart command after it

Zulhilmi Zainudi

How can I schedule a daily backup with SQL Server Express?

We have used the combination of:

  1. Cobian Backup for scheduling/maintenance

  2. ExpressMaint for backup

Both of these are free. The process is to script ExpressMaint to take a backup as a Cobian "before Backup" event. I usually let this overwrite the previous backup file. Cobian then takes a zip/7zip out of this and archives these to the backup folder. In Cobian you can specify the number of full copies to keep, make multiple backup cycles etc.

ExpressMaint command syntax example:

expressmaint -S HOST\SQLEXPRESS -D ALL_USER -T DB -R logpath -RU WEEKS -RV 1 -B backuppath -BU HOURS -BV 3 

how to remove json object key and value.?

There are several ways to do this, lets see them one by one:

  1. delete method: The most common way

_x000D_
_x000D_
const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
};_x000D_
_x000D_
delete myObject['currentIndustry'];_x000D_
// OR delete myObject.currentIndustry;_x000D_
  _x000D_
console.log(myObject);
_x000D_
_x000D_
_x000D_

  1. By making key value undefined: Alternate & a faster way:

_x000D_
_x000D_
let myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
  };_x000D_
_x000D_
myObject.currentIndustry = undefined;_x000D_
myObject = JSON.parse(JSON.stringify(myObject));_x000D_
_x000D_
console.log(myObject);
_x000D_
_x000D_
_x000D_

  1. With es6 spread Operator:

_x000D_
_x000D_
const myObject = {_x000D_
    "employeeid": "160915848",_x000D_
    "firstName": "tet",_x000D_
    "lastName": "test",_x000D_
    "email": "[email protected]",_x000D_
    "country": "Brasil",_x000D_
    "currentIndustry": "aaaaaaaaaaaaa",_x000D_
    "otherIndustry": "aaaaaaaaaaaaa",_x000D_
    "currentOrganization": "test",_x000D_
    "salary": "1234567"_x000D_
};_x000D_
_x000D_
_x000D_
const {currentIndustry, ...filteredObject} = myObject;_x000D_
console.log(filteredObject);
_x000D_
_x000D_
_x000D_

Or if you can use omit() of underscore js library:

const filteredObject = _.omit(currentIndustry, 'myObject');
console.log(filteredObject);

When to use what??

If you don't wanna create a new filtered object, simply go for either option 1 or 2. Make sure you define your object with let while going with the second option as we are overriding the values. Or else you can use any of them.

hope this helps :)

HTML Code for text checkbox '?'

This is the code for the character you posted in your question: &#xf0fe;

But that's not a checkbox character...

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

For MacOS this worked for me without the need to hardcode a particular Java version:

launchctl setenv JAVA_HOME "$(jenv javahome)"

Disabling same-origin policy in Safari

Most of these answers are old. The latest Safari 14.0.2 (in 2021), has the option to Disable Cross-Origin Restrictions, however, it doesn't work if the paths have ../../ kind of path names; even though Safari correctly resolves to a local file path, it still doesn't permit loading the file, even though it exists. This is a recent bug in Safari 14 that didn't happen in 13.

Decimal to Hexadecimal Converter in Java

One possible solution:

import java.lang.StringBuilder;

class Test {
  private static final int sizeOfIntInHalfBytes = 8;
  private static final int numberOfBitsInAHalfByte = 4;
  private static final int halfByte = 0x0F;
  private static final char[] hexDigits = { 
    '0', '1', '2', '3', '4', '5', '6', '7', 
    '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
  };

  public static String decToHex(int dec) {
    StringBuilder hexBuilder = new StringBuilder(sizeOfIntInHalfBytes);
    hexBuilder.setLength(sizeOfIntInHalfBytes);
    for (int i = sizeOfIntInHalfBytes - 1; i >= 0; --i)
    {
      int j = dec & halfByte;
      hexBuilder.setCharAt(i, hexDigits[j]);
      dec >>= numberOfBitsInAHalfByte;
    }
    return hexBuilder.toString(); 
  }

  public static void main(String[] args) {
     int dec = 305445566;
     String hex = decToHex(dec);
     System.out.println(hex);       
  }
}

Output:

1234BABE

Anyway, there is a library method for this:

String hex = Integer.toHexString(dec);

Error Dropping Database (Can't rmdir '.test\', errno: 17)

I my case the problem was a residual dump file in the database directory. That file was probably generated during a backup script test I had been working on. Once I manually deleted the file I could then drop the database.

Oracle: is there a tool to trace queries, like Profiler for sql server?

The Catch is Capture all SQL run between two points in time. Like the way SQL Server also does.

There are situations where it is useful to capture the SQL that a particular user is running in the database. Usually you would simply enable session tracing for that user, but there are two potential problems with that approach.

  1. The first is that many web based applications maintain a pool of persistent database connections which are shared amongst multiple users.
  2. The second is that some applications connect, run some SQL and disconnect very quickly, making it tricky to enable session tracing at all (you could of course use a logon trigger to enable session tracing in this case).

A quick and dirty solution to the problem is to capture all SQL statements that are run between two points in time.

The following procedure will create two tables, each containing a snapshot of the database at a particular point. The tables will then be queried to produce a list of all SQL run during that period.

If possible, you should do this on a quiet development system - otherwise you risk getting way too much data back.

  1. Take the first snapshot Run the following sql to create the first snapshot:

    create table sql_exec_before as
    select executions,hash_value
    from v$sqlarea
    /
    
  2. Get the user to perform their task within the application.

  3. Take the second snapshot.

    create table sql_exec_after as
    select executions, hash_value
    from v$sqlarea
    /
    
  4. Check the results Now that you have captured the SQL it is time to query the results.

This first query will list all query hashes that have been executed:

select  aft.hash_value
from sql_exec_after aft
left outer join sql_exec_before bef
  on aft.hash_value  =  bef.hash_value 
where aft.executions > bef.executions
   or bef.executions is null;
/

This one will display the hash and the SQL itself: set pages 999 lines 100 break on hash_value

select  hash_value, sql_text
from    v$sqltext
where   hash_value in (
    select  aft.hash_value
    from sql_exec_after aft
    left outer join sql_exec_before bef
      on aft.hash_value  =  bef.hash_value
    where aft.executions > bef.executions
       or bef.executions is null;
)
order by
    hash_value, piece
/

5. Tidy up Don't forget to remove the snapshot tables once you've finished:

drop table sql_exec_before
/

drop table sql_exec_after
/

Easiest way to develop simple GUI in Python

I would recommend wxpython. It's very easy to use and the documentation is pretty good.