Programs & Examples On #Hash of hashes

A hash-of-hashes is a multi-dimensional hash that contains nested hashes.

php how to go one level up on dirname(__FILE__)

You could use PHP's dirname function. <?php echo dirname(__DIR__); ?>. That will give you the name of the parent directory of __DIR__, which stores the current directory.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

I had the same problem. (My problem is with gradle 4.4 files)

Actually the problem is incorrect downloading of 4.4 gradle which already I had. When I delete gradle 4.4 version C:\Users\$Your_User\.gradle\wrapper\dists\gradle-4.4-all

Android studio again downloads gradle-4.4 and syncs with my project.

Now it had rectified with the help of Michelin Man

Thanks for your answer Michelin

Explanation of the UML arrows

For quick reference along with clear concise examples, Allen Holub's UML Quick Reference is excellent:

http://www.holub.com/goodies/uml/

(There are quite a few specific examples of arrows and pointers in the first column of a table, with descriptions in the second column.)

How to insert element as a first child?

$('.parent-div').children(':first').before("<div class='child-div'>some text</div>");

Postgres user does not exist?

psql -U postgres

Worked fine for me in case of db name: postgres & username: postgres. So you do not need to write sudo.

And in the case other db, you may try

psql -U yourdb postgres

As it is given in Postgres help:

psql [OPTION]... [DBNAME [USERNAME]]

What is the significance of url-pattern in web.xml and how to configure servlet?

url-pattern is used in web.xml to map your servlet to specific URL. Please see below xml code, similar code you may find in your web.xml configuration file.

<servlet>
    <servlet-name>AddPhotoServlet</servlet-name>  //servlet name
    <servlet-class>upload.AddPhotoServlet</servlet-class>  //servlet class
</servlet>
 <servlet-mapping>
    <servlet-name>AddPhotoServlet</servlet-name>   //servlet name
    <url-pattern>/AddPhotoServlet</url-pattern>  //how it should appear
</servlet-mapping>

If you change url-pattern of AddPhotoServlet from /AddPhotoServlet to /MyUrl. Then, AddPhotoServlet servlet can be accessible by using /MyUrl. Good for the security reason, where you want to hide your actual page URL.

Java Servlet url-pattern Specification:

  1. A string beginning with a '/' character and ending with a '/*' suffix is used for path mapping.
  2. A string beginning with a '*.' prefix is used as an extension mapping.
  3. A string containing only the '/' character indicates the "default" servlet of the application. In this case the servlet path is the request URI minus the context path and the path info is null.
  4. All other strings are used for exact matches only.

Reference : Java Servlet Specification

You may also read this Basics of Java Servlet

The filename, directory name, or volume label syntax is incorrect inside batch

set myPATH="C:\Users\DEB\Downloads\10.1.1.0.4"
cd %myPATH%
  • The single quotes do not indicate a string, they make it starts: 'C:\ instead of C:\ so

  • %name% is the usual syntax for expanding a variable, the !name! syntax needs to be enabled using the command setlocal ENABLEDELAYEDEXPANSION first, or by running the command prompt with CMD /V:ON.

  • Don't use PATH as your name, it is a system name that contains all the locations of executable programs. If you overwrite it, random bits of your script will stop working. If you intend to change it, you need to do set PATH=%PATH%;C:\Users\DEB\Downloads\10.1.1.0.4 to keep the current PATH content, and add something to the end.

Using module 'subprocess' with timeout

I've implemented what I could gather from a few of these. This works in Windows, and since this is a community wiki, I figure I would share my code as well:

class Command(threading.Thread):
    def __init__(self, cmd, outFile, errFile, timeout):
        threading.Thread.__init__(self)
        self.cmd = cmd
        self.process = None
        self.outFile = outFile
        self.errFile = errFile
        self.timed_out = False
        self.timeout = timeout

    def run(self):
        self.process = subprocess.Popen(self.cmd, stdout = self.outFile, \
            stderr = self.errFile)

        while (self.process.poll() is None and self.timeout > 0):
            time.sleep(1)
            self.timeout -= 1

        if not self.timeout > 0:
            self.process.terminate()
            self.timed_out = True
        else:
            self.timed_out = False

Then from another class or file:

        outFile =  tempfile.SpooledTemporaryFile()
        errFile =   tempfile.SpooledTemporaryFile()

        executor = command.Command(c, outFile, errFile, timeout)
        executor.daemon = True
        executor.start()

        executor.join()
        if executor.timed_out:
            out = 'timed out'
        else:
            outFile.seek(0)
            errFile.seek(0)
            out = outFile.read()
            err = errFile.read()

        outFile.close()
        errFile.close()

Save child objects automatically using JPA Hibernate

Here are the ways to assign parent object in child object of Bi-directional relations ?

Suppose you have a relation say One-To-Many,then for each parent object,a set of child object exists. In bi-directional relations,each child object will have reference to its parent.

eg : Each Department will have list of Employees and each Employee is part of some department.This is called Bi directional relations.

To achieve this, one way is to assign parent in child object while persisting parent object

Parent parent = new Parent();
...
Child c1 = new Child();
...
c1.setParent(parent);

List<Child> children = new ArrayList<Child>();
children.add(c1);
parent.setChilds(children);

session.save(parent);

Other way is, you can do using hibernate Intercepter,this way helps you not to write above code for all models.

Hibernate interceptor provide apis to do your own work before perform any DB operation.Likewise onSave of object, we can assign parent object in child objects using reflection.

public class CustomEntityInterceptor extends EmptyInterceptor {

    @Override
    public boolean onSave(
            final Object entity, final Serializable id, final Object[] state, final String[] propertyNames,
            final Type[] types) {
        if (types != null) {
            for (int i = 0; i < types.length; i++) {
                if (types[i].isCollectionType()) {
                    String propertyName = propertyNames[i];
                    propertyName = propertyName.substring(0, 1).toUpperCase() + propertyName.substring(1);
                    try {
                        Method method = entity.getClass().getMethod("get" + propertyName);
                        List<Object> objectList = (List<Object>) method.invoke(entity);

                        if (objectList != null) {
                            for (Object object : objectList) {
                                String entityName = entity.getClass().getSimpleName();
                                Method eachMethod = object.getClass().getMethod("set" + entityName, entity.getClass());
                                eachMethod.invoke(object, entity);
                            }
                        }

                    } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        }
        return true;
    }

}

And you can register Intercepter to configuration as

new Configuration().setInterceptor( new CustomEntityInterceptor() );

How can I create a temp file with a specific extension with .NET?

You can also do the following

string filename = Path.ChangeExtension(Path.GetTempFileName(), ".csv");

and this also works as expected

string filename = Path.ChangeExtension(Path.GetTempPath() + Guid.NewGuid().ToString(), ".csv");

Single vs Double quotes (' vs ")

The w3 org said:

By default, SGML requires that all attribute values be delimited using either double quotation marks (ASCII decimal 34) or single quotation marks (ASCII decimal 39). Single quote marks can be included within the attribute value when the value is delimited by double quote marks, and vice versa. Authors may also use numeric character references to represent double quotes (&#34;) and single quotes (&#39;). For double quotes authors can also use the character entity reference &quot;.

So... seems to be no difference. Only depends on your style.

How to add 30 minutes to a JavaScript Date object?

Here is the IsoString version:

_x000D_
_x000D_
console.log(new Date(new Date().setMinutes(new Date().getMinutes() - (30))).toISOString());
_x000D_
_x000D_
_x000D_

"The page has expired due to inactivity" - Laravel 5.5

I had the same problem but the problem is not in the framework but in the browser. I don't know why but google chrome blocks cookies automatically, in my case. After allowed cookies the problem was resolved.

Controlling a USB power supply (on/off) with Linux

You could use my tool uhubctl to control USB power per port for compatible USB hubs.

Setting format and value in input type="date"

The format is YYYY-MM-DD. You cannot change it.

$('#myinput').val('2013-12-31'); sets value

Delete terminal history in Linux

If you use bash, then the terminal history is saved in a file called .bash_history. Delete it, and history will be gone.

However, for MySQL the better approach is not to enter the password in the command line. If you just specify the -p option, without a value, then you will be prompted for the password and it won't be logged.

Another option, if you don't want to enter your password every time, is to store it in a my.cnf file. Create a file named ~/.my.cnf with something like:

[client]
user = <username>
password = <password>

Make sure to change the file permissions so that only you can read the file.

Of course, this way your password is still saved in a plaintext file in your home directory, just like it was previously saved in .bash_history.

How do I force "git pull" to overwrite local files?

You might find this command helpful to throw away local changes:

git checkout <your-branch> -f

And then do a cleanup (removes untracked files from the working tree):

git clean -f

If you want to remove untracked directories in addition to untracked files:

git clean -fd

How can bcrypt have built-in salts?

To make things even more clearer,

Registeration/Login direction ->

The password + salt is encrypted with a key generated from the: cost, salt and the password. we call that encrypted value the cipher text. then we attach the salt to this value and encoding it using base64. attaching the cost to it and this is the produced string from bcrypt:

$2a$COST$BASE64

This value is stored eventually.

What the attacker would need to do in order to find the password ? (other direction <- )

In case the attacker got control over the DB, the attacker will decode easily the base64 value, and then he will be able to see the salt. the salt is not secret. though it is random. Then he will need to decrypt the cipher text.

What is more important : There is no hashing in this process, rather CPU expensive encryption - decryption. thus rainbow tables are less relevant here.

Darken background image on hover

.image:hover {
   background: #000;
    width: 58px;
    height: 58px;
    border-radius:60px;

}

You will get darken

Call a Subroutine from a different Module in VBA

Prefix the call with Module2 (ex. Module2.IDLE). I'm assuming since you asked this that you have IDLE defined multiple times in the project, otherwise this shouldn't be necessary.

Installing ADB on macOS

  1. You must download Android SDK from this link.

  2. You can really put it anywhere, but the best place at least for me was right in the YOUR USERNAME folder root.

  3. Then you need to set the path by copying the below text, but edit your username into the path, copy the text into Terminal by hitting command+spacebar type terminal. export PATH = ${PATH}:/Users/**YOURUSERNAME**/android-sdk/platform-tools/

  4. Verify ADB works by hitting command+spacebar and type terminal, and type ADB.

There you go. You have ADB setup on MAC OS X. It works on latest MAC OS X 10.10.3.

Adding System.Web.Script reference in class library

The ScriptIgnoreAttribute class is in the System.Web.Extensions.dll assembly (Located under Assemblies > Framework in the VS Reference Manager). You have to add a reference to that assembly in your class library project.

You can find this information at top of the MSDN page for the ScriptIgnoreAttribute class.

Vbscript list all PDF files in folder and subfolders

Check this code :

Set objFSO = CreateObject("Scripting.FileSystemObject") 

objStartFolder = "C:\Folder1\"

Set objFolder = objFSO.GetFolder(objStartFolder)

Set colFiles = objFolder.Files

For Each objFile in colFiles 
    strFileName = objFile.Name

    If objFSO.GetExtensionName(strFileName) = "pdf" Then 
        Wscript.Echo objFile.Name 
    End If
Next

ShowSubfolders objFSO.GetFolder(objStartFolder)

Sub ShowSubFolders(Folder)

    For Each Subfolder in Folder.SubFolders 
        Set objFolder = objFSO.GetFolder(Subfolder.Path) 
        Set colFiles = objFolder.Files 
        for each Files in colFiles 
            if LCase(InStr(1,Files, ".pdf")) > 1 then Wscript.Echo Files 
        next
        ShowSubFolders Subfolder 
    Next 
End Sub

Returning from a void function

An old question, but I'll answer anyway. The answer to the actual question asked is that the bare return is redundant and should be left out.

Furthermore, the suggested value is false for the following reason:

if (ret<0) return;

Redefining a C reserved word as a macro is a bad idea on the face of it, but this particular suggestion is simply unsupportable, both as an argument and as code.

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

<style name="Theme.IOSched" parent="android:style/Theme.Holo.Light">
    <item name="android:windowBackground">@drawable/window_background</item>
    <item name="android:actionBarStyle">@style/ActionBar</item>
</style>

you can not give your own color and backgroud in item windowBackground. give your color in your /color.xml file.

How to set a bitmap from resource

Assuming you are calling this in an Activity class

Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.image);

The first parameter, Resources, is required. It is normally obtainable in any Context (and subclasses like Activity).

What are NDF Files?

Secondary data files are optional, are user-defined, and store user data. Secondary files can be used to spread data across multiple disks by putting each file on a different disk drive. Additionally, if a database exceeds the maximum size for a single Windows file, you can use secondary data files so the database can continue to grow.

Source: MSDN: Understanding Files and Filegroups

The recommended file name extension for secondary data files is .ndf, but this is not enforced.

Laravel-5 how to populate select box from database with id value and name value

Controller

 $campaignStatus = Campaign::lists('status', 'id');

compact('campaignStatus') will result in [id=>status]; //example [1 => 'pending']

return view('management.campaign.index', compact('campaignStatus'));

View

{!! Form::select('status', $campaignStatus, array('class' => 'form-control')) !!}

AJAX in Chrome sending OPTIONS instead of GET/POST/PUT/DELETE?

Chrome is preflighting the request to look for CORS headers. If the request is acceptable, it will then send the real request. If you're doing this cross-domain, you will simply have to deal with it or else find a way to make the request non-cross-domain. This is why the jQuery bug was closed as won't-fix. This is by design.

Unlike simple requests (discussed above), "preflighted" requests first send an HTTP request by the OPTIONS method to the resource on the other domain, in order to determine whether the actual request is safe to send. Cross-site requests are preflighted like this since they may have implications to user data. In particular, a request is preflighted if:

  • It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.
  • It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)

Time calculation in php (add 10 hours)?

$tz = new DateTimeZone('Europe/London');
$date = new DateTime($today, $tz);
$date->modify('+10 hours');
// use $date->format() to outputs the result.

see DateTime Class (PHP 5 >= 5.2.0)

JQuery $.ajax() post - data in a java servlet

For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:

  &A2168=1&A1837=5&A8472=1&A1987=2

On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:

Enumeration keys = request.getParameterNames(); 
HashMap map = new HashMap(); 
String key = null; 
while(keys.hasMoreElements()){ 
      key = keys.nextElement().toString(); 
      map.put(key, request.getParameter(key)); 
}

Wheel file installation

If you already have a wheel file (.whl) on your pc, then just go with the following code:

cd ../user
pip install file.whl

If you want to download a file from web, and then install it, go with the following in command line:

pip install package_name

or, if you have the url:

pip install http//websiteurl.com/filename.whl

This will for sure install the required file.

Note: I had to type pip2 instead of pip while using Python 2.

PHP Checking if the current date is before or after a set date

If you are looking for a generic way of doing this via MySQL, you could simply use a SELECT statement, and add the WHERE clause to it.

This will grab all fields for all rows, where the date stored in field "date" is before "now".

SELECT * FROM table WHERE UNIX_TIMESTAMP(`date`) < UNIX_TIMESTAMP()

Personally, I found this method to be more gentle on newbies in MySQL, since it uses the standard SELECT statement with WHERE to fetch the results. Obviously, you could grab only the fields relevant if you wanted to, by listing them instead of using a wildcard (*).

How to correctly display .csv files within Excel 2013?

I know that an answer has already been accepted, but one item to check is the encoding of the CSV file. I have a Powershell script that generates CSV files. By default, it was encoding them as UCS-2 Little Endian (per Notepad++). It would open the file in a single column in Excel and I'd have to do the Text to Columns conversion to split the columns. Changing the script to encode the same output as "ASCII" (UTF-8 w/o BOM per Notepad++) allowed me to open the CSV directly with the columns split out. You can change the encoding of the CSV in Notepad++ too.

  • Menu Encoding > Convert to UTF-8 without BOM
  • Save the CSV file
  • Open in Excel, columns should be split

Sorting a set of values

From a comment:

I want to sort each set.

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

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

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


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

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

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

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


* See the comments for exceptions.

SQLite - UPSERT *not* INSERT or REPLACE

Following Aristotle Pagaltzis and the idea of COALESCE from Eric B’s answer, here it is an upsert option to update only few columns or insert full row if it does not exist.

In this case, imagine that title and content should be updated, keeping the other old values when existing and inserting supplied ones when name not found:

NOTE id is forced to be NULL when INSERT as it is supposed to be autoincrement. If it is just a generated primary key then COALESCE can also be used (see Aristotle Pagaltzis comment).

WITH new (id, name, title, content, author)
     AS ( VALUES(100, 'about', 'About this site', 'Whatever new content here', 42) )
INSERT OR REPLACE INTO page (id, name, title, content, author)
SELECT
     old.id, COALESCE(old.name, new.name),
     new.title, new.content,
     COALESCE(old.author, new.author)
FROM new LEFT JOIN page AS old ON new.name = old.name;

So the general rule would be, if you want to keep old values, use COALESCE, when you want to update values, use new.fieldname

How to set a cookie for another domain

You can't, but... If you own both pages then...

1) You can send the data via query params (http://siteB.com/?key=value)

2) You can create an iframe of Site B inside site A and you can send post messages from one place to the other. As Site B is the owner of site B cookies it will be able to set whatever value you need by processing the correct post message. (You should prevent other unwanted senders to send messages to you! that is up to you and the mechanism you decide to use to prevent that from happening)

How to get full width in body element

You can use CSS to do it for example

<style>
html{
    width:100%;
    height:100%;
}
body{
    width:100%;
    height:100%;
    background-color:#DDD;
}
</style>

What is difference between sleep() method and yield() method of multi threading?

Yield : will make thread to wait for the currently executing thread and the thread which has called yield() will attaches itself at the end of the thread execution. The thread which call yield() will be in Blocked state till its turn.

Sleep : will cause the thread to sleep in sleep mode for span of time mentioned in arguments.

Join : t1 and t2 are two threads , t2.join() is called then t1 enters into wait state until t2 completes execution. Then t1 will into runnable state then our specialist JVM thread scheduler will pick t1 based on criteria's.

Convert a double to a QString

Use QString's number method (docs are here):

double valueAsDouble = 1.2;
QString valueAsString = QString::number(valueAsDouble);

How to add style from code behind?

You can't.

So just don't apply styles directly like that, and apply a class "foo", and then define that in your CSS specification:

a.foo { color : orange; }
a.foo:hover { font-weight : bold; }

How to display HTML tags as plain text

As many others have said, htmlentities() will do the trick... but it will look like shit.

Wrap it up with a <pre> tag and you'll preserve your indentation.

echo '<pre>';
echo htmlspecialchars($YOUR_HTML);
echo '</pre>';

Mosaic Grid gallery with dynamic sized images

I think you can try "Google Grid Gallery", it based on aforementioned Masonry with some additions, like styles and viewer.

Downloading a large file using curl

Find below code if you want to download the contents of the specified URL also want to saves it to a file.

<?php
$ch = curl_init();
/**
* Set the URL of the page or file to download.
*/
curl_setopt($ch, CURLOPT_URL,'http://news.google.com/news?hl=en&topic=t&output=rss');

$fp = fopen('rss.xml', 'w+');
/**
* Ask cURL to write the contents to a file
*/
curl_setopt($ch, CURLOPT_FILE, $fp);

curl_exec ($ch);

curl_close ($ch);
fclose($fp);
?>

If you want to downloads file from the FTP server you can use php FTP extension. Please find below code:

<?php
$SERVER_ADDRESS="";
$SERVER_USERNAME="";
$SERVER_PASSWORD="";
$conn_id = ftp_connect($SERVER_ADDRESS);

// login with username and password
$login_result = ftp_login($conn_id, $SERVER_USERNAME, $SERVER_PASSWORD);

$server_file="test.pdf" //FTP server file path 
$local_file = "new.pdf"; //Local server file path 

##----- DOWNLOAD $SERVER_FILE AND SAVE TO $LOCAL_FILE--------##
if (ftp_get($conn_id, $local_file, $server_file, FTP_BINARY)) {
    echo "Successfully written to $local_file\n";
} else {
    echo "There was a problem\n";
}

ftp_close($conn_id);
?>

Android button with icon and text

You can use the Material Components Library and the MaterialButton component.
Use the app:icon and app:iconGravity="start" attributes.

Something like:

  <com.google.android.material.button.MaterialButton
        style="@style/Widget.MaterialComponents.Button.Icon"
        app:icon="@drawable/..."
        app:iconGravity="start"
        ../>

enter image description here

Find out which remote branch a local branch is tracking

Following command will remote origin current fork is referring to

git remote -v

For adding a remote path,

git remote add origin path_name

Converting ISO 8601-compliant String to java.util.Date

Use string like LocalDate.parse(((String) data.get("d_iso8601")),DateTimeFormatter.ISO_DATE)

What's the difference between UTF-8 and UTF-8 without BOM?

From http://en.wikipedia.org/wiki/Byte-order_mark:

The byte order mark (BOM) is a Unicode character used to signal the endianness (byte order) of a text file or stream. Its code point is U+FEFF. BOM use is optional, and, if used, should appear at the start of the text stream. Beyond its specific use as a byte-order indicator, the BOM character may also indicate which of the several Unicode representations the text is encoded in.

Always using a BOM in your file will ensure that it always opens correctly in an editor which supports UTF-8 and BOM.

My real problem with the absence of BOM is the following. Suppose we've got a file which contains:

abc

Without BOM this opens as ANSI in most editors. So another user of this file opens it and appends some native characters, for example:

abg-aß?

Oops... Now the file is still in ANSI and guess what, "aß?" does not occupy 6 bytes, but 3. This is not UTF-8 and this causes other problems later on in the development chain.

SQL Server after update trigger

try this solution.

       DECLARE @Id INT
       DECLARE @field VARCHAR(50)

       SELECT @Id= INSERTED.CustomerId       
       FROM INSERTED

       IF UPDATE(Name)
       BEGIN
              SET @field = 'Updated Name'
       END

       IF UPDATE(Country)
       BEGIN
              SET @field = 'Updated Country'
       END

       INSERT INTO CustomerLogs
       VALUES(@Id, @field)

       // OR
       -- If you wish to update existing table records.
       UPDATE YOUR_TABLE SET [FIELD]=[VALUE] WHERE {CONDITION}

I didn't checked this with older version of sql server but this will work with sql server 2012.

How to create a readonly textbox in ASP.NET MVC3 Razor

@Html.TextBoxFor(m => m.userCode, new { @readonly="readonly" })

You are welcome to make an HTML Helper for this, but this is simply just an HTML attribute like any other. Would you make an HTML Helper for a text box that has other attributes?

Determine if map contains a value for a key?

amap.find returns amap::end when it does not find what you're looking for -- you're supposed to check for that.

What does %5B and %5D in POST requests stand for?

Not least important is why these symbols occur in url. See https://www.php.net/manual/en/function.parse-str.php#76792, specifically:

parse_str('foo[]=1&foo[]=2&foo[]=3', $bar);

the above produces:

$bar = ['foo' => ['1', '2', '3'] ];

and what is THE method to separate query vars in arrays (in php, at least).

Config Error: This configuration section cannot be used at this path

The following worked for me:

Go to project properties. Web tab. Set to Local IIS and set specific page.

I have Windows 7 and Visual Studio 2013.

How to put text over images in html?

You can try this...

<div class="image">

      <img src="" alt="" />

      <h2>Text you want to display over the image</h2>

</div>

CSS

.image { 
   position: relative; 
   width: 100%; /* for IE 6 */
}

h2 { 
   position: absolute; 
   top: 200px; 
   left: 0; 
   width: 100%; 
}

How do I write a bash script to restart a process if it dies?

I've used the following script with great success on numerous servers:

pid=`jps -v | grep $INSTALLATION | awk '{print $1}'`
echo $INSTALLATION found at PID $pid 
while [ -e /proc/$pid ]; do sleep 0.1; done

notes:

  • It's looking for a java process, so I can use jps, this is much more consistent across distributions than ps
  • $INSTALLATION contains enough of the process path that's it's totally unambiguous
  • Use sleep while waiting for the process to die, avoid hogging resources :)

This script is actually used to shut down a running instance of tomcat, which I want to shut down (and wait for) at the command line, so launching it as a child process simply isn't an option for me.

can't load package: package .: no buildable Go source files

If you want all packages in that repository, use ... to signify that, like:

go get code.google.com/p/go.text/...

Saving and loading objects and using pickle

As for your second problem:

 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "C:\Python31\lib\pickle.py", line
 1365, in load encoding=encoding,
 errors=errors).load() EOFError

After you have read the contents of the file, the file pointer will be at the end of the file - there will be no further data to read. You have to rewind the file so that it will be read from the beginning again:

file.seek(0)

What you usually want to do though, is to use a context manager to open the file and read data from it. This way, the file will be automatically closed after the block finishes executing, which will also help you organize your file operations into meaningful chunks.

Finally, cPickle is a faster implementation of the pickle module in C. So:

In [1]: import _pickle as cPickle

In [2]: d = {"a": 1, "b": 2}

In [4]: with open(r"someobject.pickle", "wb") as output_file:
   ...:     cPickle.dump(d, output_file)
   ...:

# pickle_file will be closed at this point, preventing your from accessing it any further

In [5]: with open(r"someobject.pickle", "rb") as input_file:
   ...:     e = cPickle.load(input_file)
   ...:

In [7]: print e
------> print(e)
{'a': 1, 'b': 2}

How to load image to WPF in runtime?

Make sure that your sas.png is marked as Build Action: Content and Copy To Output Directory: Copy Always in its Visual Studio Properties...

I think the C# source code goes like this...

Image image = new Image();
image.Source = (new ImageSourceConverter()).ConvertFromString("pack://application:,,,/Bilder/sas.png") as ImageSource;

and XAML should be

<Image Height="200" HorizontalAlignment="Left" Margin="12,12,0,0" 
       Name="image1" Stretch="Fill" VerticalAlignment="Top" 
       Source="../Bilder/sas.png"
       Width="350" />  

EDIT

Dynamically I think XAML would provide best way to load Images ...

<Image Source="{Binding Converter={StaticResource MyImageSourceConverter}}"
       x:Name="MyImage"/>

where image.DataContext is string path.

MyImage.DataContext = "pack://application:,,,/Bilder/sas.png";

public class MyImageSourceConverter : IValueConverter
{
    public object Convert(object value_, Type targetType_, 
    object parameter_, System.Globalization.CultureInfo culture_)
    {
        return (new ImageSourceConverter()).ConvertFromString (value.ToString());
    }

    public object ConvertBack(object value, Type targetType, 
    object parameter, CultureInfo culture)
    {
          throw new NotImplementedException();
    }
}

Now as you set a different data context, Image would be automatically loaded at runtime.

Class Not Found: Empty Test Suite in IntelliJ

I had the same issue in my environment also (MacOS). I was using IntelliJ 2016. I had a Java library project (gradle).

What I did was

  1. Opened/exported project from a IntelliJ older version (like IntelliJ14). This happened successfully and I verified it with by making the project and by running a test case.
  2. Then I imported that project again via IntelliJ 2016. After that it worked fine(building and test case running).

reading a line from ifstream into a string variable

Use the std::getline() from <string>.

 istream & getline(istream & is,std::string& str)

So, for your case it would be:

std::getline(read,x);

Is there a Google Chrome-only CSS hack?

Sure is:

@media screen and (-webkit-min-device-pixel-ratio:0)
{ 
    #element { properties:value; } 
}

And a little fiddle to see it in action - http://jsfiddle.net/Hey7J/

Must add tho... this is generally bad practice, you shouldn't really be at the point where you start to need individual browser hacks to make you CSS work. Try using reset style sheets at the start of your project, to help avoid this.

Also, these hacks may not be future proof.

jquery 3.0 url.indexOf error

I came across the same error after updating to the latest version of JQuery. Therefore I updated the jquery file I was working on, as stated in a previous answer, so it said .on("load") instead of .load().

This fix isn't very stable and sometimes it didn't work for me. Therefore to fix this issue you should update your code from:

    .load();

to

    .trigger("load");

I got this fix from the following source: https://github.com/stevenwanderski/bxslider-4/pull/1024

Run JavaScript when an element loses focus

From w3schools.com: Made compatible with Firefox Sept, 2016

<input type="text" onfocusout="myFunction()">

Android: Expand/collapse animation

I have used the same code block that have used in accepted answer , But it wont work as same in android 9 , So update the measure according to this

v.measure(MeasureSpec.makeMeasureSpec(parentView.getWidth(), MeasureSpec.EXACTLY), MeasureSpec.makeMeasureSpec(parentView.getWidth(), MeasureSpec.AT_MOST));

How the constraint works bit different in android 9.

UnicodeEncodeError: 'latin-1' codec can't encode character

I ran into this same issue when using the Python MySQLdb module. Since MySQL will let you store just about any binary data you want in a text field regardless of character set, I found my solution here:

Using UTF8 with Python MySQLdb

Edit: Quote from the above URL to satisfy the request in the first comment...

"UnicodeEncodeError:'latin-1' codec can't encode character ..."

This is because MySQLdb normally tries to encode everythin to latin-1. This can be fixed by executing the following commands right after you've etablished the connection:

db.set_character_set('utf8')
dbc.execute('SET NAMES utf8;')
dbc.execute('SET CHARACTER SET utf8;')
dbc.execute('SET character_set_connection=utf8;')

"db" is the result of MySQLdb.connect(), and "dbc" is the result of db.cursor().

PHPDoc type hinting for array of objects?

To specify a variable is an array of objects:

$needles = getAllNeedles();
/* @var $needles Needle[] */
$needles[1]->...                        //codehinting works

This works in Netbeans 7.2 (I'm using it)

Works also with:

$needles = getAllNeedles();
/* @var $needles Needle[] */
foreach ($needles as $needle) {
    $needle->...                        //codehinting works
}

Therefore use of declaration inside the foreach is not necessary.

Open file dialog box in JavaScript

First add in the head tags:

<script>
   function showDialog(openFileDialog) {
       document.getElementById(openFileDialog).click();
   }
   function fileName(openFileDialog) {
       return document.getElementById(openFileDialog).value;
   }
   function hasFile(openFileDialog) {
       return document.getElementById(openFileDialog).value != "";
   }
   function fileNameWithoutFakePath(openFileDialog) {
       var fileName = document.getElementById(openFileDialog).value;
       return fileName.substr(fileName.lastIndexOf('\\') + 1);
   }
   function fakePathWithoutFileName(openFileDialog) {
       var fileName = document.getElementById(openFileDialog).value;
       return fileName.substr(0, fileName.lastIndexOf('\\'));
   }
</script>

if you already have script tags, just add these functions above.

In your body or form tags adding:

<input type="file" style="display:none" id="yourDesiredOrFavoriteNameForTheNewOpenFileDialogInstance"/>

No matter where in your html, is just like that you've created a new instance of type OpenFileDialog class as global variable, whose name is the id of the element, no matter where in your code or xaml, but in your script or code, you can't type his name, and then read a property or call a function, because there are global functions that do those that are not defined in the element input type="file". You just have to give these functions the id of the hidden input type="file" which is the name of the OpenFileDialog instance as string.

To ease your life in creating open file dialogs instances to your html, you can make a function that does it:

function createAndAddNewOpenFileDialog(name) {
     document.getElementById("yourBodyOrFormId").innerHtml += "<input type='file' style='display:none' id='" + name + "'/>"
}

and if you want to remove open file dialog, then you can make and use the following function:

function removeOpenFileDialog(name) {
    var html = document.getElementById("yourBodyOrFormId").innerHtml;
    html = html.replace("<input type='file' style='display:none' id='" + name + "'/>", "");
    document.getElementById("yourBodyOrFormId").innerHtml = html;
}

but before you remove open file dialog, ensure that it exists by making and using the following function:

function doesOpenFileDialogExist(name) {
    return document.getElementById("yourBodyOrFormId").innerHtml.indexOf("<input type='file' style='display:none' id='" + name + "'/>") != -1
}

and if you don't want to create and add the open file dialogs in the body or form tags in the html, because this is adding hidden input type="file"s, then you can do it in script using the create function above:

function yourBodyOrFormId_onload() {
    createAndAddNewOpenFileDialog("openFileDialog1");
    createAndAddNewOpenFileDialog("openFileDialog2");
    createAndAddNewOpenFileDialog("openFileDialog3");
    createAndAddNewOpenFileDialog("File Upload");
    createAndAddNewOpenFileDialog("Image Upload");
    createAndAddNewOpenFileDialog("bla");
    //etc and rest of your code
}

Ensure that near your body or form tags, you added:

onload="yourBodyOrFormId_onload()"

You don't have to do this line above, if you did it already.

TIP: You can add to your project or website new JScript File, if you don't have yet, and in this file you can put all the open file dialog functions away from the script tags and the html or web form page, and use them in your html or web form page from this JScript file, but don't forget before to link the html or web form page to the JScript File of course. You can do it just by dragging the JScript file to your html page in the head tags. If your page is web form and not simple html, and you don't have head tags, then put it anywhere so that it can work. Don't forget to define global variable in that JScript File, whose value will be your body or form id as string. After you linked the JScript file to your html or web form page, you can onload event of your body of form, set the value of that variable to your body or form id. Then in the JScript File, you don't have to give to the document the id of the body or form of one page anymore, just give it the value of that variable. You can call that variable bodyId or formId or bodyOrFormId or any other name you want.

Good luck man!

MySQL: Enable LOAD DATA LOCAL INFILE

Add local_infile in both client and mysqld section.

[client]
local_infile=1
...

[mysqld]
local_infile=1
...

Tested in MySQL 8.x both in Windows and Linux.

The remote server returned an error: (407) Proxy Authentication Required

I had a similar proxy related problem. In my case it was enough to add:

webRequest.Proxy.Credentials = new NetworkCredential("user", "password", "domain");

T-SQL: Selecting rows to delete via joins

It's almost the same in MySQL, but you have to use the table alias right after the word "DELETE":

DELETE a
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]

How to implement a ViewPager with different Fragments / Layouts

Code for adding fragment

public Fragment getItem(int position) {

    switch (position){
        case 0:
            return new Fragment1();

        case 1:
            return new Fragment2();

        case 2:
            return new Fragment3();

        case 3:
            return new Fragment4();

        default:
            break;
    }

    return null;
}

Create an xml file for each fragment say for Fragment1, use fragment_one.xml as layout file, use the below code in Fragment1 java file.

public class Fragment1 extends Fragment {

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_one, container, false);

        return view;

    }
}

Later you can make necessary corrections.. It worked for me.

OS specific instructions in CMAKE: How to?

Use some preprocessor macro to check if it's in windows or linux. For example

#ifdef WIN32
LIB= 
#elif __GNUC__
LIB=wsock32
#endif

include -l$(LIB) in you build command.

You can also specify some command line argument to differentiate both.

Is it possible to have multiple statements in a python lambda expression?

You can in fact have multiple statements in a lambda expression in python. It is not entirely trivial but in your example, the following works:

map(lambda x: x.sort() or x[1],lst)

You have to make sure that each statement does not return anything or if it does wrap it in (.. and False). The result is what is returned by the last evaluation.

Example:

>>> f = (lambda : (print(1) and False) or (print(2) and False) or (print(3) and False))
>>> f()
1
2
3

What JSON library to use in Scala?

Lift-json is at version 2.6 and it works really well (and is also very well supported, the maintainer is always ready to fix any bugs users may find. You can find examples using it on the github repository

The maintainer (Joni Freeman) is always reachable on the Lift mailing list. There are also other users on the mailing list who are very helpful as well.

As @Alexey points out, if you want to use the library with other Scala version, say 2.11.x, change scalaVersion and use %% as follows:

scalaVersion := "2.11.5" 

"net.liftweb" %% "lift-json" % "2.6"

You can check the liftweb.net site to find out the latest version as time goes by.

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

You can use javax.xml.bind.DatatypeConverter class

DatatypeConverter.printDateTime & DatatypeConverter.parseDateTime

Can we create an instance of an interface in Java?

You can never instantiate an interface in java. You can, however, refer to an object that implements an interface by the type of the interface. For example,

public interface A
{
}
public class B implements A
{
}

public static void main(String[] args)
{
    A test = new B();
    //A test = new A(); // wont compile
}

What you did above was create an Anonymous class that implements the interface. You are creating an Anonymous object, not an object of type interface Test.

Find an object in array?

For Swift 3,

let index = array.index(where: {$0.name == "foo"})

Passing parameter via url to sql server reporting service

http://desktop-qr277sp/Reports01/report/Reports/reportName?Log%In%Name=serverUsername&paramName=value

Pass parameter to the report with server authentication

Add querystring parameters to link_to

In case you want to pass in a block, say, for a glyphicon button, as in the following:

<%= link_to my_url, class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

Then passing querystrings params could be accomplished through:

<%= link_to url_for(params.merge(my_params: "value")), class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

Select folder dialog WPF

MVVM + WinForms FolderBrowserDialog as behavior

public class FolderDialogBehavior : Behavior<Button>
{
    public string SetterName { get; set; }

    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Click += OnClick;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Click -= OnClick;
    }

    private void OnClick(object sender, RoutedEventArgs e)
    {
        var dialog = new FolderBrowserDialog();
        var result = dialog.ShowDialog();
        if (result == DialogResult.OK && AssociatedObject.DataContext != null)
        {
            var propertyInfo = AssociatedObject.DataContext.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public)
            .Where(p => p.CanRead && p.CanWrite)
            .Where(p => p.Name.Equals(SetterName))
            .First();

            propertyInfo.SetValue(AssociatedObject.DataContext, dialog.SelectedPath, null);
        }
    }
}

Usage

     <Button Grid.Column="3" Content="...">
            <Interactivity:Interaction.Behaviors>
                <Behavior:FolderDialogBehavior SetterName="SomeFolderPathPropertyName"/>
            </Interactivity:Interaction.Behaviors>
     </Button>

Blogpost: http://kostylizm.blogspot.ru/2014/03/wpf-mvvm-and-winforms-folder-dialog-how.html

sql - insert into multiple tables in one query

MySQL doesn't support multi-table insertion in a single INSERT statement. Oracle is the only one I'm aware of that does, oddly...

INSERT INTO NAMES VALUES(...)
INSERT INTO PHONES VALUES(...)

C++ performance vs. Java/C#

Whenever I talk managed vs. unmanaged performance, I like to point to the series Rico (and Raymond) did comparing C++ and C# versions of a Chinese/English dictionary. This google search will let you read for yourself, but I like Rico's summary.

So am I ashamed by my crushing defeat? Hardly. The managed code got a very good result for hardly any effort. To defeat the managed Raymond had to:

  • Write his own file I/O stuff
  • Write his own string class
  • Write his own allocator
  • Write his own international mapping

Of course he used available lower level libraries to do this, but that's still a lot of work. Can you call what's left an STL program? I don't think so, I think he kept the std::vector class which ultimately was never a problem and he kept the find function. Pretty much everything else is gone.

So, yup, you can definately beat the CLR. Raymond can make his program go even faster I think.

Interestingly, the time to parse the file as reported by both programs internal timers is about the same -- 30ms for each. The difference is in the overhead.

For me the bottom line is that it took 6 revisions for the unmanaged version to beat the managed version that was a simple port of the original unmanaged code. If you need every last bit of performance (and have the time and expertise to get it), you'll have to go unmanaged, but for me, I'll take the order of magnitude advantage I have on the first versions over the 33% I gain if I try 6 times.

Min width in window resizing

Well, you pretty much gave yourself the answer. In your CSS give the containing element a min-width. If you have to support IE6 you can use the min-width-trick:

#container {
    min-width:800px;
    width: auto !important;
    width:800px;
}

That will effectively give you 800px min-width in IE6 and any up-to-date browsers.

How do I show a console output/window in a forms application?

There are basically two things that can happen here.

Console output It is possible for a winforms program to attach itself to the console window that created it (or to a different console window, or indeed to a new console window if desired). Once attached to the console window Console.WriteLine() etc works as expected. One gotcha to this approach is that the program returns control to the console window immediately, and then carries on writing to it, so the user can also type away in the console window. You can use start with the /wait parameter to handle this I think.

Link to start Command syntax

Redirected console output This is when someone pipes the output from your program somewhere else, eg.

yourapp > file.txt

Attaching to a console window in this case effectively ignores the piping. To make this work you can call Console.OpenStandardOutput() to get a handle to the stream that the output should be piped to. This only works if the output is piped, so if you want to handle both of the scenarios you need to open the standard output and write to it and attach to the console window. This does mean that the output is sent to the console window and to the pipe but its the best solution I could find. Below the code I use to do this.

// This always writes to the parent console window and also to a redirected stdout if there is one.
// It would be better to do the relevant thing (eg write to the redirected file if there is one, otherwise
// write to the console) but it doesn't seem possible.
public class GUIConsoleWriter : IConsoleWriter
{
    [System.Runtime.InteropServices.DllImport("kernel32.dll")]
    private static extern bool AttachConsole(int dwProcessId);

    private const int ATTACH_PARENT_PROCESS = -1;

    StreamWriter _stdOutWriter;

    // this must be called early in the program
    public GUIConsoleWriter()
    {
        // this needs to happen before attachconsole.
        // If the output is not redirected we still get a valid stream but it doesn't appear to write anywhere
        // I guess it probably does write somewhere, but nowhere I can find out about
        var stdout = Console.OpenStandardOutput();
        _stdOutWriter = new StreamWriter(stdout);
        _stdOutWriter.AutoFlush = true;

        AttachConsole(ATTACH_PARENT_PROCESS);
    }

    public void WriteLine(string line)
    {
        _stdOutWriter.WriteLine(line);
        Console.WriteLine(line);
    }
}

handle textview link click in my android app

for who looks for more options here is a one

// Set text within a `TextView`
TextView textView = (TextView) findViewById(R.id.textView);
textView.setText("Hey @sarah, where did @jim go? #lost");
// Style clickable spans based on pattern
new PatternEditableBuilder().
    addPattern(Pattern.compile("\\@(\\w+)"), Color.BLUE,
       new PatternEditableBuilder.SpannableClickedListener() {
        @Override
        public void onSpanClicked(String text) {
            Toast.makeText(MainActivity.this, "Clicked username: " + text,
                Toast.LENGTH_SHORT).show();
        }
}).into(textView);

RESOURCE : CodePath

Generating a random password in php

Generates a strong password of length 8 containing at least one lower case letter, one uppercase letter, one digit, and one special character. You can change the length in the code too.

function checkForCharacterCondition($string) {
    return (bool) preg_match('/(?=.*([A-Z]))(?=.*([a-z]))(?=.*([0-9]))(?=.*([~`\!@#\$%\^&\*\(\)_\{\}\[\]]))/', $string);
}

$j = 1;

function generate_pass() {
    global $j;
    $allowedCharacters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ~`!@#$%^&*()_{}[]';
    $pass = '';
    $length = 8;
    $max = mb_strlen($allowedCharacters, '8bit') - 1;
    for ($i = 0; $i < $length; ++$i) {
        $pass .= $allowedCharacters[random_int(0, $max)];
    }

    if (checkForCharacterCondition($pass)){
        return '<br><strong>Selected password: </strong>'.$pass;
    }else{
        echo 'Iteration '.$j.':  <strong>'.$pass.'</strong>  Rejected<br>';
        $j++;
        return generate_pass();
    }

}

echo generate_pass();

Calculating arithmetic mean (one type of average) in Python

from statistics import mean
avarage=mean(your_list)

for example

from statistics import mean

my_list=[5,2,3,2]
avarage=mean(my_list)
print(avarage)

and result is

3.0

Does the Java &= operator apply & or &&?

Here's a simple way to test it:

public class OperatorTest {     
    public static void main(String[] args) {
        boolean a = false;
        a &= b();
    }

    private static boolean b() {
        System.out.println("b() was called");
        return true;
    }
}

The output is b() was called, therefore the right-hand operand is evaluated.

So, as already mentioned by others, a &= b is the same as a = a & b.

What's the whole point of "localhost", hosts and ports at all?

In computer networking, localhost (meaning "this computer") is the standard hostname given to the address of the loopback network interface.

Localhost always translates to the loopback IP address 127.0.0.1 in IPv4.

It is also used instead of the hostname of a computer. For example, directing a web browser installed on a system running an HTTP server to http://localhost will display the home page of the local web site.

Source: Wikipedia - Localhost.


The :80 part is the TCP port. You can consider these ports as communications endpoints on a particular IP address (in the case of localhost - 127.0.0.1). The IANA is responsible for maintaining the official assignments of standard port numbers for specific services. Port 80 happens to be the standard port for HTTP.

difference between iframe, embed and object elements

iframe have "sandbox" attribute that may block pop up etc

How do you add a timed delay to a C++ program?

On Windows you can include the windows library and use "Sleep(0);" to sleep the program. It takes a value that represents milliseconds.

ViewPager PagerAdapter not updating the View

I m using Tablayout with ViewPagerAdapter. For passing data between fragments or for communicating between fragments use below code which works perfectly fine and refresh the fragment when ever it appears. Inside button click of second fragment write below code.

b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            String text=e1.getText().toString(); // get the text from EditText

            // move from one fragment to another fragment on button click
            TabLayout tablayout = (TabLayout) getActivity().findViewById(R.id.tab_layout); // here tab_layout is the id of TabLayout which is there in parent Activity/Fragment
            if (tablayout.getTabAt(1).isSelected()) { // here 1 is the index number of second fragment i-e current Fragment

                LocalBroadcastManager lbm = LocalBroadcastManager.getInstance(getContext());
                Intent i = new Intent("EDIT_TAG_REFRESH");
                i.putExtra("MyTextValue",text);
                lbm.sendBroadcast(i);

            }
            tablayout.getTabAt(0).select(); // here 0 is the index number of first fragment i-e to which fragment it has to moeve

        }
    });

below is the code which has to be written in first fragment (in my case) i-e in receiving Fragment.

MyReceiver r;
Context context;
String newValue;
public void refresh() {
    //your code in refresh.
    Log.i("Refresh", "YES");
}
public void onPause() {
    super.onPause();

    LocalBroadcastManager.getInstance(context).unregisterReceiver(r);
}
public void onResume() {
    super.onResume();
    r = new MyReceiver();
    LocalBroadcastManager.getInstance(getActivity()).registerReceiver(r,
            new IntentFilter("EDIT_TAG_REFRESH"));
} // this code has to be written before onCreateview()


 // below code can be written any where in the fragment
 private class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
    PostRequestFragment.this.refresh();
        String action = intent.getAction();
        newValue=intent.getStringExtra("MyTextValue");
        t1.setText(newValue); // upon Referesh set the text
    }
}

macro for Hide rows in excel 2010

Well, you're on the right path, Benno!

There are some tips regarding VBA programming that might help you out.

  1. Use always explicit references to the sheet you want to interact with. Otherwise, Excel may 'assume' your code applies to the active sheet and eventually you'll see it screws your spreadsheet up.

  2. As lionz mentioned, get in touch with the native methods Excel offers. You might use them on most of your tricks.

  3. Explicitly declare your variables... they'll show the list of methods each object offers in VBA. It might save your time digging on the internet.

Now, let's have a draft code...

Remember this code must be within the Excel Sheet object, as explained by lionz. It only applies to Sheet 2, is up to you to adapt it to both Sheet 2 and Sheet 3 in the way you prefer.

Hope it helps!

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim oSheet As Excel.Worksheet

    'We only want to do something if the changed cell is B6, right?
    If Target.Address = "$B$6" Then

        'Checks if it's a number...
        If IsNumeric(Target.Value) Then

            'Let's avoid values out of your bonds, correct?
            If Target.Value > 0 And Target.Value < 51 Then

                'Let's assign the worksheet we'll show / hide rows to one variable and then
                '   use only the reference to the variable itself instead of the sheet name.
                '   It's safer.

                'You can alternatively replace 'sheet 2' by 2 (without quotes) which will represent
                '   the sheet index within the workbook
                Set oSheet = ActiveWorkbook.Sheets("Sheet 2")

                'We'll unhide before hide, to ensure we hide the correct ones
                oSheet.Range("A7:A56").EntireRow.Hidden = False

                oSheet.Range("A" & Target.Value + 7 & ":A56").EntireRow.Hidden = True

            End If

        End If

    End If

End Sub

How to stop a JavaScript for loop?

Use for of loop instead which is part of ES2015 release. Unlike forEach, we can use return, break and continue. See https://hacks.mozilla.org/2015/04/es6-in-depth-iterators-and-the-for-of-loop/

let arr = [1,2,3,4,5];
for (let ele of arr) {
  if (ele > 3) break;
  console.log(ele);
}

How to enable mbstring from php.ini?

All XAMPP packages come with Multibyte String (php_mbstring.dll) extension installed.

If you have accidentally removed DLL file from php/ext folder, just add it back (get the copy from XAMPP zip archive - its downloadable).

If you have deleted the accompanying INI configuration line from php.ini file, add it back as well:

extension=php_mbstring.dll

Also, ensure to restart your webserver (Apache) using XAMPP control panel.

Additional Info on Enabling PHP Extensions

  • install extension (e.g. put php_mbstring.dll into /XAMPP/php/ext directory)
  • in php.ini, ensure extension directory specified (e.g. extension_dir = "ext")
  • ensure correct build of DLL file (e.g. 32bit thread-safe VC9 only works with DLL files built using exact same tools and configuration: 32bit thread-safe VC9)
  • ensure PHP API versions match (If not, once you restart the webserver you will receive related error.)

How different is Scrum practice from Agile Practice?

Agile is a platform and scrum is a methodology to follow. Scrum recommends certain practices to be followed. Some of the basic scrum practices are following.

  • Fixed length Scrum/Releases.
  • Suggested meeting Structures (Release planning meeting, Sprint planning meeting, Sprint Review and Sprint Retrospective meetings)
  • Scrum also recommends roles. Following are the roles recommended by Scrum.

     - Scrum Master
     - Developer Team
     - Product Owner
    

The Scrum, just like other Agile methodologies follow iterative approach.

Following are some other Agile methodologies.

  • Extreme Programming.
  • Agile unified process
  • Dynamic System Development Method (DSDM)
  • Feature Driven Development (FDD)
  • Lean Software Development
  • Kanban
  • Scrum-ban

There are many scrum tool in the market. Yodiz is one of them that we use.

How to convert an Image to base64 string in java?

I think you might want:

String encodedFile = Base64.getEncoder().encodeToString(bytes);

How to convert hex strings to byte values in Java

Convert string to Byte-Array:

byte[] theByteArray = stringToConvert.getBytes();

Convert String to Byte:

 String str = "aa";

 byte b = Byte.valueOf(str);

How do I get information about an index and table owner in Oracle?

The following may help give you want you need:

SELECT
    index_owner, index_name, table_name, column_name, column_position
FROM DBA_IND_COLUMNS
ORDER BY
    index_owner, 
    table_name,
    index_name,
    column_position
    ;

For my use case, I wanted the column_names and order that they are in the indices (so that I could recreate them in a different database engine after migrating to AWS). The following was what I used, in case it is of use to anyone else:

SELECT
    index_name, table_name, column_name, column_position
FROM DBA_IND_COLUMNS
WHERE
    INDEX_OWNER = 'FOO'
    AND TABLE_NAME NOT LIKE '%$%'
ORDER BY
    table_name,
    index_name,
    column_position
    ;

Getting Google+ profile picture url with user_id

If you use Flutter, then you can access it via people.googleapis.com endpoint, code uses google_sign_in library

import 'package:google_sign_in/google_sign_in.dart';

Future<String> getPhotoUrl(GoogleSignInAccount account, String userId) async {
  // final authentication = await account.authentication;
  final url = 'https://people.googleapis.com/v1/people/${userId}?personFields=photos';
  final response = await http.get(
    url,
    headers: await account.authHeaders
  );

  final data = json.decode(response.body);
  return data['photos'].first['url'];
}

You will get something like

{
  resourceName: people/998812322529259873423, 
  etag: %EgQBAzcabcQBAgUH, 
  photos: [{metadata: {primary: true, source: {type: PROFILE, id: 107721622529987673423}}, 
  url: https://lh3.googleusercontent.com/a-/abcdefmB2p1VWxLsNT9WSV0yqwuwo6o2Ba21sh_ra7CnrZ=s100}]
}

where url is an accessible image url.

Convert SQL Server result set into string

DECLARE @result varchar(1000)

SELECT @result = ISNULL(@result, '') + StudentId + ',' FROM Student WHERE condition = xyz

select substring(@result, 0, len(@result) - 1) --trim extra "," at end

'cout' was not declared in this scope

Use std::cout, since cout is defined within the std namespace. Alternatively, add a using std::cout; directive.

How to define custom configuration variables in rails

I like to use rails-settings for global configuration values that need to be changeable via web interface.

iOS Swift - Get the Current Local Time and Date Timestamp

you can even create a function to return different time stamps depending on your necessity:

func dataatual(_ tipo:Int) -> String {
        let date = Date()
        let formatter = DateFormatter()
        if tipo == 1{
            formatter.dateFormat = "dd/MM/yyyy"
        } else if tipo == 2{
            formatter.dateFormat = "yyyy-MM-dd HH:mm"
        } else {
            formatter.dateFormat = "dd-MM-yyyy"
        }

        return formatter.string(from: date)
    } 

Accurate way to measure execution times of php scripts

You have the right idea, except a more precise timing is available with the microtime() function.

If what is inside the loop is fast, it is possible that the apparent elapsed time will be zero. If so, wrap another loop around the code and call it repeatedly. Be sure to divide the difference by the number of iterations to get a per-once time. I have profiled code which required 10,000,000 iterations to get consistent, reliable timing results.

How to delete items from a dictionary while iterating over it?

Iterate over a copy instead, such as the one returned by items():

for k, v in list(mydict.items()):

How to use a Java8 lambda to sort a stream in reverse order?

In simple, using Comparator and Collection you can sort like below in reversal order using JAVA 8

import java.util.Comparator;;
import java.util.stream.Collectors;

Arrays.asList(files).stream()
    .sorted(Comparator.comparing(File::getLastModified).reversed())
    .collect(Collectors.toList());

Cast Double to Integer in Java

Simply use the intValue method of Double

Double initialValue = 7.12;
int finalValue = initialValue.intValue();

anaconda - path environment variable in windows

C:\Users\\Anaconda3

I just added above path , to my path environment variables and it worked. Now, all we have to do is to move to the .py script location directory, open the cmd with that location and run to see the output.

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

Using an authorization header with Fetch in React Native

Example fetch with authorization header:

fetch('URL_GOES_HERE', { 
   method: 'post', 
   headers: new Headers({
     'Authorization': 'Basic '+btoa('username:password'), 
     'Content-Type': 'application/x-www-form-urlencoded'
   }), 
   body: 'A=1&B=2'
 });

Difference between int32, int, int32_t, int8 and int8_t

Between int32 and int32_t, (and likewise between int8 and int8_t) the difference is pretty simple: the C standard defines int8_t and int32_t, but does not define anything named int8 or int32 -- the latter (if they exist at all) is probably from some other header or library (most likely predates the addition of int8_t and int32_t in C99).

Plain int is quite a bit different from the others. Where int8_t and int32_t each have a specified size, int can be any size >= 16 bits. At different times, both 16 bits and 32 bits have been reasonably common (and for a 64-bit implementation, it should probably be 64 bits).

On the other hand, int is guaranteed to be present in every implementation of C, where int8_t and int32_t are not. It's probably open to question whether this matters to you though. If you use C on small embedded systems and/or older compilers, it may be a problem. If you use it primarily with a modern compiler on desktop/server machines, it probably won't be.

Oops -- missed the part about char. You'd use int8_t instead of char if (and only if) you want an integer type guaranteed to be exactly 8 bits in size. If you want to store characters, you probably want to use char instead. Its size can vary (in terms of number of bits) but it's guaranteed to be exactly one byte. One slight oddity though: there's no guarantee about whether a plain char is signed or unsigned (and many compilers can make it either one, depending on a compile-time flag). If you need to ensure its being either signed or unsigned, you need to specify that explicitly.

Best way to format multiple 'or' conditions in an if statement (Java)

If the set of possibilities is "compact" (i.e. largest-value - smallest-value is, say, less than 200) you might consider a lookup table. This would be especially useful if you had a structure like

if (x == 12 || x == 16 || x == 19 || ...)
else if (x==34 || x == 55 || ...)
else if (...)

Set up an array with values identifying the branch to be taken (1, 2, 3 in the example above) and then your tests become

switch(dispatchTable[x])
{
    case 1:
        ...
        break;
    case 2:
        ...
        break;
    case 3:
        ...
        break;
}

Whether or not this is appropriate depends on the semantics of the problem.

If an array isn't appropriate, you could use a Map<Integer,Integer>, or if you just want to test membership for a single statement, a Set<Integer> would do. That's a lot of firepower for a simple if statement, however, so without more context it's kind of hard to guide you in the right direction.

How to use JQuery with ReactJS

Earlier,I was facing problem in using jquery with React js,so I did following steps to make it working-

  1. npm install jquery --save

  2. Then, import $ from "jquery";

    See here

Convert string to variable name in python

This is the best way, I know of to create dynamic variables in python.

my_dict = {}
x = "Buffalo"
my_dict[x] = 4

I found a similar, but not the same question here Creating dynamically named variables from user input

Java String import

import java.lang.String;

This is an unnecessary import. java.lang classes are always implicitly imported. This means that you do not have to import them manually (explicitly).

How to change font of UIButton with Swift

Take a look here.

You should set the font of the button's titleLabel instead.

myButton.titleLabel!.font = UIFont(name: "...", 10)

Running a script inside a docker container using shell script

I was searching an answer for this same question and found ENTRYPOINT in Dockerfile solution for me.

Dockerfile

...
ENTRYPOINT /my-script.sh ; /my-script2.sh ; /bin/bash

Now the scripts are executed when I start the container and I get the bash prompt after the scripts has been executed.

How to replace a character by a newline in Vim

\r can do the work here for you.

Inserting a PDF file in LaTeX

The \includegraphics function has a page option for inserting a specific page of a PDF file as graphs. The default is one, but you can change it.

\includegraphics[scale=0.75,page=2]{multipage.pdf}

You can find more here.

CSS styling in Django forms

Per this blog post, you can add css classes to your fields using a custom template filter.

from django import template
register = template.Library()

@register.filter(name='addcss')
def addcss(field, css):
    return field.as_widget(attrs={"class":css})

Put this in your app's templatetags/ folder and you can now do

{{field|addcss:"form-control"}}

How to scroll to the bottom of a UITableView on the iPhone before the view appears

The accepted answer didn't work with my table (thousands of rows, dynamic loading) but the code below works:

- (void)scrollToBottom:(id)sender {
    if ([self.sections count] > 0) {
        NSInteger idx = [self.sections count] - 1;
        CGRect sectionRect = [self.tableView rectForSection:idx];
        sectionRect.size.height = self.tableView.frame.size.height;
        [self.tableView scrollRectToVisible:sectionRect animated:NO];
    }
}

phpinfo() is not working on my CentOS server

My solution was uninstalling and installing the PHP instance (7.0 in my case) again:

sudo apt-get purge php7.0
sudo apt-get install php7.0

After that you will need to restart the Apache service:

sudo service apache2 restart

Finally, verify again in your browser with your localhost or IP address.

Why is this HTTP request not working on AWS Lambda?

enter image description here

Add above code in API gateway under GET-Integration Request> mapping section.

How to set default value to all keys of a dict object in python?

You can use the following class. Just change zero to any default value you like. The solution was tested in Python 2.7.

class cDefaultDict(dict):
    # dictionary that returns zero for missing keys
    # keys with zero values are not stored

    def __missing__(self,key):
        return 0

    def __setitem__(self, key, value):
        if value==0:
            if key in self:  # returns zero anyway, so no need to store it
                del self[key]
        else:
            dict.__setitem__(self, key, value)

ORACLE convert number to string

This should solve your problem:

select replace(to_char(a, '90D90'),'.00','')
from
(
select 50 a from dual
union
select 50.57 from dual
union
select 5.57 from dual
union
select 0.35 from dual
union
select 0.4 from dual
);

Give a look also as this SQL Fiddle for test.

How to write LDAP query to test if user is member of a group?

I would add one more thing to Marc's answer: The memberOf attribute can't contain wildcards, so you can't say something like "memberof=CN=SPS*", and expect it to find all groups that start with "SPS".

TypeScript: Interfaces vs Types

https://www.typescriptlang.org/docs/handbook/advanced-types.html

One difference is that interfaces create a new name that is used everywhere. Type aliases don’t create a new name — for instance, error messages won’t use the alias name.

Increase distance between text and title on the y-axis

From ggplot2 2.0.0 you can use the margin = argument of element_text() to change the distance between the axis title and the numbers. Set the values of the margin on top, right, bottom, and left side of the element.

ggplot(mpg, aes(cty, hwy)) + geom_point()+
  theme(axis.title.y = element_text(margin = margin(t = 0, r = 20, b = 0, l = 0)))

margin can also be used for other element_text elements (see ?theme), such as axis.text.x, axis.text.y and title.

addition

in order to set the margin for axis titles when the axis has a different position (e.g., with scale_x_...(position = "top"), you'll need a different theme setting - e.g. axis.title.x.top. See https://github.com/tidyverse/ggplot2/issues/4343.

The provider is not compatible with the version of Oracle client

I had the same issue with Oracle.DataAccess.dll v4.121.2.0. with 2- homes installation (32 and 64 bit versions). 32-bit version workerd, 64-bit version didn't.

In my case (after 2 days of trying) I found that the problem was permissions on the 64-bit-home version. Many Directories in that version had exclusively overridden permissions where "Authenticated Users" role did not have "Read" access, which is set by default on the parent directory. Those sub-directories included "bin", "network/admin", "nls", "oracore", "RDBMS" and possibly others. I found them by filtering out "ACCESS DENIED" result in "Process Monitor" (Procmon.exe) utility from sysinternals. Once the permissions were inherited from the parent directory to those child subdirectories everything started to work.

I didn't what to override the permissions on the whole oracle home so I did them one directory at a time, but I guess if you don't worry about security so much you can reset it on the whole corresponding oracle home directory.

AppFabric installation failed because installer MSI returned with error code : 1603

I had the same problem today. I've found this link, where you can try 3 solutions. First solution helped for me.

Microsoft ANSWER for this issue

Java - How to access an ArrayList of another class?

Two ways

1)instantiate the first class and getter for arrayList

or

2)Make arraylist as static

And finally

Java Basics By Oracle

how to automatically scroll down a html page?

Use document.scrollTop to change the position of the document. Set the scrollTop of the document equal to the bottom of the featured section of your site

Printing image with PrintDocument. how to adjust the image to fit paper size

The solution provided by BBoy works fine. But in my case I had to use

e.Graphics.DrawImage(memoryImage, e.PageBounds);

This will print only the form. When I use MarginBounds it prints the entire screen even if the form is smaller than the monitor screen. PageBounds solved that issue. Thanks to BBoy!

CORS header 'Access-Control-Allow-Origin' missing

This happens generally when you try access another domain's resources.

This is a security feature for avoiding everyone freely accessing any resources of that domain (which can be accessed for example to have an exact same copy of your website on a pirate domain).

The header of the response, even if it's 200OK do not allow other origins (domains, port) to access the ressources.

You can fix this problem if you are the owner of both domains:

Solution 1: via .htaccess

To change that, you can write this in the .htaccess of the requested domain file:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
    </IfModule>

If you only want to give access to one domain, the .htaccess should look like this:

    <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin 'https://my-domain.tdl'
    </IfModule>

Solution 2: set headers the correct way

If you set this into the response header of the requested file, you will allow everyone to access the ressources:

Access-Control-Allow-Origin : *

OR

Access-Control-Allow-Origin : http://www.my-domain.com

Peace and code ;)

Regex using javascript to return just numbers

I guess you want to get number(s) from the string. In which case, you can use the following:

// Returns an array of numbers located in the string
function get_numbers(input) {
    return input.match(/[0-9]+/g);
}

var first_test = get_numbers('something102');
var second_test = get_numbers('something102or12');
var third_test = get_numbers('no numbers here!');

alert(first_test); // [102]
alert(second_test); // [102,12]
alert(third_test); // null

How to know that a string starts/ends with a specific string in jQuery?

For startswith, you can use indexOf:

if(str.indexOf('Hello') == 0) {

...

ref

and you can do the maths based on string length to determine 'endswith'.

if(str.lastIndexOf('Hello') == str.length - 'Hello'.length) {

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

You should set property file name without .properties extension, it works correctly for me:)

What are MVP and MVC and what is the difference?

enter image description here

MVC (Model View Controller)

The input is directed at the Controller first, not the view. That input might be coming from a user interacting with a page, but it could also be from simply entering a specific url into a browser. In either case, its a Controller that is interfaced with to kick off some functionality. There is a many-to-one relationship between the Controller and the View. That’s because a single controller may select different views to be rendered based on the operation being executed. Note the one way arrow from Controller to View. This is because the View doesn’t have any knowledge of or reference to the controller. The Controller does pass back the Model, so there is knowledge between the View and the expected Model being passed into it, but not the Controller serving it up.

MVP (Model View Presenter)

The input begins with the View, not the Presenter. There is a one-to-one mapping between the View and the associated Presenter. The View holds a reference to the Presenter. The Presenter is also reacting to events being triggered from the View, so its aware of the View its associated with. The Presenter updates the View based on the requested actions it performs on the Model, but the View is not Model aware.

For more Reference

AngularJS: How to set a variable inside of a template?

It's not the best answer, but its also an option: since you can concatenate multiple expressions, but just the last one is rendered, you can finish your expression with "" and your variable will be hidden.

So, you could define the variable with:

{{f = forecast[day.iso]; ""}}

Enable Hibernate logging

I answer to myself. As suggested by Vadzim, I must consider the jboss-logging.xml file and insert these lines:

<logger category="org.hibernate">
     <level name="TRACE"/>
</logger>

Instead of DEBUG level I wrote TRACE. Now don't look only the console but open the server.log file (debug messages aren't sent to the console but you can configure this mode!).

What's the safest way to iterate through the keys of a Perl hash?

I woudl say:

  1. Use whatever's easiest to read/understand for most people (so keys, usually, I'd argue)
  2. Use whatever you decide consistently throught the whole code base.

This give 2 major advantages:

  1. It's easier to spot "common" code so you can re-factor into functions/methiods.
  2. It's easier for future developers to maintain.

I don't think it's more expensive to use keys over each, so no need for two different constructs for the same thing in your code.

HTML SELECT - Change selected option by VALUE using JavaScript

document.getElementById('drpSelectSourceLibrary').value = 'Seven';

Getting a list item by index

list1[0];

Assuming list's type has an indexer defined.

Best TCP port number range for internal applications

I decided to download the assigned port numbers from IANA, filter out the used ports, and sort each "Unassigned" range in order of most ports available, descending. This did not work, since the csv file has ranges marked as "Unassigned" that overlap other port number reservations. I manually expanded the ranges of assigned port numbers, leaving me with a list of all assigned port numbers. I then sorted that list and generated my own list of unassigned ranges.

Since this stackoverflow.com page ranked very high in my search about the topic, I figured I'd post the largest ranges here for anyone else who is interested. These are for both TCP and UDP where the number of ports in the range is at least 500.

Total   Start   End
829     29170   29998
815     38866   39680
710     41798   42507
681     43442   44122
661     46337   46997
643     35358   36000
609     36866   37474
596     38204   38799
592     33657   34248
571     30261   30831
563     41231   41793
542     21011   21552
528     28590   29117
521     14415   14935
510     26490   26999

Source (via the CSV download button):

http://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml

What's the console.log() of java?

console.log() in java is System.out.println(); to put text on the next line

And System.out.print(); puts text on the same line.

From milliseconds to hour, minutes, seconds and milliseconds

milliseconds = x
total = 0
while (milliseconds >= 1000) {
  milliseconds = (milliseconds - 1000)
  total = total + 1
}
hr = 0
min = 0
while (total >= 60) {
  total = total - 60
  min = min + 1
  if (min >= 60) hr = hr + 1
  if (min == 60) min = 0
}
sec = total

This is on groovy, but I thing that this is not problem for you. Method work perfect.

Enter key in textarea

My scenario is when the user strikes the enter key while typing in textarea i have to include a line break.I achieved this using the below code......Hope it may helps somebody......

function CheckLength()
{
    var keyCode = event.keyCode
    if (keyCode == 13)
    {
        document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value = document.getElementById('ctl00_ContentPlaceHolder1_id_txt_Suggestions').value + "\n<br>";
    }
}

Casting int to bool in C/C++

0 values of basic types (1)(2)map to false.

Other values map to true.

This convention was established in original C, via its flow control statements; C didn't have a boolean type at the time.


It's a common error to assume that as function return values, false indicates failure. But in particular from main it's false that indicates success. I've seen this done wrong many times, including in the Windows starter code for the D language (when you have folks like Walter Bright and Andrei Alexandrescu getting it wrong, then it's just dang easy to get wrong), hence this heads-up beware beware.


There's no need to cast to bool for built-in types because that conversion is implicit. However, Visual C++ (Microsoft's C++ compiler) has a tendency to issue a performance warning (!) for this, a pure silly-warning. A cast doesn't suffice to shut it up, but a conversion via double negation, i.e. return !!x, works nicely. One can read !! as a “convert to bool” operator, much as --> can be read as “goes to”. For those who are deeply into readability of operator notation. ;-)


1) C++14 §4.12/1 “A zero value, null pointer value, or null member pointer value is converted to false; any other value is converted to true. For direct-initialization (8.5), a prvalue of type std::nullptr_t can be converted to a prvalue of type bool; the resulting value is false.”
2) C99 and C11 §6.3.1.2/1 “When any scalar value is converted to _Bool, the result is 0 if the value compares equal to 0; otherwise, the result is 1.”

How can I rollback an UPDATE query in SQL server 2005?

begin transaction

// execute SQL code here

rollback transaction

If you've already executed the query and want to roll it back, unfortunately your only real option is to restore a database backup. If you're using Full backups, then you should be able to restore the database to a specific point in time.

How to install Laravel's Artisan?

While you are working with Laravel you must be in root of laravel directory structure. There are App, route, public etc folders is root directory. Just follow below step to fix issue. check composer status using : composer -v

First, download the Laravel installer using Composer:

composer global require "laravel/installer"

Please check with below command:

php artisan serve

still not work then create new project with existing code. using LINK

ASP.NET Core Web API Authentication

You can implement a middleware which handles Basic authentication.

public async Task Invoke(HttpContext context)
{
    var authHeader = context.Request.Headers.Get("Authorization");
    if (authHeader != null && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
    {
        var token = authHeader.Substring("Basic ".Length).Trim();
        System.Console.WriteLine(token);
        var credentialstring = Encoding.UTF8.GetString(Convert.FromBase64String(token));
        var credentials = credentialstring.Split(':');
        if(credentials[0] == "admin" && credentials[1] == "admin")
        {
            var claims = new[] { new Claim("name", credentials[0]), new Claim(ClaimTypes.Role, "Admin") };
            var identity = new ClaimsIdentity(claims, "Basic");
            context.User = new ClaimsPrincipal(identity);
        }
    }
    else
    {
        context.Response.StatusCode = 401;
        context.Response.Headers.Set("WWW-Authenticate", "Basic realm=\"dotnetthoughts.net\"");
    }
    await _next(context);
}

This code is written in a beta version of asp.net core. Hope it helps.

Looping through list items with jquery

You can use each for this:

$('#productList li').each(function(i, li) {
  var $product = $(li);  
  // your code goes here
});

That being said - are you sure you want to be updating the values to be +1 each time? Couldn't you just find the count and then set the values based on that?

How to define partitioning of DataFrame?

Spark >= 2.3.0

SPARK-22614 exposes range partitioning.

val partitionedByRange = df.repartitionByRange(42, $"k")

partitionedByRange.explain
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k ASC NULLS FIRST], 42
// +- AnalysisBarrier Project [_1#2 AS k#5, _2#3 AS v#6]
// 
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- Project [_1#2 AS k#5, _2#3 AS v#6]
//    +- LocalRelation [_1#2, _2#3]
// 
// == Optimized Logical Plan ==
// RepartitionByExpression [k#5 ASC NULLS FIRST], 42
// +- LocalRelation [k#5, v#6]
// 
// == Physical Plan ==
// Exchange rangepartitioning(k#5 ASC NULLS FIRST, 42)
// +- LocalTableScan [k#5, v#6]

SPARK-22389 exposes external format partitioning in the Data Source API v2.

Spark >= 1.6.0

In Spark >= 1.6 it is possible to use partitioning by column for query and caching. See: SPARK-11410 and SPARK-4849 using repartition method:

val df = Seq(
  ("A", 1), ("B", 2), ("A", 3), ("C", 1)
).toDF("k", "v")

val partitioned = df.repartition($"k")
partitioned.explain

// scala> df.repartition($"k").explain(true)
// == Parsed Logical Plan ==
// 'RepartitionByExpression ['k], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Analyzed Logical Plan ==
// k: string, v: int
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Optimized Logical Plan ==
// RepartitionByExpression [k#7], None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- LogicalRDD [_1#5,_2#6], MapPartitionsRDD[3] at rddToDataFrameHolder at <console>:27
// 
// == Physical Plan ==
// TungstenExchange hashpartitioning(k#7,200), None
// +- Project [_1#5 AS k#7,_2#6 AS v#8]
//    +- Scan PhysicalRDD[_1#5,_2#6]

Unlike RDDs Spark Dataset (including Dataset[Row] a.k.a DataFrame) cannot use custom partitioner as for now. You can typically address that by creating an artificial partitioning column but it won't give you the same flexibility.

Spark < 1.6.0:

One thing you can do is to pre-partition input data before you create a DataFrame

import org.apache.spark.sql.types._
import org.apache.spark.sql.Row
import org.apache.spark.HashPartitioner

val schema = StructType(Seq(
  StructField("x", StringType, false),
  StructField("y", LongType, false),
  StructField("z", DoubleType, false)
))

val rdd = sc.parallelize(Seq(
  Row("foo", 1L, 0.5), Row("bar", 0L, 0.0), Row("??", -1L, 2.0),
  Row("foo", -1L, 0.0), Row("??", 3L, 0.6), Row("bar", -3L, 0.99)
))

val partitioner = new HashPartitioner(5) 

val partitioned = rdd.map(r => (r.getString(0), r))
  .partitionBy(partitioner)
  .values

val df = sqlContext.createDataFrame(partitioned, schema)

Since DataFrame creation from an RDD requires only a simple map phase existing partition layout should be preserved*:

assert(df.rdd.partitions == partitioned.partitions)

The same way you can repartition existing DataFrame:

sqlContext.createDataFrame(
  df.rdd.map(r => (r.getInt(1), r)).partitionBy(partitioner).values,
  df.schema
)

So it looks like it is not impossible. The question remains if it make sense at all. I will argue that most of the time it doesn't:

  1. Repartitioning is an expensive process. In a typical scenario most of the data has to be serialized, shuffled and deserialized. From the other hand number of operations which can benefit from a pre-partitioned data is relatively small and is further limited if internal API is not designed to leverage this property.

    • joins in some scenarios, but it would require an internal support,
    • window functions calls with matching partitioner. Same as above, limited to a single window definition. It is already partitioned internally though, so pre-partitioning may be redundant,
    • simple aggregations with GROUP BY - it is possible to reduce memory footprint of the temporary buffers**, but overall cost is much higher. More or less equivalent to groupByKey.mapValues(_.reduce) (current behavior) vs reduceByKey (pre-partitioning). Unlikely to be useful in practice.
    • data compression with SqlContext.cacheTable. Since it looks like it is using run length encoding, applying OrderedRDDFunctions.repartitionAndSortWithinPartitions could improve compression ratio.
  2. Performance is highly dependent on a distribution of the keys. If it is skewed it will result in a suboptimal resource utilization. In the worst case scenario it will be impossible to finish the job at all.

  3. A whole point of using a high level declarative API is to isolate yourself from a low level implementation details. As already mentioned by @dwysakowicz and @RomiKuntsman an optimization is a job of the Catalyst Optimizer. It is a pretty sophisticated beast and I really doubt you can easily improve on that without diving much deeper into its internals.

Related concepts

Partitioning with JDBC sources:

JDBC data sources support predicates argument. It can be used as follows:

sqlContext.read.jdbc(url, table, Array("foo = 1", "foo = 3"), props)

It creates a single JDBC partition per predicate. Keep in mind that if sets created using individual predicates are not disjoint you'll see duplicates in the resulting table.

partitionBy method in DataFrameWriter:

Spark DataFrameWriter provides partitionBy method which can be used to "partition" data on write. It separates data on write using provided set of columns

val df = Seq(
  ("foo", 1.0), ("bar", 2.0), ("foo", 1.5), ("bar", 2.6)
).toDF("k", "v")

df.write.partitionBy("k").json("/tmp/foo.json")

This enables predicate push down on read for queries based on key:

val df1 = sqlContext.read.schema(df.schema).json("/tmp/foo.json")
df1.where($"k" === "bar")

but it is not equivalent to DataFrame.repartition. In particular aggregations like:

val cnts = df1.groupBy($"k").sum()

will still require TungstenExchange:

cnts.explain

// == Physical Plan ==
// TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Final,isDistinct=false)], output=[k#90,sum(v)#93])
// +- TungstenExchange hashpartitioning(k#90,200), None
//    +- TungstenAggregate(key=[k#90], functions=[(sum(v#91),mode=Partial,isDistinct=false)], output=[k#90,sum#99])
//       +- Scan JSONRelation[k#90,v#91] InputPaths: file:/tmp/foo.json

bucketBy method in DataFrameWriter (Spark >= 2.0):

bucketBy has similar applications as partitionBy but it is available only for tables (saveAsTable). Bucketing information can used to optimize joins:

// Temporarily disable broadcast joins
spark.conf.set("spark.sql.autoBroadcastJoinThreshold", -1)

df.write.bucketBy(42, "k").saveAsTable("df1")
val df2 = Seq(("A", -1.0), ("B", 2.0)).toDF("k", "v2")
df2.write.bucketBy(42, "k").saveAsTable("df2")

// == Physical Plan ==
// *Project [k#41, v#42, v2#47]
// +- *SortMergeJoin [k#41], [k#46], Inner
//    :- *Sort [k#41 ASC NULLS FIRST], false, 0
//    :  +- *Project [k#41, v#42]
//    :     +- *Filter isnotnull(k#41)
//    :        +- *FileScan parquet default.df1[k#41,v#42] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df1], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v:int>
//    +- *Sort [k#46 ASC NULLS FIRST], false, 0
//       +- *Project [k#46, v2#47]
//          +- *Filter isnotnull(k#46)
//             +- *FileScan parquet default.df2[k#46,v2#47] Batched: true, Format: Parquet, Location: InMemoryFileIndex[file:/spark-warehouse/df2], PartitionFilters: [], PushedFilters: [IsNotNull(k)], ReadSchema: struct<k:string,v2:double>

* By partition layout I mean only a data distribution. partitioned RDD has no longer a partitioner. ** Assuming no early projection. If aggregation covers only small subset of columns there is probably no gain whatsoever.

Is there a JavaScript strcmp()?

How about:

String.prototype.strcmp = function(s) {
    if (this < s) return -1;
    if (this > s) return 1;
    return 0;
}

Then, to compare s1 with 2:

s1.strcmp(s2)

Is it possible to put a ConstraintLayout inside a ScrollView?

use NestedScrollView with viewport true is working good for me

<android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:fillViewport="true">

        <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="700dp">

        </android.support.constraint.ConstraintLayout>

</android.support.v4.widget.NestedScrollView>

Select last row in MySQL

on tables with many rows are two queries probably faster...

SELECT @last_id := MAX(id) FROM table;

SELECT * FROM table WHERE id = @last_id;

Concatenating Column Values into a Comma-Separated List

Another solution within a query :

select 
    Id, 
    STUFF(
        (select (', "' + od.ProductName + '"')
        from OrderDetails od (nolock)
        where od.Order_Id = o.Id
        order by od.ProductName
        FOR XML PATH('')), 1, 2, ''
    ) ProductNames
from Orders o (nolock)
where o.Customer_Id = 525188
order by o.Id desc

(EDIT: thanks @user007 for the STUFF declaration)

Quickest way to convert a base 10 number to any base in .NET?

One can also use slightly modified version of the accepted one and adjust base characters string to it's needs:

public static string Int32ToString(int value, int toBase)
{
    string result = string.Empty;
    do
    {
        result = "0123456789ABCDEF"[value % toBase] + result;
        value /= toBase;
    }
    while (value > 0);

    return result;
}

Limit Decimal Places in Android EditText

For Kotlin

val inputFilter =  arrayOf<InputFilter>(DecimalDigitsInputFilter(5,2))
            et_total_value.setFilters(inputFilter)

How to get time (hour, minute, second) in Swift 3 using NSDate?

swift 4

==> Getting iOS device current time:-

print(" ---> ",(Calendar.current.component(.hour, from: Date())),":",
               (Calendar.current.component(.minute, from: Date())),":",
               (Calendar.current.component(.second, from: Date())))

output: ---> 10 : 11: 34

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

Rock, Paper, Scissors Game Java

Before we try to solve the invalid character problem, the lack of curly braces around the if and else if statements is wreaking havoc on your program's logic. Change it to this:

if (personPlay.equals(computerPlay)) {
   System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
   if (computerPlay.equals("S")) 
      System.out.println("Rock crushes scissors. You win!!");
   else if (computerPlay.equals("P")) 
        System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
   if (computerPlay.equals("S")) 
       System.out.println("Scissor cuts paper. You lose!!"); 
   else if (computerPlay.equals("R")) 
        System.out.println("Paper eats rock. You win!!");
} 
else if (personPlay.equals("S")) {
     if (computerPlay.equals("P")) 
         System.out.println("Scissor cuts paper. You win!!"); 
     else if (computerPlay.equals("R")) 
        System.out.println("Rock breaks scissors. You lose!!");
}
else 
     System.out.println("Invalid user input.");

Much clearer! It's now actually a piece of cake to catch the bad characters. You need to move the else statement to somewhere that will catch the errors before you attempt to process anything else. So change everything to:

if( /* insert your check for bad characters here */ ) { 
     System.out.println("Invalid user input.");
}
else if (personPlay.equals(computerPlay)) {
   System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
   if (computerPlay.equals("S")) 
      System.out.println("Rock crushes scissors. You win!!");
   else if (computerPlay.equals("P")) 
        System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
   if (computerPlay.equals("S")) 
       System.out.println("Scissor cuts paper. You lose!!"); 
   else if (computerPlay.equals("R")) 
        System.out.println("Paper eats rock. You win!!");
} 
else if (personPlay.equals("S")) {
     if (computerPlay.equals("P")) 
         System.out.println("Scissor cuts paper. You win!!"); 
     else if (computerPlay.equals("R")) 
        System.out.println("Rock breaks scissors. You lose!!");
}

jQuery Ajax simple call

please set dataType config property in your ajax call and give it another try!

another point is you are using ajax call setup configuration properties as string and it is wrong as reference site

$.ajax({

    url : 'http://voicebunny.comeze.com/index.php',
    type : 'GET',
    data : {
        'numberOfWords' : 10
    },
    dataType:'json',
    success : function(data) {              
        alert('Data: '+data);
    },
    error : function(request,error)
    {
        alert("Request: "+JSON.stringify(request));
    }
});

I hope be helpful!

Capturing window.onbeforeunload

Yes what everybody says above.

For your immediate situation, instead of onChange, you can use onInput, new in html5. The input event is the same, but it'll fire upon every keystroke, regardless of the focus. Also works on selects and all the rest just like onChange.

Position: absolute and parent height?

This is a late answer, but by looking at the source code, I noticed that when the video is fullscreen, the "mejs-container-fullscreen" class is added to the "mejs-container" element. It is thus possible to change the styling based on this class.

.mejs-container.mejs-container-fullscreen {
    // This rule applies only to the container when in fullscreen
    padding-top: 57%;
}

Also, if you wish to make your MediaElement video fluid using CSS, below is a great trick by Chris Coyier: http://css-tricks.com/rundown-of-handling-flexible-media/

Just add this to your CSS:

.mejs-container {
    width: 100% !important;
    height: auto !important;
    padding-top: 57%;
}
.mejs-overlay, .mejs-poster {
    width: 100% !important;
    height: 100% !important;
}
.mejs-mediaelement video {
    position: absolute;
    top: 0; left: 0; right: 0; bottom: 0;
    width: 100% !important;
    height: 100% !important;
}

I hope it helps.

How do I test a single file using Jest?

Simple solution that works:

yarn test -g fileName or

npm test -g fileName

Example:

yarn test -g cancelTransaction or

npm test -g cancelTransaction

More about test filters:

Test Filters
--fgrep, -f Only run tests containing this string [string]
--grep, -g Only run tests matching this string or regexp [string]
--invert, -i Inverts --grep and --fgrep matches [boolean]

Why aren't python nested functions called closures?

def nested1(num1): 
    print "nested1 has",num1
    def nested2(num2):
        print "nested2 has",num2,"and it can reach to",num1
        return num1+num2    #num1 referenced for reading here
    return nested2

Gives:

In [17]: my_func=nested1(8)
nested1 has 8

In [21]: my_func(5)
nested2 has 5 and it can reach to 8
Out[21]: 13

This is an example of what a closure is and how it can be used.

Detect when input has a 'readonly' attribute

You can just use the attribute selector and then test the length:

$('input[readonly]').length == 0 // --> ok
$('input[readonly]').length > 0  // --> not ok

Postgresql 9.2 pg_dump version mismatch

On Ubuntu you can simply add the most recent Apt repository and then run:

sudo apt-get install postgresql-client-11

java: How can I do dynamic casting of a variable from one type to another?

It works and there's even a common pattern for your approach: the Adapter pattern. But of course, (1) it does not work for casting java primitives to objects and (2) the class has to be adaptable (usually by implementing a custom interface).

With this pattern you could do something like:

Wolf bigBadWolf = new Wolf();
Sheep sheep = (Sheep) bigBadWolf.getAdapter(Sheep.class);

and the getAdapter method in Wolf class:

public Object getAdapter(Class clazz) {
  if (clazz.equals(Sheep.class)) {
    // return a Sheep implementation
    return getWolfDressedAsSheep(this);
  }

  if (clazz.equals(String.class)) {
    // return a String
    return this.getName();
  }

  return null; // not adaptable
}

For you special idea - that is impossible. You can't use a String value for casting.

Generate signed apk android studio

I dont think anyone has answered the question correctly.So, for anyone else who has the same question, this should help :

Step 1 Go to Build>Generate Signed APK>Next (module selected would be your module , most often called "app")

Step 2 Click on create new

Step 3 Basically, fill in the form with the required details. The confusing bit it is where it asks for a Key Store Path. Click on the icon on the right with the 3 dots ("..."), which will open up a navigator window asking you to navigate and select a .jks file.Navigate to a folder where you want your keystore file saved and then at the File Name box at the bottom of that window, simply enter a name of your liking and the OK button will be clickable now. What is happening is that the window isnt really asking you chose a .jks file but rather it wants you to give it the location and name that you want it to have.

Step 4 Click on Next and then select Release and Voila ! you are done.

Match whitespace but not newlines

m/ /g just give space in / /, and it will work. Or use \S — it will replace all the special characters like tab, newlines, spaces, and so on.

Remove ListView items in Android

You will want to remove() the item from your adapter object and then just run the notifyDatasetChanged() on the Adapter, any ListViews will (should) recycle and update on it's own.

Here's a brief activity example with AlertDialogs:

adapter = new MyListAdapter(this);
    lv = (ListView) findViewById(android.R.id.list);
    lv.setAdapter(adapter);
    lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> a, View v, int position, long id) {
        AlertDialog.Builder adb=new AlertDialog.Builder(MyActivity.this);
        adb.setTitle("Delete?");
        adb.setMessage("Are you sure you want to delete " + position);
        final int positionToRemove = position;
        adb.setNegativeButton("Cancel", null);
        adb.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                MyDataObject.remove(positionToRemove);
                adapter.notifyDataSetChanged();
            }});
        adb.show();
        }
    });

How to convert JSON to XML or XML to JSON?

You can do these conversions also with the .NET Framework:

JSON to XML: by using System.Runtime.Serialization.Json

var xml = XDocument.Load(JsonReaderWriterFactory.CreateJsonReader(
    Encoding.ASCII.GetBytes(jsonString), new XmlDictionaryReaderQuotas()));

XML to JSON: by using System.Web.Script.Serialization

var json = new JavaScriptSerializer().Serialize(GetXmlData(XElement.Parse(xmlString)));

private static Dictionary<string, object> GetXmlData(XElement xml)
{
    var attr = xml.Attributes().ToDictionary(d => d.Name.LocalName, d => (object)d.Value);
    if (xml.HasElements) attr.Add("_value", xml.Elements().Select(e => GetXmlData(e)));
    else if (!xml.IsEmpty) attr.Add("_value", xml.Value);

    return new Dictionary<string, object> { { xml.Name.LocalName, attr } };
}

When does a process get SIGABRT (signal 6)?

In my case, it was due to an input in an array at an index equal to the length of the array.

string x[5];

for(int i=1; i<=5; i++){

    cin>>x[i];

}

x[5] is being accessed which is not present.

Set a cookie to never expire

Maximum value: 2147483647

setcookie("CookieName", "CookieValue", 2147483647);

To avoid integer overflow the timestamp should be set to:

2^31 - 1 = 2147483647 = 2038-01-19 04:14:07

Setting a higher value might cause problems with older browsers.

Also see the RFC about cookies:

Max-Age=value
  OPTIONAL.  The value of the Max-Age attribute is delta-seconds,
  the lifetime of the cookie in seconds, a decimal non-negative
  integer.  To handle cached cookies correctly, a client SHOULD
  calculate the age of the cookie according to the age calculation
  rules in the HTTP/1.1 specification [RFC2616].  When the age is
  greater than delta-seconds seconds, the client SHOULD discard the
  cookie.  A value of zero means the cookie SHOULD be discarded
  immediately.

and RFC 2616, 14.6 Age:

If a cache receives a value larger than the largest positive integer it can represent, or if any of its age calculations overflows, it MUST transmit an Age header with a value of 2147483648 (2^31).

http://www.faqs.org/rfcs/rfc2616.html

How to update std::map after using the find method?

I would use the operator[].

map <char, int> m1;

m1['G'] ++;  // If the element 'G' does not exist then it is created and 
             // initialized to zero. A reference to the internal value
             // is returned. so that the ++ operator can be applied.

// If 'G' did not exist it now exist and is 1.
// If 'G' had a value of 'n' it now has a value of 'n+1'

So using this technique it becomes really easy to read all the character from a stream and count them:

map <char, int>                m1;
std::ifstream                  file("Plop");
std::istreambuf_iterator<char> end;

for(std::istreambuf_iterator<char> loop(file); loop != end; ++loop)
{
    ++m1[*loop]; // prefer prefix increment out of habbit
}

How can I create a link to a local file on a locally-run web page?

If you are running IIS on your PC you can add the directory that you are trying to reach as a Virtual Directory. To do this you right-click on your Site in ISS and press "Add Virtual Directory". Name the virtual folder. Point the virtual folder to your folder location on your local PC. You also have to supply credentials that has privileges to access the specific folder eg. HOSTNAME\username and password. After that you can access the file in the virtual folder as any other file on your site.

http://sitename.com/virtual_folder_name/filename.fileextension

By the way, this also works with Chrome that otherwise does not accept the file-protocol file://

Hope this helps someone :)

Convert Array to Object

Below method would convert array to object with particular given key.

    /**
     * Converts array to object
     * @param  {Array} array
     * @param  {string} key (optional)
     */
    Array.prototype.ArrayToObject = function(key) {
       const array = this;
       const obj = {};

       array.forEach((element, index) => {
           if(!key) {
              obj[index] = element;
           } else if ((element && typeof element == 'object' && element[key])) {
              obj[element[key]] = element;
           }
       });
    return obj;
    }

For Ex -

[{name: 'test'}, {name: 'test1'}].ArrayToObject('name');

would give

{test: {name: 'test'}, test1: {name: 'test1'}}

and incase key is not provided as param to the method

i.e. [{name: 'test'}, {name: 'test1'}].ArrayToObject();

would give

{0: {name: 'test'}, 1: {name: 'test1'}}

pandas convert some columns into rows

I guess I found a simpler solution

temp1 = pd.melt(df1, id_vars=["location"], var_name='Date', value_name='Value')
temp2 = pd.melt(df1, id_vars=["name"], var_name='Date', value_name='Value')

Concat whole temp1 with temp2's column name

temp1['new_column'] = temp2['name']

You now have what you asked for.

Extracting .jar file with command line

Java has a class specifically for zip files and one even more specifically for Jar Files.

java.util.jar.JarOutputStream
java.util.jar.JarInputStream

using those you could, on a command from the console, using a scanner set to system.in

Scanner console = new Scanner(System.in);
String input = console.nextLine();

then get all the components and write them as a file.

JarEntry JE = null;
while((JE = getNextJarEntry()) != null)
{
    //do stuff with JE
}

You can also use java.util.zip.ZipInputStream instead, as seeing a JAR file is in the same format as a ZIP file, ZipInputStream will be able to handle the Jar file, in fact JarInputStream actually extends ZipInputStream.

an alternative is also instead of getNextJarEntry, to use getNextEntry

How to make a <div> always full screen?

This is the trick I use. Good for responsive designs. Works perfectly when user tries to mess with browser resizing.

<head>
    <title></title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <style type="text/css">
        #container {
            position: absolute;
            width: 100%;
            min-height: 100%;
            left: 0;
            top: 0;
        }
    </style>
</head>

<body>
    <div id="container">some content</div>
</body>

How do you make a div follow as you scroll?

A better JQuery answer would be:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()});
});

You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.

A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})

Align image in center and middle within div

This would be a simpler approach

#over > img{
    display: block;
    margin:0 auto; 
}

How to get the list of all printers in computer

If you are working with MVC C#, this is the way to deal with printers and serial ports for dropdowns.

using System.Collections.Generic;
using System.Linq;
using System.IO.Ports;
using System.Drawing.Printing;

    public class Miclass
    {
        private void AllViews()
        {
            List<PortClass> ports = new List<PortClass>();
            List<Printersclass> Printersfor = new List<Printersclass>();
            string[] portnames = SerialPort.GetPortNames();
            /*PORTS*/
            for (int i = 0; i < portnames.Count(); i++)
            {
                ports.Add(new PortClass() { Name = portnames[i].Trim(), Desc = portnames[i].Trim() });
            }
            /*PRINTER*/
            for (int i = 0; i < PrinterSettings.InstalledPrinters.Count; i++)
            {
                Printersfor.Add(new Printersclass() { Name = PrinterSettings.InstalledPrinters[i].Trim(), Desc = PrinterSettings.InstalledPrinters[i].Trim() });
            }
        }
    }
    public class PortClass
    {
        public string Name { get; set; }
        public string Desc { get; set; }

        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, Desc);
        }
    }
    public class Printersclass
    {
        public string Name { get; set; }
        public string Desc { get; set; }

        public override string ToString()
        {
            return string.Format("{0} ({1})", Name, Desc);
        }
    }

Create 3D array using Python

"""
Create 3D array for given dimensions - (x, y, z)

@author: Naimish Agarwal
"""


def three_d_array(value, *dim):
    """
    Create 3D-array
    :param dim: a tuple of dimensions - (x, y, z)
    :param value: value with which 3D-array is to be filled
    :return: 3D-array
    """

    return [[[value for _ in xrange(dim[2])] for _ in xrange(dim[1])] for _ in xrange(dim[0])]

if __name__ == "__main__":
    array = three_d_array(False, *(2, 3, 1))
    x = len(array)
    y = len(array[0])
    z = len(array[0][0])
    print x, y, z

    array[0][0][0] = True
    array[1][1][0] = True

    print array

Prefer to use numpy.ndarray for multi-dimensional arrays.

regex match any whitespace

The reason I used a + instead of a '*' is because a plus is defined as one or more of the preceding element, where an asterisk is zero or more. In this case we want a delimiter that's a little more concrete, so "one or more" spaces.

word[Aa]\s+word[Bb]\s+word[Cc]

will match:

wordA wordB     wordC
worda wordb wordc
wordA   wordb   wordC

The words, in this expression, will have to be specific, and also in order (a, b, then c)

Python: json.loads returns items prefixing with 'u'

Everything is cool, man. The 'u' is a good thing, it indicates that the string is of type Unicode in python 2.x.

http://docs.python.org/2/howto/unicode.html#the-unicode-type

Is it possible to view RabbitMQ message contents directly from the command line?

You should enable the management plugin.

rabbitmq-plugins enable rabbitmq_management

See here:

http://www.rabbitmq.com/plugins.html

And here for the specifics of management.

http://www.rabbitmq.com/management.html

Finally once set up you will need to follow the instructions below to install and use the rabbitmqadmin tool. Which can be used to fully interact with the system. http://www.rabbitmq.com/management-cli.html

For example:

rabbitmqadmin get queue=<QueueName> requeue=false

will give you the first message off the queue.

How to convert a string from uppercase to lowercase in Bash?

Why not execute in backticks ?

 x=`echo "$y" | tr '[:upper:]' '[:lower:]'` 

This assigns the result of the command in backticks to the variable x. (i.e. it's not particular to tr but is a common pattern/solution for shell scripting)

You can use $(..) instead of the backticks. See here for more info.

Change Text Color of Selected Option in a Select Box

<html>
  <style>
.selectBox{
 color:White;
}
.optionBox{
  color:black;
}

</style>
<body>
<select class = "selectBox">
  <option class = "optionBox">One</option>
  <option class = "optionBox">Two</option>
  <option class = "optionBox">Three</option>
</select>

Sort a Map<Key, Value> by values

You can try Guava's multimaps:

TreeMap<Integer, Collection<String>> sortedMap = new TreeMap<>(
        Multimaps.invertFrom(Multimaps.forMap(originalMap), 
        ArrayListMultimap.<Integer, String>create()).asMap());

As a result you get a map from original values to collections of keys that correspond to them. This approach can be used even if there are multiple keys for the same value.

Running a shell script through Cygwin on Windows

The existing answers all seem to run this script in a DOS console window.

This may be acceptable, but for example means that colour codes (changing text colour) don't work but instead get printed out as they are:

there is no item "[032mGroovy[0m"

I found this solution some time ago, so I'm not sure whether mintty.exe is a standard Cygwin utility or whether you have to run the setup program to get it, but I run like this:

D:\apps\cygwin64\bin\mintty.exe -i /Cygwin-Terminal.ico  bash.exe .\myShellScript.sh

... this causes the script to run in a Cygwin BASH console instead of a Windows DOS console.

How to get current foreground activity context in android?

Knowing that ActivityManager manages Activity, so we can gain information from ActivityManager. We get the current foreground running Activity by

ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE);
ComponentName cn = am.getRunningTasks(1).get(0).topActivity;

UPDATE 2018/10/03
getRunningTasks() is DEPRECATED. see the solutions below.

This method was deprecated in API level 21. As of Build.VERSION_CODES.LOLLIPOP, this method is no longer available to third party applications: the introduction of document-centric recents means it can leak person information to the caller. For backwards compatibility, it will still return a small subset of its data: at least the caller's own tasks, and possibly some other tasks such as home that are known to not be sensitive.

How to pass a value from Vue data to href?

You need to use v-bind: or its alias :. For example,

<a v-bind:href="'/job/'+ r.id">

or

<a :href="'/job/' + r.id">

How can I build XML in C#?

For simple cases, I would also suggest looking at XmlOutput a fluent interface for building Xml.

XmlOutput is great for simple Xml creation with readable and maintainable code, while generating valid Xml. The orginal post has some great examples.