Programs & Examples On #Edititemtemplate

Gridview row editing - dynamic binding to a DropDownList

protected void grvSecondaryLocations_RowEditing(object sender, GridViewEditEventArgs e)  
{  
    grvSecondaryLocations.EditIndex = e.NewEditIndex;  

    DropDownList ddlPbx = (DropDownList)(grvSecondaryLocations.Rows[grvSecondaryLocations.EditIndex].FindControl("ddlPBXTypeNS"));
    if (ddlPbx != null)  
    {  
        ddlPbx.DataSource = _pbxTypes;  
        ddlPbx.DataBind();  
    }  

    .... (more stuff)  
}

How are POST and GET variables handled in Python?

suppose you're posting a html form with this:

<input type="text" name="username">

If using raw cgi:

import cgi
form = cgi.FieldStorage()
print form["username"]

If using Django, Pylons, Flask or Pyramid:

print request.GET['username'] # for GET form method
print request.POST['username'] # for POST form method

Using Turbogears, Cherrypy:

from cherrypy import request
print request.params['username']

Web.py:

form = web.input()
print form.username

Werkzeug:

print request.form['username']

If using Cherrypy or Turbogears, you can also define your handler function taking a parameter directly:

def index(self, username):
    print username

Google App Engine:

class SomeHandler(webapp2.RequestHandler):
    def post(self):
        name = self.request.get('username') # this will get the value from the field named username
        self.response.write(name) # this will write on the document

So you really will have to choose one of those frameworks.

How do I plot list of tuples in Python?

As others have answered, scatter() or plot() will generate the plot you want. I suggest two refinements to answers that are already here:

  1. Use numpy to create the x-coordinate list and y-coordinate list. Working with large data sets is faster in numpy than using the iteration in Python suggested in other answers.

  2. Use pyplot to apply the logarithmic scale rather than operating directly on the data, unless you actually want to have the logs.

    import matplotlib.pyplot as plt
    import numpy as np
    
    data = [(2, 10), (3, 100), (4, 1000), (5, 100000)]
    data_in_array = np.array(data)
    '''
    That looks like array([[     2,     10],
                           [     3,    100],
                           [     4,   1000],
                           [     5, 100000]])
    '''
    
    transposed = data_in_array.T
    '''
    That looks like array([[     2,      3,      4,      5],
                           [    10,    100,   1000, 100000]])
    '''    
    
    x, y = transposed 
    
    # Here is the OO method
    # You could also the state-based methods of pyplot
    fig, ax = plt.subplots(1,1) # gets a handle for the AxesSubplot object
    ax.plot(x, y, 'ro')
    ax.plot(x, y, 'b-')
    ax.set_yscale('log')
    fig.show()
    

result

I've also used ax.set_xlim(1, 6) and ax.set_ylim(.1, 1e6) to make it pretty.

I've used the object-oriented interface to matplotlib. Because it offers greater flexibility and explicit clarity by using names of the objects created, the OO interface is preferred over the interactive state-based interface.

Wrap text in <td> tag

table-layout:fixed will resolve the expanding cell problem, but will create a new one. IE by default will hide the overflow but Mozilla will render it outside the box.

Another solution would be to use: overflow:hidden;width:?px

<table style="table-layout:fixed; width:100px">
 <tr>
   <td style="overflow:hidden; width:50px;">fearofthedarkihaveaconstantfearofadark</td>
   <td>
     test
   </td>
 </tr>
</table>

A tool to convert MATLAB code to Python

There's also oct2py which can call .m files within python

https://pypi.python.org/pypi/oct2py

It requires GNU Octave, which is highly compatible with MATLAB.

https://www.gnu.org/software/octave/

Git with SSH on Windows

I've found my ssh.exe in "C:/Program Files/Git/usr/bin" directory

Detect when an HTML5 video finishes

Here is a full example, I hope it helps =).

<!DOCTYPE html> 
<html> 
<body> 

<video id="myVideo" controls="controls">
  <source src="your_video_file.mp4" type="video/mp4">
  <source src="your_video_file.mp4" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<script type='text/javascript'>
    document.getElementById('myVideo').addEventListener('ended',myHandler,false);
    function myHandler(e) {
        if(!e) { e = window.event; }
        alert("Video Finished");
    }
</script>
</body> 
</html>

Test if something is not undefined in JavaScript

It'll be because response[0] itself is undefined.

How can I check if given int exists in array?

int index = std::distance(std::begin(myArray), std::find(begin(myArray), end(std::myArray), VALUE));

Returns an invalid index (length of the array) if not found.

How to Load an Assembly to AppDomain with all references recursively?

I have had to do this several times and have researched many different solutions.

The solution I find in most elegant and easy to accomplish can be implemented as such.

1. Create a project that you can create a simple interface

the interface will contain signatures of any members you wish to call.

public interface IExampleProxy
{
    string HelloWorld( string name );
}

Its important to keep this project clean and lite. It is a project that both AppDomain's can reference and will allow us to not reference the Assembly we wish to load in seprate domain from our client assembly.

2. Now create project that has the code you want to load in seperate AppDomain.

This project as with the client proj will reference the proxy proj and you will implement the interface.

public interface Example : MarshalByRefObject, IExampleProxy
{
    public string HelloWorld( string name )
    {
        return $"Hello '{ name }'";
    }
}

3. Next, in the client project, load code in another AppDomain.

So, now we create a new AppDomain. Can specify the base location for assembly references. Probing will check for dependent assemblies in GAC and in current directory and the AppDomain base loc.

// set up domain and create
AppDomainSetup domaininfo = new AppDomainSetup
{
    ApplicationBase = System.Environment.CurrentDirectory
};

Evidence adevidence = AppDomain.CurrentDomain.Evidence;

AppDomain exampleDomain = AppDomain.CreateDomain("Example", adevidence, domaininfo);

// assembly ant data names
var assemblyName = "<AssemblyName>, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null|<keyIfSigned>";
var exampleTypeName = "Example";

// Optional - get a reflection only assembly type reference
var @type = Assembly.ReflectionOnlyLoad( assemblyName ).GetType( exampleTypeName ); 

// create a instance of the `Example` and assign to proxy type variable
IExampleProxy proxy= ( IExampleProxy )exampleDomain.CreateInstanceAndUnwrap( assemblyName, exampleTypeName );

// Optional - if you got a type ref
IExampleProxy proxy= ( IExampleProxy )exampleDomain.CreateInstanceAndUnwrap( @type.Assembly.Name, @type.Name );    

// call any members you wish
var stringFromOtherAd = proxy.HelloWorld( "Tommy" );

// unload the `AppDomain`
AppDomain.Unload( exampleDomain );

if you need to, there are a ton of different ways to load an assembly. You can use a different way with this solution. If you have the assembly qualified name then I like to use the CreateInstanceAndUnwrap since it loads the assembly bytes and then instantiates your type for you and returns an object that you can simple cast to your proxy type or if you not that into strongly-typed code you could use the dynamic language runtime and assign the returned object to a dynamic typed variable then just call members on that directly.

There you have it.

This allows to load an assembly that your client proj doesnt have reference to in a seperate AppDomain and call members on it from client.

To test, I like to use the Modules window in Visual Studio. It will show you your client assembly domain and what all modules are loaded in that domain as well your new app domain and what assemblies or modules are loaded in that domain.

The key is to either make sure you code either derives MarshalByRefObject or is serializable.

`MarshalByRefObject will allow you to configure the lifetime of the domain its in. Example, say you want the domain to destroy if the proxy hasnt been called in 20 minutes.

I hope this helps.

How to convert unsigned long to string

The standard approach is to use sprintf(buffer, "%lu", value); to write a string rep of value to buffer. However, overflow is a potential problem, as sprintf will happily (and unknowingly) write over the end of your buffer.

This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.

This site discusses this and related problems at some length.

Some libraries offer snprintf as an alternative which lets you specify a maximum buffer size.

Install shows error in console: INSTALL FAILED CONFLICTING PROVIDER

If you are using the emulator, you may try the following. The below worked for me. Go to Tools --> AVD Manager --> (Pick Your emulator) --> Wipe Data. The error went away.

How to find event listeners on a DOM node when debugging or from the JavaScript code?

(Rewriting the answer from this question since it's relevant here.)

When debugging, if you just want to see the events, I recommend either...

  1. Visual Event
  2. The Elements section of Chrome's Developer Tools: select an element and look for "Event Listeners" on the bottom right (similar in Firefox)

If you want to use the events in your code, and you are using jQuery before version 1.8, you can use:

$(selector).data("events")

to get the events. As of version 1.8, using .data("events") is discontinued (see this bug ticket). You can use:

$._data(element, "events")

Another example: Write all click events on a certain link to the console:

var $myLink = $('a.myClass');
console.log($._data($myLink[0], "events").click);

(see http://jsfiddle.net/HmsQC/ for a working example)

Unfortunately, using $._data this is not recommended except for debugging since it is an internal jQuery structure, and could change in future releases. Unfortunately I know of no other easy means of accessing the events.

how to permit an array with strong parameters

If you want to permit an array of hashes(or an array of objects from the perspective of JSON)

params.permit(:foo, array: [:key1, :key2])

2 points to notice here:

  1. array should be the last argument of the permit method.
  2. you should specify keys of the hash in the array, otherwise you will get an error Unpermitted parameter: array, which is very difficult to debug in this case.

Disable Required validation attribute under certain circumstances

Yes it is possible to disable Required Attribute. Create your own custom class attribute (sample code called ChangeableRequired) to extent from RequiredAtribute and add a Disabled Property and override the IsValid method to check if it is disbaled. Use reflection to set the disabled poperty, like so:

Custom Attribute:

namespace System.ComponentModel.DataAnnotations
{
    public class ChangeableRequired : RequiredAttribute
    {
       public bool Disabled { get; set; }

       public override bool IsValid(object value)
       {
          if (Disabled)
          {
            return true;
          }

          return base.IsValid(value);
       }
    }
}

Update you property to use your new custom Attribute:

 class Forex
 {
 ....
    [ChangeableRequired]
    public decimal? ExchangeRate {get;set;}
 ....
 }

where you need to disable the property use reflection to set it:

Forex forex = new Forex();
// Get Property Descriptor from instance with the Property name
PropertyDescriptor descriptor = TypeDescriptor.GetProperties(forex.GetType())["ExchangeRate"];
//Search for Attribute
ChangeableRequired attrib =  (ChangeableRequired)descriptor.Attributes[typeof(ChangeableRequired)];

// Set Attribute to true to Disable
attrib.Disabled = true;

This feels nice and clean?

NB: The validation above will be disabled while your object instance is alive\active...

System.IO.IOException: file used by another process

The code works as best I can tell. I would fire up Sysinternals process explorer and find out what is holding the file open. It might very well be Visual Studio.

If else in stored procedure sql server

You do not have to have the RETURN stament.

Have anther look at Using a Stored Procedure with Output Parameters

Also have another look at the OUT section in CREATE PROCEDURE

Optional query string parameters in ASP.NET Web API

Use initial default values for all parameters like below

public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null) 
{
    // ...
}

How to remove all numbers from string?

Use Predefined Character Ranges

echo $words= preg_replace('/[[:digit:]]/','', $words);

global variable for all controller and views

View::share('site_settings', $site_settings);

Add to

app->Providers->AppServiceProvider file boot method

it's global variable.

PHP - iterate on string characters

Step 1: convert the string to an array using the str_split function

$array = str_split($your_string);

Step 2: loop through the newly created array

foreach ($array as $char) {
 echo $char;
}

You can check the PHP docs for more information: str_split

Making a triangle shape using xml definitions?

 <layer-list xmlns:android="http://schemas.android.com/apk/res/android">
        <item>
            <rotate
                android:fromDegrees="45"
                android:pivotX="135%"
                android:pivotY="1%"
                android:toDegrees="45">
                <shape android:shape="rectangle">
                    <stroke
                        android:width="-60dp"
                        android:color="@android:color/transparent" />
                    <solid android:color="@color/orange" />
                </shape>
            </rotate>
        </item>
    </layer-list>

Best practices for adding .gitignore file for Python projects?

Covers most of the general stuff -

# Byte-compiled / optimized / DLL files
__pycache__/
*.py[cod]
*$py.class

# C extensions
*.so

# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST

# PyInstaller
#  Usually these files are written by a python script from a template
#  before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec

# Installer logs
pip-log.txt
pip-delete-this-directory.txt

# Unit test / coverage reports
htmlcov/
.tox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
.hypothesis/
.pytest_cache/

# Translations
*.mo
*.pot

# Django stuff:
*.log
local_settings.py
db.sqlite3

# Flask stuff:
instance/
.webassets-cache

# Scrapy stuff:
.scrapy

# Sphinx documentation
docs/_build/

# PyBuilder
target/

# Jupyter Notebook
.ipynb_checkpoints

# pyenv
.python-version

# celery beat schedule file
celerybeat-schedule

# SageMath parsed files
*.sage.py

# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/

# Spyder project settings
.spyderproject
.spyproject

# Rope project settings
.ropeproject

# mkdocs documentation
/site

# mypy
.mypy_cache/

Reference: python .gitignore

Java 11 package javax.xml.bind does not exist

According to the release-notes, Java 11 removed the Java EE modules:

java.xml.bind (JAXB) - REMOVED
  • Java 8 - OK
  • Java 9 - DEPRECATED
  • Java 10 - DEPRECATED
  • Java 11 - REMOVED

See JEP 320 for more info.

You can fix the issue by using alternate versions of the Java EE technologies. Simply add Maven dependencies that contain the classes you need:

<dependency>
  <groupId>javax.xml.bind</groupId>
  <artifactId>jaxb-api</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-core</artifactId>
  <version>2.3.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.0</version>
</dependency>

Jakarta EE 8 update (Mar 2020)

Instead of using old JAXB modules you can fix the issue by using Jakarta XML Binding from Jakarta EE 8:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>2.3.3</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>2.3.3</version>
  <scope>runtime</scope>
</dependency>

Jakarta EE 9 update (Nov 2020)

Use latest release of Eclipse Implementation of JAXB 3.0.0:

<dependency>
  <groupId>jakarta.xml.bind</groupId>
  <artifactId>jakarta.xml.bind-api</artifactId>
  <version>3.0.0</version>
</dependency>
<dependency>
  <groupId>com.sun.xml.bind</groupId>
  <artifactId>jaxb-impl</artifactId>
  <version>3.0.0</version>
  <scope>runtime</scope>
</dependency>

Note: Jakarta EE 9 adopts new API package namespace jakarta.xml.bind.*, so update import statements:

javax.xml.bind -> jakarta.xml.bind

Call an activity method from a fragment

Here is how I did this:

first make interface

interface NavigationInterface {
    fun closeActivity()
}

next make sure activity implements interface and overrides interface method(s)

class NotesActivity : AppCompatActivity(), NavigationInterface {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_notes)
        setSupportActionBar(findViewById(R.id.toolbar))
    }

    override fun closeActivity() {
        this.finish()
    }
}

then make sure to create interface listener in fragment

private lateinit var navigationInterface: NavigationInterface

override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
): View? {
    //establish interface communication
    activity?.let {
        instantiateNavigationInterface(it)
    }
    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_notes_info, container, false)
}

private fun instantiateNavigationInterface(context: FragmentActivity) {
    navigationInterface = context as NavigationInterface
}

then you can make calls like such:

view.findViewById<Button>(R.id.button_second).setOnClickListener {
    navigationInterface.closeActivity()
}

Get DataKey values in GridView RowCommand

you can just do this:

string id = GridName.DataKeys[Convert.ToInt32(e.CommandArgument)].Value.ToString();

Find the last element of an array while using a foreach loop in PHP

If I understand you, then all you need is to reverse the array and get the last element by a pop command:

   $rev_array = array_reverse($array);

   echo array_pop($rev_array);

How can I combine two commits into one commit?

You want to git rebase -i to perform an interactive rebase.

If you're currently on your "commit 1", and the commit you want to merge, "commit 2", is the previous commit, you can run git rebase -i HEAD~2, which will spawn an editor listing all the commits the rebase will traverse. You should see two lines starting with "pick". To proceed with squashing, change the first word of the second line from "pick" to "squash". Then save your file, and quit. Git will squash your first commit into your second last commit.

Note that this process rewrites the history of your branch. If you are pushing your code somewhere, you'll have to git push -f and anybody sharing your code will have to jump through some hoops to pull your changes.

Note that if the two commits in question aren't the last two commits on the branch, the process will be slightly different.

How to use _CRT_SECURE_NO_WARNINGS

Adding _CRT_SECURE_NO_WARNINGS to Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions didn't work for me, don't know why.

The following hint works: In stdafx.h file, please add

#define _CRT_SECURE_NO_DEPRECATE

before include other header files.

How to pass a value from Vue data to href?

If you want to display links coming from your state or store in Vue 2.0, you can do like this:

<a v-bind:href="''"> {{ url_link }} </a>

Modifying a query string without reloading the page

If you are looking for Hash modification, your solution works ok. However, if you want to change the query, you can use the pushState, as you said. Here it is an example that might help you to implement it properly. I tested and it worked fine:

if (history.pushState) {
    var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
    window.history.pushState({path:newurl},'',newurl);
}

It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values. And of course that it requires modern browsers that can process HTML5 History API.

For more information:

http://diveintohtml5.info/history.html

https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history

Only allow Numbers in input Tag without Javascript

Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.

So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title attribute).

There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.

On the other hand, in HTML 5 you have two options:

  • input of type number:

    <input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
    

    – only validates the range – if user enters a non-number, an empty value is submitted
    – the field visual is enhanced with increment / decrement controls (browser dependent)

  • the pattern attribute:

    <input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
    <input type="text" pattern="\d{3}" title="Format: 3 digits" />
    

    – this gives you a full contorl over the format (anything you can specify by regular expression)
    – no visual difference / enhancement

But here you still rely on browser capabilities, so do a server-side validation in either case.

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

In swift 4 & Xcode 9.2 , you can detect if a device is iPhone/iPad by below ways.

if (UIDevice.current.userInterfaceIdiom == .pad){
   print("iPad")
}
else{
   print("iPhone")
}

Another Way

    let deviceName = UIDevice.current.model
    print(deviceName);
    if deviceName == "iPhone"{
        print("iPhone")
    }
    else{
        print("iPad")
    }

Using array map to filter results with if conditional

Here's some info if someone comes upon this in 2019.

I think reduce vs map + filter might be somewhat dependent on what you need to loop through. Not sure on this but reduce does seem to be slower.

One thing is for sure - if you're looking for performance improvements the way you write the code is extremely important!

Here a JS perf test that shows the massive improvements when typing out the code fully rather than checking for "falsey" values (e.g. if (string) {...}) or returning "falsey" values where a boolean is expected.

Hope this helps someone

extract month from date in python

import datetime

a = '2010-01-31'

datee = datetime.datetime.strptime(a, "%Y-%m-%d")


datee.month
Out[9]: 1

datee.year
Out[10]: 2010

datee.day
Out[11]: 31

Reloading submodules in IPython

Any subobjects will not be reloaded by this, I believe you have to use IPython's deepreload for that.

How to read from standard input in the console?

You need to provide a pointer to the var you want to scan, like so:

fmt.scan(&text2)

SQL Server: Is it possible to insert into two tables at the same time?

-- ================================================
-- Template generated from Template Explorer using:
-- Create Procedure (New Menu).SQL
--
-- Use the Specify Values for Template Parameters 
-- command (Ctrl-Shift-M) to fill in the parameter 
-- values below.
--
-- This block of comments will not be included in
-- the definition of the procedure.
-- ================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE InsetIntoTwoTable

(
@name nvarchar(50),
@Email nvarchar(50)
)

AS
BEGIN

    SET NOCOUNT ON;


    insert into dbo.info(name) values (@name)
    insert into dbo.login(Email) values (@Email)
END
GO

Deleting specific rows from DataTable

I know this is, very, old question, and I have similar situation few days ago.

Problem was, in my table are approx. 10000 rows, so looping trough DataTable rows was very slow.

Finally, I found much faster solution, where I make copy of source DataTable with desired results, clear source DataTable and merge results from temporary DataTable into source one.

note : instead search for Joe in DataRow called name You have to search for all records whose not have name Joe (little opposite way of searching)

There is example (vb.net) :

'Copy all rows into tmpTable whose not contain Joe in name DataRow
Dim tmpTable As DataTable = drPerson.Select("name<>'Joe'").CopyToTable
'Clear source DataTable, in Your case dtPerson
dtPerson.Clear()
'merge tmpTable into dtPerson (rows whose name not contain Joe)
dtPerson.Merge(tmpTable)
tmpTable = Nothing

I hope so this shorter solution will help someone.

There is c# code (not sure is it correct because I used online converter :( ):

//Copy all rows into tmpTable whose not contain Joe in name DataRow
DataTable tmpTable = drPerson.Select("name<>'Joe'").CopyToTable;
//Clear source DataTable, in Your case dtPerson
dtPerson.Clear();
//merge tmpTable into dtPerson (rows whose name not contain Joe)
dtPerson.Merge(tmpTable);
tmpTable = null;

Of course, I used Try/Catch in case if there is no result (for example, if Your dtPerson don't contain name Joe it will throw exception), so You do nothing with Your table, it stays unchanged.

Default session timeout for Apache Tomcat applications

Open $CATALINA_BASE/conf/web.xml and find this

<!-- ==================== Default Session Configuration ================= -->
<!-- You can set the default session timeout (in minutes) for all newly   -->
<!-- created sessions by modifying the value below.                       -->

<session-config>
  <session-timeout>30</session-timeout>
</session-config>

all webapps implicitly inherit from this default web descriptor. You can override session-config as well as other settings defined there in your web.xml.

This is actually from my Tomcat 7 (Windows) but I think 5.5 conf is not very different

Moving from JDK 1.7 to JDK 1.8 on Ubuntu

This is what I do on debian - I suspect it should work on ubuntu (amend the version as required + adapt the folder where you want to copy the JDK files as you wish, I'm using /opt/jdk):

wget --header "Cookie: oraclelicense=accept-securebackup-cookie" http://download.oracle.com/otn-pub/java/jdk/8u71-b15/jdk-8u71-linux-x64.tar.gz
sudo mkdir /opt/jdk
sudo tar -zxf jdk-8u71-linux-x64.tar.gz -C /opt/jdk/
rm jdk-8u71-linux-x64.tar.gz

Then update-alternatives:

sudo update-alternatives --install /usr/bin/java java /opt/jdk/jdk1.8.0_71/bin/java 1
sudo update-alternatives --install /usr/bin/javac javac /opt/jdk/jdk1.8.0_71/bin/javac 1

Select the number corresponding to the /opt/jdk/jdk1.8.0_71/bin/java when running the following commands:

sudo update-alternatives --config java
sudo update-alternatives --config javac

Finally, verify that the correct version is selected:

java -version
javac -version

Axios having CORS issue

This work out for me :

in javascript :

Axios({
            method: 'post',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            url: 'https://localhost:44346/Order/Order/GiveOrder',
            data: order
          }).then(function (response) {
            console.log(response.data);
          });

and in the backend (.net core) : in startup:

 #region Allow-Orgin
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });
            #endregion

and in controller before action

[EnableCors("AllowOrigin")]

How to add two edit text fields in an alert dialog

I found another set of examples for customizing an AlertDialog from a guy named Mossila. I think they're better than Google's examples. To quickly see Google's API demos, you must import their demo jar(s) into your project, which you probably don't want.

But Mossila's example code is fully self-contained. It can be directly cut-and-pasted into your project. It just works! Then you only need to tweak it to your needs. See here

Converting date between DD/MM/YYYY and YYYY-MM-DD?

you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:

lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')

img tag displays wrong orientation

save as png solved the problem for me.

How can I convert JSON to CSV?

JSON can represent a wide variety of data structures -- a JS "object" is roughly like a Python dict (with string keys), a JS "array" roughly like a Python list, and you can nest them as long as the final "leaf" elements are numbers or strings.

CSV can essentially represent only a 2-D table -- optionally with a first row of "headers", i.e., "column names", which can make the table interpretable as a list of dicts, instead of the normal interpretation, a list of lists (again, "leaf" elements can be numbers or strings).

So, in the general case, you can't translate an arbitrary JSON structure to a CSV. In a few special cases you can (array of arrays with no further nesting; arrays of objects which all have exactly the same keys). Which special case, if any, applies to your problem? The details of the solution depend on which special case you do have. Given the astonishing fact that you don't even mention which one applies, I suspect you may not have considered the constraint, neither usable case in fact applies, and your problem is impossible to solve. But please do clarify!

How to Toggle a div's visibility by using a button click

with JQuery .toggle() you can accomplish it easily

$( ".target" ).toggle();

XML Schema (XSD) validation tool?

An XML editor for quick and easy XML validation is available at http://www.xml-buddy.com

You just need to run the installer and after that you can validate your XML files with an easy to use desktop application or the command-line. In addition you also get support for Schematron and RelaxNG. Batch validation is also supported...

Update 1/13/2012: The command line tool is free to use and uses Xerces as XML parser.

CSS3 Transition - Fade out effect

You can use transitions instead:

.successfully-saved.hide-opacity{
    opacity: 0;
}

.successfully-saved {
    color: #FFFFFF;
    text-align: center;

    -webkit-transition: opacity 3s ease-in-out;
    -moz-transition: opacity 3s ease-in-out;
    -ms-transition: opacity 3s ease-in-out;
    -o-transition: opacity 3s ease-in-out;
     opacity: 1;
}

Powershell import-module doesn't find modules

I experienced the same error and tried numerous things before I succeeded. The solution was to prepend the path of the script to the relative path of the module like this:

// Note that .Path will only be available during script-execution
$ScriptPath = Split-Path $MyInvocation.MyCommand.Path

Import-Module $ScriptPath\Modules\Builder.psm1

Btw you should take a look at http://msdn.microsoft.com/en-us/library/dd878284(v=vs.85).aspx which states:

Beginning in Windows PowerShell 3.0, modules are imported automatically when any cmdlet or function in the module is used in a command. This feature works on any module in a directory that this included in the value of the PSModulePath environment variable ($env:PSModulePath)

How can I add or update a query string parameter?

Use this function to add, remove and modify query string parameter from URL based on jquery

/**
@param String url
@param object param {key: value} query parameter
*/
function modifyURLQuery(url, param){
    var value = {};

    var query = String(url).split('?');

    if (query[1]) {
        var part = query[1].split('&');

        for (i = 0; i < part.length; i++) {
            var data = part[i].split('=');

            if (data[0] && data[1]) {
                value[data[0]] = data[1];
            }
        }
    }

    value = $.extend(value, param);

    // Remove empty value
    for (i in value){
        if(!value[i]){
            delete value[i];
        }
    }

    // Return url with modified parameter
    if(value){
        return query[0] + '?' + $.param(value);
    } else {
        return query[0];
    }
}

Add new and modify existing parameter to url

var new_url = modifyURLQuery("http://google.com?foo=34", {foo: 50, bar: 45});
// Result: http://google.com?foo=50&bar=45

Remove existing

var new_url = modifyURLQuery("http://google.com?foo=50&bar=45", {bar: null});
// Result: http://google.com?foo=50

Angular 6: saving data to local storage

you can use localStorage for storing the json data:

the example is given below:-

let JSONDatas = [
    {"id": "Open"},
    {"id": "OpenNew", "label": "Open New"},
    {"id": "ZoomIn", "label": "Zoom In"},
    {"id": "ZoomOut", "label": "Zoom Out"},
    {"id": "Find", "label": "Find..."},
    {"id": "FindAgain", "label": "Find Again"},
    {"id": "Copy"},
    {"id": "CopyAgain", "label": "Copy Again"},
    {"id": "CopySVG", "label": "Copy SVG"},
    {"id": "ViewSVG", "label": "View SVG"}
]

localStorage.setItem("datas", JSON.stringify(JSONDatas));

let data = JSON.parse(localStorage.getItem("datas"));

console.log(data);

How to Maximize window in chrome using webDriver (python)

Try this:

driver.manage().window().maximize();

how do I create an array in jquery?

Here is the clear working example:

//creating new array
var custom_arr1 = [];


//storing value in array
custom_arr1.push("test");
custom_arr1.push("test1");

alert(custom_arr1);
//output will be  test,test1

How to add new DataRow into DataTable?

//?Creating a new row with the structure of the table:

DataTable table = new DataTable();
DataRow row = table.NewRow();
table.Rows.Add(row);

//Giving values to the columns of the row(this row is supposed to have 28 columns):

for (int i = 0; i < 28; i++)
{
    row[i] = i.ToString();
}

How do I set a conditional breakpoint in gdb, when char* x points to a string whose value equals "hello"?

break x if ((int)strcmp(y, "hello")) == 0

On some implementations gdb might not know the return type of strcmp. That means you would have to cast, otherwise it would always evaluate to true!

Get current URL from IFRAME

If you are in the iframe context,

you could do

const currentIframeHref = new URL(document.location.href);
const urlOrigin = currentIframeHref.origin;
const urlFilePath = decodeURIComponent(currentIframeHref.pathname);

If you are in the parent window/frame, then you can use https://stackoverflow.com/a/938195/2305243 's answer, which is

document.getElementById("iframe_id").contentWindow.location.href

How do I get a YouTube video thumbnail from the YouTube API?

In YouTube Data API v3, you can get video's thumbnails with the videos->list function. From snippet.thumbnails.(key), you can pick the default, medium or high resolution thumbnail, and get its width, height and URL.

You can also update thumbnails with the thumbnails->set functionality.

For examples, you can check out the YouTube API Samples project. (PHP ones.)

How do you performance test JavaScript code?

We can always measure time taken by any function by simple date object.

var start = +new Date();  // log start timestamp
function1();
var end =  +new Date();  // log end timestamp
var diff = end - start;

How to build splash screen in windows forms application?

simple and easy solution to create splash screen

  1. open new form use name "SPLASH"
  2. change background image whatever you want
  3. select progress bar
  4. select timer

now set timer tick in timer:

private void timer1_Tick(object sender, EventArgs e)
{
    progressBar1.Increment(1);
    if (progressBar1.Value == 100) timer1.Stop();        
}

add new form use name "FORM-1"and use following command in FORM 1.

note: Splash form works before opening your form1

  1. add this library

    using System.Threading;
    
  2. create function

    public void splash()
    {     
        Application.Run(new splash());
    }
    
  3. use following command in initialization like below.

    public partial class login : Form
    {     
        public login()
        {
            Thread t = new Thread(new ThreadStart(splash));
            t.Start();
            Thread.Sleep(15625);
    
            InitializeComponent();
    
            enter code here
    
            t.Abort();
        }
    }
    

http://solutions.musanitech.com/c-create-splash-screen/

change html text from link with jquery

try this in javascript

 document.getElementById("22IdMObileFull").text ="itsClicked"

How can I disable notices and warnings in PHP within the .htaccess file?

Fortes is right, thank you.

When you have a shared hosting it is usual to obtain an 500 server error.

I have a website with Joomla and I added to the index.php:

ini_set('display_errors','off');

The error line showed in my website disappeared.

currently unable to handle this request HTTP ERROR 500

I found this was caused by adding a new scope variable to the login scope

Bootstrap 4 Change Hamburger Toggler Color

You can create the toggler button with css only in a very easy way, there is no need to use any fonts in SVG or ... foramt.

Your Button:

<button 
     class="navbar-toggler collapsed" 
    data-target="#navbarsExampleDefault" 
    data-toggle="collapse">
        <span class="line"></span> 
        <span class="line"></span> 
        <span class="line"></span>
</button>

Your Button Style:

.navbar-toggler{
width: 47px;
height: 34px;
background-color: #7eb444;

}

Your horizontal line Style:

.navbar-toggler .line{
width: 100%;
float: left;
height: 2px;
background-color: #fff;
margin-bottom: 5px;

}

Demo

_x000D_
_x000D_
.navbar-toggler{_x000D_
    width: 47px;_x000D_
    height: 34px;_x000D_
    background-color: #7eb444;_x000D_
    border:none;_x000D_
}_x000D_
.navbar-toggler .line{_x000D_
    width: 100%;_x000D_
    float: left;_x000D_
    height: 2px;_x000D_
    background-color: #fff;_x000D_
    margin-bottom: 5px;_x000D_
}
_x000D_
<button class="navbar-toggler" data-target="#navbarsExampleDefault" data-toggle="collapse" aria-expanded="true" >_x000D_
        <span class="line"></span> _x000D_
        <span class="line"></span> _x000D_
        <span class="line" style="margin-bottom: 0;"></span>_x000D_
</button>
_x000D_
_x000D_
_x000D_

Generate unique random numbers between 1 and 100

To avoid any long and unreliable shuffles, I'd do the following...

  1. Generate an array that contains the number between 1 and 100, in order.
  2. Generate a random number between 1 and 100
  3. Look up the number at this index in the array and store in your results
  4. Remove the elemnt from the array, making it one shorter
  5. Repeat from step 2, but use 99 as the upper limit of the random number
  6. Repeat from step 2, but use 98 as the upper limit of the random number
  7. Repeat from step 2, but use 97 as the upper limit of the random number
  8. Repeat from step 2, but use 96 as the upper limit of the random number
  9. Repeat from step 2, but use 95 as the upper limit of the random number
  10. Repeat from step 2, but use 94 as the upper limit of the random number
  11. Repeat from step 2, but use 93 as the upper limit of the random number

Voila - no repeated numbers.

I may post some actual code later, if anybody is interested.

Edit: It's probably the competitive streak in me but, having seen the post by @Alsciende, I couldn't resist posting the code that I promised.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<html>
<head>
<title>8 unique random number between 1 and 100</title>
<script type="text/javascript" language="Javascript">
    function pick(n, min, max){
        var values = [], i = max;
        while(i >= min) values.push(i--);
        var results = [];
        var maxIndex = max;
        for(i=1; i <= n; i++){
            maxIndex--;
            var index = Math.floor(maxIndex * Math.random());
            results.push(values[index]);
            values[index] = values[maxIndex];
        }
        return results;
    }
    function go(){
        var running = true;
        do{
            if(!confirm(pick(8, 1, 100).sort(function(a,b){return a - b;}))){
                running = false;
            }
        }while(running)
    }
</script>
</head>

<body>
    <h1>8 unique random number between 1 and 100</h1>
    <p><button onclick="go()">Click me</button> to start generating numbers.</p>
    <p>When the numbers appear, click OK to generate another set, or Cancel to stop.</p>
</body>

How do I install and use the ASP.NET AJAX Control Toolkit in my .NET 3.5 web applications?

It's really simple, just download the latest toolkit from Codeplex and add the extracted AjaxControlToolkit.dll to your toolbox in Visual Studio by right clicking the toolbox and selecting 'choose items'. You will then have the controls in your Visual STudio toolbox and using them is just a matter of dragging and dropping them onto your form, of course don't forget to add a asp:ScriptManager to every page that uses controls from the toolkit, or optionally include it in your master page only and your content pages will inherit the script manager.

Why can't Python find shared objects that are in directories in sys.path?

For me what works here is to using a version manager such as pyenv, which I strongly recommend to get your project environments and package versions well managed and separate from that of the operative system.

I had this same error after an OS update, but was easily fixed with pyenv install 3.7-dev (the version I use).

Link to reload current page

There is no global way of doing this unfortunately with only HTML. You can try doing <a href="">test</a> however it only works in some browsers.

How do I round to the nearest 0.5?

The Correct way to do this is:

  public static Decimal GetPrice(Decimal price)
            {
                var DecPrice = price / 50;
                var roundedPrice = Math.Round(DecPrice, MidpointRounding.AwayFromZero);
                var finalPrice = roundedPrice * 50;

                return finalPrice;

            }

Const in JavaScript: when to use it and is it necessary?

When it comes to the decision between let and const (both block scoped), always prefer const so that the usage is clear in the code. That way, if you try to redeclare the variable, you'll get an error. If there's no other choice but redeclare it, just switch for let. Note that, as Anthony says, the const values aren't immutable (for instances, a const object can have properties mutated).

When it comes to var, since ES6 is out, I never used it in production code and can't think of a use case for it. One point that might consider one to use it is JavaScript hosting - while let and const are not hoisted, var declaration is. Yet, beware that variables declared with var have a function scope, not a block scope («if declared outside any function, they will be globally available throughout the program; if declared within a function, they are only available within the function itself», in HackerRank - Variable Declaration Keywords). You can think of let as the block scoped version of var.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

This example:Views Collection, CommandText Property Example (VB) Shows how to use ADOX to maintain VIEWS by changing COMMAND related to VIEW. But instead using it like this:

 Set cmd = cat.Views("AllCustomers").Command  

' Update the CommandText of the command.  
cmd.CommandText = _  
"Select CustomerId, CompanyName, ContactName From Customers"  

just try to use this way:

Set CommandText = cat.Views("AllCustomers").Command.CommandText

What's the difference between git reset --mixed, --soft, and --hard?

--mixed vs --soft vs --hard:

--mixed:

   Delete changes from the local repository and staging area.

   It won't touch the working directory.

   Possible to revert back changes by using the following commands.

     - git add

     - git commit

   Working tree won't be clean.

--soft:

    Deleted changes only from the local repository.

    It won't touch the staging area and working directory.

    Possible to revert back changes by using the following command.

     - git commit.

    Working tree won't be clean

--hard:

    Deleted changes from everywhere.

    Not possible to revert changes.

    The working tree will be clean.

NOTE: If the commits are confirmed to the local repository and to discard those commits we can use:

 `git reset command`.

But if the commits are confirmed to the remote repository then not recommended to use the reset command and we have to use the revert command to discard the remote commits.

Parse Json string in C#

What you are trying to deserialize to a Dictionary is actually a Javascript object serialized to JSON. In Javascript, you can use this object as an associative array, but really it's an object, as far as the JSON standard is concerned.

So you would have no problem deserializing what you have with a standard JSON serializer (like the .net ones, DataContractJsonSerializer and JavascriptSerializer) to an object (with members called AppName, AnotherAppName, etc), but to actually interpret this as a dictionary you'll need a serializer that goes further than the Json spec, which doesn't have anything about Dictionaries as far as I know.

One such example is the one everybody uses: JSON .net

There is an other solution if you don't want to use an external lib, which is to convert your Javascript object to a list before serializing it to JSON.

var myList = [];
$.each(myObj, function(key, value) { myList.push({Key:key, Value:value}) });

now if you serialize myList to a JSON object, you should be capable of deserializing to a List<KeyValuePair<string, ValueDescription>> with any of the aforementioned serializers. That list would then be quite obvious to convert to a dictionary.

Note: ValueDescription being this class:

public class ValueDescription
{
    public string Description { get; set; }
    public string Value { get; set; }
}

Remove all special characters from a string in R?

Convert the Special characters to apostrophe,

Data  <- gsub("[^0-9A-Za-z///' ]","'" , Data ,ignore.case = TRUE)

Below code it to remove extra ''' apostrophe

Data <- gsub("''","" , Data ,ignore.case = TRUE)

Use gsub(..) function for replacing the special character with apostrophe

How to VueJS router-link active style

When you are creating the router, you can specify the linkExactActiveClass as a property to set the class that will be used for the active router link.

const routes = [
  { path: '/foo', component: Foo },
  { path: '/bar', component: Bar }
]

const router = new VueRouter({
  routes,
  linkActiveClass: "active", // active class for non-exact links.
  linkExactActiveClass: "active" // active class for *exact* links.
})

This is documented here.

How to set Linux environment variables with Ansible

I did not have enough reputation to comment and hence am adding a new answer.
Gasek answer is quite correct. Just one thing: if you are updating the .bash_profile file or the /etc/profile, those changes would be reflected only after you do a new login. In case you want to set the env variable and then use it in subsequent tasks in the same playbook, consider adding those environment variables in the .bashrc file.
I guess the reason behind this is the login and the non-login shells.
Ansible, while executing different tasks, reads the parameters from a .bashrc file instead of the .bash_profile or the /etc/profile.

As an example, if I updated my path variable to include the custom binary in the .bash_profile file of the respective user and then did a source of the file. The next subsequent tasks won't recognize my command. However if you update in the .bashrc file, the command would work.

 - name: Adding the path in the bashrc files
   lineinfile: dest=/root/.bashrc line='export PATH=$PATH:path-to-mysql/bin' insertafter='EOF' regexp='export PATH=\$PATH:path-to-mysql/bin' state=present
 
-  - name: Source the bashrc file
   shell: source /root/.bashrc

 - name: Start the mysql client
   shell: mysql -e "show databases";

This would work, but had I done it using profile files the mysql -e "show databases" would have given an error.

- name: Adding the path in the Profile files
   lineinfile: dest=/root/.bash_profile line='export PATH=$PATH:{{install_path}}/{{mysql_folder_name}}/bin' insertafter='EOF' regexp='export PATH=\$PATH:{{install_path}}/{{mysql_folder_name}}/bin' state=present

 - name: Source the bash_profile file
   shell: source /root/.bash_profile

 - name: Start the mysql client
   shell: mysql -e "show databases";

This one won't work, if we have all these tasks in the same playbook.

How to use hex color values

If you're wanting from hex string rather than hex value...

    let hex = "#FADE2B"  // yellow
    let color = NSColor(fromHex: hex)

Supported formats:

  • "#fff" // RGB
  • "#ffff" // RGBA
  • "#ffffff" // RRGGBB
  • "#ffffffff" // RRGGBBAA

with or without the # character


    extension NSColor {
        /// Initialises NSColor from a hexadecimal string. Color is clear if string is invalid.
        /// - Parameter fromHex: supported formats are "#RGB", "#RGBA", "#RRGGBB", "#RRGGBBAA", with or without the # character
        public convenience init(fromHex:String) {
            var r = 0, g = 0, b = 0, a = 0
            let offset = fromHex.hasPrefix("#") ? 1 : 0
            let ch = fromHex.map{$0}
            switch(ch.count - offset) {
            case 4:
                a = ch[offset+3].hexDigitValue ?? 0
                fallthrough
            case 3:
                r = ch[offset+0].hexDigitValue ?? 0
                g = ch[offset+1].hexDigitValue ?? 0
                b = ch[offset+2].hexDigitValue ?? 0
                break
            case 8:
                a = (ch[offset+6].hexDigitValue ?? 0) + 16 * (ch[offset+7].hexDigitValue ?? 0)
                fallthrough
            case 6:
                r = (ch[offset+0].hexDigitValue ?? 0) + 16 * (ch[offset+1].hexDigitValue ?? 0)
                g = (ch[offset+2].hexDigitValue ?? 0) + 16 * (ch[offset+3].hexDigitValue ?? 0)
                b = (ch[offset+4].hexDigitValue ?? 0) + 16 * (ch[offset+5].hexDigitValue ?? 0)
                break
            default:
                break
            }
            self.init(red: CGFloat(r)/255, green: CGFloat(g)/255, blue: CGFloat(b)/255, alpha: CGFloat(a)/255)
            
        }
    }
    // Author: Andrew Kingdom

License: CC BY

How to print Two-Dimensional Array like table

I'll post a solution with a bit more elaboration, in addition to code, as the initial mistake and the subsequent ones that have been demonstrated in comments are common errors in this sort of string concatenation problem.

From the initial question, as has been adequately explained by @djechlin, we see that there is the need to print a new line after each line of your table has been completed. So, we need this statement:

System.out.println();

However, printing that immediately after the first print statement gives erroneous results. What gives?

1 
2 
...
n 

This is a problem of scope. Notice that there are two loops for a reason -- one loop handles rows, while the other handles columns. Your inner loop, the "j" loop, iterates through each array element "j" for a given "i." Therefore, at the end of the j loop, you should have a single row. You can think of each iterate of this "j" loop as building the "columns" of your table. Since the inner loop builds our columns, we don't want to print our line there -- it would make a new line for each element!

Once you are out of the j loop, you need to terminate that row before moving on to the next "i" iterate. This is the correct place to handle a new line, because it is the "scope" of your table's rows, instead of your table's columns.

for(i=0;i<7;i++){
    for(j=0;j<5;j++) {
        System.out.print(twoDm[i][j]+" ");  
    }
    System.out.println();
}

And you can see that this new line will hold true, even if you change the dimensions of your table by changing the end values of your "i" and "j" loops.

How to kill a nodejs process in Linux?

You can use the killall command as follows:

killall node

jQuery selector for id starts with specific text

If all your divs start with editDialog as you stated, then you can use the following selector:

$("div[id^='editDialog']")

Or you could use a class selector instead if it's easier for you

<div id="editDialog-0" class="editDialog">...</div>

$(".editDialog")

Rails: Get Client IP address

request.remote_ip is an interpretation of all the available IP address information and it will make a best-guess. If you access the variables directly you assume responsibility for testing them in the correct precedence order. Proxies introduce a number of headers that create environment variables with different names.

Take n rows from a spark dataframe and pass to toPandas()

You can use the limit(n) function:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.limit(2).withColumn('age2', df.age + 2).toPandas()

Or:

l = [('Alice', 1),('Jim',2),('Sandra',3)]
df = sqlContext.createDataFrame(l, ['name', 'age'])
df.withColumn('age2', df.age + 2).limit(2).toPandas()

How to get the sign, mantissa and exponent of a floating point number

Cast a pointer to the floating point variable as something like an unsigned int. Then you can shift and mask the bits to get each component.

float foo;
unsigned int ival, mantissa, exponent, sign;

foo = -21.4f;
ival = *((unsigned int *)&foo);
mantissa = ( ival & 0x7FFFFF);
ival = ival >> 23;
exponent = ( ival  & 0xFF );
ival = ival >> 8;
sign = ( ival & 0x01 );

Obviously you probably wouldn't use unsigned ints for the exponent and sign bits but this should at least give you the idea.

Array initialization syntax when not in a declaration

For those of you, who doesn't like this monstrous new AClass[] { ... } syntax, here's some sugar:

public AClass[] c(AClass... arr) { return arr; }

Use this little function as you like:

AClass[] array;
...
array = c(object1, object2);

How to add files/folders to .gitignore in IntelliJ IDEA?

I'm using intelliJ 15 community edition and I'm able to right click a file and select 'add to .gitignore'

How to create a service running a .exe file on Windows 2012 Server?

You can just do that too, it seems to work well too. sc create "Servicename" binPath= "Path\To\your\App.exe" DisplayName= "My Custom Service"

You can open the registry and add a string named Description in your service's registry key to add a little more descriptive information about it. It will be shown in services.msc.

How do I create a list of random numbers without duplicates?

If you need to sample extremely large numbers, you cannot use range

random.sample(range(10000000000000000000000000000000), 10)

because it throws:

OverflowError: Python int too large to convert to C ssize_t

Also, if random.sample cannot produce the number of items you want due to the range being too small

 random.sample(range(2), 1000)

it throws:

 ValueError: Sample larger than population

This function resolves both problems:

import random

def random_sample(count, start, stop, step=1):
    def gen_random():
        while True:
            yield random.randrange(start, stop, step)

    def gen_n_unique(source, n):
        seen = set()
        seenadd = seen.add
        for i in (i for i in source() if i not in seen and not seenadd(i)):
            yield i
            if len(seen) == n:
                break

    return [i for i in gen_n_unique(gen_random,
                                    min(count, int(abs(stop - start) / abs(step))))]

Usage with extremely large numbers:

print('\n'.join(map(str, random_sample(10, 2, 10000000000000000000000000000000))))

Sample result:

7822019936001013053229712669368
6289033704329783896566642145909
2473484300603494430244265004275
5842266362922067540967510912174
6775107889200427514968714189847
9674137095837778645652621150351
9969632214348349234653730196586
1397846105816635294077965449171
3911263633583030536971422042360
9864578596169364050929858013943

Usage where the range is smaller than the number of requested items:

print(', '.join(map(str, random_sample(100000, 0, 3))))

Sample result:

2, 0, 1

It also works with with negative ranges and steps:

print(', '.join(map(str, random_sample(10, 10, -10, -2))))
print(', '.join(map(str, random_sample(10, 5, -5, -2))))

Sample results:

2, -8, 6, -2, -4, 0, 4, 10, -6, 8
-3, 1, 5, -1, 3

Exception of type 'System.OutOfMemoryException' was thrown.

I just restarted Visual Studio and did IISRESET which solved the problem.

img src SVG changing the styles with CSS

Simple..

You can use this code:

<svg class="logo">
  <use xlink:href="../../static/icons/logo.svg#Capa_1"></use>
</svg>

First specify the path of svg and then write it's ID, In this case "Capa_1". You can get the ID of svg by opening it in any editor.

In css:

.logo {
  fill: red;
}

How to force Docker for a clean build of an image

The command docker build --no-cache . solved our similar problem.

Our Dockerfile was:

RUN apt-get update
RUN apt-get -y install php5-fpm

But should have been:

RUN apt-get update && apt-get -y install php5-fpm

To prevent caching the update and install separately.

See: Best practices for writing Dockerfiles

How to use Collections.sort() in Java?

Use the method that accepts a Comparator when you want to sort in something other than natural order.

Collections.sort(List, Comparator)

Using fonts with Rails asset pipeline

In my case the original question was using asset-url without results instead of plain url css property. Using asset-url ended up working for me in Heroku. Plus setting the fonts in /assets/fonts folder and calling asset-url('font.eot') without adding any subfolder or any other configuration to it.

MySQL SELECT DISTINCT multiple columns

I know that the question is too old, anyway:

select a, b from mytable group by a, b

will give your all the combinations.

How to show imageView full screen on imageView click?

Use this property for an Image view such as,

1) android:scaleType="fitXY" - It means the Images will be stretched to fit all the sides of the parent that is based on your ImageView!

2) By using above property, it will affect your Image resolution so if you want to maintain the resolution then add a property such as android:scaleType="centerInside".

How to validate a url in Python? (Malformed or not)

Use the validators package:

>>> import validators
>>> validators.url("http://google.com")
True
>>> validators.url("http://google")
ValidationFailure(func=url, args={'value': 'http://google', 'require_tld': True})
>>> if not validators.url("http://google"):
...     print "not valid"
... 
not valid
>>>

Install it from PyPI with pip (pip install validators).

How to convert DateTime? to DateTime

You need to call the Value property of the nullable DateTime. This will return a DateTime.

Assuming that UpdatedDate is DateTime?, then this should work:

DateTime UpdatedTime = (DateTime)_objHotelPackageOrder.UpdatedDate == null ? DateTime.Now : _objHotelPackageOrder.UpdatedDate.Value;

To make the code a bit easier to read, you could use the HasValue property instead of the null check:

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate.HasValue
                          ? _objHotelPackageOrder.UpdatedDate.Value
                          : DateTime.Now;

This can be then made even more concise:

DateTime UpdatedTime = _objHotelPackageOrder.UpdatedDate ?? DateTime.Now;

Why SpringMVC Request method 'GET' not supported?

Change

@RequestMapping(value = "/test", method = RequestMethod.POST)

To

@RequestMapping(value = "/test", method = RequestMethod.GET)

Is there a numpy builtin to reject outliers from a list

Building on Benjamin's, using pandas.Series, and replacing MAD with IQR:

def reject_outliers(sr, iq_range=0.5):
    pcnt = (1 - iq_range) / 2
    qlow, median, qhigh = sr.dropna().quantile([pcnt, 0.50, 1-pcnt])
    iqr = qhigh - qlow
    return sr[ (sr - median).abs() <= iqr]

For instance, if you set iq_range=0.6, the percentiles of the interquartile-range would become: 0.20 <--> 0.80, so more outliers will be included.

Simple URL GET/POST function in Python

import urllib

def fetch_thing(url, params, method):
    params = urllib.urlencode(params)
    if method=='POST':
        f = urllib.urlopen(url, params)
    else:
        f = urllib.urlopen(url+'?'+params)
    return (f.read(), f.code)


content, response_code = fetch_thing(
                              'http://google.com/', 
                              {'spam': 1, 'eggs': 2, 'bacon': 0}, 
                              'GET'
                         )

[Update]

Some of these answers are old. Today I would use the requests module like the answer by robaple.

Call of overloaded function is ambiguous

replace p.setval(0); with the following.

const unsigned int param = 0;
p.setval(param);

That way it knows for sure which type the constant 0 is.

Module is not available, misspelled or forgot to load (but I didn't)

Using AngularJS 1.6.9+

There is one more incident, it also happen when you declare variable name different of module name.

var indexPageApp = angular.module('indexApp', []);

to get rid of this error,

Error: [$injector:nomod] Module 'indexPageApp' is not available! You either misspelled the module name or forgot to load it. If registering a module ensure that you specify the dependencies as the second argument.

change the module name similar to var declared name or vice versa -

var indexPageApp = angular.module('indexPageApp', []);

Django return redirect() with parameters

Firstly, your URL definition does not accept any parameters at all. If you want parameters to be passed from the URL into the view, you need to define them in the urlconf.

Secondly, it's not at all clear what you are expecting to happen to the cleaned_data dictionary. Don't forget you can't redirect to a POST - this is a limitation of HTTP, not Django - so your cleaned_data either needs to be a URL parameter (horrible) or, slightly better, a series of GET parameters - so the URL would be in the form:

/link/mybackend/?field1=value1&field2=value2&field3=value3

and so on. In this case, field1, field2 and field3 are not included in the URLconf definition - they are available in the view via request.GET.

So your urlconf would be:

url(r'^link/(?P<backend>\w+?)/$', my_function)

and the view would look like:

def my_function(request, backend):
   data = request.GET

and the reverse would be (after importing urllib):

return "%s?%s" % (redirect('my_function', args=(backend,)),
                  urllib.urlencode(form.cleaned_data))

Edited after comment

The whole point of using redirect and reverse, as you have been doing, is that you go to the URL - it returns an Http code that causes the browser to redirect to the new URL, and call that.

If you simply want to call the view from within your code, just do it directly - no need to use reverse at all.

That said, if all you want to do is store the data, then just put it in the session:

request.session['temp_data'] = form.cleaned_data

Parsing a pcap file in python

I would use python-dpkt. Here is the documentation: http://www.commercialventvac.com/dpkt.html

This is all I know how to do though sorry.

#!/usr/local/bin/python2.7

import dpkt

counter=0
ipcounter=0
tcpcounter=0
udpcounter=0

filename='sampledata.pcap'

for ts, pkt in dpkt.pcap.Reader(open(filename,'r')):

    counter+=1
    eth=dpkt.ethernet.Ethernet(pkt) 
    if eth.type!=dpkt.ethernet.ETH_TYPE_IP:
       continue

    ip=eth.data
    ipcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_TCP: 
       tcpcounter+=1

    if ip.p==dpkt.ip.IP_PROTO_UDP:
       udpcounter+=1

print "Total number of packets in the pcap file: ", counter
print "Total number of ip packets: ", ipcounter
print "Total number of tcp packets: ", tcpcounter
print "Total number of udp packets: ", udpcounter

Update:

Project on GitHub, documentation here

Html attributes for EditorFor() in ASP.NET MVC

Now ASP.Net MVC 5.1 got a built in support for it.

From Release Notes

We now allow passing in HTML attributes in EditorFor as an anonymous object.

For example:

@Html.EditorFor(model => model, 
              new { htmlAttributes = new { @class = "form-control" }, })

PHP display current server path

You can also use the following alternative realpath.

Create a file called path.php

Put the following code inside by specifying the name of the created file.

<?php 
    echo realpath('path.php'); 
?>

A php file that you can move to all your folders to always have the absolute path from where the executed file is located.

;-)

getResourceAsStream() vs FileInputStream

The FileInputStream class works directly with the underlying file system. If the file in question is not physically present there, it will fail to open it. The getResourceAsStream() method works differently. It tries to locate and load the resource using the ClassLoader of the class it is called on. This enables it to find, for example, resources embedded into jar files.

datetime.parse and making it work with a specific format

DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);

assuming you meant to say that minutes followed the hours, not seconds - your example is a little confusing.

The ParseExact documentation details other overloads, in case you want to have the parse automatically convert to Universal Time or something like that.

As @Joel Coehoorn mentions, there's also the option of using TryParseExact, which will return a Boolean value indicating success or failure of the operation - I'm still on .Net 1.1, so I often forget this one.

If you need to parse other formats, you can check out the Standard DateTime Format Strings.

Could not install packages due to an EnvironmentError: [WinError 5] Access is denied:

I experienced the same issue when trying to install tensorflow from a jupyter notebook using Anaconda. --user did not work.

conda install tensorflow worked for me, and I didn't have to change any security settings.

django import error - No module named core.management

For those of you using Django 1.6 or newer, note that execute_manager was removed. There is a solution posted in the second SO answer here.

MySQL "WITH" clause

MariaDB is now supporting WITH. MySQL for now is not. https://mariadb.com/kb/en/mariadb/with/

What __init__ and self do in Python?

A brief illustrative example

In the hope it might help a little, here's a simple example I used to understand the difference between a variable declared inside a class, and a variable declared inside an __init__ function:

class MyClass(object):
    i = 123
    def __init__(self):
        self.i = 345
     
a = MyClass()
print(a.i)
print(MyClass.i)

Output:

345
123

How do I replace multiple spaces with a single space in C#?

Consolodating other answers, per Joel, and hopefully improving slightly as I go:

You can do this with Regex.Replace():

string s = Regex.Replace (
    "   1  2    4 5", 
    @"[ ]{2,}", 
    " "
    );

Or with String.Split():

static class StringExtensions
{
    public static string Join(this IList<string> value, string separator)
    {
        return string.Join(separator, value.ToArray());
    }
}

//...

string s = "     1  2    4 5".Split (
    " ".ToCharArray(), 
    StringSplitOptions.RemoveEmptyEntries
    ).Join (" ");

Swapping pointers in C (char, int)

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

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

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

Including one C source file in another?

Including C file into another file is legal, but not advisable thing to do, unless you know exactly why are you doing this and what are you trying to achieve.
I'm almost sure that if you will post here the reason that behind your question the community will find you another more appropriate way to achieve you goal (please note the "almost", since it is possible that this is the solution given the context).

By the way i missed the second part of the question. If C file is included to another file and in the same time included to the project you probably will end up with duplicate symbol problem why linking the objects, i.e same function will be defined twice (unless they all static).

How to write to an existing excel file without overwriting data (using pandas)?

Here is a helper function:

def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False, 
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    Parameters:
      filename : File path or existing ExcelWriter
                 (Example: '/path/to/file.xlsx')
      df : dataframe to save to workbook
      sheet_name : Name of sheet which will contain DataFrame.
                   (default: 'Sheet1')
      startrow : upper left cell row to dump data frame.
                 Per default (startrow=None) calculate the last row
                 in the existing DF and write to the next row...
      truncate_sheet : truncate (remove and recreate) [sheet_name]
                       before writing DataFrame to Excel file
      to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
                        [can be dictionary]

    Returns: None

    (c) [MaxU](https://stackoverflow.com/users/5741205/maxu?tab=profile)
    """
    from openpyxl import load_workbook

    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl')

    # Python 2.x: define [FileNotFoundError] exception if it doesn't exist 
    try:
        FileNotFoundError
    except NameError:
        FileNotFoundError = IOError


    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename)
        
        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row

        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)
        
        # copy existing sheets
        writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
    except FileNotFoundError:
        # file does not exist yet, we will create it
        pass

    if startrow is None:
        startrow = 0

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()
            

NOTE: for Pandas < 0.21.0, replace sheet_name with sheetname!

Usage examples:

append_df_to_excel('d:/temp/test.xlsx', df)

append_df_to_excel('d:/temp/test.xlsx', df, header=None, index=False)

append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', index=False)

append_df_to_excel('d:/temp/test.xlsx', df, sheet_name='Sheet2', index=False, startrow=25)

Create random list of integers in Python

All the random methods end up calling random.random() so the best way is to call it directly:

[int(1000*random.random()) for i in xrange(10000)]

For example,

  • random.randint calls random.randrange.
  • random.randrange has a bunch of overhead to check the range before returning istart + istep*int(self.random() * n).

NumPy is much faster still of course.

java.sql.SQLException: - ORA-01000: maximum open cursors exceeded

I faced the same issue because I was querying db for more than 1000 iterations. I have used try and finally in my code. But was still getting error.

To solve this I just logged into oracle db and ran below query:

ALTER SYSTEM SET open_cursors = 8000 SCOPE=BOTH;

And this solved my problem immediately.

How do I execute a MS SQL Server stored procedure in java/jsp, returning table data?

Our server calls stored procs from Java like so - works on both SQL Server 2000 & 2008:

String SPsql = "EXEC <sp_name> ?,?";   // for stored proc taking 2 parameters
Connection con = SmartPoolFactory.getConnection();   // java.sql.Connection
PreparedStatement ps = con.prepareStatement(SPsql);
ps.setEscapeProcessing(true);
ps.setQueryTimeout(<timeout value>);
ps.setString(1, <param1>);
ps.setString(2, <param2>);
ResultSet rs = ps.executeQuery();

How to save an HTML5 Canvas as an image on a server?

I just made an imageCrop and Upload feature with

https://www.npmjs.com/package/react-image-crop

to get the ImagePreview ( the cropped image rendering in a canvas)

https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob

canvas.toBlob(function(blob){...}, 'image/jpeg', 0.95);

I prefer sending data in blob with content type image/jpeg rather than toDataURL ( a huge base64 string`

My implementation for uploading to Azure Blob using SAS URL

axios.post(azure_sas_url, image_in_blob, {
   headers: {
      'x-ms-blob-type': 'BlockBlob',
      'Content-Type': 'image/jpeg'
   }
})

How to find value using key in javascript dictionary

Arrays in JavaScript don't use strings as keys. You will probably find that the value is there, but the key is an integer.

If you make Dict into an object, this will work:

var dict = {};
var addPair = function (myKey, myValue) {
    dict[myKey] = myValue;
};
var giveValue = function (myKey) {
    return dict[myKey];
};

The myKey variable is already a string, so you don't need more quotes.

Local and global temporary tables in SQL Server

Quoting from Books Online:

Local temporary tables are visible only in the current session; global temporary tables are visible to all sessions.

Temporary tables are automatically dropped when they go out of scope, unless explicitly dropped using DROP TABLE:

  • A local temporary table created in a stored procedure is dropped automatically when the stored procedure completes. The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. The table cannot be referenced by the process which called the stored procedure that created the table.
  • All other local temporary tables are dropped automatically at the end of the current session.
  • Global temporary tables are automatically dropped when the session that created the table ends and all other tasks have stopped referencing them. The association between a task and a table is maintained only for the life of a single Transact-SQL statement. This means that a global temporary table is dropped at the completion of the last Transact-SQL statement that was actively referencing the table when the creating session ended.

Resolving ORA-4031 "unable to allocate x bytes of shared memory"

Even though you are using ASMM, you can set a minimum size for the large pool (MMAN will not shrink it below that value). You can also try pinning some objects and increasing SGA_TARGET.

Android Canvas.drawText

It should be noted that the documentation recommends using a Layout rather than Canvas.drawText directly. My full answer about using a StaticLayout is here, but I will provide a summary below.

String text = "This is some text.";

TextPaint textPaint = new TextPaint();
textPaint.setAntiAlias(true);
textPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
textPaint.setColor(0xFF000000);

int width = (int) textPaint.measureText(text);
StaticLayout staticLayout = new StaticLayout(text, textPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
staticLayout.draw(canvas);

Here is a fuller example in the context of a custom view:

enter image description here

public class MyView extends View {

    String mText = "This is some text.";
    TextPaint mTextPaint;
    StaticLayout mStaticLayout;

    // use this constructor if creating MyView programmatically
    public MyView(Context context) {
        super(context);
        initLabelView();
    }

    // this constructor is used when created from xml
    public MyView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initLabelView();
    }

    private void initLabelView() {
        mTextPaint = new TextPaint();
        mTextPaint.setAntiAlias(true);
        mTextPaint.setTextSize(16 * getResources().getDisplayMetrics().density);
        mTextPaint.setColor(0xFF000000);

        // default to a single line of text
        int width = (int) mTextPaint.measureText(mText);
        mStaticLayout = new StaticLayout(mText, mTextPaint, (int) width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);

        // New API alternate
        //
        // StaticLayout.Builder builder = StaticLayout.Builder.obtain(mText, 0, mText.length(), mTextPaint, width)
        //        .setAlignment(Layout.Alignment.ALIGN_NORMAL)
        //        .setLineSpacing(1, 0) // multiplier, add
        //        .setIncludePad(false);
        // mStaticLayout = builder.build();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        // Tell the parent layout how big this view would like to be
        // but still respect any requirements (measure specs) that are passed down.

        // determine the width
        int width;
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthRequirement = MeasureSpec.getSize(widthMeasureSpec);
        if (widthMode == MeasureSpec.EXACTLY) {
            width = widthRequirement;
        } else {
            width = mStaticLayout.getWidth() + getPaddingLeft() + getPaddingRight();
            if (widthMode == MeasureSpec.AT_MOST) {
                if (width > widthRequirement) {
                    width = widthRequirement;
                    // too long for a single line so relayout as multiline
                    mStaticLayout = new StaticLayout(mText, mTextPaint, width, Layout.Alignment.ALIGN_NORMAL, 1.0f, 0, false);
                }
            }
        }

        // determine the height
        int height;
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightRequirement = MeasureSpec.getSize(heightMeasureSpec);
        if (heightMode == MeasureSpec.EXACTLY) {
            height = heightRequirement;
        } else {
            height = mStaticLayout.getHeight() + getPaddingTop() + getPaddingBottom();
            if (heightMode == MeasureSpec.AT_MOST) {
                height = Math.min(height, heightRequirement);
            }
        }

        // Required call: set width and height
        setMeasuredDimension(width, height);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        // do as little as possible inside onDraw to improve performance

        // draw the text on the canvas after adjusting for padding
        canvas.save();
        canvas.translate(getPaddingLeft(), getPaddingTop());
        mStaticLayout.draw(canvas);
        canvas.restore();
    }
}

How to read file from relative path in Java project? java.io.File cannot find the path specified

String basePath = new File("myFile.txt").getAbsolutePath(); this basepath you can use as the correct path of your file

HTML - Display image after selecting filename

You can achieve this with the following code:

$("input").change(function(e) {

    for (var i = 0; i < e.originalEvent.srcElement.files.length; i++) {

        var file = e.originalEvent.srcElement.files[i];

        var img = document.createElement("img");
        var reader = new FileReader();
        reader.onloadend = function() {
             img.src = reader.result;
        }
        reader.readAsDataURL(file);
        $("input").after(img);
    }
});

Demo: http://jsfiddle.net/ugPDx/

How to create a simple map using JavaScript/JQuery

If you're not restricted to JQuery, you can use the prototype.js framework. It has a class called Hash: You can even use JQuery & prototype.js together. Just type jQuery.noConflict();

var h = new Hash();
h.set("key", "value");
h.get("key");
h.keys(); // returns an array of keys
h.values(); // returns an array of values

Making Python loggers output all messages to stdout in addition to log file

You could create two handlers for file and stdout and then create one logger with handlers argument to basicConfig. It could be useful if you have the same log_level and format output for both handlers:

import logging
import sys

file_handler = logging.FileHandler(filename='tmp.log')
stdout_handler = logging.StreamHandler(sys.stdout)
handlers = [file_handler, stdout_handler]

logging.basicConfig(
    level=logging.DEBUG, 
    format='[%(asctime)s] {%(filename)s:%(lineno)d} %(levelname)s - %(message)s',
    handlers=handlers
)

logger = logging.getLogger('LOGGER_NAME')

gnuplot plotting multiple line graphs

I think your problem is your version numbers. Try making 8.1 --> 8.01, and so forth. That should put the points in the right order.

Alternatively, you could plot using X, where X is the column number you want, instead of using 1:X. That will plot those values on the y axis and integers on the x axis. Try:

plot "ls.dat" using 2 title 'Removed' with lines, \
     "ls.dat" using 3 title 'Added' with lines, \
     "ls.dat" using 4 title 'Modified' with lines

Convert a SQL query result table to an HTML table for email

I made a dynamic proc which turns any random query into an HTML table, so you don't have to hardcode columns like in the other responses.

-- Description: Turns a query into a formatted HTML table. Useful for emails. 
-- Any ORDER BY clause needs to be passed in the separate ORDER BY parameter.
-- =============================================
CREATE PROC [dbo].[spQueryToHtmlTable] 
(
  @query nvarchar(MAX), --A query to turn into HTML format. It should not include an ORDER BY clause.
  @orderBy nvarchar(MAX) = NULL, --An optional ORDER BY clause. It should contain the words 'ORDER BY'.
  @html nvarchar(MAX) = NULL OUTPUT --The HTML output of the procedure.
)
AS
BEGIN   
  SET NOCOUNT ON;

  IF @orderBy IS NULL BEGIN
    SET @orderBy = ''  
  END

  SET @orderBy = REPLACE(@orderBy, '''', '''''');

  DECLARE @realQuery nvarchar(MAX) = '
    DECLARE @headerRow nvarchar(MAX);
    DECLARE @cols nvarchar(MAX);    

    SELECT * INTO #dynSql FROM (' + @query + ') sub;

    SELECT @cols = COALESCE(@cols + '', '''''''', '', '''') + ''['' + name + ''] AS ''''td''''''
    FROM tempdb.sys.columns 
    WHERE object_id = object_id(''tempdb..#dynSql'')
    ORDER BY column_id;

    SET @cols = ''SET @html = CAST(( SELECT '' + @cols + '' FROM #dynSql ' + @orderBy + ' FOR XML PATH(''''tr''''), ELEMENTS XSINIL) AS nvarchar(max))''    

    EXEC sys.sp_executesql @cols, N''@html nvarchar(MAX) OUTPUT'', @html=@html OUTPUT

    SELECT @headerRow = COALESCE(@headerRow + '''', '''') + ''<th>'' + name + ''</th>'' 
    FROM tempdb.sys.columns 
    WHERE object_id = object_id(''tempdb..#dynSql'')
    ORDER BY column_id;

    SET @headerRow = ''<tr>'' + @headerRow + ''</tr>'';

    SET @html = ''<table border="1">'' + @headerRow + @html + ''</table>'';    
    ';

  EXEC sys.sp_executesql @realQuery, N'@html nvarchar(MAX) OUTPUT', @html=@html OUTPUT
END
GO

Usage:

DECLARE @html nvarchar(MAX);
EXEC spQueryToHtmlTable @html = @html OUTPUT,  @query = N'SELECT * FROM dbo.People', @orderBy = N'ORDER BY FirstName';

EXEC msdb.dbo.sp_send_dbmail
    @profile_name = 'Foo',
    @recipients = '[email protected];',
    @subject = 'HTML email',
    @body = @html,
    @body_format = 'HTML',
    @query_no_truncate = 1,
    @attach_query_result_as_file = 0;

Related: Here is similar code to turn any arbitrary query into a CSV string.

Difference between Big-O and Little-O Notation

In general

Asymptotic notation is something you can understand as: how do functions compare when zooming out? (A good way to test this is simply to use a tool like Desmos and play with your mouse wheel). In particular:

  • f(n) ? o(n) means: at some point, the more you zoom out, the more f(n) will be dominated by n (it will progressively diverge from it).
  • g(n) ? T(n) means: at some point, zooming out will not change how g(n) compare to n (if we remove ticks from the axis you couldn't tell the zoom level).

Finally h(n) ? O(n) means that function h can be in either of these two categories. It can either look a lot like n or it could be smaller and smaller than n when n increases. Basically, both f(n) and g(n) are also in O(n).

In computer science

In computer science, people will usually prove that a given algorithm admits both an upper O and a lower bound . When both bounds meet that means that we found an asymptotically optimal algorithm to solve that particular problem.

For example, if we prove that the complexity of an algorithm is both in O(n) and (n) it implies that its complexity is in T(n). That's the definition of T and it more or less translates to "asymptotically equal". Which also means that no algorithm can solve the given problem in o(n). Again, roughly saying "this problem can't be solved in less than n steps".

An upper bound of O(n) simply means that even in the worse case, the algorithm will terminate in at most n steps (ignoring all constant factors, both multiplicative and additive). A lower bound of (n) means on the opposite that we built some examples where the problem solved by this algorithm couldn't be solved in less than n steps (again ignoring multiplicative and additive constants). The number of steps is at most n and at least n so this problem complexity is "exactly n". Instead of saying "ignoring constant multiplicative/additive factor" every time we just write T(n) for short.

How do you get assembler output from C/C++ source in gcc?

Use the -S option to gcc (or g++).

gcc -S helloworld.c

This will run the preprocessor (cpp) over helloworld.c, perform the initial compilation and then stop before the assembler is run.

By default this will output a file helloworld.s. The output file can be still be set by using the -o option.

gcc -S -o my_asm_output.s helloworld.c

Of course this only works if you have the original source. An alternative if you only have the resultant object file is to use objdump, by setting the --disassemble option (or -d for the abbreviated form).

objdump -S --disassemble helloworld > helloworld.dump

This option works best if debugging option is enabled for the object file (-g at compilation time) and the file hasn't been stripped.

Running file helloworld will give you some indication as to the level of detail that you will get by using objdump.

Combine Multiple child rows into one row MYSQL

If you really need multiple columns in your result, and the amount of options is limited, you can even do this:

select
  ordered_item.id as `Id`,
  ordered_item.Item_Name as `ItemName`,
  if(ordered_options.id=1,Ordered_Options.Value,null) as `Option1`,
  if(ordered_options.id=2,Ordered_Options.Value,null) as `Option2`,
  if(ordered_options.id=43,Ordered_Options.Value,null) as `Option43`,
  if(ordered_options.id=44,Ordered_Options.Value,null) as `Option44`,
  GROUP_CONCAT(if(ordered_options.id not in (1,2,43,44),Ordered_Options.Value,null)) as `OtherOptions`
from
  ordered_item,
  ordered_options
where
  ordered_item.id=ordered_options.ordered_item_id
group by
  ordered_item.id

Setting up SSL on a local xampp/apache server

It turns out that OpenSSL is compiled and enabled in php 5.3 of XAMPP 1.7.2 and so no longer requires a separate extension dll.

However, you STILL need to enable it in your PHP.ini file the line extension=php_openssl.dll

Open file dialog box in JavaScript

AFAIK you still need an <input type="file"> element, then you can use some of the stuff from quirksmode to style it up

How To Launch Git Bash from DOS Command Line?

start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login -i

Git bash will get open.

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

How to extract a substring using regex

Some how the group(1) didnt work for me. I used group(0) to find the url version.

Pattern urlVersionPattern = Pattern.compile("\\/v[0-9][a-z]{0,1}\\/");
Matcher m = urlVersionPattern.matcher(url);
if (m.find()) { 
    return StringUtils.substringBetween(m.group(0), "/", "/");
}
return "v0";

What is attr_accessor in Ruby?

attr_accessor is just a method. (The link should provide more insight with how it works - look at the pairs of methods generated, and a tutorial should show you how to use it.)

The trick is that class is not a definition in Ruby (it is "just a definition" in languages like C++ and Java), but it is an expression that evaluates. It is during this evaluation when the attr_accessor method is invoked which in turn modifies the current class - remember the implicit receiver: self.attr_accessor, where self is the "open" class object at this point.

The need for attr_accessor and friends, is, well:

  1. Ruby, like Smalltalk, does not allow instance variables to be accessed outside of methods1 for that object. That is, instance variables cannot be accessed in the x.y form as is common in say, Java or even Python. In Ruby y is always taken as a message to send (or "method to call"). Thus the attr_* methods create wrappers which proxy the instance @variable access through dynamically created methods.

  2. Boilerplate sucks

Hope this clarifies some of the little details. Happy coding.


1 This isn't strictly true and there are some "techniques" around this, but there is no syntax support for "public instance variable" access.

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

"Error 404 Not Found" in Magento Admin Login Page

Finally, I found the solution to my problem.

I looked into the Magento system log file (var/log/system.log). There I saw the exact error.

The error is as below:-

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 555 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store.php on line 285

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 575 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store\Group.php on line 227

Actually, I had this error before. But, error display message like Error: 404 Not Found was new to me.

The reason for this error is that store_id and website_id for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.

Open PhpMyAdmin and run the following query in your database:-

SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;

I have written about this problem and solution over here:-

Magento: Solution to "Error: 404 Not Found" in Admin Login Page

What characters are allowed in an email address?

You can start from wikipedia article:

  • Uppercase and lowercase English letters (a-z, A-Z)
  • Digits 0 to 9
  • Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~
  • Character . (dot, period, full stop) provided that it is not the first or last character, and provided also that it does not appear two or more times consecutively.

Save a list to a .txt file

You can use inbuilt library pickle

This library allows you to save any object in python to a file

This library will maintain the format as well

import pickle
with open('/content/list_1.txt', 'wb') as fp:
    pickle.dump(list_1, fp)

you can also read the list back as an object using same library

with open ('/content/list_1.txt', 'rb') as fp:
    list_1 = pickle.load(fp)

reference : Writing a list to a file with Python

Allow only numbers and dot in script

<input type="text" class="decimal" value="" />
$('.decimal').keypress(function(evt){
    return (/^[0-9]*\.?[0-9]*$/).test($(this).val()+evt.key);
});

I think this simple solution may be.

How do I find out what keystore my JVM is using?

For me using the official OpenJDK 12 Docker image, the location of the Java keystore was:

/usr/java/openjdk-12/lib/security/cacerts

warning: incompatible implicit declaration of built-in function ‘xyz’

In C, using a previously undeclared function constitutes an implicit declaration of the function. In an implicit declaration, the return type is int if I recall correctly. Now, GCC has built-in definitions for some standard functions. If an implicit declaration does not match the built-in definition, you get this warning.

To fix the problem, you have to declare the functions before using them; normally you do this by including the appropriate header. I recommend not to use the -fno-builtin-* flags if possible.

Instead of stdlib.h, you should try:

#include <string.h>

That's where strcpy and strncpy are defined, at least according to the strcpy(2) man page.

The exit function is defined in stdlib.h, though, so I don't know what's going on there.

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

line breaks in a textarea

Ahh, it is really simple

just add

white-space:pre-wrap;

to your displaying element css

I mean if you are showing result using <p> then your css should be

p{
   white-space:pre-wrap;
}

Get the date of next monday, tuesday, etc

You can use Carbon library.

Example: Next week friday

Carbon::parse("friday next week");

preg_match(); - Unknown modifier '+'

This happened to me because I put a variable in the regex and sometimes its string value included a slash. Solution: preg_quote.

How to make java delay for a few seconds?

Use Thread.sleep(2000); //2000 for 2 seconds

How do I align views at the bottom of the screen?

In case you have a hierarchy like this:

<ScrollView> 
  |-- <RelativeLayout> 
    |-- <LinearLayout>

First, apply android:fillViewport="true" to the ScrollView and then apply android:layout_alignParentBottom="true" to the LinearLayout.

This worked for me perfectly.

<ScrollView
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:scrollbars="none"
    android:fillViewport="true">
    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:id="@+id/linearLayoutHorizontal"
            android:layout_alignParentBottom="true">
        </LinearLayout>
    </RelativeLayout>
</ScrollView>

Convert laravel object to array

If you want to get only ID in array, can use array_map:

    $data = array_map(function($object){
        return $object->ID;
    }, $data);

With that, return an array with ID in every pos.

How to show row number in Access query like ROW_NUMBER in SQL

You can try this query:

Select A.*, (select count(*) from Table1 where A.ID>=ID) as RowNo
from Table1 as A
order by A.ID

How do you kill all current connections to a SQL Server 2005 database?

Using SQL Management Studio Express:

In the Object Explorer tree drill down under Management to "Activity Monitor" (if you cannot find it there then right click on the database server and select "Activity Monitor"). Opening the Activity Monitor, you can view all process info. You should be able to find the locks for the database you're interested in and kill those locks, which will also kill the connection.

You should be able to rename after that.

Angular cli generate a service and include the provider in one step

slight change in syntax from the accepted answer for Angular 5 and angular-cli 1.7.0

ng g service backendApi --module=app.module

Setting different color for each series in scatter plot on matplotlib

An easy fix

If you have only one type of collections (e.g. scatter with no error bars) you can also change the colours after that you have plotted them, this sometimes is easier to perform.

import matplotlib.pyplot as plt
from random import randint
import numpy as np

#Let's generate some random X, Y data X = [ [frst group],[second group] ...]
X = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
Y = [ [randint(0,50) for i in range(0,5)] for i in range(0,24)]
labels = range(1,len(X)+1)

fig = plt.figure()
ax = fig.add_subplot(111)
for x,y,lab in zip(X,Y,labels):
        ax.scatter(x,y,label=lab)

The only piece of code that you need:

#Now this is actually the code that you need, an easy fix your colors just cut and paste not you need ax.
colormap = plt.cm.gist_ncar #nipy_spectral, Set1,Paired  
colorst = [colormap(i) for i in np.linspace(0, 0.9,len(ax.collections))]       
for t,j1 in enumerate(ax.collections):
    j1.set_color(colorst[t])


ax.legend(fontsize='small')

The output gives you differnent colors even when you have many different scatter plots in the same subplot.

enter image description here

Can't install Scipy through pip

For windows(7 in my case):

  1. download scipy-0.19.1-cp36-cp36m-win32.whl from http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy
  2. create one some.bat file with content

    @echo off C:\Python36\python.exe -m pip -V C:\Python36\python.exe -m pip install scipy-0.19.1-cp36-cp36m-win32.whl C:\Python36\python.exe -m pip list pause

  3. then run this batch file some.bat

  4. call python shell "C:\Python36\pythonw.exe "C:\Python36\Lib\idlelib\idle.pyw" and test if scipy was installed with

import scipy

Check that a input to UITextField is numeric only

   #import "NSString+Extension.h"

//@interface NSString (Extension)
//
//- (BOOL) isAnEmail;
//- (BOOL) isNumeric;
//
//@end

@implementation NSString (Extension)
 - (BOOL) isNumeric
    {
        NSString *emailRegex = @"[0-9]+";
        NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];

        return [emailTest evaluateWithObject:self];

    //    NSString *localDecimalSymbol = [[NSLocale currentLocale] objectForKey:NSLocaleDecimalSeparator];
    //    NSMutableCharacterSet *decimalCharacterSet = [NSMutableCharacterSet characterSetWithCharactersInString:localDecimalSymbol];
    //    [decimalCharacterSet formUnionWithCharacterSet:[NSCharacterSet alphanumericCharacterSet]];
    //    
    //    NSCharacterSet* nonNumbers = [decimalCharacterSet invertedSet];
    //    NSRange r = [self rangeOfCharacterFromSet: nonNumbers];
    //    
    //    if (r.location == NSNotFound)
    //    {
    //        // check to see how many times the decimal symbol appears in the string. It should only appear once for the number to be numeric.
    //        int numberOfOccurances = [[self componentsSeparatedByString:localDecimalSymbol] count]-1;
    //        return (numberOfOccurances > 1) ? NO : YES;
    //    }
    //    else return NO;
    }

jQuery Mobile: document ready vs. page events

jQuery Mobile 1.4 Update:

My original article was intended for old way of page handling, basically everything before jQuery Mobile 1.4. Old way of handling is now deprecated and it will stay active until (including) jQuery Mobile 1.5, so you can still use everything mentioned below, at least until next year and jQuery Mobile 1.6.

Old events, including pageinit don't exist any more, they are replaced with pagecontainer widget. Pageinit is erased completely and you can use pagecreate instead, that event stayed the same and its not going to be changed.

If you are interested in new way of page event handling take a look here, in any other case feel free to continue with this article. You should read this answer even if you are using jQuery Mobile 1.4 +, it goes beyond page events so you will probably find a lot of useful information.

Older content:

This article can also be found as a part of my blog HERE.

$(document).on('pageinit') vs $(document).ready()

The first thing you learn in jQuery is to call code inside the $(document).ready() function so everything will execute as soon as the DOM is loaded. However, in jQuery Mobile, Ajax is used to load the contents of each page into the DOM as you navigate. Because of this $(document).ready() will trigger before your first page is loaded and every code intended for page manipulation will be executed after a page refresh. This can be a very subtle bug. On some systems it may appear that it works fine, but on others it may cause erratic, difficult to repeat weirdness to occur.

Classic jQuery syntax:

$(document).ready(function() {

});

To solve this problem (and trust me this is a problem) jQuery Mobile developers created page events. In a nutshell page events are events triggered in a particular point of page execution. One of those page events is a pageinit event and we can use it like this:

$(document).on('pageinit', function() {

});

We can go even further and use a page id instead of document selector. Let's say we have jQuery Mobile page with an id index:

<div data-role="page" id="index">
    <div data-theme="a" data-role="header">
        <h3>
            First Page
        </h3>
        <a href="#second" class="ui-btn-right">Next</a>
    </div>

    <div data-role="content">
        <a href="#" data-role="button" id="test-button">Test button</a>
    </div>

    <div data-theme="a" data-role="footer" data-position="fixed">

    </div>
</div>

To execute code that will only available to the index page we could use this syntax:

$('#index').on('pageinit', function() {

});

Pageinit event will be executed every time page is about be be loaded and shown for the first time. It will not trigger again unless page is manually refreshed or Ajax page loading is turned off. In case you want code to execute every time you visit a page it is better to use pagebeforeshow event.

Here's a working example: http://jsfiddle.net/Gajotres/Q3Usv/ to demonstrate this problem.

Few more notes on this question. No matter if you are using 1 html multiple pages or multiple HTML files paradigm it is advised to separate all of your custom JavaScript page handling into a single separate JavaScript file. This will note make your code any better but you will have much better code overview, especially while creating a jQuery Mobile application.

There's also another special jQuery Mobile event and it is called mobileinit. When jQuery Mobile starts, it triggers a mobileinit event on the document object. To override default settings, bind them to mobileinit. One of a good examples of mobileinit usage is turning off Ajax page loading, or changing default Ajax loader behavior.

$(document).on("mobileinit", function(){
  //apply overrides here
});

Page events transition order

First all events can be found here: http://api.jquerymobile.com/category/events/

Lets say we have a page A and a page B, this is a unload/load order:

  1. page B - event pagebeforecreate

  2. page B - event pagecreate

  3. page B - event pageinit

  4. page A - event pagebeforehide

  5. page A - event pageremove

  6. page A - event pagehide

  7. page B - event pagebeforeshow

  8. page B - event pageshow

For better page events understanding read this:

  • pagebeforeload, pageload and pageloadfailed are fired when an external page is loaded
  • pagebeforechange, pagechange and pagechangefailed are page change events. These events are fired when a user is navigating between pages in the applications.
  • pagebeforeshow, pagebeforehide, pageshow and pagehide are page transition events. These events are fired before, during and after a transition and are named.
  • pagebeforecreate, pagecreate and pageinit are for page initialization.
  • pageremove can be fired and then handled when a page is removed from the DOM

Page loading jsFiddle example: http://jsfiddle.net/Gajotres/QGnft/

If AJAX is not enabled, some events may not fire.

Prevent page transition

If for some reason page transition needs to be prevented on some condition it can be done with this code:

$(document).on('pagebeforechange', function(e, data){
    var to = data.toPage,
        from = data.options.fromPage;

    if (typeof to  === 'string') {
        var u = $.mobile.path.parseUrl(to);
        to = u.hash || '#' + u.pathname.substring(1);
        if (from) from = '#' + from.attr('id');

        if (from === '#index' && to === '#second') {
            alert('Can not transition from #index to #second!');
            e.preventDefault();
            e.stopPropagation();

            // remove active status on a button, if transition was triggered with a button
            $.mobile.activePage.find('.ui-btn-active').removeClass('ui-btn-active ui-focus ui-btn');;
        }
    }
});

This example will work in any case because it will trigger at a begging of every page transition and what is most important it will prevent page change before page transition can occur.

Here's a working example:

Prevent multiple event binding/triggering

jQuery Mobile works in a different way than classic web applications. Depending on how you managed to bind your events each time you visit some page it will bind events over and over. This is not an error, it is simply how jQuery Mobile handles its pages. For example, take a look at this code snippet:

$(document).on('pagebeforeshow','#index' ,function(e,data){
    $(document).on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/CCfL4/

Each time you visit page #index click event will is going to be bound to button #test-button. Test it by moving from page 1 to page 2 and back several times. There are few ways to prevent this problem:

Solution 1

Best solution would be to use pageinit to bind events. If you take a look at an official documentation you will find out that pageinit will trigger ONLY once, just like document ready, so there's no way events will be bound again. This is best solution because you don't have processing overhead like when removing events with off method.

Working jsFiddle example: http://jsfiddle.net/Gajotres/AAFH8/

This working solution is made on a basis of a previous problematic example.

Solution 2

Remove event before you bind it:

$(document).on('pagebeforeshow', '#index', function(){
    $(document).off('click', '#test-button').on('click', '#test-button',function(e) {
        alert('Button click');
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/K8YmG/

Solution 3

Use a jQuery Filter selector, like this:

$('#carousel div:Event(!click)').each(function(){
    //If click is not bind to #carousel div do something
});

Because event filter is not a part of official jQuery framework it can be found here: http://www.codenothing.com/archives/2009/event-filter/

In a nutshell, if speed is your main concern then Solution 2 is much better than Solution 1.

Solution 4

A new one, probably an easiest of them all.

$(document).on('pagebeforeshow', '#index', function(){
    $(document).on('click', '#test-button',function(e) {
        if(e.handled !== true) // This will prevent event triggering more than once
        {
            alert('Clicked');
            e.handled = true;
        }
    });
});

Working jsFiddle example: http://jsfiddle.net/Gajotres/Yerv9/

Tnx to the sholsinger for this solution: http://sholsinger.com/archive/2011/08/prevent-jquery-live-handlers-from-firing-multiple-times/

pageChange event quirks - triggering twice

Sometimes pagechange event can trigger twice and it does not have anything to do with the problem mentioned before.

The reason the pagebeforechange event occurs twice is due to the recursive call in changePage when toPage is not a jQuery enhanced DOM object. This recursion is dangerous, as the developer is allowed to change the toPage within the event. If the developer consistently sets toPage to a string, within the pagebeforechange event handler, regardless of whether or not it was an object an infinite recursive loop will result. The pageload event passes the new page as the page property of the data object (This should be added to the documentation, it's not listed currently). The pageload event could therefore be used to access the loaded page.

In few words this is happening because you are sending additional parameters through pageChange.

Example:

<a data-role="button" data-icon="arrow-r" data-iconpos="right" href="#care-plan-view?id=9e273f31-2672-47fd-9baa-6c35f093a800&amp;name=Sat"><h3>Sat</h3></a>

To fix this problem use any page event listed in Page events transition order.

Page Change Times

As mentioned, when you change from one jQuery Mobile page to another, typically either through clicking on a link to another jQuery Mobile page that already exists in the DOM, or by manually calling $.mobile.changePage, several events and subsequent actions occur. At a high level the following actions occur:

  • A page change process is begun
  • A new page is loaded
  • The content for that page is “enhanced” (styled)
  • A transition (slide/pop/etc) from the existing page to the new page occurs

This is a average page transition benchmark:

Page load and processing: 3 ms

Page enhance: 45 ms

Transition: 604 ms

Total time: 670 ms

*These values are in milliseconds.

So as you can see a transition event is eating almost 90% of execution time.

Data/Parameters manipulation between page transitions

It is possible to send a parameter/s from one page to another during page transition. It can be done in few ways.

Reference: https://stackoverflow.com/a/13932240/1848600

Solution 1:

You can pass values with changePage:

$.mobile.changePage('page2.html', { dataUrl : "page2.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : true, changeHash : true });

And read them like this:

$(document).on('pagebeforeshow', "#index", function (event, data) {
    var parameters = $(this).data("url").split("?")[1];;
    parameter = parameters.replace("parameter=","");
    alert(parameter);
});

Example:

index.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
    <script>_x000D_
        $(document).on('pagebeforeshow', "#index",function () {_x000D_
            $(document).on('click', "#changePage",function () {_x000D_
                $.mobile.changePage('second.html', { dataUrl : "second.html?paremeter=123", data : { 'paremeter' : '123' }, reloadPage : false, changeHash : true });_x000D_
            });_x000D_
        });_x000D_
_x000D_
        $(document).on('pagebeforeshow', "#second",function () {_x000D_
            var parameters = $(this).data("url").split("?")[1];;_x000D_
            parameter = parameters.replace("parameter=","");_x000D_
            alert(parameter);_x000D_
        });_x000D_
    </script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="index">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                First Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
          <a data-role="button" id="changePage">Test</a>_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

second.html

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
  <html>_x000D_
    <head>_x000D_
    <meta charset="utf-8" />_x000D_
    <meta name="viewport" content="widdiv=device-widdiv, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />_x000D_
    <meta name="apple-mobile-web-app-capable" content="yes" />_x000D_
    <meta name="apple-mobile-web-app-status-bar-style" content="black" />_x000D_
    <title>_x000D_
    </title>_x000D_
    <link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />_x000D_
    <script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js">_x000D_
    </script>_x000D_
    <script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>_x000D_
   </head>_x000D_
   <body>_x000D_
    <!-- Home -->_x000D_
    <div data-role="page" id="second">_x000D_
        <div data-role="header">_x000D_
            <h3>_x000D_
                Second Page_x000D_
            </h3>_x000D_
        </div>_x000D_
        <div data-role="content">_x000D_
_x000D_
        </div> <!--content-->_x000D_
    </div><!--page-->_x000D_
_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Solution 2:

Or you can create a persistent JavaScript object for a storage purpose. As long Ajax is used for page loading (and page is not reloaded in any way) that object will stay active.

var storeObject = {
    firstname : '',
    lastname : ''
}

Example: http://jsfiddle.net/Gajotres/9KKbx/

Solution 3:

You can also access data from the previous page like this:

$(document).on('pagebeforeshow', '#index',function (e, data) {
    alert(data.prevPage.attr('id'));
});

prevPage object holds a complete previous page.

Solution 4:

As a last solution we have a nifty HTML implementation of localStorage. It only works with HTML5 browsers (including Android and iOS browsers) but all stored data is persistent through page refresh.

if(typeof(Storage)!=="undefined") {
    localStorage.firstname="Dragan";
    localStorage.lastname="Gaic";
}

Example: http://jsfiddle.net/Gajotres/J9NTr/

Probably best solution but it will fail in some versions of iOS 5.X. It is a well know error.

Don’t Use .live() / .bind() / .delegate()

I forgot to mention (and tnx andleer for reminding me) use on/off for event binding/unbinding, live/die and bind/unbind are deprecated.

The .live() method of jQuery was seen as a godsend when it was introduced to the API in version 1.3. In a typical jQuery app there can be a lot of DOM manipulation and it can become very tedious to hook and unhook as elements come and go. The .live() method made it possible to hook an event for the life of the app based on its selector. Great right? Wrong, the .live() method is extremely slow. The .live() method actually hooks its events to the document object, which means that the event must bubble up from the element that generated the event until it reaches the document. This can be amazingly time consuming.

It is now deprecated. The folks on the jQuery team no longer recommend its use and neither do I. Even though it can be tedious to hook and unhook events, your code will be much faster without the .live() method than with it.

Instead of .live() you should use .on(). .on() is about 2-3x faster than .live(). Take a look at this event binding benchmark: http://jsperf.com/jquery-live-vs-delegate-vs-on/34, everything will be clear from there.

Benchmarking:

There's an excellent script made for jQuery Mobile page events benchmarking. It can be found here: https://github.com/jquery/jquery-mobile/blob/master/tools/page-change-time.js. But before you do anything with it I advise you to remove its alert notification system (each “change page” is going to show you this data by halting the app) and change it to console.log function.

Basically this script will log all your page events and if you read this article carefully (page events descriptions) you will know how much time jQm spent of page enhancements, page transitions ....

Final notes

Always, and I mean always read official jQuery Mobile documentation. It will usually provide you with needed information, and unlike some other documentation this one is rather good, with enough explanations and code examples.

Changes:

  • 30.01.2013 - Added a new method of multiple event triggering prevention
  • 31.01.2013 - Added a better clarification for chapter Data/Parameters manipulation between page transitions
  • 03.02.2013 - Added new content/examples to the chapter Data/Parameters manipulation between page transitions
  • 22.05.2013 - Added a solution for page transition/change prevention and added links to the official page events API documentation
  • 18.05.2013 - Added another solution against multiple event binding

How to set Bullet colors in UL/LI html lists via CSS without using any images or span tags

The current spec of the CSS 3 Lists module does specify the ::marker pseudo-element which would do exactly what you want; FF has been tested to not support ::marker and I doubt that either Safari or Opera has it. IE, of course, does not support it.

So right now, the only way to do this is to use an image with list-style-image.

I guess you could wrap the contents of an li with a span and then you could set the color of each, but that seems a little hackish to me.

How to find first element of array matching a boolean condition in JavaScript?

I have got inspiration from multiple sources on the internet to derive into the solution below. Wanted to take into account both some default value and to provide a way to compare each entry for a generic approach which this solves.

Usage: (giving value "Second")

var defaultItemValue = { id: -1, name: "Undefined" };
var containers: Container[] = [{ id: 1, name: "First" }, { id: 2, name: "Second" }];
GetContainer(2).name;

Implementation:

class Container {
    id: number;
    name: string;
}

public GetContainer(containerId: number): Container {
  var comparator = (item: Container): boolean => {
      return item.id == containerId;
    };
    return this.Get<Container>(this.containers, comparator, this.defaultItemValue);
  }

private Get<T>(array: T[], comparator: (item: T) => boolean, defaultValue: T): T {
  var found: T = null;
  array.some(function(element, index) {
    if (comparator(element)) {
      found = element;
      return true;
    }
  });

  if (!found) {
    found = defaultValue;
  }

  return found;
}

Create mysql table directly from CSV file using the CSV Storage engine?

In addition to the other solutions mentioned Mac users may want to note that SQL Pro has a CSV import option which works fairly well and is flexible - you can change column names, and field types on import. Choose new table otherwise the initial dialogue can appear somewhat disheartening.

Sequel Pro - database management application for working with MySQL databases.

INSERT with SELECT

The right Syntax for your query is:

INSERT INTO courses (name, location, gid) 
SELECT (name, location, gid) 
FROM courses 
WHERE cid = $cid

How to implement a FSM - Finite State Machine in Java

I design & implemented a simple finite state machine example with java.

IFiniteStateMachine: The public interface to manage the finite state machine
such as add new states to the finite state machine or transit to next states by
specific actions.

interface IFiniteStateMachine {
    void setStartState(IState startState);

    void setEndState(IState endState);

    void addState(IState startState, IState newState, Action action);

    void removeState(String targetStateDesc);

    IState getCurrentState();

    IState getStartState();

    IState getEndState();

    void transit(Action action);
}

IState: The public interface to get state related info
such as state name and mappings to connected states.

interface IState {
    // Returns the mapping for which one action will lead to another state
    Map<String, IState> getAdjacentStates();

    String getStateDesc();

    void addTransit(Action action, IState nextState);

    void removeTransit(String targetStateDesc);
}

Action: the class which will cause the transition of states.

public class Action {
    private String mActionName;

    public Action(String actionName) {
        mActionName = actionName;
    }

    String getActionName() {
        return mActionName;
    }

    @Override
    public String toString() {
        return mActionName;
    }

}

StateImpl: the implementation of IState. I applied data structure such as HashMap to keep Action-State mappings.

public class StateImpl implements IState {
    private HashMap<String, IState> mMapping = new HashMap<>();
    private String mStateName;

    public StateImpl(String stateName) {
        mStateName = stateName;
    }

    @Override
    public Map<String, IState> getAdjacentStates() {
        return mMapping;
    }

    @Override
    public String getStateDesc() {
        return mStateName;
    }

    @Override
    public void addTransit(Action action, IState state) {
        mMapping.put(action.toString(), state);
    }

    @Override
    public void removeTransit(String targetStateDesc) {
        // get action which directs to target state
        String targetAction = null;
        for (Map.Entry<String, IState> entry : mMapping.entrySet()) {
            IState state = entry.getValue();
            if (state.getStateDesc().equals(targetStateDesc)) {
                targetAction = entry.getKey();
            }
        }
        mMapping.remove(targetAction);
    }

}

FiniteStateMachineImpl: Implementation of IFiniteStateMachine. I use ArrayList to keep all the states.

public class FiniteStateMachineImpl implements IFiniteStateMachine {
    private IState mStartState;
    private IState mEndState;
    private IState mCurrentState;
    private ArrayList<IState> mAllStates = new ArrayList<>();
    private HashMap<String, ArrayList<IState>> mMapForAllStates = new HashMap<>();

    public FiniteStateMachineImpl(){}
    @Override
    public void setStartState(IState startState) {
        mStartState = startState;
        mCurrentState = startState;
        mAllStates.add(startState);
        // todo: might have some value
        mMapForAllStates.put(startState.getStateDesc(), new ArrayList<IState>());
    }

    @Override
    public void setEndState(IState endState) {
        mEndState = endState;
        mAllStates.add(endState);
        mMapForAllStates.put(endState.getStateDesc(), new ArrayList<IState>());
    }

    @Override
    public void addState(IState startState, IState newState, Action action) {
        // validate startState, newState and action

        // update mapping in finite state machine
        mAllStates.add(newState);
        final String startStateDesc = startState.getStateDesc();
        final String newStateDesc = newState.getStateDesc();
        mMapForAllStates.put(newStateDesc, new ArrayList<IState>());
        ArrayList<IState> adjacentStateList = null;
        if (mMapForAllStates.containsKey(startStateDesc)) {
            adjacentStateList = mMapForAllStates.get(startStateDesc);
            adjacentStateList.add(newState);
        } else {
            mAllStates.add(startState);
            adjacentStateList = new ArrayList<>();
            adjacentStateList.add(newState);
        }
        mMapForAllStates.put(startStateDesc, adjacentStateList);

        // update mapping in startState
        for (IState state : mAllStates) {
            boolean isStartState = state.getStateDesc().equals(startState.getStateDesc());
            if (isStartState) {
                startState.addTransit(action, newState);
            }
        }
    }

    @Override
    public void removeState(String targetStateDesc) {
        // validate state
        if (!mMapForAllStates.containsKey(targetStateDesc)) {
            throw new RuntimeException("Don't have state: " + targetStateDesc);
        } else {
            // remove from mapping
            mMapForAllStates.remove(targetStateDesc);
        }

        // update all state
        IState targetState = null;
        for (IState state : mAllStates) {
            if (state.getStateDesc().equals(targetStateDesc)) {
                targetState = state;
            } else {
                state.removeTransit(targetStateDesc);
            }
        }

        mAllStates.remove(targetState);

    }

    @Override
    public IState getCurrentState() {
        return mCurrentState;
    }

    @Override
    public void transit(Action action) {
        if (mCurrentState == null) {
            throw new RuntimeException("Please setup start state");
        }
        Map<String, IState> localMapping = mCurrentState.getAdjacentStates();
        if (localMapping.containsKey(action.toString())) {
            mCurrentState = localMapping.get(action.toString());
        } else {
            throw new RuntimeException("No action start from current state");
        }
    }

    @Override
    public IState getStartState() {
        return mStartState;
    }

    @Override
    public IState getEndState() {
        return mEndState;
    }
}

example:

public class example {

    public static void main(String[] args) {
        System.out.println("Finite state machine!!!");
        IState startState = new StateImpl("start");
        IState endState = new StateImpl("end");
        IFiniteStateMachine fsm = new FiniteStateMachineImpl();
        fsm.setStartState(startState);
        fsm.setEndState(endState);
        IState middle1 = new StateImpl("middle1");
        middle1.addTransit(new Action("path1"), endState);
        fsm.addState(startState, middle1, new Action("path1"));
        System.out.println(fsm.getCurrentState().getStateDesc());
        fsm.transit(new Action(("path1")));
        System.out.println(fsm.getCurrentState().getStateDesc());
        fsm.addState(middle1, endState, new Action("path1-end"));
        fsm.transit(new Action(("path1-end")));
        System.out.println(fsm.getCurrentState().getStateDesc());
        fsm.addState(endState, middle1, new Action("path1-end"));
    }

}

Full example on Github

Javascript to display the current date and time

You can try the below:

function formatAMPM() {
    var date = new Date();
    var currDate = date.getDate();
    var hours = date.getHours();
    var dayName = getDayName(date.getDay());
    var minutes = date.getMinutes();
    var monthName = getMonthName(date.getMonth());
    var year = date.getFullYear();
    var ampm = hours >= 12 ? 'pm' : 'am';
    hours = hours % 12;
    hours = hours ? hours : 12; // the hour '0' should be '12'
    minutes = minutes < 10 ? '0' + minutes : minutes;
    var strTime = dayName + ' ' + monthName + ' ' + currDate + ' ' + year + ' ' + hours + ':' + minutes + ' ' + ampm;
    alert(strTime);
}

function getMonthName(month) {
    var ar = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
    return ar[month];
}

function getDayName(day) {
    var ar1 = new Array("Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat");
    return ar1[day];
}

EDIT: Refer here for a working demo.

Is it possible to reference one CSS rule within another?

You can use var() function.

The var() CSS function can be used to insert the value of a custom property (sometimes called a "CSS variable") instead of any part of a value of another property.

Example:

:root {
  --main-bg-color: yellow;
}

@media (prefers-color-scheme: dark) {
  :root {
    --main-bg-color: black;
  }
}

body {
  background-color: var(--main-bg-color);
}

dyld: Library not loaded: /usr/local/opt/openssl/lib/libssl.1.0.0.dylib

This might be a problem because of having the older version of brew and installed byobu which require new dependency in order to solve this problem run the following command

brew update && brew upgrade
brew uninstall openssl; brew uninstall openssl; brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb

Python 101: Can't open file: No such file or directory

I resolved this problem by navigating to C:\Python27\Scripts folder and then run file.py file instead of C:\Python27 folder

iOS change navigation bar title font and color

My Swift code for change Navigation Bar title:

let attributes = [NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 16)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
self.navigationController.navigationBar.titleTextAttributes = attributes

And if you want to change background font too then I have this in my AppDelegate:

let attributes = [NSFontAttributeName : UIFont(name: "Roboto-Medium", size: 16)!, NSForegroundColorAttributeName : UIColor.whiteColor()]
UIBarButtonItem.appearance().setTitleTextAttributes(attributes, forState: UIControlState.Normal)

How do I turn off PHP Notices?

Use phpinfo() and search for Configuration File (php.ini) Path to see which config file path for php is used. PHP can have multiple config files depending on environment it's running. Usually, for console it's:

/etc/php5/cli/php.ini

and for php run by apache it's:

/etc/php5/apache2/php.ini

And then set error_reporting the way you need it:

http://www.phpknowhow.com/configuration/php-ini-error-settings/ http://www.zootemplate.com/news-updates/how-to-disable-notice-and-warning-in-phpini-file

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

Also, see the Stack Overflow question How to detect what .NET Framework versions and service packs are installed? which also mentions:

There is an official Microsoft answer to this question at the knowledge base article [How to determine which versions and service pack levels of the Microsoft .NET Framework are installed][2]

Article ID: 318785 - Last Review: November 7, 2008 - Revision: 20.1 How to determine which versions of the .NET Framework are installed and whether service packs have been applied.

Unfortunately, it doesn't appear to work, because the mscorlib.dll version in the 2.0 directory has a 2.0 version, and there is no mscorlib.dll version in either the 3.0 or 3.5 directories even though 3.5 SP1 is installed ... Why would the official Microsoft answer be so misinformed?

How to read the post request parameters using JavaScript

I have a simple code to make it:

In your index.php :

<input id="first_post_data" type="hidden" value="<?= $_POST['first_param']; ?>"/>

In your main.js :

let my_first_post_param = $("#first_post_data").val();

So when you will include main.js in index.php (<script type="text/javascript" src="./main.js"></script>) you could get the value of your hidden input which contains your post data.

Replace spaces with dashes and make all letters lower-case

_x000D_
_x000D_
var str = "Tatwerat Development Team";_x000D_
str = str.replace(/\s+/g, '-');_x000D_
console.log(str);_x000D_
console.log(str.toLowerCase())
_x000D_
_x000D_
_x000D_

What is the use of <<<EOD in PHP?

That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.

The HTML in your example will be:

    <tr>
      <td>TEST</td>
    </tr>

Read the PHP documentation that explains it.

How can I simulate an array variable in MySQL?

I know that this is a bit of a late response, but I recently had to solve a similar problem and thought that this may be useful to others.

Background

Consider the table below called 'mytable':

Starting table

The problem was to keep only latest 3 records and delete any older records whose systemid=1 (there could be many other records in the table with other systemid values)

It would be good is you could do this simply using the statement

DELETE FROM mytable WHERE id IN (SELECT id FROM `mytable` WHERE systemid=1 ORDER BY id DESC LIMIT 3)

However this is not yet supported in MySQL and if you try this then you will get an error like

...doesn't yet support 'LIMIT & IN/ALL/SOME subquery'

So a workaround is needed whereby an array of values is passed to the IN selector using variable. However, as variables need to be single values, I would need to simulate an array. The trick is to create the array as a comma separated list of values (string) and assign this to the variable as follows

SET @myvar := (SELECT GROUP_CONCAT(id SEPARATOR ',') AS myval FROM (SELECT * FROM `mytable` WHERE systemid=1 ORDER BY id DESC LIMIT 3 ) A GROUP BY A.systemid);

The result stored in @myvar is

5,6,7

Next, the FIND_IN_SET selector is used to select from the simulated array

SELECT * FROM mytable WHERE FIND_IN_SET(id,@myvar);

The combined final result is as follows:

SET @myvar := (SELECT GROUP_CONCAT(id SEPARATOR ',') AS myval FROM (SELECT * FROM `mytable` WHERE systemid=1 ORDER BY id DESC LIMIT 3 ) A GROUP BY A.systemid);
DELETE FROM mytable WHERE FIND_IN_SET(id,@myvar);

I am aware that this is a very specific case. However it can be modified to suit just about any other case where a variable needs to store an array of values.

I hope that this helps.

Psql could not connect to server: No such file or directory, 5432 error?

Open your database manager and execute this script

update pg_database set datallowconn = 'true' where datname = 'your_database_name';

Why doesn't C++ have a garbage collector?

Stroustrup made some good comments on this at the 2013 Going Native conference.

Just skip to about 25m50s in this video. (I'd recommend watching the whole video actually, but this skips to the stuff about garbage collection.)

When you have a really great language that makes it easy (and safe, and predictable, and easy-to-read, and easy-to-teach) to deal with objects and values in a direct way, avoiding (explicit) use of the heap, then you don't even want garbage collection.

With modern C++, and the stuff we have in C++11, garbage collection is no longer desirable except in limited circumstances. In fact, even if a good garbage collector is built into one of the major C++ compilers, I think that it won't be used very often. It will be easier, not harder, to avoid the GC.

He shows this example:

void f(int n, int x) {
    Gadget *p = new Gadget{n};
    if(x<100) throw SomeException{};
    if(x<200) return;
    delete p;
}

This is unsafe in C++. But it's also unsafe in Java! In C++, if the function returns early, the delete will never be called. But if you had full garbage collection, such as in Java, you merely get a suggestion that the object will be destructed "at some point in the future" (Update: it's even worse that this. Java does not promise to call the finalizer ever - it maybe never be called). This isn't good enough if Gadget holds an open file handle, or a connection to a database, or data which you have buffered for write to a database at a later point. We want the Gadget to be destroyed as soon as it's finished, in order to free these resources as soon as possible. You don't want your database server struggling with thousands of database connections that are no longer needed - it doesn't know that your program is finished working.

So what's the solution? There are a few approaches. The obvious approach, which you'll use for the vast majority of your objects is:

void f(int n, int x) {
    Gadget p = {n};  // Just leave it on the stack (where it belongs!)
    if(x<100) throw SomeException{};
    if(x<200) return;
}

This takes fewer characters to type. It doesn't have new getting in the way. It doesn't require you to type Gadget twice. The object is destroyed at the end of the function. If this is what you want, this is very intuitive. Gadgets behave the same as int or double. Predictable, easy-to-read, easy-to-teach. Everything is a 'value'. Sometimes a big value, but values are easier to teach because you don't have this 'action at a distance' thing that you get with pointers (or references).

Most of the objects you make are for use only in the function that created them, and perhaps passed as inputs to child functions. The programmer shouldn't have to think about 'memory management' when returning objects, or otherwise sharing objects across widely separated parts of the software.

Scope and lifetime are important. Most of the time, it's easier if the lifetime is the same as the scope. It's easier to understand and easier to teach. When you want a different lifetime, it should be obvious reading the code that you're doing this, by use of shared_ptr for example. (Or returning (large) objects by value, leveraging move-semantics or unique_ptr.

This might seem like an efficiency problem. What if I want to return a Gadget from foo()? C++11's move semantics make it easier to return big objects. Just write Gadget foo() { ... } and it will just work, and work quickly. You don't need to mess with && yourself, just return things by value and the language will often be able to do the necessary optimizations. (Even before C++03, compilers did a remarkably good job at avoiding unnecessary copying.)

As Stroustrup said elsewhere in the video (paraphrasing): "Only a computer scientist would insist on copying an object, and then destroying the original. (audience laughs). Why not just move the object directly to the new location? This is what humans (not computer scientists) expect."

When you can guarantee only one copy of an object is needed, it's much easier to understand the lifetime of the object. You can pick what lifetime policy you want, and garbage collection is there if you want. But when you understand the benefits of the other approaches, you'll find that garbage collection is at the bottom of your list of preferences.

If that doesn't work for you, you can use unique_ptr, or failing that, shared_ptr. Well written C++11 is shorter, easier-to-read, and easier-to-teach than many other languages when it comes to memory management.

Vertically align text within a div

I know it’s totally stupid and you normally really shouldn’t use tables when not creating tables, but:

Table cells can align multiple lines of text vertically centered and even do this by default. So a solution which works quite fine could be something like this:

HTML:

<div class="box">
  <table class="textalignmiddle">
    <tr>
      <td>lorem ipsum ...</td>
    </tr>
  </table>
</div>

CSS (make the table item always fit to the box div):

.box {
  /* For example */
  height: 300px;
}

.textalignmiddle {
  width: 100%;
  height: 100%;
}

See here: http://www.cssdesk.com/LzpeV

List of lists into numpy array

I had a list of lists of equal length. Even then Ignacio Vazquez-Abrams's answer didn't work out for me. I got a 1-D numpy array whose elements are lists. If you faced the same problem, you can use the below method

Use numpy.vstack

import numpy as np

np_array = np.empty((0,4), dtype='float')
for i in range(10)
     row_data = ...   # get row_data as list
     np_array = np.vstack((np_array, np.array(row_data)))

Getting full JS autocompletion under Sublime Text

As already mentioned, tern.js is a new and promising project with plugins for Sublime Text, Vim and Emacs. I´ve been using TernJS for Sublime for a while and the suggestions I get are way better than the standard ones:

enter image description here

Tern scans all .js files in your project. You can get support for DOM, nodejs, jQuery, and more by adding "libs" in your .sublime-project file:

"ternjs": {
    "exclude": ["wordpress/**", "node_modules/**"],
    "libs": ["browser", "jquery"],
    "plugins": {
        "requirejs": {
            "baseURL": "./js"
        }
    }
}

enter image description here

How to check for null/empty/whitespace values with a single test?

As in Oracle you can use NVL function in MySQL you can use IFNULL(columnaName, newValue) to achieve your desired result as in this example

SELECT column_name from table_name WHERE IFNULL(column_name,'') NOT LIKE '%_%';

How to write both h1 and h2 in the same line?

Keyword float:

<h1 style="text-align:left;float:left;">Title</h1> 
<h2 style="text-align:right;float:right;">Context</h2> 
<hr style="clear:both;"/>

Set Background cell color in PHPExcel

Seems like there's a bug with applyFromArray right now that won't accept color, but this worked for me:

$objPHPExcel
    ->getActiveSheet()
    ->getStyle('A1')
    ->getFill()
    ->getStartColor()
    ->setRGB('FF0000');

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

My problem was, that Visual Studio somehow automatically lowercased *ngFor to *ngfor on copy&paste.

Delete commit on gitlab

We've had similar problem and it was not enough to only remove commit and force push to GitLab.
It was still available in GitLab interface using url:

https://gitlab.example.com/<group>/<project>/commit/<commit hash>

We've had to remove project from GitLab and recreate it to get rid of this commit in GitLab UI.

How to fix missing dependency warning when using useEffect React Hook?

The solution is also given by react, they advice you use useCallback which will return a memoize version of your function :

The 'fetchBusinesses' function makes the dependencies of useEffect Hook (at line NN) change on every render. To fix this, wrap the 'fetchBusinesses' definition into its own useCallback() Hook react-hooks/exhaustive-deps

useCallback is simple to use as it has the same signature as useEffect the difference is that useCallback returns a function. It would look like this :

 const fetchBusinesses = useCallback( () => {
        return fetch("theURL", {method: "GET"}
    )
    .then(() => { /* some stuff */ })
    .catch(() => { /* some error handling */ })
  }, [/* deps */])
  // We have a first effect thant uses fetchBusinesses
  useEffect(() => {
    // do things and then fetchBusinesses
    fetchBusinesses(); 
  }, [fetchBusinesses]);
   // We can have many effect thant uses fetchBusinesses
  useEffect(() => {
    // do other things and then fetchBusinesses
    fetchBusinesses();
  }, [fetchBusinesses]);

Android: How to rotate a bitmap on a center point

Look at the sample from Google called Lunar Lander, the ship image there is rotated dynamically.

Lunar Lander code sample

Swift: Sort array of objects alphabetically

*import Foundation
import CoreData


extension Messages {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Messages> {
        return NSFetchRequest<Messages>(entityName: "Messages")
    }

    @NSManaged public var text: String?
    @NSManaged public var date: Date?
    @NSManaged public var friends: Friends?

}

    //here arrMessage is the array you can sort this array as under bellow 

    var arrMessages = [Messages]()

    arrMessages.sort { (arrMessages1, arrMessages2) -> Bool in
               arrMessages1.date! > arrMessages2.date!
    }*

PHP 5.4 Call-time pass-by-reference - Easy fix available?

PHP and references are somewhat unintuitive. If used appropriately references in the right places can provide large performance improvements or avoid very ugly workarounds and unusual code.

The following will produce an error:

 function f(&$v){$v = true;}
 f(&$v);

 function f($v){$v = true;}
 f(&$v);

None of these have to fail as they could follow the rules below but have no doubt been removed or disabled to prevent a lot of legacy confusion.

If they did work, both involve a redundant conversion to reference and the second also involves a redundant conversion back to a scoped contained variable.

The second one used to be possible allowing a reference to be passed to code that wasn't intended to work with references. This is extremely ugly for maintainability.

This will do nothing:

 function f($v){$v = true;}
 $r = &$v;
 f($r);

More specifically, it turns the reference back into a normal variable as you have not asked for a reference.

This will work:

 function f(&$v){$v = true;}
 f($v);

This sees that you are passing a non-reference but want a reference so turns it into a reference.

What this means is that you can't pass a reference to a function where a reference is not explicitly asked for making it one of the few areas where PHP is strict on passing types or in this case more of a meta type.

If you need more dynamic behaviour this will work:

 function f(&$v){$v = true;}
 $v = array(false,false,false);
 $r = &$v[1];
 f($r);

Here it sees that you want a reference and already have a reference so leaves it alone. It may also chain the reference but I doubt this.

Get Substring between two characters using javascript

var str = '[basic_salary]+100/[basic_salary]';
var arr = str.split('');
var myArr = [];
for(var i=0;i<arr.length;i++){
    if(arr[i] == '['){
        var a = '';
        for(var j=i+1;j<arr.length;j++){
            if(arr[j] == ']'){
                var i = j-1;
                break;
            }else{
                a += arr[j];
            }
        }
        myArr.push(a);
    }
    var operatorsArr = ['+','-','*','/','%'];
    if(operatorsArr.includes(arr[i])){
        myArr.push(arr[i]);
    }
    var numbArr = ['0','1','2','3','4','5','6','7','8','9'];
    if(numbArr.includes(arr[i])){
        var a = '';
        for(var j=i;j<arr.length;j++){
            if(numbArr.includes(arr[j])){
                a += arr[j];
            }else{
                var i = j-1;
                break;
            }
        }
        myArr.push(a);
    }
}
myArr = ["basic_salary", "+", "100", "/", "basic_salary"]

best way to get the key of a key/value javascript object

Well $.each is a library construct, whereas for ... in is native js, which should be better

Cross-thread operation not valid: Control accessed from a thread other than the thread it was created on

As per Prerak K's update comment (since deleted):

I guess I have not presented the question properly.

Situation is this: I want to load data into a global variable based on the value of a control. I don't want to change the value of a control from the child thread. I'm not going to do it ever from a child thread.

So only accessing the value so that corresponding data can be fetched from the database.

The solution you want then should look like:

UserContrl1_LOadDataMethod()
{
    string name = "";
    if(textbox1.InvokeRequired)
    {
        textbox1.Invoke(new MethodInvoker(delegate { name = textbox1.text; }));
    }
    if(name == "MyName")
    {
        // do whatever
    }
}

Do your serious processing in the separate thread before you attempt to switch back to the control's thread. For example:

UserContrl1_LOadDataMethod()
{
    if(textbox1.text=="MyName") //<<======Now it wont give exception**
    {
        //Load data correspondin to "MyName"
        //Populate a globale variable List<string> which will be
        //bound to grid at some later stage
        if(InvokeRequired)
        {
            // after we've done all the processing, 
            this.Invoke(new MethodInvoker(delegate {
                // load the control with the appropriate data
            }));
            return;
        }
    }
}

Call parent method from child class c#

Found the solution.

In the parent I declare a new instance of the ChildClass() then bind the event handler in that class to the local method in the parent

In the child class I add a public event handler:

public EventHandler UpdateProgress;

In the parent I create a new instance of this child class then bind the local parent event to the public eventhandler in the child

ChildClass child = new ChildClass();
child.UpdateProgress += this.MyMethod;
child.LoadData(this.MyDataTable);

Then in the LoadData() of the child class I can call

private LoadData() {
    this.OnMyMethod();
}

Where OnMyMethod is:

public void OnMyMethod()
{
     // has the event handler been assigned?
     if (this.UpdateProgress!= null)
     {
         // raise the event
         this.UpdateProgress(this, new EventArgs());
     }
}

This runs the event in the parent class

git undo all uncommitted or unsaved changes

I'm using source tree.... You can do revert all uncommitted changes with 2 easy steps:

1) just need to reset the workspace file status

enter image description here 2) select all unstage files (command +a), right click and select remove

enter image description here

It's that simple :D

Cannot implicitly convert type 'int?' to 'int'.

Int32 OrdersPerHour = 0;
OrdersPerHour = Convert.ToInt32(dbcommand.ExecuteScalar());

How do I decode a base64 encoded string?

The m000493 method seems to perform some kind of XOR encryption. This means that the same method can be used for both encrypting and decrypting the text. All you have to do is reverse m0001cd:

string p0 = Encoding.UTF8.GetString(Convert.FromBase64String("OBFZDT..."));

string result = m000493(p0, "_p0lizei.");
//    result == "gaia^unplugged^Ta..."

with return m0001cd(builder3.ToString()); changed to return builder3.ToString();.

Error:Cause: unable to find valid certification path to requested target

I got the same issue and I fixed it by changing my firewall setting or you can switch to another network

reasons behind it

when we are running our project run command its configure and check for exiting packages and make proceed to download the new or required package and the packages are stored on non-secure IP/hosting so your firewall will try to protect you and you will get these errors

How to correctly use Html.ActionLink with ASP.NET MVC 4 Areas

Just to add up my bit:
Remember, you're gonna need to have at least 2 areas in your MVC application to get the routeValues: { area="" } working; otherwise the area value will be used as a query-string parameter and you link will look like this: /?area=

If you don't have at least 2 areas, you can fix this behavior by:
1. editing the default route in RouteConfig.cs like this:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { area = "", controller = "Home", action = "Index", id = UrlParameter.Optional }
);

OR
2. Adding a dummy area to your MVC project.