Programs & Examples On #Simplehttpserver

SimpleHTTPServer refers to the basic HTTP server which can serve requests with files from the file system with a few lines of code. http://docs.python.org/library/simplehttpserver.html

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

The equivalent is:

python3 -m http.server

socket.error: [Errno 48] Address already in use

By the way, to prevent this from happening in the first place, simply press Ctrl+C in terminal while SimpleHTTPServer is still running normally. This will "properly" stop the server and release the port so you don't have to find and kill the process again before restarting the server.

(Mods: I did try to put this comment on the best answer where it belongs, but I don't have enough reputation.)

Set up Python simpleHTTPserver on Windows

From Stack Overflow question What is the Python 3 equivalent of "python -m SimpleHTTPServer":

The following works for me:

python -m http.server [<portNo>]

Because I am using Python 3 the module SimpleHTTPServer has been replaced by http.server, at least in Windows.

How do I shut down a python simpleHTTPserver?

It seems like overkill but you can use supervisor to start and stop your simpleHttpserver, and completely manage it as a service.

Or just run it in the foreground as suggested and kill it with control c

What is a faster alternative to Python's http.server (or SimpleHTTPServer)?

I recommend: Twisted (http://twistedmatrix.com)

an event-driven networking engine written in Python and licensed under the open source MIT license.

It's cross-platform and was preinstalled on OS X 10.5 to 10.12. Amongst other things you can start up a simple web server in the current directory with:

twistd -no web --path=.

Details

Explanation of Options (see twistd --help for more):

-n, --nodaemon       don't daemonize, don't use default umask of 0077
-o, --no_save        do not save state on shutdown

"web" is a Command that runs a simple web server on top of the Twisted async engine. It also accepts command line options (after the "web" command - see twistd web --help for more):

  --path=             <path> is either a specific file or a directory to be
                      set as the root of the web server. Use this if you
                      have a directory full of HTML, cgi, php3, epy, or rpy
                      files or any other files that you want to be served up
                      raw.

There are also a bunch of other commands such as:

conch            A Conch SSH service.
dns              A domain name server.
ftp              An FTP server.
inetd            An inetd(8) replacement.
mail             An email service
... etc

Installation

Ubuntu

sudo apt-get install python-twisted-web (or python-twisted for the full engine)

Mac OS-X (comes preinstalled on 10.5 - 10.12, or is available in MacPorts and through Pip)

sudo port install py-twisted

Windows

installer available for download at http://twistedmatrix.com/

HTTPS

Twisted can also utilise security certificates to encrypt the connection. Use this with your existing --path and --port (for plain HTTP) options.

twistd -no web -c cert.pem -k privkey.pem --https=4433

Placeholder Mixin SCSS/CSS

Why not something like this?

It uses a combination of lists, iteration, and interpolation.

@mixin placeholder ($rules) {

  @each $rule in $rules {
    ::-webkit-input-placeholder,
    :-moz-placeholder,
    ::-moz-placeholder,
    :-ms-input-placeholder {
      #{nth($rule, 1)}: #{nth($rule, 2)};
    }  
  }
}

$rules: (('border', '1px solid red'),
         ('color', 'green'));

@include placeholder( $rules );

How can I get a user's media from Instagram without authenticating as a user?

The Instagram API requires user authentication through OAuth to access the recent media endpoint for a user. There doesn't appear to be any other way right now to get all media for a user.

Can I use CASE statement in a JOIN condition?

Yes, you can. Here is an example.

SELECT a.*
FROM TableA a
LEFT OUTER JOIN TableB j1 ON  (CASE WHEN LEN(COALESCE(a.NoBatiment, '')) = 3 
                                THEN RTRIM(a.NoBatiment) + '0' 
                                ELSE a.NoBatiment END ) = j1.ColumnName 

Programmatically switching between tabs within Swift

If your window rootViewController is UITabbarController(which is in most cases) then you can access tabbar in didFinishLaunchingWithOptions in the AppDelegate file.

func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
    // Override point for customization after application launch.

    if let tabBarController = self.window!.rootViewController as? UITabBarController {
        tabBarController.selectedIndex = 1
    }

    return true
}

This will open the tab with the index given (1) in selectedIndex.

If you do this in viewDidLoad of your firstViewController, you need to manage by flag or another way to keep track of the selected tab. The best place to do this in didFinishLaunchingWithOptions of your AppDelegate file or rootViewController custom class viewDidLoad.

How to change a TextView's style at runtime

Depending on which style you want to set, you have to use different methods. TextAppearance stuff has its own setter, TypeFace has its own setter, background has its own setter, etc.

How do I increase modal width in Angular UI Bootstrap?

You can specify custom width for .modal-lg class specifically for your popup for wider viewport resolution. Here is how to do it:

CSS:

@media (min-width: 1400px){

   .my-modal-popup .modal-lg {
       width: 1308px;
   }       

}

JS:

var modal = $modal.open({
    animation: true,
    templateUrl: 'modalTemplate.html',
    controller: 'modalController',
    size: 'lg',
    windowClass: 'my-modal-popup'
});

Plot smooth line with PyPlot

For this example spline works well, but if the function is not smooth inherently and you want to have smoothed version you can also try:

from scipy.ndimage.filters import gaussian_filter1d

ysmoothed = gaussian_filter1d(y, sigma=2)
plt.plot(x, ysmoothed)
plt.show()

if you increase sigma you can get a more smoothed function.

Proceed with caution with this one. It modifies the original values and may not be what you want.

Circular dependency in Spring

If you generally use constructor-injection and don't want to switch to property-injection then Spring's lookup-method-injection will let one bean lazily lookup the other and hence workaround the cyclic dependency. See here: http://docs.spring.io/spring/docs/1.2.9/reference/beans.html#d0e1161

JavaScript: IIF like statement

I typed this in my URL bar:

javascript:{ var col = 'screwdriver'; var x = '<option value="' + col + '"' + ((col == 'screwdriver') ? ' selected' : '') + '>Very roomy</option>'; alert(x); }

C++ Matrix Class

nota bene.

This answer has 20 upvotes now, but it is not intended as an endorsement of std::valarray.

In my experience, time is better spent installing and learning to use a full-fledged math library such as Eigen. Valarray has fewer features than the competition, but it isn't more efficient or particularly easier to use.

If you only need a little bit of linear algebra, and you are dead-set against adding anything to your toolchain, then maybe valarray would fit. But, being stuck unable to express the mathematically correct solution to your problem is a very bad position to be in. Math is relentless and unforgiving. Use the right tool for the job.


The standard library provides std::valarray<double>. std::vector<>, suggested by a few others here, is intended as a general-purpose container for objects. valarray, lesser known because it is more specialized (not using "specialized" as the C++ term), has several advantages:

  • It does not allocate extra space. A vector rounds up to the nearest power of two when allocating, so you can resize it without reallocating every time. (You can still resize a valarray; it's just still as expensive as realloc().)
  • You may slice it to access rows and columns easily.
  • Arithmetic operators work as you would expect.

Of course, the advantage over using C is that you don't need to manage memory. The dimensions can reside on the stack, or in a slice object.

std::valarray<double> matrix( row * col ); // no more, no less, than a matrix
matrix[ std::slice( 2, col, row ) ] = pi; // set third column to pi
matrix[ std::slice( 3*row, row, 1 ) ] = e; // set fourth row to e

PHP: cannot declare class because the name is already in use

You should use require_once and include_once. Inside parent.php use

include_once 'database.php';

And inside child1.php and child2.php use

include_once 'parent.php';

var functionName = function() {} vs function functionName() {}

The var functionOne = function() {} defines at run-time and the function functionTwo() {} defines at parse-time.

// Run-Time function declaration 
functionOne(); // Calling functionOne function here will give an Error
var functionOne = function () {
  // Some code
};

// Parse-Time function declaration 
functionTwo(); // Calling functionTwo function will not give an Error
function functionTwo() {
  // Some code...
}

The explanation between Run-time vs Parse-time javascript run-time vs parse-time

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

The import org.apache.commons cannot be resolved in eclipse juno

Look for "poi-3.17.jar"!!!

  1. Download from "https://poi.apache.org/download.html".
  2. Click the one Binary Distribution -> poi-bin-3.17-20170915.tar.gz
  3. Unzip the file download and look for this "poi-3.17.jar".

Problem solved and errors disappeared.

Difference between `Optional.orElse()` and `Optional.orElseGet()`

Short Answer:

  • orElse() will always call the given function whether you want it or not, regardless of Optional.isPresent() value
  • orElseGet() will only call the given function when the Optional.isPresent() == false

In real code, you might want to consider the second approach when the required resource is expensive to get.

// Always get heavy resource
getResource(resourceId).orElse(getHeavyResource()); 

// Get heavy resource when required.
getResource(resourceId).orElseGet(() -> getHeavyResource()) 

For more details, consider the following example with this function:

public Optional<String> findMyPhone(int phoneId)

The difference is as below:

                           X : buyNewExpensivePhone() called

+——————————————————————————————————————————————————————————————————+——————————————+
|           Optional.isPresent()                                   | true | false |
+——————————————————————————————————————————————————————————————————+——————————————+
| findMyPhone(int phoneId).orElse(buyNewExpensivePhone())          |   X  |   X   |
+——————————————————————————————————————————————————————————————————+——————————————+
| findMyPhone(int phoneId).orElseGet(() -> buyNewExpensivePhone()) |      |   X   |
+——————————————————————————————————————————————————————————————————+——————————————+

When optional.isPresent() == false, there is no difference between two ways. However, when optional.isPresent() == true, orElse() always calls the subsequent function whether you want it or not.

Finally, the test case used is as below:

Result:

------------- Scenario 1 - orElse() --------------------
  1.1. Optional.isPresent() == true (Redundant call)
    Going to a very far store to buy a new expensive phone
    Used phone: MyCheapPhone

  1.2. Optional.isPresent() == false
    Going to a very far store to buy a new expensive phone
    Used phone: NewExpensivePhone

------------- Scenario 2 - orElseGet() --------------------
  2.1. Optional.isPresent() == true
    Used phone: MyCheapPhone

  2.2. Optional.isPresent() == false
    Going to a very far store to buy a new expensive phone
    Used phone: NewExpensivePhone

Code:

public class TestOptional {
    public Optional<String> findMyPhone(int phoneId) {
        return phoneId == 10
                ? Optional.of("MyCheapPhone")
                : Optional.empty();
    }

    public String buyNewExpensivePhone() {
        System.out.println("\tGoing to a very far store to buy a new expensive phone");
        return "NewExpensivePhone";
    }


    public static void main(String[] args) {
        TestOptional test = new TestOptional();
        String phone;
        System.out.println("------------- Scenario 1 - orElse() --------------------");
        System.out.println("  1.1. Optional.isPresent() == true (Redundant call)");
        phone = test.findMyPhone(10).orElse(test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");

        System.out.println("  1.2. Optional.isPresent() == false");
        phone = test.findMyPhone(-1).orElse(test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");

        System.out.println("------------- Scenario 2 - orElseGet() --------------------");
        System.out.println("  2.1. Optional.isPresent() == true");
        // Can be written as test::buyNewExpensivePhone
        phone = test.findMyPhone(10).orElseGet(() -> test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");

        System.out.println("  2.2. Optional.isPresent() == false");
        phone = test.findMyPhone(-1).orElseGet(() -> test.buyNewExpensivePhone());
        System.out.println("\tUsed phone: " + phone + "\n");
    }
}

What does "hard coded" mean?

The antonym of Hard-Coding is Soft-Coding. For a better understanding of Hard Coding, I will introduce both terms.

  • Hard-coding: feature is coded to the system not allowing for configuration;
  • Parametric: feature is configurable via table driven, or properties files with limited parametric values ;
  • Soft-coding: feature uses “engines” that derive results based on any number of parametric values (e.g. business rules in BRE); rules are coded but exist as parameters in system, written in script form

Examples:

// firstName has a hard-coded value of "hello world"
string firstName = "hello world";

// firstName has a non-hard-coded provided as input
Console.WriteLine("first name :");
string firstName = Console.ReadLine();

A hard-coded constant[1]:

float areaOfCircle(int radius)
{
    float area = 0;
    area = 3.14*radius*radius;  //  3.14 is a hard-coded value
    return area;
}

Additionally, hard-coding and soft-coding could be considered to be anti-patterns[2]. Thus, one should strive for balance between hard and soft-coding.

  1. Hard CodingHard coding” is a well-known antipattern against which most web development books warns us right in the preface. Hard coding is the unfortunate practice in which we store configuration or input data, such as a file path or a remote host name, in the source code rather than obtaining it from a configuration file, a database, a user input, or another external source.

    The main problem with hard code is that it only works properly in a certain environment, and at any time the conditions change, we need to modify the source code, usually in multiple separate places.

  2. Soft Coding
    If we try very hard to avoid the pitfall of hard coding, we can easily run into another antipattern called “soft coding”, which is its exact opposite.

    In soft coding, we put things that should be in the source code into external sources, for example we store business logic in the database. The most common reason why we do so, is the fear that business rules will change in the future, therefore we will need to rewrite the code.

    In extreme cases, a soft coded program can become so abstract and convoluted that it is almost impossible to comprehend it (especially for new team members), and extremely hard to maintain and debug.

Sources and Citations:

1: Quora: What does hard-coded something mean in computer programming context?
2: Hongkiat: The 10 Coding Antipatterns You Must Avoid

Further Reading:

Software Engineering SE: Is it ever a good idea to hardcode values into our applications?
Wikipedia: Hardcoding
Wikipedia: Soft-coding

How to allow access outside localhost

  • Use ng serve --host<Your IP> --port<Required if any>.

  • ng serve --host=192.111.1.11 --port=4545.

  • You can now see the below line at the end of compilation.

Angular Live Development Server is listening on 192.111.1.11:4545, open your browser on http://192.111.1.11:4545/ **.

Iterating through map in template

Check the Variables section in the Go template docs. A range may declare two variables, separated by a comma. The following should work:

{{ range $key, $value := . }}
   <li><strong>{{ $key }}</strong>: {{ $value }}</li>
{{ end }}

jquery ajax get responsetext from http url

You simply must rewrite it like that:

var response = '';
$.ajax({ type: "GET",   
         url: "http://www.google.de",   
         async: false,
         success : function(text)
         {
             response = text;
         }
});

alert(response);

How to edit default.aspx on SharePoint site without SharePoint Designer

Go to view all content of the site (http://yourdmain.sharepoint/sitename/_layouts/viewlsts.aspx). Select the document library "Pages" (the "Pages" library are named based on the language you created the site in. I.E. in norwegian the library is named "Sider"). Download the default.aspx to you computer and fix it (remove the web part and the <%Register tag). Save it and upload it back to the library (remember to check in the file).

EDIT:

ahh.. you are not using a publishing site template. Go to site action -> site settings. Under "site administration" select the menu "content and structure" you should now see your default.aspx page. But you cant do much with it...(delete, copy or move)

workaround: Enable publishing feature to the root web. Add the fixed default.aspx file to the Pages library and change the welcome page to this. Disable the publishing feature (this will delete all other list create from this feature but not the Pages library since one page is in use.). You will now have a new default.aspx page for the root web but the url is changed from sitename/default.aspx to sitename/Pages/default.aspx.

workaround II Use a feature to change the default.aspx file. The solution is explained here: http://wssguy.com/blogs/dan/archive/2008/10/29/how-to-change-the-default-page-of-a-sharepoint-site-using-a-feature.aspx

How can I iterate JSONObject to get individual items

How about this?

JSONObject jsonObject = new JSONObject           (YOUR_JSON_STRING);
JSONObject ipinfo     = jsonObject.getJSONObject ("ipinfo");
String     ip_address = ipinfo.getString         ("ip_address");
JSONObject location   = ipinfo.getJSONObject     ("Location");
String     latitude   = location.getString       ("latitude");
System.out.println (latitude);

This sample code using "org.json.JSONObject"

Visual Studio opens the default browser instead of Internet Explorer

With VS 2017, debugging ASP.NET project with Chrome doesn't sign you in with your Google account.

To fix that go to Tools -> Options -> Debugging -> General and turn off the setting Enable JavaScript Debugging for ASP.NET (Chrome and IE).

https://msdnshared.blob.core.windows.net/media/2016/11/debugger-settings-1024x690.png

How do I show the value of a #define at compile-time?

If you are using Visual C++, you can use #pragma message:

#include <boost/preprocessor/stringize.hpp>
#pragma message("BOOST_VERSION=" BOOST_PP_STRINGIZE(BOOST_VERSION))

Edit: Thanks to LB for link

Apparently, the GCC equivalent is (not tested):

#pragma message "BOOST_VERSION=" BOOST_PP_STRINGIZE(BOOST_VERSION)

Open existing file, append a single line

using (StreamWriter w = File.AppendText("myFile.txt"))
{
  w.WriteLine("hello");
}

java.lang.NoClassDefFoundError: org/hamcrest/SelfDescribing

The problem is when you set up eclipse to point to JRE instead of JDK. JRE has junit4.jar in the lib/ext folder, but not hamcrest.jar :) So the solution is to check installed JREs in Eclipse, remove the existing one and create a new one pointing to your JDK.

What is the correct way to restore a deleted file from SVN?

If you're using Tortoise SVN, you should be able to revert changes from just that revision into your working copy (effectively performing a reverse-merge), then do another commit to re-add the file. Steps to follow are:

  1. Browse to folder in working copy where you deleted the file.
  2. Go to repo-browser.
  3. Browse to revision where you deleted the file.
  4. In the change list, find the file you deleted.
  5. Right click on the file and go to "Revert changes from this revision".
  6. This will restore the file to your working copy, keeping history.
  7. Commit the file to add it back into your repository.

java.lang.OutOfMemoryError: bitmap size exceeds VM budget - Android

It sounds like you have a memory leak. The problem isn't handling many images, it's that your images aren't getting deallocated when your activity is destroyed.

It's difficult to say why this is without looking at your code. However, this article has some tips that might help:

http://android-developers.blogspot.de/2009/01/avoiding-memory-leaks.html

In particular, using static variables is likely to make things worse, not better. You might need to add code that removes callbacks when your application redraws -- but again, there's not enough information here to say for sure.

What is the difference between _tmain() and main() in C++?

the _T convention is used to indicate the program should use the character set defined for the application (Unicode, ASCII, MBCS, etc.). You can surround your strings with _T( ) to have them stored in the correct format.

 cout << _T( "There are " ) << argc << _T( " arguments:" ) << endl;

Increase bootstrap dropdown menu width

You can for example just add a "col-xs-12" class to the <ul> which holds the list items:

<div class="col-md-6" data-toggle="dropdown">
            First column
            <ul class="dropdown-menu col-xs-12" role="menu" aria-labelledby="dLabel">
                <li>Insert your menus here</li>
                <li>Insert your menus here</li>
                <li>Insert your menus here</li>
                <li>Insert your menus here</li>
                <li>Insert your menus here</li>
                <li>Insert your menus here</li>
            </ul>
        </div>

This worked ok on any screen resolution in my site. The class will match the list width to it's containing div I believe:

enter image description here

Java Command line arguments

Try to pass value a and compare using the equals method like this:

public static void main(String str[]) {

    boolean b = str[0].equals("a");

    System.out.println(b);

}

Follow this link to know more about Command line argument in Java

Background thread with QThread in PyQt

Very nice example from Matt, I fixed the typo and also pyqt4.8 is common now so I removed the dummy class as well and added an example for the dataReady signal

# -*- coding: utf-8 -*-
import sys
from PyQt4 import QtCore, QtGui
from PyQt4.QtCore import Qt


# very testable class (hint: you can use mock.Mock for the signals)
class Worker(QtCore.QObject):
    finished = QtCore.pyqtSignal()
    dataReady = QtCore.pyqtSignal(list, dict)

    @QtCore.pyqtSlot()
    def processA(self):
        print "Worker.processA()"
        self.finished.emit()

    @QtCore.pyqtSlot(str, list, list)
    def processB(self, foo, bar=None, baz=None):
        print "Worker.processB()"
        for thing in bar:
            # lots of processing...
            self.dataReady.emit(['dummy', 'data'], {'dummy': ['data']})
        self.finished.emit()


def onDataReady(aList, aDict):
    print 'onDataReady'
    print repr(aList)
    print repr(aDict)


app = QtGui.QApplication(sys.argv)

thread = QtCore.QThread()  # no parent!
obj = Worker()  # no parent!
obj.dataReady.connect(onDataReady)

obj.moveToThread(thread)

# if you want the thread to stop after the worker is done
# you can always call thread.start() again later
obj.finished.connect(thread.quit)

# one way to do it is to start processing as soon as the thread starts
# this is okay in some cases... but makes it harder to send data to
# the worker object from the main gui thread.  As you can see I'm calling
# processA() which takes no arguments
thread.started.connect(obj.processA)
thread.finished.connect(app.exit)

thread.start()

# another way to do it, which is a bit fancier, allows you to talk back and
# forth with the object in a thread safe way by communicating through signals
# and slots (now that the thread is running I can start calling methods on
# the worker object)
QtCore.QMetaObject.invokeMethod(obj, 'processB', Qt.QueuedConnection,
                                QtCore.Q_ARG(str, "Hello World!"),
                                QtCore.Q_ARG(list, ["args", 0, 1]),
                                QtCore.Q_ARG(list, []))

# that looks a bit scary, but its a totally ok thing to do in Qt,
# we're simply using the system that Signals and Slots are built on top of,
# the QMetaObject, to make it act like we safely emitted a signal for
# the worker thread to pick up when its event loop resumes (so if its doing
# a bunch of work you can call this method 10 times and it will just queue
# up the calls.  Note: PyQt > 4.6 will not allow you to pass in a None
# instead of an empty list, it has stricter type checking

app.exec_()

Align inline-block DIVs to top of container element

<style type="text/css">
        div {
  text-align: center;
         }

         .img1{
            width: 150px;
            height: 150px;
            border-radius: 50%;
         }

         span{
            display: block;
         }
    </style>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type='password' class='secondInput mt-4 mr-1' placeholder="Password">
  <span class='dif'></span>
  <br>
  <button>ADD</button>
</div>

<script type="text/javascript">

$('button').click(function() {
  $('.dif').html("<img/>");

})

failed to load ad : 3

There is one option which helped in our case. As @blizzard mentioned in your application settings in Google Developer Console there is a section which called "Pricing and Distribution". In this section there is a checkbox "CONTAINS ADS". In our case it was disabled. After enabling we successfully received ads.

enter image description here

Java division by zero doesnt throw an ArithmeticException - why?

Why can't you just check it yourself and throw an exception if that is what you want.

    try {
        for (int i = 0; i < tab.length; i++) {
            tab[i] = 1.0 / tab[i];

            if (tab[i] == Double.POSITIVE_INFINITY ||
                    tab[i] == Double.NEGATIVE_INFINITY)
                throw new ArithmeticException();
        }
    } catch (ArithmeticException ae) {
        System.out.println("ArithmeticException occured!");
    }

How do a LDAP search/authenticate against this LDAP in Java

Another approach is using UnboundID. Its api is very readable and shorter

Create a Ldap Connection

public static LDAPConnection getConnection() throws LDAPException {
    // host, port, username and password
    return new LDAPConnection("com.example.local", 389, "[email protected]", "admin");
}

Get filter result

public static List<SearchResultEntry> getResults(LDAPConnection connection, String baseDN, String filter) throws LDAPSearchException {
    SearchResult searchResult;

    if (connection.isConnected()) {
        searchResult = connection.search(baseDN, SearchScope.ONE, filter);

        return searchResult.getSearchEntries();
    }

    return null;
}

Get all Oragnization Units and Containers

String baseDN = "DC=com,DC=example,DC=local";
String filter = "(&(|(objectClass=organizationalUnit)(objectClass=container)))";

LDAPConnection connection = getConnection();        
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific Organization Unit

String baseDN = "DC=com,DC=example,DC=local";
String dn = "CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(|(objectClass=organizationalUnit)(objectClass=container))(distinguishedName=%s))";
String filter = String.format(filterFormat, dn);

LDAPConnection connection =  getConnection();

List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get all users under an Organizational Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String filter = "(&(objectClass=user)(!(objectCategory=computer)))";

LDAPConnection connection =  getConnection();       
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Get a specific user under an Organization Unit

String baseDN = "CN=Users,DC=com,DC=example,DC=local";
String userDN = "CN=abc,CN=Users,DC=com,DC=example,DC=local";

String filterFormat = "(&(objectClass=user)(distinguishedName=%s))";
String filter = String.format(filterFormat, userDN);

LDAPConnection connection =  getConnection();
List<SearchResultEntry> results = getResults(connection, baseDN, filter);

Display result

for (SearchResultEntry e : results) {
    System.out.println("name: " + e.getAttributeValue("name"));
}

T-SQL loop over query results

DECLARE @id INT
DECLARE @filename NVARCHAR(100)
DECLARE @getid CURSOR

SET @getid = CURSOR FOR
SELECT top 3 id,
filename 
FROM  table

OPEN @getid
WHILE 1=1
BEGIN

    FETCH NEXT
    FROM @getid INTO @id, @filename
    IF @@FETCH_STATUS < 0 BREAK

    print @id

END


CLOSE @getid
DEALLOCATE @getid

How does strtok() split the string into tokens in C?

For those who are still having hard time understanding this strtok() function, take a look at this pythontutor example, it is a great tool to visualize your C (or C++, Python ...) code.

In case the link got broken, paste in:

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

int main()
{
    char s[] = "Hello, my name is? Matthew! Hey.";
    char* p;
    for (char *p = strtok(s," ,?!."); p != NULL; p = strtok(NULL, " ,?!.")) {
      puts(p);
    }
    return 0;
}

Credits go to Anders K.

How to initailize byte array of 100 bytes in java with all 0's

Simply create it as new byte[100] it will be initialized with 0 by default

JComboBox Selection Change Listener?

I would try the itemStateChanged() method of the ItemListener interface if jodonnell's solution fails.

Numpy: Checking if a value is NaT

Since NumPy version 1.13 it contains an isnat function:

>>> import numpy as np
>>> np.isnat(np.datetime64('nat'))
True

It also works for arrays:

>>> np.isnat(np.array(['nat', 1, 2, 3, 4, 'nat', 5], dtype='datetime64[D]'))
array([ True, False, False, False, False,  True, False], dtype=bool)

How to Change Margin of TextView

Your layout in xml probably already has a layout_margin(Left|Right|etc) attribute in it, which means you need to access the object generated by that xml and modify it.

I found this solution to be very simple:

ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) mTextView
        .getLayoutParams();

mlp.setMargins(adjustmentPxs, 0, 0, 0);

break;

Get the LayoutParams instance of your textview, downcast it to MarginLayoutParams, and use the setMargins method to set the margins.

Reading in double values with scanf in c

Use this line of code when scanning the second value: scanf(" %lf", &b); also replace all %ld with %lf.

It's a problem related with input stream buffer. You can also use fflush(stdin); after the first scanning to clear the input buffer and then the second scanf will work as expected. An alternate way is place a getch(); or getchar(); function after the first scanf line.

Difference between logger.info and logger.debug

  1. INFO is used to log the information your program is working as expected.
  2. DEBUG is used to find the reason in case your program is not working as expected or an exception has occurred. it's in the interest of the developer.

Passing an array by reference in C?

To expand a little bit on some of the answers here...

In C, when an array identifier appears in a context other than as an operand to either & or sizeof, the type of the identifier is implicitly converted from "N-element array of T" to "pointer to T", and its value is implicitly set to the address of the first element in the array (which is the same as the address of the array itself). That's why when you just pass the array identifier as an argument to a function, the function receives a pointer to the base type, rather than an array. Since you can't tell how big an array is just by looking at the pointer to the first element, you have to pass the size in as a separate parameter.

struct Coordinate { int x; int y; };
void SomeMethod(struct Coordinate *coordinates, size_t numCoordinates)
{
    ...
    coordinates[i].x = ...;
    coordinates[i].y = ...; 
    ...
}
int main (void)
{
    struct Coordinate coordinates[10];
    ...
    SomeMethod (coordinates, sizeof coordinates / sizeof *coordinates);
    ...
}

There are a couple of alternate ways of passing arrays to functions.

There is such a thing as a pointer to an array of T, as opposed to a pointer to T. You would declare such a pointer as

T (*p)[N];

In this case, p is a pointer to an N-element array of T (as opposed to T *p[N], where p is an N-element array of pointer to T). So you could pass a pointer to the array as opposed to a pointer to the first element:

struct Coordinate { int x; int y };

void SomeMethod(struct Coordinate (*coordinates)[10])
{
    ...
    (*coordinates)[i].x = ...;
    (*coordinates)[i].y = ...;
    ...
}

int main(void)
{
    struct Coordinate coordinates[10];
    ...
    SomeMethod(&coordinates);
    ...
}

The disadvantage of this method is that the array size is fixed, since a pointer to a 10-element array of T is a different type from a pointer to a 20-element array of T.

A third method is to wrap the array in a struct:

struct Coordinate { int x; int y; };
struct CoordinateWrapper { struct Coordinate coordinates[10]; };
void SomeMethod(struct CoordinateWrapper wrapper)
{
    ...
    wrapper.coordinates[i].x = ...;
    wrapper.coordinates[i].y = ...;
    ...
}
int main(void)
{
    struct CoordinateWrapper wrapper;
    ...
    SomeMethod(wrapper);
    ...
}

The advantage of this method is that you aren't mucking around with pointers. The disadvantage is that the array size is fixed (again, a 10-element array of T is a different type from a 20-element array of T).

Windows service on Local Computer started and then stopped error

Not sure this will be helpful, but for debugging a service you could always use the following in the OnStart method:

protected override void OnStart(string[] args)
{
     System.Diagnostics.Debugger.Launch();
     ...
}

than you could attach your visual studio to the process and have better debug abilities.

hope this was helpful, good luck

Creating Scheduled Tasks

This works for me https://www.nuget.org/packages/ASquare.WindowsTaskScheduler/

It is nicely designed Fluent API.

//This will create Daily trigger to run every 10 minutes for a duration of 18 hours
SchedulerResponse response = WindowTaskScheduler
    .Configure()
    .CreateTask("TaskName", "C:\\Test.bat")
    .RunDaily()
    .RunEveryXMinutes(10)
    .RunDurationFor(new TimeSpan(18, 0, 0))
    .SetStartDate(new DateTime(2015, 8, 8))
    .SetStartTime(new TimeSpan(8, 0, 0))
    .Execute();

Delete all rows in an HTML table

I needed to delete all rows except the first and solution posted by @strat but that resulted in uncaught exception (referencing Node in context where it does not exist). The following worked for me.

var myTable = document.getElementById("myTable");
var rowCount = myTable.rows.length;
for (var x=rowCount-1; x>0; x--) {
   myTable.deleteRow(x);
}

How to automatically import data from uploaded CSV or XLS file into Google Sheets

You can get Google Drive to automatically convert csv files to Google Sheets by appending

?convert=true

to the end of the api url you are calling.

EDIT: Here is the documentation on available parameters: https://developers.google.com/drive/v2/reference/files/insert

Also, while searching for the above link, I found this question has already been answered here:

Upload CSV to Google Drive Spreadsheet using Drive v2 API

Get immediate first child element

Both these will give you the first child node:

console.log(parentElement.firstChild); // or
console.log(parentElement.childNodes[0]);

If you need the first child that is an element node then use:

console.log(parentElement.children[0]);

Edit

Ah, I see your problem now; parentElement is an array.

If you know that getElementsByClassName will only return one result, which it seems you do, you should use [0] to dearray (yes, I made that word up) the element:

var parentElement = document.getElementsByClassName("uniqueClassName")[0];

Angular-cli from css to scss

For Angular 6 check the Official documentation

Note: For @angular/cli versions older than 6.0.0-beta.6 use ng set in place of ng config.

For existing projects

In an existing angular-cli project that was set up with the default css styles you will need to do a few things:

  1. Change the default style extension to scss

Manually change in .angular-cli.json (Angular 5.x and older) or angular.json (Angular 6+) or run:

ng config defaults.styleExt=scss

if you get an error: Value cannot be found. use the command:

ng config schematics.@schematics/angular:component.styleext scss

(*source: Angular CLI SASS options)

  1. Rename your existing .css files to .scss (i.e. styles.css and app/app.component.css)

  2. Point the CLI to find styles.scss

Manually change the file extensions in apps[0].styles in angular.json

  1. Point the components to find your new style files

Change the styleUrls in your components to match your new file names

For future projects

As @Serginho mentioned you can set the style extension when running the ng new command

ng new your-project-name --style=scss

If you want to set the default for all projects you create in the future run the following command:

ng config --global defaults.styleExt=scss

Convert Java String to sql.Timestamp

Here's the intended way to convert a String to a Date:

String timestamp = "2011-10-02-18.48.05.123";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd-kk.mm.ss.SSS");
Date parsedDate = df.parse(timestamp);

Admittedly, it only has millisecond resolution, but in all services slower than Twitter, that's all you'll need, especially since most machines don't even track down to the actual nanoseconds.

Javascript replace all "%20" with a space

If you want to use jQuery you can use .replaceAll()

Convert String to Type in C#

Try:

Type type = Type.GetType(inputString); //target type
object o = Activator.CreateInstance(type); // an instance of target type
YourType your = (YourType)o;

Jon Skeet is right as usually :)

Update: You can specify assembly containing target type in various ways, as Jon mentioned, or:

YourType your = (YourType)Activator.CreateInstance("AssemblyName", "NameSpace.MyClass");

parseInt with jQuery

Two issues:

  1. You're passing the jQuery wrapper of the element into parseInt, which isn't what you want, as parseInt will call toString on it and get back "[object Object]". You need to use val or text or something (depending on what the element is) to get the string you want.

  2. You're not telling parseInt what radix (number base) it should use, which puts you at risk of odd input giving you odd results when parseInt guesses which radix to use.

Fix if the element is a form field:

//                               vvvvv-- use val to get the value
var test = parseInt($("#testid").val(), 10);
//                                    ^^^^-- tell parseInt to use decimal (base 10)

Fix if the element is something else and you want to use the text within it:

//                               vvvvvv-- use text to get the text
var test = parseInt($("#testid").text(), 10);
//                                     ^^^^-- tell parseInt to use decimal (base 10)

Doctrine2: Best way to handle many-to-many with extra columns in reference table

While getting all album tracks form inside album class, you'll generate one more query for one more record. That's because of proxy method. There's another example of my code (see last post in topic): http://groups.google.com/group/doctrine-user/browse_thread/thread/d1d87c96052e76f7/436b896e83c10868#436b896e83c10868

Is there any other method to resolve that? Isn't a single join a better solution?

Appending an element to the end of a list in Scala

Lists in Scala are not designed to be modified. In fact, you can't add elements to a Scala List; it's an immutable data structure, like a Java String. What you actually do when you "add an element to a list" in Scala is to create a new List from an existing List. (Source)

Instead of using lists for such use cases, I suggest to either use an ArrayBuffer or a ListBuffer. Those datastructures are designed to have new elements added.

Finally, after all your operations are done, the buffer then can be converted into a list. See the following REPL example:

scala> import scala.collection.mutable.ListBuffer
import scala.collection.mutable.ListBuffer

scala> var fruits = new ListBuffer[String]()
fruits: scala.collection.mutable.ListBuffer[String] = ListBuffer()

scala> fruits += "Apple"
res0: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple)

scala> fruits += "Banana"
res1: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana)

scala> fruits += "Orange"
res2: scala.collection.mutable.ListBuffer[String] = ListBuffer(Apple, Banana, Orange)

scala> val fruitsList = fruits.toList
fruitsList: List[String] = List(Apple, Banana, Orange)

How to compare two dates along with time in java

Use compareTo()

Return Values

0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

Like

if(date1.compareTo(date2)>0) 

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

You are using setTimeout wrong way. The (one of) function signature is setTimeout(callback, delay). So you can easily specify what code should be run after what delay.

var codeAddress = (function() {
    var index = 0;
    var delay = 100;

    function GeocodeCallback(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            new google.maps.Marker({ map: map, position: results[0].geometry.location, animation: google.maps.Animation.DROP });
            console.log(results);
        }
        else alert("Geocode was not successful for the following reason: " + status);
    };

    return function(vPostCode) {
        if (geocoder) setTimeout(geocoder.geocode.bind(geocoder, { 'address': "'" + vPostCode + "'"}, GeocodeCallback), index*delay);
        index++;
    };
})();

This way, every codeAddress() call will result in geocoder.geocode() being called 100ms later after previous call.

I also added animation to marker so you will have a nice animation effect with markers being added to map one after another. I'm not sure what is the current google limit, so you may need to increase the value of delay variable.

Also, if you are each time geocoding the same addresses, you should instead save the results of geocode to your db and next time just use those (so you will save some traffic and your application will be a little bit quicker)

What are Runtime.getRuntime().totalMemory() and freeMemory()?

To understand it better, run this following program (in jdk1.7.x) :

$ java -Xms1025k -Xmx1025k -XshowSettings:vm  MemoryTest

This will print jvm options and the used, free, total and maximum memory available in jvm.

public class MemoryTest {    
    public static void main(String args[]) {
                System.out.println("Used Memory   :  " + (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) + " bytes");
                System.out.println("Free Memory   : " + Runtime.getRuntime().freeMemory() + " bytes");
                System.out.println("Total Memory  : " + Runtime.getRuntime().totalMemory() + " bytes");
                System.out.println("Max Memory    : " + Runtime.getRuntime().maxMemory() + " bytes");            
        }
}

Loop through all the rows of a temp table and call a stored procedure for each row

you could use a cursor:

DECLARE @id int
DECLARE @pass varchar(100)

DECLARE cur CURSOR FOR SELECT Id, Password FROM @temp
OPEN cur

FETCH NEXT FROM cur INTO @id, @pass

WHILE @@FETCH_STATUS = 0 BEGIN
    EXEC mysp @id, @pass ... -- call your sp here
    FETCH NEXT FROM cur INTO @id, @pass
END

CLOSE cur    
DEALLOCATE cur

Query to get all rows from previous month

WHERE created_date >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY) 
  AND created_date <= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH)), INTERVAL 0 DAY) 

This worked for me (Selects all records created from last month, regardless of the day you run the query this month)

How to write data to a JSON file using Javascript

You have to be clear on what you mean by "JSON".

Some people use the term JSON incorrectly to refer to a plain old JavaScript object, such as [{a: 1}]. This one happens to be an array. If you want to add a new element to the array, just push it, as in

var arr = [{a: 1}];
arr.push({b: 2});

< [{a: 1}, {b: 2}]

The word JSON may also be used to refer to a string which is encoded in JSON format:

var json = '[{"a": 1}]';

Note the (single) quotation marks indicating that this is a string. If you have such a string that you obtained from somewhere, you need to first parse it into a JavaScript object, using JSON.parse:

var obj = JSON.parse(json);

Now you can manipulate the object any way you want, including push as shown above. If you then want to put it back into a JSON string, then you use JSON.stringify:

var new_json = JSON.stringify(obj.push({b: 2}));
'[{"a": 1}, {"b": 1}]'

JSON is also used as a common way to format data for transmission of data to and from a server, where it can be saved (persisted). This is where ajax comes in. Ajax is used both to obtain data, often in JSON format, from a server, and/or to send data in JSON format up to to the server. If you received a response from an ajax request which is JSON format, you may need to JSON.parse it as described above. Then you can manipulate the object, put it back into JSON format with JSON.stringify, and use another ajax call to send the data to the server for storage or other manipulation.

You use the term "JSON file". Normally, the word "file" is used to refer to a physical file on some device (not a string you are dealing with in your code, or a JavaScript object). The browser has no access to physical files on your machine. It cannot read or write them. Actually, the browser does not even really have the notion of a "file". Thus, you cannot just read or write some JSON file on your local machine. If you are sending JSON to and from a server, then of course, the server might be storing the JSON as a file, but more likely the server would be constructing the JSON based on some ajax request, based on data it retrieves from a database, or decoding the JSON in some ajax request, and then storing the relevant data back into its database.

Do you really have a "JSON file", and if so, where does it exist and where did you get it from? Do you have a JSON-format string, that you need to parse, mainpulate, and turn back into a new JSON-format string? Do you need to get JSON from the server, and modify it and then send it back to the server? Or is your "JSON file" actually just a JavaScript object, that you simply need to manipulate with normal JavaScript logic?

Is there a way to use PhantomJS in Python?

The easiest way to use PhantomJS in python is via Selenium. The simplest installation method is

  1. Install NodeJS
  2. Using Node's package manager install phantomjs: npm -g install phantomjs-prebuilt
  3. install selenium (in your virtualenv, if you are using that)

After installation, you may use phantom as simple as:

from selenium import webdriver

driver = webdriver.PhantomJS() # or add to your PATH
driver.set_window_size(1024, 768) # optional
driver.get('https://google.com/')
driver.save_screenshot('screen.png') # save a screenshot to disk
sbtn = driver.find_element_by_css_selector('button.gbqfba')
sbtn.click()

If your system path environment variable isn't set correctly, you'll need to specify the exact path as an argument to webdriver.PhantomJS(). Replace this:

driver = webdriver.PhantomJS() # or add to your PATH

... with the following:

driver = webdriver.PhantomJS(executable_path='/usr/local/lib/node_modules/phantomjs/lib/phantom/bin/phantomjs')

References:

Eclipse : Failed to connect to remote VM. Connection refused.

  • The port number in the Eclipse configuration and the port number of your application might not be the same.
  • You might not have been started your application with the right parameters.

    Those are the simple problems when I have faced "Connection refused" error.

IF formula to compare a date with current date and return result

I think this will cover any possible scenario for what is in O10:

=IF(ISBLANK(O10),"",IF(O10<TODAY(),IF(TODAY()-O10<>1,CONCATENATE("Due in ",TEXT(TODAY()-O10,"d")," days"),CONCATENATE("Due in ",TEXT(TODAY()-O10,"d")," day")),IF(O10=TODAY(),"Due Today","Overdue")))

For Dates that are before Today, it will tell you how many days the item is due in. If O10 = Today then it will say "Due Today". Anything past Today and it will read overdue. Lastly, if it is blank, the cell will also appear blank. Let me know what you think!

How to take last four characters from a varchar?

tested solution on hackerrank....

select distinct(city) from station
where substr(lower(city), length(city), 1) in ('a', 'e', 'i', 'o', 'u') and substr(lower(city), 1, 1) in ('a', 'e', 'i', 'o', 'u');

Convert a row of a data frame to vector

When you extract a single row from a data frame you get a one-row data frame. Convert it to a numeric vector:

as.numeric(df[1,])

As @Roland suggests, unlist(df[1,]) will convert the one-row data frame to a numeric vector without dropping the names. Therefore unname(unlist(df[1,])) is another, slightly more explicit way to get to the same result.

As @Josh comments below, if you have a not-completely-numeric (alphabetic, factor, mixed ...) data frame, you need as.character(df[1,]) instead.

How to select an element by classname using jqLite?

If elem.find() is not working for you, check that you are including JQuery script before angular script....

What is the significance of 1/1/1753 in SQL Server?

1752 was the year of Britain switching from the Julian to the Gregorian calendar. I believe two weeks in September 1752 never happened as a result, which has implications for dates in that general area.

An explanation: http://uneasysilence.com/archive/2007/08/12008/ (Internet Archive version)

Start redis-server with config file

I think that you should make the reference to your config file

26399:C 16 Jan 08:51:13.413 # Warning: no config file specified, using the default config. In order to specify a config file use ./redis-server /path/to/redis.conf

you can try to start your redis server like

./redis-server /path/to/redis-stable/redis.conf

I can't find my git.exe file in my Github folder

I faced the same issue and was not able to find it out where git.exe is located. After spending so much time I fount that in my windows 8, it is located at

C:\Program Files (x86)\Git\bin

And for command line :

C:\Program Files (x86)\Git\cmd

Hope this helps someone facing the same issue.

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

In my case, I was calling a delegate method but the method wasn't declared.

This error is generic and can appear by a number of reasons. Make sure you have not disabled your Logs to actually see what happened. Enable OS_ACTIVITY_MODE in the schemes if you have disabled it. You might have disabled it to prevent a lot of irrelevant logs but they are handy.

You can also trace the cause in more details by adding an exception breakpoint po $arg1. As already mentioned by Ahmed-Lotfi

Here is a common checklist that you can go through.

2) Check if you have renamed an IBOutlet and calling it
3) Check if you have renamed a method name or the method doesn't exist
4) Check if you are trying to add or remove any view from hierarchy
5) Check for any missing framework or library
6) Check if you’ve forgot to register your custom cell identifier
7) Check for any missing flag in the Proejct Setting (-obj) or any other linker flag etc.

Access blocked by CORS policy: Response to preflight request doesn't pass access control check

If you are using Spring as Back-End server and especially using Spring Security then i found a solution by putting http.cors(); in the configure method. The method looks like that:

protected void configure(HttpSecurity http) throws Exception {
        http
                .csrf().disable()
                .authorizeRequests() // authorize
                .anyRequest().authenticated() // all requests are authenticated
                .and()
                .httpBasic();

        http.cors();
}

How to read AppSettings values from a .json file in ASP.NET Core

The following works for console applications;

  1. Install the following NuGet packages (.csproj);

    <ItemGroup>
        <PackageReference Include="Microsoft.Extensions.Configuration" Version="2.2.0-preview2-35157" />
        <PackageReference Include="Microsoft.Extensions.Configuration.FileExtensions" Version="2.2.0-preview2-35157" />
        <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="2.2.0-preview2-35157" />
    </ItemGroup>
    
  2. Create appsettings.json at root level. Right click on it and "Copy to Output Directory" as "Copy if newer".

  3. Sample configuration file:

    {
      "AppConfig": {
        "FilePath": "C:\\temp\\logs\\output.txt"
      }
    }
    
  4. Program.cs

    configurationSection.Key and configurationSection.Value will have config properties.

    static void Main(string[] args)
    {
        try
        {
    
            IConfigurationBuilder builder = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
    
            IConfigurationRoot configuration = builder.Build();
            // configurationSection.Key => FilePath
            // configurationSection.Value => C:\\temp\\logs\\output.txt
            IConfigurationSection configurationSection = configuration.GetSection("AppConfig").GetSection("FilePath");
    
        }
        catch (Exception e)
        {
            Console.WriteLine(e);
        }
    }
    

PHP MySQL Google Chart JSON - Complete Example

You can do this more easy way. And 100% works that you want

<?php
    $servername = "localhost";
    $username = "root";
    $password = "";  //your database password
    $dbname = "demo";  //your database name

    $con = new mysqli($servername, $username, $password, $dbname);

    if ($con->connect_error) {
        die("Connection failed: " . $con->connect_error);
    }
    else
    {
        //echo ("Connect Successfully");
    }
    $query = "SELECT Date_time, Tempout FROM alarm_value"; // select column
    $aresult = $con->query($query);

?>

<!DOCTYPE html>
<html>
<head>
    <title>Massive Electronics</title>
    <script type="text/javascript" src="loder.js"></script>
    <script type="text/javascript">
        google.charts.load('current', {'packages':['corechart']});

        google.charts.setOnLoadCallback(drawChart);
        function drawChart(){
            var data = new google.visualization.DataTable();
            var data = google.visualization.arrayToDataTable([
                ['Date_time','Tempout'],
                <?php
                    while($row = mysqli_fetch_assoc($aresult)){
                        echo "['".$row["Date_time"]."', ".$row["Tempout"]."],";
                    }
                ?>
               ]);

            var options = {
                title: 'Date_time Vs Room Out Temp',
                curveType: 'function',
                legend: { position: 'bottom' }
            };

            var chart = new google.visualization.AreaChart(document.getElementById('areachart'));
            chart.draw(data, options);
        }

    </script>
</head>
<body>
     <div id="areachart" style="width: 900px; height: 400px"></div>
</body>
</html>

loder.js link here loder.js

SQL Server Error : String or binary data would be truncated

This error is usually encountered when inserting a record in a table where one of the columns is a VARCHAR or CHAR data type and the length of the value being inserted is longer than the length of the column.

I am not satisfied how Microsoft decided to inform with this "dry" response message, without any point of where to look for the answer.

how to convert object into string in php

you have the print_r function DOC

SCRIPT7002: XMLHttpRequest: Network Error 0x2ef3, Could not complete the operation due to error 00002ef3

I have stumbled across this questions and answers after receiving the aforementioned error in IE11 when trying to upload files using XMLHttpRequest:

var reqObj = new XMLHttpRequest();

//event Handler
reqObj.upload.addEventListener("progress", uploadProgress, false);
reqObj.addEventListener("load", uploadComplete, false);
reqObj.addEventListener("error", uploadFailed, false);
reqObj.addEventListener("abort", uploadCanceled, false);

//open the object and set method of call (post), url to call, isAsynchronous(true)
reqObj.open("POST", $rootUrlService.rootUrl + "Controller/UploadFiles", true);

//set Content-Type at request header.for file upload it's value must be multipart/form-data
reqObj.setRequestHeader("Content-Type", "multipart/form-data");

//Set header properties : file name and project milestone id
reqObj.setRequestHeader('X-File-Name', name);

// send the file
// this is the line where the error occurs
reqObj.send(fileToUpload);

Removing the line reqObj.setRequestHeader("Content-Type", "multipart/form-data"); fixed the problem.

Note: this error is shown very differently in other browsers. I.e. Chrome shows something similar to a connection reset which is similar to what Fiddler reports (an empty response due to sudden connection close).

Also, this error appeared only when upload was done from a machine different from WebServer (no problems on localhost).

Purpose of ESI & EDI registers?

There are a few operations you can only do with DI/SI (or their extended counterparts, if you didn't learn ASM in 1985). Among these are

REP STOSB
REP MOVSB
REP SCASB

Which are, respectively, operations for repeated (= mass) storing, loading and scanning. What you do is you set up SI and/or DI to point at one or both operands, perhaps put a count in CX and then let 'er rip. These are operations that work on a bunch of bytes at a time, and they kind of put the CPU in automatic. Because you're not explicitly coding loops, they do their thing more efficiently (usually) than a hand-coded loop.

Just in case you're wondering: Depending on how you set the operation up, repeated storing can be something simple like punching the value 0 into a large contiguous block of memory; MOVSB is used, I think, to copy data from one buffer (well, any bunch of bytes) to another; and SCASB is used to look for a byte that matches some search criterion (I'm not sure if it's only searching on equality, or what – you can look it up :) )

That's most of what those regs are for.

Store JSON object in data attribute in HTML jQuery

The trick for me was to add double quotes around keys and values. If you use a PHP function like json_encode will give you a JSON encoded string and an idea how to properly encode yours.

jQuery('#elm-id').data('datakey') will return an object of the string, if the string is properly encoded as json.

As per jQuery documentation: (http://api.jquery.com/jquery.parsejson/)

Passing in a malformed JSON string results in a JavaScript exception being thrown. For example, the following are all invalid JSON strings:

  1. "{test: 1}" (test does not have double quotes around it).
  2. "{'test': 1}" ('test' is using single quotes instead of double quotes).
  3. "'test'" ('test' is using single quotes instead of double quotes).
  4. ".1" (a number must start with a digit; "0.1" would be valid).
  5. "undefined" (undefined cannot be represented in a JSON string; null, however, can be).
  6. "NaN" (NaN cannot be represented in a JSON string; direct representation of Infinity is also n

Command not found error in Bash variable assignment

You cannot have spaces around the = sign.

When you write:

STR = "foo"

bash tries to run a command named STR with 2 arguments (the strings = and foo)

When you write:

STR =foo

bash tries to run a command named STR with 1 argument (the string =foo)

When you write:

STR= foo

bash tries to run the command foo with STR set to the empty string in its environment.

I'm not sure if this helps to clarify or if it is mere obfuscation, but note that:

  1. the first command is exactly equivalent to: STR "=" "foo",
  2. the second is the same as STR "=foo",
  3. and the last is equivalent to STR="" foo.

The relevant section of the sh language spec, section 2.9.1 states:

A "simple command" is a sequence of optional variable assignments and redirections, in any sequence, optionally followed by words and redirections, terminated by a control operator.

In that context, a word is the command that bash is going to run. Any string containing = (in any position other than at the beginning of the string) which is not a redirection and in which the portion of the string before the = is a valid variable name is a variable assignment, while any string that is not a redirection or a variable assignment is a command. In STR = "foo", STR is not a variable assignment.

Converting HTML files to PDF

You can use a headless firefox with an extension. It's pretty annoying to get running but it does produce good results.

Check out this answer for more info.

Why cannot change checkbox color whatever I do?

Transparency maybe: checkbox inside span

<span style="display:inline-block; background-color:silver;padding:0px;margin:0px;height:13px; width:13px; overflow:hidden"><input type="checkbox" style="opacity:0.50;padding:0px;margin:0px" /></span>

iterate through a map in javascript

The callback to $.each() is passed the property name and the value, in that order. You're therefore trying to iterate over the property names in the inner call to $.each(). I think you want:

$.each(myMap, function (i, val) {
  $.each(val, function(innerKey, innerValue) {
    // ...
  });
});

In the inner loop, given an object like your map, the values are arrays. That's OK, but note that the "innerKey" values will all be numbers.

edit — Now once that's straightened out, here's the next problem:

    setTimeout(function () {

      // ...

    }, i * 6000);

The first time through that loop, "i" will be the string "partnr1". Thus, that multiplication attempt will result in a NaN. You can keep an external counter to keep track of the property count of the outer map:

var pcount = 1;
$.each(myMap, function(i, val) {
  $.each(val, function(innerKey, innerValue) {
    setTimeout(function() {
      // ...
    }, pcount++ * 6000);
  });
});

How to make rpm auto install dependencies

I found a simpler solution. If you have all the RPMs in the same directory, all you need to do is,

$ sudo rpm -i *.rpm

rpm seems to figure out the correct order to install these and installs the RPMs.

Check for database connection, otherwise display message

Try this:

<?php
$servername   = "localhost";
$database = "database";
$username = "user";
$password = "password";

// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
   die("Connection failed: " . $conn->connect_error);
}
  echo "Connected successfully";
?>

Using arrays or std::vectors in C++, what's the performance gap?

Vectors use a tiny bit more memory than arrays since they contain the size of the array. They also increase the hard disk size of programs and probably the memory footprint of programs. These increases are tiny, but may matter if you're working with an embedded system. Though most places where these differences matter are places where you would use C rather than C++.

Is there an onSelect event or equivalent for HTML <select>?

The one True answer is to not use the select field (if you need to do something when you re-select same answer.)

Create a dropdown menu with conventional div, button, show/hide menu. Link: https://www.w3schools.com/howto/howto_js_dropdown.asp

Could have been avoided had one been able to add event listeners to options. If there had been an onSelect listener for select element. And if clicking on the select field didn't aggravatingly fire off mousedown, mouseup, and click all at the same time on mousedown.

How do I call a function twice or more times consecutively?

My two cents:

from itertools import repeat 

list(repeat(f(), x))  # for pure f
[f() for f in repeat(f, x)]  # for impure f

SQL Server after update trigger

CREATE TRIGGER [dbo].[after_update] ON [dbo].[MYTABLE]
AFTER UPDATE
AS
BEGIN
    DECLARE @ID INT

    SELECT @ID = D.ID
    FROM inserted D

    UPDATE MYTABLE
    SET mytable.CHANGED_ON = GETDATE()
        ,CHANGED_BY = USER_NAME(USER_ID())
    WHERE ID = @ID
END

Python Error: "ValueError: need more than 1 value to unpack"

I assume you found this code on Exercise 14: Prompting And Passing.

Do the following:

script = '*some arguments*' 
user_name = '*some arguments*'

and that works perfectly

Solving a "communications link failure" with JDBC and MySQL

In my case (I am a noob), I was testing Servlet that make database connection with MySQL and one of the Exception is the one mentioned above.

It made my head swing for some seconds but I came to realize that it was because I have not started my MySQL server in localhost.
After starting the server, the problem was fixed.

So, check whether MySQL server is running properly.

How to get the Display Name Attribute of an Enum member via MVC Razor code?

With Core 2.1,

public static string GetDisplayName(Enum enumValue)
{
  return enumValue.GetType()?
 .GetMember(enumValue.ToString())?[0]?
 .GetCustomAttribute<DisplayAttribute>()?
 .Name;
}

How to convert datetime to timestamp using C#/.NET (ignoring current timezone)

Find timestamp from DateTime:

private long ConvertToTimestamp(DateTime value)
{
    TimeZoneInfo NYTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
    DateTime NyTime = TimeZoneInfo.ConvertTime(value, NYTimeZone);
    TimeZone localZone = TimeZone.CurrentTimeZone;
    System.Globalization.DaylightTime dst = localZone.GetDaylightChanges(NyTime.Year);
    NyTime = NyTime.AddHours(-1);
    DateTime epoch = new DateTime(1970, 1, 1, 0, 0, 0, 0).ToLocalTime();
    TimeSpan span = (NyTime - epoch);
    return (long)Convert.ToDouble(span.TotalSeconds);
}

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

Well, yeah, that's what it does. I use it for members that are modified by methods that do not logically change the state of a class - for instance, to speed up lookups by implementing a cache:

class CIniWrapper
{
public:
   CIniWrapper(LPCTSTR szIniFile);

   // non-const: logically modifies the state of the object
   void SetValue(LPCTSTR szName, LPCTSTR szValue);

   // const: does not logically change the object
   LPCTSTR GetValue(LPCTSTR szName, LPCTSTR szDefaultValue) const;

   // ...

private:
   // cache, avoids going to disk when a named value is retrieved multiple times
   // does not logically change the public interface, so declared mutable
   // so that it can be used by the const GetValue() method
   mutable std::map<string, string> m_mapNameToValue;
};

Now, you must use this with care - concurrency issues are a big concern, as a caller might assume that they are thread safe if only using const methods. And of course, modifying mutable data shouldn't change the behavior of the object in any significant fashion, something that could be violated by the example i gave if, for instance, it was expected that changes written to disk would be immediately visible to the app.

Oracle SQL Developer spool output?

Another way simpler than me has worked with SQL Developer 4 in Windows 7

spool "path_to_file\\filename.txt"
query to execute
spool of

You have to execute it as a script, because if not only the query will be saved in the output file In the path name I use the double character "\" as a separator when working with Windows and SQL, The output file will display the query and the result.

Check/Uncheck a checkbox on datagridview

I was making my own version of a Checkbox to control a DataGridViewCheckBoxColumn when I saw this post wasn't actually answered. To set the checked state of a DataGridViewCheckBoxCell use:

foreach (DataGridViewRow row in dataGridView1.Rows)
{
    dataGridView1.Rows[row.Index].SetValues(true);
}

For anyone else trying to accomplish the same thing, here is what I came up with.

This makes the two controls behave like the checkbox column in Gmail. It keeps functionality for both mouse and keyboard.

using System;
using System.Windows.Forms;

namespace Check_UnCheck_All
{
    public partial class Check_UnCheck_All : Form
    {
        public Check_UnCheck_All()
        {
            InitializeComponent();
            dataGridView1.RowCount = 10;
            dataGridView1.AllowUserToAddRows = false;
            this.dataGridView1.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvApps_CellContentClick);
            this.dataGridView1.CellMouseUp += new System.Windows.Forms.DataGridViewCellMouseEventHandler(this.myDataGrid_OnCellMouseUp);
            this.dataGridView1.CellValueChanged += new System.Windows.Forms.DataGridViewCellEventHandler(this.myDataGrid_OnCellValueChanged);
            this.checkBox1.Click += new System.EventHandler(this.checkBox1_Click);
        }

        public int chkInt = 0;
        public bool chked = false;

        public void myDataGrid_OnCellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
            {
                DataGridViewCheckBoxCell chk = dataGridView1.Rows[e.RowIndex].Cells[0] as DataGridViewCheckBoxCell;

                if (Convert.ToBoolean(chk.Value) == true) chkInt++;
                if (Convert.ToBoolean(chk.Value) == false) chkInt--;
                if (chkInt < dataGridView1.Rows.Count && chkInt > 0)
                {
                    checkBox1.CheckState = CheckState.Indeterminate;
                    chked = true;
                }
                else if (chkInt == 0)
                {
                    checkBox1.CheckState = CheckState.Unchecked;
                    chked = false;
                }
                else if (chkInt == dataGridView1.Rows.Count)
                {
                    checkBox1.CheckState = CheckState.Checked;
                    chked = true;
                }
            }
        }
        public void myDataGrid_OnCellMouseUp(object sender, DataGridViewCellMouseEventArgs e)
        {
            // End of edition on each click on column of checkbox
            if (e.ColumnIndex == dataGridView1.Rows[0].Index && e.RowIndex != -1)
            {
                dataGridView1.EndEdit();
            }
            dataGridView1.BeginEdit(true);
        }
        public void dgvApps_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            if (dataGridView1.CurrentCell.GetType() == typeof(DataGridViewCheckBoxCell))
            {
                if (dataGridView1.CurrentCell.IsInEditMode)
                {
                    if (dataGridView1.IsCurrentCellDirty)
                    {
                        dataGridView1.EndEdit();
                    }
                }
                dataGridView1.BeginEdit(true);
            }
        }
        public void checkBox1_Click(object sender, EventArgs e)
        {
            if (chked == true)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[0];
                    if (chk.Value == chk.TrueValue)
                    {
                        chk.Value = chk.FalseValue;
                    }
                    else
                    {
                        chk.Value = chk.TrueValue;
                    }
                }
                chked = false;
                chkInt = 0;
                return;
            }
            if (chked == false)
            {
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    dataGridView1.Rows[row.Index].SetValues(true);
                }
                chked = true;
                chkInt = dataGridView1.Rows.Count;
            }
        }
    }
}

Create a copy of a table within the same database DB2

Try this:

CREATE TABLE SCHEMA.NEW_TB LIKE SCHEMA.OLD_TB;
INSERT INTO SCHEMA.NEW_TB (SELECT * FROM SCHEMA.OLD_TB);

Options that are not copied include:

  • Check constraints
  • Column default values
  • Column comments
  • Foreign keys
  • Logged and compact option on BLOB columns
  • Distinct types

Can anonymous class implement interface?

No; an anonymous type can't be made to do anything except have a few properties. You will need to create your own type. I didn't read the linked article in depth, but it looks like it uses Reflection.Emit to create new types on the fly; but if you limit discussion to things within C# itself you can't do what you want.

jQuery - Detect value change on hidden input field

Since hidden input does not trigger "change" event on change, I used MutationObserver to trigger this instead.

(Sometimes hidden input value changes are done by some other scripts you can't modify)

This does not work in IE10 and below

MutationObserver = window.MutationObserver || window.WebKitMutationObserver;

var trackChange = function(element) {
  var observer = new MutationObserver(function(mutations, observer) {
    if(mutations[0].attributeName == "value") {
        $(element).trigger("change");
    }
  });
  observer.observe(element, {
    attributes: true
  });
}

// Just pass an element to the function to start tracking
trackChange( $("input[name=foo]")[0] );

Manage toolbar's navigation and back button from fragment in android

Add a toolbar to your xml

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="?attr/actionBarSize"
    android:background="?attr/colorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.ActionBar"
    app:popupTheme="@style/ThemeOverlay.AppCompat.Light">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Fragment title"/>

</android.support.v7.widget.Toolbar>

Then inside your onCreateView method in the Fragment:

Toolbar toolbar = view.findViewById(R.id.toolbar);
toolbar.setNavigationIcon(R.drawable.ic_back_button);
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
         getActivity().onBackPressed();
    }
});

set default schema for a sql query

A quick google pointed me to this page. It explains that from sql server 2005 onwards you can set the default schema of a user with the ALTER USER statement. Unfortunately, that means that you change it permanently, so if you need to switch between schemas, you would need to set it every time you execute a stored procedure or a batch of statements. Alternatively, you could use the technique described here.

If you are using sql server 2000 or older this page explains that users and schemas are then equivalent. If you don't prepend your table name with a schema\user, sql server will first look at the tables owned by the current user and then the ones owned by the dbo to resolve the table name. It seems that for all other tables you must prepend the schema\user.

Execute CMD command from code

Using Process.Start:

using System.Diagnostics;

class Program
{
    static void Main()
    {
        Process.Start("example.txt");
    }
}

Python: count repeated elements in the list

yourList = ["a", "b", "a", "c", "c", "a", "c"]

expected outputs {a: 3, b: 1,c:3}

duplicateFrequencies = {}
for i in set(yourList):
    duplicateFrequencies[i] = yourList.count(i)

Cheers!! Reference

Assigning strings to arrays of characters

What I would use is

char *s = "abcd";

Case Insensitive String comp in C

You can get an idea, how to implement an efficient one, if you don't have any in the library, from here

It use a table for all 256 chars.

  • in that table for all chars, except letters - used its ascii codes.
  • for upper case letter codes - the table list codes of lower cased symbols.

then we just need to traverse a strings and compare our table cells for a given chars:

const char *cm = charmap,
        *us1 = (const char *)s1,
        *us2 = (const char *)s2;
while (cm[*us1] == cm[*us2++])
    if (*us1++ == '\0')
        return (0);
return (cm[*us1] - cm[*--us2]);

Add days to JavaScript Date

As simple as this:

new Date((new Date()).getTime() + (60*60*24*1000));

How to install wget in macOS?

I update mac to Sierra , 10.12.3

My wget stop working.

When I tried to install by typing

brew install wget --with-libressl

I got the following warning

Warning: wget-1.19.1 already installed, it's just not linked.

Then tried to unsintall by typing

brew uninstall wget --with-libressl

Then I reinstalled by typing

brew install wget --with-libressl

Finally I got it worked.Thank God!

chrome undo the action of "prevent this page from creating additional dialogs"

Close the tab of the page you disabled alerts. Re-open the page in a new tab. The setting only lasts for the session, so alerts will be re-enabled once the new session begins in the new tab.

Changing Background Image with CSS3 Animations

It works in Chrome 19.0.1084.41 beta!

So at some point in the future, keyframes could really be... frames!

You are living in the future ;)

My Application Could not open ServletContext resource

If you are getting this error with a Java configuration, it is usually because you forget to pass in the application context to the DispatcherServlet constructor:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet()); // <-- no constructor args!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

Fix it by adding the context as the constructor arg:

AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
ctx.register(WebConfig.class);

ServletRegistration.Dynamic dispatcher = sc.addServlet("dispatcher", 
    new DispatcherServlet(ctx)); // <-- hooray! Spring doesn't look for XML files!
dispatcher.setLoadOnStartup(1);
dispatcher.addMapping("/*");

jquery $(this).id return Undefined

Hiya demo http://jsfiddle.net/LYTbc/

this is a reference to the DOM element, so you can wrap it directly.

attr api: http://api.jquery.com/attr/

The .attr() method gets the attribute value for only the first element in the matched set.

have a nice one, cheers!

code

$(document).ready(function () {
    $(".inputs").click(function () {
         alert(this.id);

        alert(" or " + $(this).attr("id"));

    });

});?

How to debug in Android Studio using adb over WiFi

I successfully debug app through WiFi by following the official site's guide.

Note,

  • WiFi debugging in Android 11+ is different from Android 10 and lower.
  • Please update your adb, i.e. Android SDK Platform-tools to the latest version, otherwise you may miss some adb commands like adb pair.

How to split a list by comma not space

I think the canonical method is:

while IFS=, read field1 field2 field3 field4 field5 field6; do 
  do stuff
done < CSV.file

If you don't know or don't care about how many fields there are:

IFS=,
while read line; do
  # split into an array
  field=( $line )
  for word in "${field[@]}"; do echo "$word"; done

  # or use the positional parameters
  set -- $line
  for word in "$@"; do echo "$word"; done

done < CSV.file

How do you completely remove the button border in wpf?

Programmatically, you can do this:

btn.BorderBrush = new SolidColorBrush(Colors.Transparent);

What does this symbol mean in IntelliJ? (red circle on bottom-left corner of file name, with 'J' in it)

Actually this can happens because of two reason.

  1. Your project not getting/ Updating your dependencies. Go to your terminal and enter mvn clean install. Or right click on pom.xml and click Add as Mevan Project.

  2. Check your jdk has set properly to the project.

How to disable clicking inside div

You can use css

.ads{pointer-events:none}

or Using javascript prevent event

$("selector").click(function(event){
   event.preventDefault();
});

Add newly created specific folder to .gitignore in Git

From "git help ignore" we learn:

If the pattern ends with a slash, it is removed for the purpose of the following description, but it would only find a match with a directory. In other words, foo/ will match a directory foo and paths underneath it, but will not match a regular file or a symbolic link foo (this is consistent with the way how pathspec works in general in git).

Therefore what you need is

public_html/stats/

Cannot declare instance members in a static class in C#

public static class Employee
{
    public static string SomeSetting
    {
        get 
        {
            return ConfigurationManager.AppSettings["SomeSetting"];    
        }
    }
}

Declare the property as static, as well. Also, Don't bother storing a private reference to ConfigurationManager.AppSettings. ConfigurationManager is already a static class.

If you feel that you must store a reference to appsettings, try

public static class Employee
{
    private static NameValueCollection _appSettings=ConfigurationManager.AppSettings;

    public static NameValueCollection AppSettings { get { return _appSettings; } }

}

It's good form to always give an explicit access specifier (private, public, etc) even though the default is private.

Scroll to bottom of div?

Newer method that works on all current browsers:

this.scrollIntoView(false);

Google Maps Android API v2 - Interactive InfoWindow (like in original android google maps)

I see that this question is already old but still...

We made a sipmle library at our company for achieving what is desired - An interactive info window with views and everything. You can check it out on github.

I hope it helps :)

Open another page in php

Use something like header( 'Location: /my-other-page.html' ); to redirect. You can't have sent any other data on the page before you do this though.

Error: Node Sass does not yet support your current environment: Windows 64-bit with false

In my case, it was related to the node version.

My project was using 12.18.3 but I was on 14.5.0

So npm rebuild node-sass didn't solve the issue on the wrong node version(14.5.0).

I switched to the correct version(12.18.3) so it worked.

How do I create a folder in VB if it doesn't exist?

If Not Directory.Exists(somePath) then
    Directory.CreateDirectory(somePath)
End If

Adding headers to requests module

You can also do this to set a header for all future gets for the Session object, where x-test will be in all s.get() calls:

s = requests.Session()
s.auth = ('user', 'pass')
s.headers.update({'x-test': 'true'})

# both 'x-test' and 'x-test2' are sent
s.get('http://httpbin.org/headers', headers={'x-test2': 'true'})

from: http://docs.python-requests.org/en/latest/user/advanced/#session-objects

Is div inside list allowed?

I'm starting in the webdesign universe and i used DIVs inside LIs with no problem with the semantics. I think that DIVs aren't allowed on lists, that means you can't put a DIV inside an UL, but it has no problem inserting it on a LI (because LI are just list items haha) The problem that i have been encountering is that sometimes the DIV behaves somewhat different from usual, but nothing that our good CSS can't handle haha. Anyway, sorry for my bad english and if my response wasn't helpful haha good luck!

Comparing floating point number to zero

You can use std::nextafter with a fixed factor of the epsilon of a value like the following:

bool isNearlyEqual(double a, double b)
{
  int factor = /* a fixed factor of epsilon */;

  double min_a = a - (a - std::nextafter(a, std::numeric_limits<double>::lowest())) * factor;
  double max_a = a + (std::nextafter(a, std::numeric_limits<double>::max()) - a) * factor;

  return min_a <= b && max_a >= b;
}

Git push rejected "non-fast-forward"

I had this problem! I tried: git fetch + git merge, but dont resolved! I tried: git pull, and also dont resolved

Then I tried this and resolved my problem (is similar of answer of Engineer):

git fetch origin master:tmp
git rebase tmp
git push origin HEAD:master
git branch -D tmp

Change icon-bar (?) color in bootstrap

I am using Bootstrap & HTML5. I wanted to override the look of the toggle button.

.navbar-toggle{
    background-color: #5DADB0;
    color: #F3DBAA;
    border:none;        
}

.navbar-toggle.but-menu:link {
    color: #F00;
    background-color: #CF995F;
}

.navbar-toggle.but-menu:visited {
    color: #FFF;
    background-color: #CF995F;
}
.navbar-toggle.but-menu:hover {
    color: #FFF0C9;
    background-color: #CF995F;
}
.navbar-toggle.but-menu:active {
    color: #FFF;
    background-color: #CF995F;
}
.navbar-toggle.but-menu:focus {
    color: #FFF;
    background-color: #CF995F;
}

Get current date in DD-Mon-YYY format in JavaScript/Jquery

var date = new Date();

console.log(date.toJSON().slice(0,10).replace(new RegExp("-", 'g'),"/" ).split("/").reverse().join("/")+" "+date.toJSON().slice(11,19));

// output : 01/09/2016 18:30:00

Excel concatenation quotes

Try this:

CONCATENATE(""""; B2 ;"""")

@widor provided a nice solution alternative too - integrated with mine:

CONCATENATE(char(34); B2 ;char(34))

How to remove an iOS app from the App Store

To remove an app from the App Store, deselect all territories in your app's Rights and Pricing section on the App Summary page accessible from the Manage Your Applications module. Your app status will change to Developer Removed from Sale and will be removed from the App Store until you make it available again using the Rights and Pricing section.

Multiple aggregate functions in HAVING clause

For your example query, the only possible value greater than 2 and less than 4 is 3, so we simplify:

GROUP BY meetingID
HAVING COUNT(caseID) = 3

In your general case:

GROUP BY meetingID
HAVING COUNT(caseID) > x AND COUNT(caseID) < 7

Or (possibly easier to read?),

GROUP BY meetingID
HAVING COUNT(caseID) BETWEEN x+1 AND 6

Get Today's date in Java at midnight time

Defining ‘Midnight’

The word “midnight” is tricky to define.

Some think of it as the moment before a new day starts. Trying to represent that in software as tricky as the last moment of the day can always be subdivided as a smaller fraction of a second.

I suggest a better way of thinking about this is to get “first moment of the day”.

This supports the commonly used approach of defining a span of time as ‘Half-Open’, where the beginning is inclusive while the ending is exclusive. So a full day starts with the first moment of the day and runs up to, but not including, the first moment of the following day. A full day would like this (notice the date going from the 3rd to the 4th):

2016-02-03T00:00:00.0-08:00[America/Los_Angeles]/2016-02-04T00:00:00.0-08:00[America/Los_Angeles]

Joda-Time

If using the Joda-Time library, call withTimeAtStartOfDay.

Note how we specify the time zone. If omitted, the JVM’s current default time zone is implicitly applied. Better to be explicit.

DateTime todayStart = DateTime.now( DateTimeZone.forID( "America/Montreal" ) ).withTimeAtStartOfDay() ;

If using Java 8 or later, better to use the java.time package built into Java. See sibling Answer by Jens Hoffman.

How to generate a random alpha-numeric string

  1. Change String characters as per as your requirements.

  2. String is immutable. Here StringBuilder.append is more efficient than string concatenation.


public static String getRandomString(int length) {
    final String characters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJLMNOPQRSTUVWXYZ1234567890!@#$%^&*()_+";
    StringBuilder result = new StringBuilder();

    while(length > 0) {
        Random rand = new Random();
        result.append(characters.charAt(rand.nextInt(characters.length())));
        length--;
    }
    return result.toString();
}

Create a unique number with javascript time

This performs faster than creating a Date instance, uses less code and will always produce a unique number (locally):

function uniqueNumber() {
    var date = Date.now();

    // If created at same millisecond as previous
    if (date <= uniqueNumber.previous) {
        date = ++uniqueNumber.previous;
    } else {
        uniqueNumber.previous = date;
    }

    return date;
}

uniqueNumber.previous = 0;

jsfiddle: http://jsfiddle.net/j8aLocan/

I've released this on Bower and npm: https://github.com/stevenvachon/unique-number

You could also use something more elaborate such as cuid, puid or shortid to generate a non-number.

Github permission denied: ssh add agent has no identities

I had this issue after restoring a hard drive from a backup.

My problem: I could check & see my remote (using git remote -v), but when I executed git push origin master, it returned : Permission denied (publickey). fatal: Could not read from remote repository.

I already had an SSH folder and SSH keys, and adding them via Terminal (ssh-add /path/to/my-ssh-folder/id_rsa) successfully added my identity, but I still couldn't push and still got the same error. Generating a new key was a bad idea for me, because it was tied to other very secure permissions on AWS.

It turned out the link between the key and my Github profile had broken.

Solution: Re-adding the key to Github in Profile > Settings > SSH and GPG keys resolved the issue.

Also: My account had 2-factor authentication set up. When this is the case, if Terminal requests credentials, use your username - but NOT your Github password. For 2-factor authentication, you need to use your authentication code (for me, this was generated by Authy on my phone, and I had to copy it into Terminal for the pw).

POST request send json data java HttpUrlConnection

You can use this code for connect and request using http and json

try {
         
        URL url = new URL("https://www.googleapis.com/youtube/v3/playlistItems?part=snippet"
                + "&key="+key
                + "&access_token=" + access_token);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setDoOutput(true);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "application/json");
 
        String input = "{ \"snippet\": {\"playlistId\": \"WL\",\"resourceId\": {\"videoId\": \""+videoId+"\",\"kind\": \"youtube#video\"},\"position\": 0}}";
 
        OutputStream os = conn.getOutputStream();
        os.write(input.getBytes());
        os.flush();
 
        if (conn.getResponseCode() != HttpURLConnection.HTTP_CREATED) {
            throw new RuntimeException("Failed : HTTP error code : "
                + conn.getResponseCode());
        }
 
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (conn.getInputStream())));
 
        String output;
        System.out.println("Output from Server .... \n");
        while ((output = br.readLine()) != null) {
            System.out.println(output);
        }
 
        conn.disconnect();
 
      } catch (MalformedURLException e) {
 
        e.printStackTrace();
 
      } catch (IOException e) {
 
        e.printStackTrace();
 
     }

Can I get image from canvas element and use it in img src tag?

canvas.toDataURL() will provide you a data url which can be used as source:

var image = new Image();
image.id = "pic";
image.src = canvas.toDataURL();
document.getElementById('image_for_crop').appendChild(image);

Complete example

Here's a complete example with some random lines. The black-bordered image is generated on a <canvas>, whereas the blue-bordered image is a copy in a <img>, filled with the <canvas>'s data url.

_x000D_
_x000D_
// This is just image generation, skip to DATAURL: below
var canvas = document.getElementById("canvas")
var ctx = canvas.getContext("2d");

// Just some example drawings
var gradient = ctx.createLinearGradient(0, 0, 200, 100);
gradient.addColorStop("0", "#ff0000");
gradient.addColorStop("0.5" ,"#00a0ff");
gradient.addColorStop("1.0", "#f0bf00");

ctx.beginPath();
ctx.moveTo(0, 0);
for (let i = 0; i < 30; ++i) {
  ctx.lineTo(Math.random() * 200, Math.random() * 100);
}
ctx.strokeStyle = gradient;
ctx.stroke();

// DATAURL: Actual image generation via data url
var target = new Image();
target.src = canvas.toDataURL();

document.getElementById('result').appendChild(target);
_x000D_
canvas { border: 1px solid black; }
img    { border: 1px solid blue;  }
body   { display: flex; }
div + div {margin-left: 1ex; }
_x000D_
<div>
  <p>Original:</p>
  <canvas id="canvas" width=200 height=100></canvas>
</div>
<div id="result">
  <p>Result via &lt;img&gt;:</p>
</div>
_x000D_
_x000D_
_x000D_

See also:

Correct way to initialize HashMap and can HashMap hold different value types?

The way you're writing it is equivalent to

HashMap<Object, Object> map = new HashMap<Object, Object>();

What goes inside the brackets is you communicating to the compiler what you're going to put in the HashMap so that it can do error checking for you. If Object, Object is what you actually want (probably not) you should explicitly declare it. In general you should be as explicit as you can with the declaration to facilitate error checking by the compiler. What you've described should probably be declared like this:

HashMap<String, Object> map = new HashMap<String, Object>();

That way you at least declare that your keys are going to be strings, but your values can be anything. Just remember to use a cast when you get a value back out.

How do I store an array in localStorage?

Just created this:

https://gist.github.com/3854049

//Setter
Storage.setObj('users.albums.sexPistols',"blah");
Storage.setObj('users.albums.sexPistols',{ sid : "My Way", nancy : "Bitch" });
Storage.setObj('users.albums.sexPistols.sid',"Other songs");

//Getters
Storage.getObj('users');
Storage.getObj('users.albums');
Storage.getObj('users.albums.sexPistols');
Storage.getObj('users.albums.sexPistols.sid');
Storage.getObj('users.albums.sexPistols.nancy');

Rails: Get Client IP address

Get client ip using command:

request.remote_ip

How to get hostname from IP (Linux)?

In order to use nslookup, host or gethostbyname() then the target's name will need to be registered with DNS or statically defined in the hosts file on the machine running your program. Yes, you could connect to the target with SSH or some other application and query it directly, but for a generic solution you'll need some sort of DNS entry for it.

How to query GROUP BY Month in a Year

For MS SQL you can do this.

    select  CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+ 
CAST(DATEPART(YEAR, DateTyme) as VARCHAR) as 'Date' from #temp
    group by Name, CAST(DATEPART(MONTH, DateTyme) as VARCHAR) +'/'+
 CAST(DATEPART(YEAR, DateTyme) as VARCHAR) 

Custom Input[type="submit"] style not working with jquerymobile button

jQuery Mobile >= 1.4

Create a custom class, e.g. .custom-btn. Note that to override jQM styles without using !important, CSS hierarchy should be respected. .ui-btn.custom-class or .ui-input-btn.custom-class.

.ui-input-btn.custom-btn {
   border:1px solid red;
   text-decoration:none;
   font-family:helvetica;
   color:red;
   background:url(img.png) repeat-x;
}

Add a data-wrapper-class to input. The custom class will be added to input wrapping div.

<input type="button" data-wrapper-class="custom-btn">

Demo


jQuery Mobile <= 1.3

Input button is wrapped by a DIV with class ui-btn. You need to select that div and the input[type="submit"]. Using !important is essential to override Jquery Mobile styles.

Demo

div.ui-btn, input[type="submit"] {
 border:1px solid red !important;
 text-decoration:none !important;
 font-family:helvetica !important;
 color:red !important;
 background:url(../images/btn_hover.png) repeat-x !important;
}

MongoDB: How to query for records where field is null or not set?

If you want to ONLY count the documents with sent_at defined with a value of null (don't count the documents with sent_at not set):

db.emails.count({sent_at: { $type: 10 }})

How to get the last row of an Oracle a table

The last row according to a strict total order over composite key K(k1, ..., kn):

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
                OR  (i.k1 = o.k1 AND i.k2 > o.k2)
                ...
                OR  (i.k1 = o.k1 AND i.k2 = o.k2 AND i.k3 = o.k3 AND ... AND i.kn > o.kn)
        )
;

Given the special case where K is simple (i.e. not composite), the above is shortened to:

SELECT  *
FROM    TableX AS o
WHERE   NOT EXISTS (
            SELECT  *
            FROM    TableX AS i
            WHERE   i.k1 > o.k1
        )
;

Note that for this query to return just one row the key must order without ties. If ties are allowed, this query will return all the rows tied with the greatest key.

Disable arrow key scrolling in users browser

I've tried different ways of blocking scrolling when the arrow keys are pressed, both jQuery and native Javascript - they all work fine in Firefox, but don't work in recent versions of Chrome.
Even the explicit {passive: false} property for window.addEventListener, which is recommended as the only working solution, for example here.

In the end, after many tries, I found a way that works for me in both Firefox and Chrome:

window.addEventListener('keydown', (e) => {
    if (e.target.localName != 'input') {   // if you need to filter <input> elements
        switch (e.keyCode) {
            case 37: // left
            case 39: // right
                e.preventDefault();
                break;
            case 38: // up
            case 40: // down
                e.preventDefault();
                break;
            default:
                break;
        }
    }
}, {
    capture: true,   // this disables arrow key scrolling in modern Chrome
    passive: false   // this is optional, my code works without it
});

Quote for EventTarget.addEventListener() from MDN

options Optional
   An options object specifies characteristics about the event listener. The available options are:

capture
   A Boolean indicating that events of this type will be dispatched to the registered listener before being dispatched to any EventTarget beneath it in the DOM tree.
once
   ...
passive
   A Boolean that, if true, indicates that the function specified by listener will never call preventDefault(). If a passive listener does call preventDefault(), the user agent will do nothing other than generate a console warning. ...

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

LINQ Using Max() to select a single row

You can also do:

(from u in table
orderby u.Status descending
select u).Take(1);

How do I increase the RAM and set up host-only networking in Vagrant?

To increase the memory or CPU count when using Vagrant 2, add this to your Vagrantfile

Vagrant.configure("2") do |config|
    # usual vagrant config here

    config.vm.provider "virtualbox" do |v|
        v.memory = 1024
        v.cpus = 2
    end
end

Why does configure say no C compiler found when GCC is installed?

Maybe gcc is not in your path? Try finding gcc using which gcc and add it to your path if it's not already there.

Notice: Undefined variable: _SESSION in "" on line 9

First, you'll need to add session_start() at the top of any page that you wish to use SESSION variables on.

Also, you should check to make sure the variable is set first before using it:

if(isset($_SESSION['SESS_fname'])){
    echo $_SESSION['SESS_fname'];
}

Or, simply:

echo (isset($_SESSION['SESS_fname']) ? $_SESSION['SESS_fname'] : "Visitor");

Amazon S3 upload file and get URL

Similarly if you want link through s3Client you can use below.

System.out.println("filelink: " + s3Client.getUrl("your_bucket_name", "your_file_key"));

How do I log errors and warnings into a file?

In addition, you need the "AllowOverride Options" directive for this to work. (Apache 2.2.15)

Looping through all rows in a table column, Excel-VBA

If this is in fact a ListObject table (Insert Table from the ribbon) then you can use the table's .DataBodyRange object to get the number of rows and columns. This ignores the header row.

Sub TableTest()

Dim tbl As ListObject
Dim tRows As Long
Dim tCols As Long

Set tbl = ActiveSheet.ListObjects("Table1")  '## modify to your table name.

With tbl.DataBodyRange
    tRows = .Rows.Count
    tCols = .Columns.Count
End With

MsgBox tbl.Name & " contains " & tRows & " rows and " & tCols & " columns.", vbInformation

End Sub

If you need to use the header row, instead of using tbl.DataBodyRange just use tbl.Range.

Nesting optgroups in a dropdownlist/select

This is just fine but if you add option which is not in optgroup it gets buggy.

_x000D_
_x000D_
<select>_x000D_
  <optgroup label="Level One">_x000D_
    <option> A.1 </option>_x000D_
    <optgroup label="&nbsp;&nbsp;&nbsp;&nbsp;Level Two">_x000D_
      <option>&nbsp;&nbsp;&nbsp;&nbsp; A.B.1 </option>_x000D_
    </optgroup>_x000D_
    <option> A.2 </option>_x000D_
  </optgroup>_x000D_
  <option> A </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Would be much better if you used css and close optgroup right away :

_x000D_
_x000D_
<select>_x000D_
  <optgroup label="Level One"></optgroup>_x000D_
  <option style="padding-left:15px"> A.1 </option>_x000D_
  <optgroup label="Level Two" style="padding-left:15px"></optgroup>_x000D_
  <option style="padding-left:30px"> A.B.1 </option>_x000D_
  <option style="padding-left:15px"> A.2 </option>_x000D_
  <option> A </option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

How do I use itertools.groupby()?

@CaptSolo, I tried your example, but it didn't work.

from itertools import groupby 
[(c,len(list(cs))) for c,cs in groupby('Pedro Manoel')]

Output:

[('P', 1), ('e', 1), ('d', 1), ('r', 1), ('o', 1), (' ', 1), ('M', 1), ('a', 1), ('n', 1), ('o', 1), ('e', 1), ('l', 1)]

As you can see, there are two o's and two e's, but they got into separate groups. That's when I realized you need to sort the list passed to the groupby function. So, the correct usage would be:

name = list('Pedro Manoel')
name.sort()
[(c,len(list(cs))) for c,cs in groupby(name)]

Output:

[(' ', 1), ('M', 1), ('P', 1), ('a', 1), ('d', 1), ('e', 2), ('l', 1), ('n', 1), ('o', 2), ('r', 1)]

Just remembering, if the list is not sorted, the groupby function will not work!

IF statement: how to leave cell blank if condition is false ("" does not work)

I wanted to add that there is another possibility - to use the function na().

e.g. =if(a2 = 5,"good",na());

This will fill the cell with #N/A and if you chart the column, the data won't be graphed. I know it isn't "blank" as such, but it's another possibility if you have blank strings in your data and "" is a valid option.

Also, count(a:a) will not count cells which have been set to n/a by doing this.

Can I make a phone call from HTML on Android?

Yes you can; it works on Android too:

tel: phone_number
Calls the entered phone number. Valid telephone numbers as defined in the IETF RFC 3966 are accepted. Valid examples include the following:

* tel:2125551212
* tel: (212) 555 1212

The Android browser uses the Phone app to handle the “tel” scheme, as defined by RFC 3966.
Clicking a link like:

<a href="tel:2125551212">2125551212</a>

on Android will bring up the Phone app and pre-enter the digits for 2125551212 without autodialing.

Have a look to RFC3966

Hibernate SessionFactory vs. JPA EntityManagerFactory

I want to add on this that you can also get Hibernate's session by calling getDelegate() method from EntityManager.

ex:

Session session = (Session) entityManager.getDelegate();

fork() and wait() with two child processes

Put your wait() function in a loop and wait for all the child processes. The wait function will return -1 and errno will be equal to ECHILD if no more child processes are available.

Convert .pem to .crt and .key

0. Prerequisite: openssl should be installed. On Windows, if Git Bash is installed, try that! Alternate binaries can be found here.

1. Extract .key from .pem:

openssl pkey -in cert.pem -out cert.key

2. Extract .crt from .pem:

openssl crl2pkcs7 -nocrl -certfile cert.pem | openssl pkcs7 -print_certs -out cert.crt

How do I make an HTTP request in Swift?

An example for a sample "GET" request is given below.

let urlString = "YOUR_GET_URL"
let yourURL = URL(string: urlstring)
let dataTask = URLSession.shared.dataTask(with: yourURL) { (data, response, error) in
do {
    let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers)
    print("json --- \(json)")
    }catch let err {
    print("err---\(err.localizedDescription)")
    }
   }
dataTask.resume()

How to get the day name from a selected date?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace GuessTheDay
{
class Program
{
    static void Main(string[] args)
    { 
 Console.WriteLine("Enter the Day Number ");
 int day = int.Parse(Console.ReadLine());
 Console.WriteLine(" Enter The Month");
int month = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Year ");
int year = int.Parse(Console.ReadLine());
DateTime mydate = new DateTime(year,month,day);
string formatteddate = string.Format("{0:dddd}", mydate);
Console.WriteLine("The day should be " + formatteddate);
}  
 } 
   }

Where can I find the .apk file on my device, when I download any app and install?

All user installed apks are located in /data/app/, but you can only access this if you are rooted(afaik, you can try without root and if it doesn't work, rooting isn't hard. I suggest you search xda-developers for rooting instructions)

Use Root explorer or ES File Explorer to access /data/app/ (you have to keep going "up" until you reach the root directory /, kind of like C: in windows, before you can see the data directory(folder)). In ES file explorer you must also tick a checkbox in settings to allow going up to the root directory.

When you are in there you will see all your applications apks, though they might be named strangely. Just copy the wanted .apk and paste in the sd card, after that you can copy it to your computer and when you want to install it just open the .apk in a file manager (be sure to have install from unknown sources enabled in android settings). Even if you only want to send over bluetooth I would recommend copying it to the SD first.

PS Note that paid apps probably won't work being copied this way, since they usually check their licence online. PPS Installing an app this way may not link it with google play(you won't see it in my apps and it won't get updates).

Cannot enqueue Handshake after invoking quit

SOLUTION: to prevent this error(for AWS LAMBDA):

In order to exit of "Nodejs event Loop" you must end the connection, and then reconnect. Add the next code to invoke the callback:

connection.end( function(err) {
        if (err) {console.log("Error ending the connection:",err);}

       //  reconnect in order to prevent the"Cannot enqueue Handshake after invoking quit"

         connection = mysql.createConnection({
                host     : 'rds.host',
                port     :  3306,
                user     : 'user',
               password : 'password',
               database : 'target database'

               });
        callback(null, {
            statusCode: 200,
            body: response,

        });
    });

Generate random 5 characters string

function CaracteresAleatorios( $Tamanno, $Opciones) {
    $Opciones = empty($Opciones) ? array(0, 1, 2) : $Opciones;
    $Tamanno = empty($Tamanno) ? 16 : $Tamanno;
    $Caracteres=array("0123456789","abcdefghijklmnopqrstuvwxyz","ABCDEFGHIJKLMNOPQRSTUVWXYZ");
    $Caracteres= implode("",array_intersect_key($Caracteres, array_flip($Opciones)));
    $CantidadCaracteres=strlen($Caracteres)-1;
    $CaracteresAleatorios='';
    for ($k = 0; $k < $Tamanno; $k++) {
        $CaracteresAleatorios.=$Caracteres[rand(0, $CantidadCaracteres)];
    }
    return $CaracteresAleatorios;
}

Adding elements to object

Your element is not an array, however your cart needs to be an array in order to support many element objects. Code example:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push(element);

If you want cart to be an array of objects in the form { element: { id: 10, quantity: 1} } then perform:

var element = {}, cart = [];
element.id = id;
element.quantity = quantity;
cart.push({element: element});

JSON.stringify() was mentioned as a concern in the comment:

>> JSON.stringify([{a: 1}, {a: 2}]) 
      "[{"a":1},{"a":2}]" 

jQuery find parent form

I would suggest using closest, which selects the closest matching parent element:

$('input[name="submitButton"]').closest("form");

Instead of filtering by the name, I would do this:

$('input[type=submit]').closest("form");

In R, how to find the standard error of the mean?

The standard error is just the standard deviation divided by the square root of the sample size. So you can easily make your own function:

> std <- function(x) sd(x)/sqrt(length(x))
> std(c(1,2,3,4))
[1] 0.6454972

Create a file if it doesn't exist

Using input() implies Python 3, recent Python 3 versions have made the IOError exception deprecated (it is now an alias for OSError). So assuming you are using Python 3.3 or later:

fn = input('Enter file name: ')
try:
    file = open(fn, 'r')
except FileNotFoundError:
    file = open(fn, 'w')

how to configuring a xampp web server for different root directory

You can also put in a new virtual Host entry in the

c:\xampp\apache\conf\httpd-vhosts.conf

like:

<VirtualHost *:80>
  ServerAdmin [email protected]
  DocumentRoot "C:/xampp/htdocs/myproject/web"
  ServerName localhost
  ErrorLog "logs/dummy-host2.example.com-error.log"
  CustomLog "logs/dummy-host2.example.com-access.log" common
</VirtualHost>

Calling startActivity() from outside of an Activity?

Android Doc says -

FLAG_ACTIVITY_NEW_TASK requirement is now enforced

With Android 9, you cannot start an activity from a non-activity context unless you pass the intent flag FLAG_ACTIVITY_NEW_TASK. If you attempt to start an activity without passing this flag, the activity does not start, and the system prints a message to the log.

Note: The flag requirement has always been the intended behavior, and was enforced on versions lower than Android 7.0 (API level 24). A bug in Android 7.0 prevented the flag requirement from being enforced.

That means for (Build.VERSION.SDK_INT <= Build.VERSION_CODES.M) || (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) it is mandatory to add Intent.FLAG_ACTIVITY_NEW_TASK while calling startActivity() from outside of an Activity context.

So it is better to add flag for all the versions -

...
Intent i = new Intent(this, Wakeup.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
...

TSQL PIVOT MULTIPLE COLUMNS

Since you want to pivot multiple columns of data, I would first suggest unpivoting the result, score and grade columns so you don't have multiple columns but you will have multiple rows.

Depending on your version of SQL Server you can use the UNPIVOT function or CROSS APPLY. The syntax to unpivot the data will be similar to:

select ratio, col, value
from GRAND_TOTALS
cross apply
(
  select 'result', cast(result as varchar(10)) union all
  select 'score', cast(score as varchar(10)) union all
  select 'grade', grade
) c(col, value)

See SQL Fiddle with Demo. Once the data has been unpivoted, then you can apply the PIVOT function:

select ratio = col,
  [current ratio], [gearing ratio], [performance ratio], total
from
(
  select ratio, col, value
  from GRAND_TOTALS
  cross apply
  (
    select 'result', cast(result as varchar(10)) union all
    select 'score', cast(score as varchar(10)) union all
    select 'grade', grade
  ) c(col, value)
) d
pivot
(
  max(value)
  for ratio in ([current ratio], [gearing ratio], [performance ratio], total)
) piv;

See SQL Fiddle with Demo. This will give you the result:

|  RATIO | CURRENT RATIO | GEARING RATIO | PERFORMANCE RATIO |     TOTAL |
|--------|---------------|---------------|-------------------|-----------|
|  grade |          Good |          Good |      Satisfactory |      Good |
| result |       1.29400 |       0.33840 |           0.04270 |    (null) |
|  score |      60.00000 |      70.00000 |          50.00000 | 180.00000 |

Javascript "Not a Constructor" Exception while creating objects

The code as posted in the question cannot generate that error, because Project is not a user-defined function / valid constructor.

function x(a,b,c){}
new x(1,2,3);               // produces no errors

You've probably done something like this:

function Project(a,b,c) {}
Project = {};               // or possibly   Project = new Project
new Project(1,2,3);         // -> TypeError: Project is not a constructor

Variable declarations using var are hoisted and thus always evaluated before the rest of the code. So, this can also be causing issues:

function Project(){}
function localTest() {
    new Project(1,2,3); // `Project` points to the local variable,
                        // not the global constructor!

   //...some noise, causing you to forget that the `Project` constructor was used
    var Project = 1;    // Evaluated first
}

MySQL: Selecting multiple fields into multiple variables in a stored procedure

Alternatively to Martin's answer, you could also add the INTO part at the end of the query to make the query more readable:

SELECT Id, dateCreated FROM products INTO iId, dCreate

How to rename a single column in a data.frame?

This is a generalized way in which you do not have to remember the exact location of the variable:

# df = dataframe
# old.var.name = The name you don't like anymore
# new.var.name = The name you want to get

names(df)[names(df) == 'old.var.name'] <- 'new.var.name'

This code pretty much does the following:

  1. names(df) looks into all the names in the df
  2. [names(df) == old.var.name] extracts the variable name you want to check
  3. <- 'new.var.name' assigns the new variable name.

How can I check the system version of Android?

Use This method:

 public static String getAndroidVersion() {
        String versionName = "";

        try {
             versionName = String.valueOf(Build.VERSION.RELEASE);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return versionName;
    }

Convert String to Float in Swift

you can use,

let wg = Float(wage.text!)

If you want to round the float to 2 decimal places:

let wg = Float(String(format: "%.2f",wage.text!)

Save string to the NSUserDefaults?

Here Swift updated:

let userID = "BOB"  

Declare userDefaults:

let defaults = UserDefaults.standard
defaults.setValue(userID, forKey: "userID")

And get it:

let userID = defaults.object(forKey: "userID")

How to send and receive JSON data from a restful webservice using Jersey API

For me, parameter (JSONObject inputJsonObj) was not working. I am using jersey 2.* Hence I feel this is the

java(Jax-rs) and Angular way

I hope it's helpful to someone using JAVA Rest and AngularJS like me.

@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public Map<String, String> methodName(String data) throws Exception {
    JSONObject recoData = new JSONObject(data);
    //Do whatever with json object
}

Client side I used AngularJS

factory.update = function () {
data = {user:'Shreedhar Bhat',address:[{houseNo:105},{city:'Bengaluru'}]};
        data= JSON.stringify(data);//Convert object to string
        var d = $q.defer();
        $http({
            method: 'POST',
            url: 'REST/webApp/update',
            headers: {'Content-Type': 'text/plain'},
            data:data
        })
        .success(function (response) {
            d.resolve(response);
        })
        .error(function (response) {
            d.reject(response);
        });

        return d.promise;
    };

Laravel Check If Related Model Exists

As Hemerson Varela already said in Php 7.1 count(null) will throw an error and hasOne returns null if no row exists. Since you have a hasOnerelation I would use the empty method to check:

$model = RepairItem::find($id);
if (!empty($temp = $request->input('option'))) {
   $option = $model->option;

   if(empty($option)){
      $option = $model->option()->create();
   }

   $option->someAttribute = temp;
   $option->save();
};

But this is superfluous. There is no need to check if the relation exists, to determine if you should do an update or a create call. Simply use the updateOrCreate method. This is equivalent to the above:

$model = RepairItem::find($id);
if (!empty($temp = $request->input('option'))) {  
   $model->option()
         ->updateOrCreate(['repair_item_id' => $model->id],
                          ['option' => $temp]);
}

How can I sort generic list DESC and ASC?

Without Linq:

Ascending:

li.Sort();

Descending:

li.Sort();
li.Reverse();

Verilog: How to instantiate a module

This is all generally covered by Section 23.3.2 of SystemVerilog IEEE Std 1800-2012.

The simplest way is to instantiate in the main section of top, creating a named instance and wiring the ports up in order:

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  clk, rst_n, data_rx_1, data_tx ); 

endmodule

This is described in Section 23.3.2.1 of SystemVerilog IEEE Std 1800-2012.

This has a few draw backs especially regarding the port order of the subcomponent code. simple refactoring here can break connectivity or change behaviour. for example if some one else fixs a bug and reorders the ports for some reason, switching the clk and reset order. There will be no connectivity issue from your compiler but will not work as intended.

module subcomponent(
  input        rst_n,       
  input        clk,
  ...

It is therefore recommended to connect using named ports, this also helps tracing connectivity of wires in the code.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk(clk), .rst_n(rst_n), .data_rx(data_rx_1), .data_tx(data_tx) ); 

endmodule

This is described in Section 23.3.2.2 of SystemVerilog IEEE Std 1800-2012.

Giving each port its own line and indenting correctly adds to the readability and code quality.

subcomponent subcomponent_instance_name (
  .clk      ( clk       ), // input
  .rst_n    ( rst_n     ), // input
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

So far all the connections that have been made have reused inputs and output to the sub module and no connectivity wires have been created. What happens if we are to take outputs from one component to another:

clk_gen( 
  .clk      ( clk_sub   ), // output
  .en       ( enable    )  // input

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This nominally works as a wire for clk_sub is automatically created, there is a danger to relying on this. it will only ever create a 1 bit wire by default. An example where this is a problem would be for the data:

Note that the instance name for the second component has been changed

subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

The issue with the above code is that data_temp is only 1 bit wide, there would be a compile warning about port width mismatch. The connectivity wire needs to be created and a width specified. I would recommend that all connectivity wires be explicitly written out.

wire [9:0] data_temp
subcomponent subcomponent_instance_name (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_temp )  // output [9:0]
);
subcomponent subcomponent_instance_name2 (
  .clk      ( clk_sub   ), // input
  .rst_n    ( rst_n     ), // input 
  .data_rx  ( data_temp ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

Moving to SystemVerilog there are a few tricks available that save typing a handful of characters. I believe that they hinder the code readability and can make it harder to find bugs.

Use .port with no brackets to connect to a wire/reg of the same name. This can look neat especially with lots of clk and resets but at some levels you may generate different clocks or resets or you actually do not want to connect to the signal of the same name but a modified one and this can lead to wiring bugs that are not obvious to the eye.

module top(
   input        clk,
   input        rst_n,
   input        enable,
   input  [9:0] data_rx_1,
   input  [9:0] data_rx_2,
   output [9:0] data_tx_2
);

subcomponent subcomponent_instance_name (
  .clk,                    // input **Auto connect**
  .rst_n,                  // input **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

endmodule

This is described in Section 23.3.2.3 of SystemVerilog IEEE Std 1800-2012.

Another trick that I think is even worse than the one above is .* which connects unmentioned ports to signals of the same wire. I consider this to be quite dangerous in production code. It is not obvious when new ports have been added and are missing or that they might accidentally get connected if the new port name had a counter part in the instancing level, they get auto connected and no warning would be generated.

subcomponent subcomponent_instance_name (
  .*,                      // **Auto connect**
  .data_rx  ( data_rx_1 ), // input  [9:0]
  .data_tx  ( data_tx   )  // output [9:0]
);

This is described in Section 23.3.2.4 of SystemVerilog IEEE Std 1800-2012.

Error handling in Bash

This trick is useful for missing commands or functions. The name of the missing function (or executable) will be passed in $_

function handle_error {
    status=$?
    last_call=$1

    # 127 is 'command not found'
    (( status != 127 )) && return

    echo "you tried to call $last_call"
    return
}

# Trap errors.
trap 'handle_error "$_"' ERR

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

Prevent BODY from scrolling when a modal is opened

The best solution is the css-only body{overflow:hidden} solution used by most of these answers. Some answers provide a fix that also prevent the "jump" caused by the disappearing scrollbar; however, none were too elegant. So, I wrote these two functions, and they seem to work pretty well.

var $body = $(window.document.body);

function bodyFreezeScroll() {
    var bodyWidth = $body.innerWidth();
    $body.css('overflow', 'hidden');
    $body.css('marginRight', ($body.css('marginRight') ? '+=' : '') + ($body.innerWidth() - bodyWidth))
}

function bodyUnfreezeScroll() {
    var bodyWidth = $body.innerWidth();
    $body.css('marginRight', '-=' + (bodyWidth - $body.innerWidth()))
    $body.css('overflow', 'auto');
}

Check out this jsFiddle to see it in use.

Split string to equal length substrings in Java

@Test
public void regexSplit() {
    String source = "Thequickbrownfoxjumps";
    // define matcher, any char, min length 1, max length 4
    Matcher matcher = Pattern.compile(".{1,4}").matcher(source);
    List<String> result = new ArrayList<>();
    while (matcher.find()) {
        result.add(source.substring(matcher.start(), matcher.end()));
    }
    String[] expected = {"Theq", "uick", "brow", "nfox", "jump", "s"};
    assertArrayEquals(result.toArray(), expected);
}

Pass variables by reference in JavaScript

Yet another approach to pass any (local, primitive) variables by reference is by wrapping variable with closure "on the fly" by eval. This also works with "use strict". (Note: be aware that eval is not friendly to JavaScript optimizers, and also missing quotes around variable name may cause unpredictive results)

"use strict"

// Return text that will reference variable by name (by capturing that variable to closure)
function byRef(varName){
    return "({get value(){return "+varName+";}, set value(v){"+varName+"=v;}})";
}

// Demo

// Assign argument by reference
function modifyArgument(argRef, multiplier){
    argRef.value = argRef.value * multiplier;
}

(function(){
    var x = 10;

    alert("x before: " + x);
    modifyArgument(eval(byRef("x")), 42);
    alert("x after: " + x);
})()

Live sample: https://jsfiddle.net/t3k4403w/

Regex for remove everything after | (with | )

In a .txt file opened with Notepad++,
press Ctrl-F
go in the tab "Replace"
write the regex pattern \|.+ in the space Find what
and let the space Replace with blank

Then tick the choice matches newlines after the choice Regular expression
and press two times on the Replace button

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end