Programs & Examples On #Datamart

A data mart is the access layer of the data warehouse environment that is used to get data out to the users. The data mart is a subset of the data warehouse which is usually oriented to a specific business line or team.

Excel function to make SQL-like queries on worksheet data?

You can use Get External Data (dispite its name), located in the 'Data' tab of Excel 2010, to set up a connection in a workbook to query data from itself. Use From Other Sources From Microsoft Query to connect to Excel

Once set up you can use VBA to manipulate the connection to, among other thing, view and modify the SQL command that drives the query. This query does reference the in memory workbook, so doen't require a save to refresh the latest data.

Here's a quick Sub to demonstrate accessing the connection objects

Sub DemoConnection()
    Dim c As Connections
    Dim wb As Workbook
    Dim i As Long
    Dim strSQL As String

    Set wb = ActiveWorkbook
    Set c = wb.Connections
    For i = 1 To c.Count
        ' Reresh the data
        c(i).Refresh 
        ' view the SQL query
        strSQL = c(i).ODBCConnection.CommandText
        MsgBox strSQL
    Next
End Sub

Compare two Timestamp in java

java.util.Date mytime = null;
if (mytime.after(now) && mytime.before(last_download_time) )

Worked for me

Converting RGB to grayscale/intensity

Heres some code in c to convert rgb to grayscale. The real weighting used for rgb to grayscale conversion is 0.3R+0.6G+0.11B. these weights arent absolutely critical so you can play with them. I have made them 0.25R+ 0.5G+0.25B. It produces a slightly darker image.

NOTE: The following code assumes xRGB 32bit pixel format

unsigned int *pntrBWImage=(unsigned int*)..data pointer..;  //assumes 4*width*height bytes with 32 bits i.e. 4 bytes per pixel
unsigned int fourBytes;
        unsigned char r,g,b;
        for (int index=0;index<width*height;index++)
        {
            fourBytes=pntrBWImage[index];//caches 4 bytes at a time
            r=(fourBytes>>16);
            g=(fourBytes>>8);
            b=fourBytes;

            I_Out[index] = (r >>2)+ (g>>1) + (b>>2); //This runs in 0.00065s on my pc and produces slightly darker results
            //I_Out[index]=((unsigned int)(r+g+b))/3;     //This runs in 0.0011s on my pc and produces a pure average
        }

how to set "camera position" for 3d plots using python/matplotlib?

By "camera position," it sounds like you want to adjust the elevation and the azimuth angle that you use to view the 3D plot. You can set this with ax.view_init. I've used the below script to first create the plot, then I determined a good elevation, or elev, from which to view my plot. I then adjusted the azimuth angle, or azim, to vary the full 360deg around my plot, saving the figure at each instance (and noting which azimuth angle as I saved the plot). For a more complicated camera pan, you can adjust both the elevation and angle to achieve the desired effect.

    from mpl_toolkits.mplot3d import Axes3D
    ax = Axes3D(fig)
    ax.scatter(xx,yy,zz, marker='o', s=20, c="goldenrod", alpha=0.6)
    for ii in xrange(0,360,1):
        ax.view_init(elev=10., azim=ii)
        savefig("movie%d.png" % ii)

Convert Bitmap to File

Try this:

bitmap.compress(Bitmap.CompressFormat.PNG, quality, outStream);

See this

How to clear https proxy setting of NPM?

I was struggling with this for ages. What I finally did was go into the .npmrc file (which can be found in the user's directory followed by the user's name, ie. C:\Users\erikj/.npmrc), opened it with a text editor, manually removed any proxy settings and changed the http:// setting to https://. In this case, it is a matter of experimenting whether http or https will work for you. In my case, https worked. Go figure.

How to detect a loop in a linked list?

An alternative solution to the Turtle and Rabbit, not quite as nice, as I temporarily change the list:

The idea is to walk the list, and reverse it as you go. Then, when you first reach a node that has already been visited, its next pointer will point "backwards", causing the iteration to proceed towards first again, where it terminates.

Node prev = null;
Node cur = first;
while (cur != null) {
    Node next = cur.next;
    cur.next = prev;
    prev = cur;
    cur = next;
}
boolean hasCycle = prev == first && first != null && first.next != null;

// reconstruct the list
cur = prev;
prev = null;
while (cur != null) {
    Node next = cur.next;
    cur.next = prev;
    prev = cur;
    cur = next;
}

return hasCycle;

Test code:

static void assertSameOrder(Node[] nodes) {
    for (int i = 0; i < nodes.length - 1; i++) {
        assert nodes[i].next == nodes[i + 1];
    }
}

public static void main(String[] args) {
    Node[] nodes = new Node[100];
    for (int i = 0; i < nodes.length; i++) {
        nodes[i] = new Node();
    }
    for (int i = 0; i < nodes.length - 1; i++) {
        nodes[i].next = nodes[i + 1];
    }
    Node first = nodes[0];
    Node max = nodes[nodes.length - 1];

    max.next = null;
    assert !hasCycle(first);
    assertSameOrder(nodes);
    max.next = first;
    assert hasCycle(first);
    assertSameOrder(nodes);
    max.next = max;
    assert hasCycle(first);
    assertSameOrder(nodes);
    max.next = nodes[50];
    assert hasCycle(first);
    assertSameOrder(nodes);
}

Calling multiple JavaScript functions on a button click

Change

OnClientClick="return validateView();ShowDiv1();">

to

OnClientClick="javascript: if(validateView()) ShowDiv1();">

Changing all files' extensions in a folder with one command on Windows

You can use ren (as in rename):

ren *.XXX *.YYY

And of course, switch XXX and YYY for the appropriate extensions. It will change from XXX to YYY. If you want to change all extensions, just use the wildcard again:

ren *.* *.YYY

One way to make this work recursively is with the FOR command. It can be used with the /R option to recursively apply a command to matching files. For example:

for /R %x in (*.txt) do ren "%x" *.renamed

will change all .txt extensions to .renamed recursively, starting in the current directory. %x is the variable that holds the matched file names.

And, since you have thousands of files, make sure to wait until the cursor starts blinking again indicating that it's done working.

Note: this works only on cmd. Won't work on Powershell or Bash

phpmailer - The following SMTP Error: Data not accepted

For AWS users who work with Amazon SES in conjunction with PHPMailer, this error also appears when your "from" mail sender isn't a verified sender.

To add a verified sender:

  1. Log in to your Amazon AWS console: https://console.aws.amazon.com

  2. Select "Amazon SES" from your list of available AWS applications

  3. Select, under "Verified Senders", the "Email Addresses" --> "Verify a new email address"

  4. Navigate to that new sender's email, click the confirmation e-mail's link.

And you're all set.

What's the best way to store co-ordinates (longitude/latitude, from Google Maps) in SQL Server?

If you are just going to substitute it into a URL I suppose one field would do - so you can form a URL like

http://maps.google.co.uk/maps?q=12.345678,12.345678&z=6

but as it is two pieces of data I would store them in separate fields

vba: get unique values from array

This post contains 2 examples. I like the 2nd one:

Sub unique() 
  Dim arr As New Collection, a 
  Dim aFirstArray() As Variant 
  Dim i As Long 
 
  aFirstArray() = Array("Banana", "Apple", "Orange", "Tomato", "Apple", _ 
  "Lemon", "Lime", "Lime", "Apple") 
 
  On Error Resume Next 
  For Each a In aFirstArray 
     arr.Add a, a 
  Next
  On Error Goto 0 ' added to original example by PEH
 
  For i = 1 To arr.Count 
     Cells(i, 1) = arr(i) 
  Next 
 
End Sub 

How to hide first section header in UITableView (grouped style)

Here is how to get rid of the top section header in a grouped UITableView, in Swift:

tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: 0, height: CGFloat.leastNormalMagnitude))

How can I use xargs to copy files that have spaces and quotes in their names?

This method works on Mac OS X v10.7.5 (Lion):

find . | grep FooBar | xargs -I{} cp {} ~/foo/bar

I also tested the exact syntax you posted. That also worked fine on 10.7.5.

What is the best way to conditionally apply a class?

Ternary operator has just been added to angular parser in 1.1.5.

So the simplest way to do this is now :

ng:class="($index==selectedIndex)? 'selected' : ''"

switch case statement error: case expressions must be constant expression

How about this other solution to keep the nice switch instead of an if-else:

private enum LayoutElement {
    NONE(-1),
    PLAY_BUTTON(R.id.playbtn),
    STOP_BUTTON(R.id.stopbtn),
    MENU_BUTTON(R.id.btnmenu);

    private static class _ {
        static SparseArray<LayoutElement> elements = new SparseArray<LayoutElement>();
    }

    LayoutElement(int id) {
        _.elements.put(id, this);
    }

    public static LayoutElement from(View view) {
        return _.elements.get(view.getId(), NONE);
    }

}

So in your code you can do this:

public void onClick(View src) {
    switch(LayoutElement.from(src)) {
    case PLAY_BUTTTON:
        checkwificonnection();
        break;

    case STOP_BUTTON:
        Log.d(TAG, "onClick: stopping srvice");
        Playbutton.setImageResource(R.drawable.playbtn1);
        Playbutton.setVisibility(0); //visible
        Stopbutton.setVisibility(4); //invisible
        stopService(new Intent(RakistaRadio.this,myservice.class));
        clearstatusbar();
        timer.cancel();
        Title.setText(" ");
        Artist.setText(" ");
        break;

    case MENU_BUTTON:
        openOptionsMenu();
        break;
    }
}

Enums are static so this will have very limited impact. The only window for concern would be the double lookup involved (first on the internal SparseArray and later on the switch table)

That said, this enum can also be utilised to fetch the items in a fluent manner, if needed by keeping a reference to the id... but that's a story for some other time.

Best way to work with transactions in MS SQL Server Management Studio

The easisest thing to do is to wrap your code in a transaction, and then execute each batch of T-SQL code line by line.

For example,

Begin Transaction

         -Do some T-SQL queries here.

Rollback transaction -- OR commit transaction

If you want to incorporate error handling you can do so by using a TRY...CATCH BLOCK. Should an error occur you can then rollback the tranasction within the catch block.

For example:

USE AdventureWorks;
GO
BEGIN TRANSACTION;

BEGIN TRY
    -- Generate a constraint violation error.
    DELETE FROM Production.Product
    WHERE ProductID = 980;
END TRY
BEGIN CATCH
    SELECT 
        ERROR_NUMBER() AS ErrorNumber
        ,ERROR_SEVERITY() AS ErrorSeverity
        ,ERROR_STATE() AS ErrorState
        ,ERROR_PROCEDURE() AS ErrorProcedure
        ,ERROR_LINE() AS ErrorLine
        ,ERROR_MESSAGE() AS ErrorMessage;

    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

IF @@TRANCOUNT > 0
    COMMIT TRANSACTION;
GO

See the following link for more details.

http://msdn.microsoft.com/en-us/library/ms175976.aspx

Hope this helps but please let me know if you need more details.

JavaScript closure inside loops – simple practical example

With new features of ES6 block level scoping is managed:

var funcs = [];
for (let i = 0; i < 3; i++) {          // let's create 3 functions
    funcs[i] = function() {            // and store them in funcs
        console.log("My value: " + i); // each should log its value.
    };
}
for (let j = 0; j < 3; j++) {
    funcs[j]();                        // and now let's run each one to see
}

The code in OP's question is replaced with let instead of var.

No String-argument constructor/factory method to deserialize from String value ('')

Had this when I accidentally was calling

mapper.convertValue(...)

instead of

mapper.readValue(...)

So, just make sure you call correct method, since argument are same and IDE can find many things

How to move certain commits to be based on another branch in git?

You can use git cherry-pick to just pick the commit that you want to copy over.

Probably the best way is to create the branch out of master, then in that branch use git cherry-pick on the 2 commits from quickfix2 that you want.

How to select a record and update it, with a single queryset in Django?

This answer compares the above two approaches. If you want to update many objects in a single line, go for:

# Approach 1
MyModel.objects.filter(field1='Computer').update(field2='cool')

Otherwise you would have to iterate over the query set and update individual objects:

#Approach 2    
objects = MyModel.objects.filter(field1='Computer')
for obj in objects:
    obj.field2 = 'cool'
    obj.save()
  1. Approach 1 is faster because, it makes only one database query, compared to approach 2 which makes 'n+1' database queries. (For n items in the query set)

  2. Fist approach makes one db query ie UPDATE, the second one makes two: SELECT and then UPDATE.

  3. The tradeoff is that, suppose you have any triggers, like updating updated_on or any such related fields, it will not be triggered on direct update ie approach 1.

  4. Approach 1 is used on a queryset, so it is possible to update multiple objects at once, not in the case of approach 2.

How to cherry-pick from a remote branch?

Just as an addendum to OP accepted answer:

If you having issues with

fatal: bad object xxxxx

that's because you don't have access to that commit. Which means you don't have that repo stored locally. Then:

git remote add LABEL_FOR_THE_REPO REPO_YOU_WANT_THE_COMMIT_FROM
git fetch LABEL_FOR_THE_REPO
git cherry-pick xxxxxxx

Where xxxxxxx is the commit hash you want.

string in namespace std does not name a type

Nouns.h doesn't include <string>, but it needs to. You need to add

#include <string>

at the top of that file, otherwise the compiler doesn't know what std::string is when it is encountered for the first time.

How do I use .toLocaleTimeString() without displaying seconds?

With locales :

var date = new Date();
date.toLocaleTimeString('fr-FR', {hour: '2-digit', minute: '2-digit'})

What is the best way to concatenate two vectors?

This is precisely what the member function std::vector::insert is for

std::vector<int> AB = A;
AB.insert(AB.end(), B.begin(), B.end());

Get array of object's keys

I don't know about less verbose but I was inspired to coerce the following onto one line by the one-liner request, don't know how Pythonic it is though ;)

var keys = (function(o){var ks=[]; for(var k in o) ks.push(k); return ks})(foo);

How to calculate the width of a text string of a specific font and font-size?

This is for swift 2.3 Version. You can get the width of string.

var sizeOfString = CGSize()
if let font = UIFont(name: "Helvetica", size: 14.0)
    {
        let finalDate = "Your Text Here"
        let fontAttributes = [NSFontAttributeName: font] // it says name, but a UIFont works
        sizeOfString = (finalDate as NSString).sizeWithAttributes(fontAttributes)
    }

Cloning a private Github repo

As everyone aware about the process of cloning, I would like to add few more things here. Don't worry about special character or writing "@" as "%40" see character encoding

$ git clone https://username:[email protected]/user/repo   

This line can do the job

  1. Suppose if I have a password containing special character ( I don't know what to replace for '@' in my password)
  2. What if I want to use other temporary password other than my original password

To solve this issue I encourage to use GitHub Developer option to generate Access token. I believe Access token is secure and you wont find any special character.

creating-a-personal-access-token

Now I will write the below code to access my repository.

$ git clone https://username:[email protected]/user/repo

I am just replacing my original password with Access-token, Now I am not worried if some one see my access credential , I can regenerate the token when ever I feel.

Make sure you have checked repo Full control of private repositories here is the snap short

How to append text to a text file in C++?

I got my code for the answer from a book called "C++ Programming In Easy Steps". The could below should work.

#include <fstream>
#include <string>
#include <iostream>

using namespace std;

int main()
{
    ofstream writer("filename.file-extension" , ios::app);

    if (!writer)
    {
        cout << "Error Opening File" << endl;
        return -1;
    }

    string info = "insert text here";
    writer.append(info);

    writer << info << endl;
    writer.close;
    return 0;   
} 

I hope this helps you.

Why use armeabi-v7a code over armeabi code?

Depends on what your native code does, but v7a has support for hardware floating point operations, which makes a huge difference. armeabi will work fine on all devices, but will be a lot slower, and won't take advantage of newer devices' CPU capabilities. Do take some benchmarks for your particular application, but removing the armeabi-v7a binaries is generally not a good idea. If you need to reduce size, you might want to have two separate apks for older (armeabi) and newer (armeabi-v7a) devices.

Add error bars to show standard deviation on a plot in R

A solution with ggplot2 :

qplot(x,y)+geom_errorbar(aes(x=x, ymin=y-sd, ymax=y+sd), width=0.25)

enter image description here

JPA and Hibernate - Criteria vs. JPQL or HQL

I mostly prefer Criteria Queries for dynamic queries. For example it is much easier to add some ordering dynamically or leave some parts (e.g. restrictions) out depending on some parameter.

On the other hand I'm using HQL for static and complex queries, because it's much easier to understand/read HQL. Also, HQL is a bit more powerful, I think, e.g. for different join types.

Android - how to make a scrollable constraintlayout?

Just use constraint layout inside NestedScrollView or ScrollView.

<android.support.v4.widget.NestedScrollView
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    <android.support.constraint.ConstraintLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@color/white">

 </android.support.constraint.ConstraintLayout>

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

thats it. enjoy your coding.

Version vs build in Xcode

Another way is to set the version number in appDelegate didFinishLaunchingWithOptions:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
     NSString * ver = [self myVersion];
     NSLog(@"version: %@",ver);

     NSUserDefaults* userDefaults = [NSUserDefaults standardUserDefaults];
     [userDefaults setObject:ver forKey:@"version"];
     return YES;
}

- (NSString *) myVersion {
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSString *build = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    return [NSString stringWithFormat:@"%@ build %@", version, build];
}

How to put a text beside the image?

You need to go throgh these scenario:

How about using display:inline-block?

1) Take one <div/> give it style=display:inline-block make it vertical-align:top and put image inside that div.

2) Take another div and give it also the same style display:inline-block; and put all the labels/divs inside this div.

Here is the prototype of your requirement

JS Fiddle Demo

How do I calculate tables size in Oracle

select segment_name,segment_type,bytes/1024/1024 MB
from dba_segments
where segment_name='TABLENAME' and owner ='OWNERNAME' order by mb desc;

Chrome: console.log, console.debug are not working

In my case it was just an old cached Javascript file. After clearing the cache I saw my logs.

How do you implement a class in C?

Do you want virtual methods?

If not then you just define a set of function pointers in the struct itself. If you assign all the function pointers to standard C functions then you will be able to call functions from C in very similar syntax to how you would under C++.

If you want to have virtual methods it gets more complicated. Basically you will need to implement your own VTable to each struct and assign function pointers to the VTable depending on which function is called. You would then need a set of function pointers in the struct itself that in turn call the function pointer in the VTable. This is, essentially, what C++ does.

TBH though ... if you want the latter then you are probably better off just finding a C++ compiler you can use and re-compiling the project. I have never understood the obsession with C++ not being usable in embedded. I've used it many a time and it works is fast and doesn't have memory problems. Sure you have to be a bit more careful about what you do but its really not that complicated.

GIT clone repo across local file system in windows

Not sure if it was because of my git version (1.7.2) or what, but the approaches listed above using machine name and IP options were not working for me. An additional detail that may/may not be important is that the repo was a bare repo that I had initialized and pushed to from a different machine.

I was trying to clone project1 as advised above with commands like:

$ git clone file:////<IP_ADDRESS>/home/user/git/project1
Cloning into project1...
fatal: '//<IP_ADDRESS>/home/user/git/project1' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

and

$ git clone file:////<MACHINE_NAME>/home/user/git/project1
Cloning into project1...
fatal: '//<MACHINE_NAME>/home/user/git/project1' does not appear to be a git repository
fatal: The remote end hung up unexpectedly

What did work for me was something simpler:

$ git clone ../git/project1
Cloning into project1...
done.

Note - even though the repo being cloned from was bare, this did produce a 'normal' clone with all the actual code/image/resource files that I was hoping for (as opposed to the internals of the git repo).

How to remove a directory from git repository?

First git command need to know who you are before deleting anything

  1. git init
  2. git config user.name "someone"
  3. git config user.email "[email protected]"
  4. git rm -r
  5. git commit -m "deleting dir"
  6. git push origin master

The character encoding of the plain text document was not declared - mootool script

FireFox is reporting that the response did not even specify the character encoding in the header, eg. Content-Type: text/html; charset=utf-8 and not just Content-Type: text/plain;.

What web server are you using? Are you sure you are not requesting a non-existing page (404) that responds poorly?

Build error: You must add a reference to System.Runtime

I was also facing this problem trying to run an ASP .NET MVC project after a minor update to our codebase, even though it compiled without errors:

Compiler Error Message: CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

Our project had never run into this problem, so I was skeptical about changing configuration files before finding out the root cause. From the error logs I was able to locate this detailed compiler output which pointed out to what was really happening:

warning CS1685: The predefined type 'System.Runtime.CompilerServices.ExtensionAttribute' is defined in multiple assemblies in the global alias; using definition from 'c:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.dll'

c:\Users\Admin\Software Development\source-control\Binaries\Publish\WebApp\Views\Account\Index.cshtml(35,20): error CS0012: The type 'System.Object' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Runtime, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\meseems.webapp\68e2ea0f\8c5ee951\assembly\dl3\52ad4dac\84698469_3bb3d401\System.Collections.Immutable.DLL: (Location of symbol related to previous error)

Apparently a new package added to our project was referencing an older version of the .NET Framework, causing the "definition in multiple assemblies" issue (CS1685), which led to the razor view compiler error at runtime.

I removed the incompatible package (System.Collections.Immutable.dll) and the problem stopped occurring. However, if the package cannot be removed in your project you will need to try Baahubali's answer.

api-ms-win-crt-runtime-l1-1-0.dll is missing when opening Microsoft Office file

While the answer from alireza is correct, it has one gotcha:

You can't install Microsoft Visual C++ 2015 redist (runtime) unless you have Windows Update KB2999226 installed (at least on Windows 7 64-bit SP1).

how to make a countdown timer in java

You can create a countdown timer using applet, below is the code,

   import java.applet.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.Timer; // not java.util.Timer
   import java.text.NumberFormat;
   import java.net.*;



/**
    * An applet that counts down from a specified time. When it reaches 00:00,
    * it optionally plays a sound and optionally moves the browser to a new page.
    * Place the mouse over the applet to pause the count; move it off to resume.
    * This class demonstrates most applet methods and features.
    **/

public class Countdown extends JApplet implements ActionListener, MouseListener
{
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00

// Called when the applet is first loaded
public void init() {
    // Figure out how long to count for by reading the "minutes" parameter
    // defined in a <param> tag inside the <applet> tag. Convert to ms.
    String minutes = getParameter("minutes");
    if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
    else remaining = 600000; // 10 minutes by default

    // Create a JLabel to display remaining time, and set some properties.
    label = new JLabel();
    label.setHorizontalAlignment(SwingConstants.CENTER );
    label.setOpaque(true); // So label draws the background color

    // Read some parameters for this JLabel object
    String font = getParameter("font");
    String foreground = getParameter("foreground");
    String background = getParameter("background");
    String imageURL = getParameter("image");

    // Set label properties based on those parameters
    if (font != null) label.setFont(Font.decode(font));
    if (foreground != null) label.setForeground(Color.decode(foreground));
    if (background != null) label.setBackground(Color.decode(background));
    if (imageURL != null) {
        // Load the image, and save it so we can release it later
        image = getImage(getDocumentBase(), imageURL);
        // Now display the image in the JLabel.
        label.setIcon(new ImageIcon(image));
    }

    // Now add the label to the applet. Like JFrame and JDialog, JApplet
    // has a content pane that you add children to
    getContentPane().add(label, BorderLayout.CENTER);

    // Get an optional AudioClip to play when the count expires
    String soundURL = getParameter("sound");
    if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);

    // Obtain a NumberFormat object to convert number of minutes and
    // seconds to strings. Set it up to produce a leading 0 if necessary
    format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(2); // pad with 0 if necessary

    // Specify a MouseListener to handle mouse events in the applet.
    // Note that the applet implements this interface itself
    addMouseListener(this);

    // Create a timer to call the actionPerformed() method immediately,
    // and then every 1000 milliseconds. Note we don't start the timer yet.
    timer = new Timer(1000, this);
    timer.setInitialDelay(0); // First timer is immediate.
}

// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }

// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates

// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates

// Return information about the applet
public String getAppletInfo() {
    return "Countdown applet Copyright (c) 2003 by David Flanagan";
}

// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }

// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
    {"minutes", "number", "time, in minutes, to countdown from"},
    {"font", "font", "optional font for the time display"},
    {"foreground", "color", "optional foreground color for the time"},
    {"background", "color", "optional background color"},
    {"image", "image URL", "optional image to display next to countdown"},
    {"sound", "sound URL", "optional sound to play when we reach 00:00"},
    {"newpage", "document URL", "URL to load when timer expires"},
};

// Start or resume the countdown
void resume() {
    // Restore the time we're counting down from and restart the timer.
    lastUpdate = System.currentTimeMillis();
    timer.start(); // Start the timer
}

// Pause the countdown
void pause() {
    // Subtract elapsed time from the remaining time and stop timing
    long now = System.currentTimeMillis();
    remaining -= (now - lastUpdate);
    timer.stop(); // Stop the timer
}

// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
    long now = System.currentTimeMillis(); // current time in ms
    long elapsed = now - lastUpdate; // ms elapsed since last update
    remaining -= elapsed; // adjust remaining time
    lastUpdate = now; // remember this update time

    // Convert remaining milliseconds to mm:ss format and display
    if (remaining < 0) remaining = 0;
    int minutes = (int)(remaining/60000);
    int seconds = (int)((remaining)/1000);
    label.setText(format.format(minutes) + ":" + format.format(seconds));

    // If we've completed the countdown beep and display new page
    if (remaining == 0) {
        // Stop updating now.
        timer.stop();
        // If we have an alarm sound clip, play it now.
        if (sound != null) sound.play();
        // If there is a newpage URL specified, make the browser
        // load that page now.
        String newpage = getParameter("newpage");
        if (newpage != null) {
            try {
                URL url = new URL(getDocumentBase(), newpage);
                getAppletContext().showDocument(url);
            }
            catch(MalformedURLException ex) {      showStatus(ex.toString()); }
        }
    }
}

// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }

// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
    pause(); // pause countdown
    showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
    resume(); // resume countdown
    showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
} 

Resize image with javascript canvas (smoothly)

I don't understand why nobody is suggesting createImageBitmap.

createImageBitmap(
    document.getElementById('image'), 
    { resizeWidth: 300, resizeHeight: 234, resizeQuality: 'high' }
)
.then(imageBitmap => 
    document.getElementById('canvas').getContext('2d').drawImage(imageBitmap, 0, 0)
);

works beautifully (assuming you set ids for image and canvas).

Get MD5 hash of big files in Python

I don't like loops. Based on @Nathan Feger:

md5 = hashlib.md5()
with open(filename, 'rb') as f:
    functools.reduce(lambda _, c: md5.update(c), iter(lambda: f.read(md5.block_size * 128), b''), None)
md5.hexdigest()

What is __main__.py?

Often, a Python program is run by naming a .py file on the command line:

$ python my_program.py

You can also create a directory or zipfile full of code, and include a __main__.py. Then you can simply name the directory or zipfile on the command line, and it executes the __main__.py automatically:

$ python my_program_dir
$ python my_program.zip
# Or, if the program is accessible as a module
$ python -m my_program

You'll have to decide for yourself whether your application could benefit from being executed like this.


Note that a __main__ module usually doesn't come from a __main__.py file. It can, but it usually doesn't. When you run a script like python my_program.py, the script will run as the __main__ module instead of the my_program module. This also happens for modules run as python -m my_module, or in several other ways.

If you saw the name __main__ in an error message, that doesn't necessarily mean you should be looking for a __main__.py file.

How can I set the aspect ratio in matplotlib?

After many years of success with the answers above, I have found this not to work again - but I did find a working solution for subplots at

https://jdhao.github.io/2017/06/03/change-aspect-ratio-in-mpl

With full credit of course to the author above (who can perhaps rather post here), the relevant lines are:

ratio = 1.0
xleft, xright = ax.get_xlim()
ybottom, ytop = ax.get_ylim()
ax.set_aspect(abs((xright-xleft)/(ybottom-ytop))*ratio)

The link also has a crystal clear explanation of the different coordinate systems used by matplotlib.

Thanks for all great answers received - especially @Yann's which will remain the winner.

Creating an Instance of a Class with a variable in Python

I think you can use eval. Something like this

def toclass(strcls):
    return eval(strcls)()

Easy way to dismiss keyboard?

In swift 3 you can do the following

UIApplication.shared.sendAction(#selector(UIResponder.resignFirstResponder), to: nil, from: nil, for: nil)

What are the benefits of learning Vim?

If you're a programmer who edits a lot of text, then it's important to learn an A Serious Text Editor. Which Serious Text Editor you learn is not terribly important and is largely dependent on the types of environments you expect to be editing in.

The reason is that these editors are highly optimized to perform the kinds of tasks that you will be doing a lot. For example, consider adding the same bit of text to the end of every line. This is trivial in A Serious Text Editor, but ridiculously cumbersome otherwise.

Usually vim's killer features are considered: A) that it's available on pretty much every Unix you'll ever encounter and B) your fingers very rarely have to leave the home row, which means you'll be able to edit text very, very quickly. It's also usually very fast and lightweight even when editing huge files.

There are plenty of alternatives, however. Emacs is the most common example, of course, and it's much more than just an advanced text editor if you really dig into it. I'm personally a very happy TextMate user now after years of using vim/gvim.

The trick to switching to any of these is to force yourself to use them the way they were intended. For example, in vim, if you're manually performing every step in a multi-step process or if you're using the arrow keys or the mouse then there's probably a better way to do it. Stop what you're doing and look it up.

If you do nothing else, learn the basic navigation controls for both vim and Emacs since they pop up all over the place. For example, you can use Emacs-style controls in any text input field in Mac OS, in most Unix shells, in Eclipse, etc. You can use vim-style controls in the less(1) command, on Slashdot, on gmail, etc.

Have fun!

Is there any kind of hash code function in JavaScript?

I will try to go a little deeper than other answers.

Even if JS had better hashing support it would not magically hash everything perfectly, in many cases you will have to define your own hash function. For example Java has good hashing support, but you still have to think and do some work.

One problem is with the term hash/hashcode ... there is cryptographic hashing and non-cryptographic hashing. The other problem, is you have to understand why hashing is useful and how it works.

When we talk about hashing in JavaScript or Java most of the time we are talking about non-cryptographic hashing, usually about hashing for hashmap/hashtable (unless we are working on authentication or passwords, which you could be doing server-side using NodeJS ...).

It depends on what data you have and what you want to achieve.

Your data has some natural "simple" uniqueness:

  • The hash of an integer is ... the integer, as it is unique, lucky you !
  • The hash of a string ... it depends on the string, if the string represents a unique identifier, you may consider it as a hash (so no hashing needed).
  • Anything which is indirectly pretty much a unique integer is the simplest case
  • This will respect: hashcode equal if objects are equal

Your data has some natural "composite" uniqueness:

  • For example with a person object, you may compute a hash using firstname, lastname, birthdate, ... see how Java does it: Good Hash Function for Strings, or use some other ID info that is cheap and unique enough for your usecase

You have no idea what your data will be:

  • Good luck ... you could serialize to string and hash it Java style, but that may be expensive if the string is large and it will not avoid collisions as well as say the hash of an integer (self).

There is no magically efficient hashing technique for unknown data, in some cases it is quite easy, in other cases you may have to think twice. So even if JavaScript/ECMAScript adds more support, there is no magic language solution for this problem.

In practice you need two things: enough uniqueness, enough speed

In addition to that it is great to have: "hashcode equal if objects are equal"

sqlplus how to find details of the currently connected database session

Try:

select * from v$session where sid = SYS_CONTEXT('USERENV','SID');

You might also be interested in this AskTom post

After seing your comment, you can do:

SELECT * FROM global_name;

Why is this printing 'None' in the output?

Because there are two print statements. First is inside function and second is outside function. When function not return any thing that time it return None value.

Use return statement at end of function to return value.

e.g.:

Return None value.

>>> def test1():
...    print "In function."
... 
>>> a = test1()
In function.
>>> print a
None
>>> 
>>> print test1()
In function.
None
>>>
>>> test1()
In function.
>>> 

Use return statement

>>> def test():
...   return "ACV"
... 
>>> print test()
ACV
>>> 
>>> a = test()
>>> print a
ACV
>>> 

Max size of URL parameters in _GET

See What is the maximum length of a URL in different browsers?

The length of the url can't be changed in PHP. The linked question is about the URL size limit, you will find what you want.

Trying to get property of non-object - CodeIgniter

In my case, I was looping through a series of objects from an XML file, but some of the instances apparently were not objects which was causing the error. Checking if the object was empty before processing it fixed the problem.

In other words, without checking if the object was empty, the script would error out on any empty object with the error as given below.

Trying to get property of non-object

For Example:

if (!empty($this->xml_data->thing1->thing2))
{
   foreach ($this->xml_data->thing1->thing2 as $thing)
   {

   }
}

ValueError: unsupported pickle protocol: 3, python2 pickle can not load the file dumped by python 3 pickle?

Pickle uses different protocols to convert your data to a binary stream.

You must specify in python 3 a protocol lower than 3 in order to be able to load the data in python 2. You can specify the protocol parameter when invoking pickle.dump.

Inserting values into a SQL Server database using ado.net via C#

you should remove last comma and as nrodic said your command is not correct.

you should change it like this :

SqlCommand cmd = new SqlCommand("INSERT INTO dbo.regist (" + " FirstName, Lastname, Username, Password, Age, Gender,Contact " + ") VALUES (" + " textBox1.Text, textBox2.Text, textBox3.Text, textBox4.Text, comboBox1.Text,comboBox2.Text,textBox7.Text" + ")", cn);

Warning: date_format() expects parameter 1 to be DateTime

Best way is use DateTime object to convert your date.

$myDateTime = DateTime::createFromFormat('Y-m-d', $weddingdate);
$formattedweddingdate = $myDateTime->format('d-m-Y');

Note: It will support for PHP 5 >= 5.3.0 only.

What's the easiest way to escape HTML in Python?

In Python 3.2 a new html module was introduced, which is used for escaping reserved characters from HTML markup.

It has one function escape():

>>> import html
>>> html.escape('x > 2 && x < 7 single quote: \' double quote: "')
'x &gt; 2 &amp;&amp; x &lt; 7 single quote: &#x27; double quote: &quot;'

disabling spring security in spring boot app

Use @profile("whatever-name-profile-to-activate-if-needed") on your security configuration class that extends WebSecurityConfigurerAdapter

security.ignored=/**

security.basic.enable: false

NB. I need to debug to know why why exclude auto configuration did not work for me. But the profile is sot so bad as you can still re-activate it via configuration properties if needed

Java HTTP Client Request with defined timeout

HttpParams is deprecated in the new Apache HTTPClient library. Using the code provided by Laz leads to deprecation warnings.

I suggest to use RequestConfig instead on your HttpGet or HttpPost instance:

final RequestConfig params = RequestConfig.custom().setConnectTimeout(3000).setSocketTimeout(3000).build();
httpPost.setConfig(params);

What is the ideal data type to use when storing latitude / longitude in a MySQL database?

The spatial functions in PostGIS are much more functional (i.e. not constrained to BBOX operations) than those in the MySQL spatial functions. Check it out: link text

How do I download a file with Angular2 or greater

I am using Angular 4 with the 4.3 httpClient object. I modified an answer I found in Js' Technical Blog which creates a link object, uses it to do the download, then destroys it.

Client:

doDownload(id: number, contentType: string) {
    return this.http
        .get(this.downloadUrl + id.toString(), { headers: new HttpHeaders().append('Content-Type', contentType), responseType: 'blob', observe: 'body' })
}

downloadFile(id: number, contentType: string, filename:string)  {

    return this.doDownload(id, contentType).subscribe(  
        res => { 
            var url = window.URL.createObjectURL(res);
            var a = document.createElement('a');
            document.body.appendChild(a);
            a.setAttribute('style', 'display: none');
            a.href = url;
            a.download = filename;
            a.click();
            window.URL.revokeObjectURL(url);
            a.remove(); // remove the element
        }, error => {
            console.log('download error:', JSON.stringify(error));
        }, () => {
            console.log('Completed file download.')
        }); 

} 

The value of this.downloadUrl has been set previously to point to the api. I am using this to download attachments, so I know the id, contentType and filename: I am using an MVC api to return the file:

 [ResponseCache(Location = ResponseCacheLocation.None, NoStore = true)]
    public FileContentResult GetAttachment(Int32 attachmentID)
    { 
        Attachment AT = filerep.GetAttachment(attachmentID);            
        if (AT != null)
        {
            return new FileContentResult(AT.FileBytes, AT.ContentType);  
        }
        else
        { 
            return null;
        } 
    } 

The attachment class looks like this:

 public class Attachment
{  
    public Int32 AttachmentID { get; set; }
    public string FileName { get; set; }
    public byte[] FileBytes { get; set; }
    public string ContentType { get; set; } 
}

The filerep repository returns the file from the database.

Hope this helps someone :)

How to apply an XSLT Stylesheet in C#

Based on Daren's excellent answer, note that this code can be shortened significantly by using the appropriate XslCompiledTransform.Transform overload:

var myXslTrans = new XslCompiledTransform(); 
myXslTrans.Load("stylesheet.xsl"); 
myXslTrans.Transform("source.xml", "result.html"); 

(Sorry for posing this as an answer, but the code block support in comments is rather limited.)

In VB.NET, you don't even need a variable:

With New XslCompiledTransform()
    .Load("stylesheet.xsl")
    .Transform("source.xml", "result.html")
End With

Declaring a boolean in JavaScript using just var

As this very useful tutorial says:

var age = 0;

// bad
var hasAge = new Boolean(age);

// good
var hasAge = Boolean(age);

// good
var hasAge = !!age;

jQuery trigger event when click outside the element

I do not think document fires the click event. Try using the body element to capture the click event. Might need to check on that...

How to get the current plugin directory in WordPress?

When I need to get the directory, not only for the plugins (plugin_dir_path), but a more generic one, you can use __DIR__, it will give you the path of the directory of the file where is called. Now you can used from functions.php or another file!

Description:

The directory of the file. If used inside an include, the directory of the included file is returned. This is equivalent to dirname(__FILE__). This directory name does not have a trailing slash unless it is the root directory. 1

Does IE9 support console.log, and is it a real function?

I would like to mention that IE9 does not raise the error if you use console.log with developer tools closed on all versions of Windows. On XP it does, but on Windows 7 it doesn't. So if you dropped support for WinXP in general, you're fine using console.log directly.

How do I set up CLion to compile and run?

I ran into the same issue with CLion 1.2.1 (at the time of writing this answer) after updating Windows 10. It was working fine before I had updated my OS. My OS is installed in C:\ drive and CLion 1.2.1 and Cygwin (64-bit) are installed in D:\ drive.

The issue seems to be with CMake. I am using Cygwin. Below is the short answer with steps I used to fix the issue.

SHORT ANSWER (should be similar for MinGW too but I haven't tried it):

  1. Install Cygwin with GCC, G++, GDB and CMake (the required versions)
  2. Add full path to Cygwin 'bin' directory to Windows Environment variables
  3. Restart CLion and check 'Settings' -> 'Build, Execution, Deployment' to make sure CLion has picked up the right versions of Cygwin, make and gdb
  4. Check the project configuration ('Run' -> 'Edit configuration') to make sure your project name appears there and you can select options in 'Target', 'Configuration' and 'Executable' fields.
  5. Build and then Run
  6. Enjoy

LONG ANSWER:

Below are the detailed steps that solved this issue for me:

  1. Uninstall/delete the previous version of Cygwin (MinGW in your case)

  2. Make sure that CLion is up-to-date

  3. Run Cygwin setup (x64 for my 64-bit OS)

  4. Install at least the following packages for Cygwin: gcc g++ make Cmake gdb Make sure you are installing the correct versions of the above packages that CLion requires. You can find the required version numbers at CLion's Quick Start section (I cannot post more than 2 links until I have more reputation points).

  5. Next, you need to add Cygwin (or MinGW) to your Windows Environment Variable called 'Path'. You can Google how to find environment variables for your version of Windows

[On Win 10, right-click on 'This PC' and select Properties -> Advanced system settings -> Environment variables... -> under 'System Variables' -> find 'Path' -> click 'Edit']

  1. Add the 'bin' folder to the Path variable. For Cygwin, I added: D:\cygwin64\bin

  2. Start CLion and go to 'Settings' either from the 'Welcome Screen' or from File -> Settings

  3. Select 'Build, Execution, Deployment' and then click on 'Toolchains'

  4. Your 'Environment' should show the correct path to your Cygwin installation directory (or MinGW)

  5. For 'CMake executable', select 'Use bundled CMake x.x.x' (3.3.2 in my case at the time of writing this answer)

  6. 'Debugger' shown to me says 'Cygwin GDB GNU gdb (GDB) 7.8' [too many gdb's in that line ;-)]

  7. Below that it should show a checkmark for all the categories and should also show the correct path to 'make', 'C compiler' and 'C++ compiler'

See screenshot: Check all paths to the compiler, make and gdb

  1. Now go to 'Run' -> 'Edit configuration'. You should see your project name in the left-side panel and the configurations on the right side

See screenshot: Check the configuration to run the project

  1. There should be no errors in the console window. You will see that the 'Run' -> 'Build' option is now active

  2. Build your project and then run the project. You should see the output in the terminal window

Hope this helps! Good luck and enjoy CLion.

How do I toggle an ng-show in AngularJS based on a boolean?

Here's an example to use ngclick & ng-if directives.

Note: that ng-if removes the element from the DOM, but ng-hide just hides the display of the element.

<!-- <input type="checkbox" ng-model="hideShow" ng-init="hideShow = false"></input> -->

<input type = "button" value = "Add Book"ng-click="hideShow=(hideShow ? false : true)"> </input>
     <div ng-app = "mainApp" ng-controller = "bookController" ng-if="hideShow">
             Enter book name: <input type = "text" ng-model = "book.name"><br>
             Enter book category: <input type = "text" ng-model = "book.category"><br>
             Enter book price: <input type = "text" ng-model = "book.price"><br>
             Enter book author: <input type = "text" ng-model = "book.author"><br>


             You are entering book: {{book.bookDetails()}}
     </div>

    <script>
             var mainApp = angular.module("mainApp", []);

             mainApp.controller('bookController', function($scope) {
                $scope.book = {
                   name: "",
                   category: "",
                   price:"",
                   author: "",


                   bookDetails: function() {
                      var bookObject;
                      bookObject = $scope.book;
                      return "Book name: " + bookObject.name +  '\n' + "Book category: " + bookObject.category + "  \n" + "Book price: " + bookObject.price + "  \n" + "Book Author: " + bookObject.author;
                   }

                };
             });
    </script>

How to connect to mysql with laravel?

It's also much more better to not modify the app/config/database.php file itself... otherwise modify .env file and put your DB info there. (.env file is available in Laravel 5, not sure if it was there in previous versions...)

NOTE: Of course you should have already set mysql as your default database connection in the app/config/database.php file.

Conversion of System.Array to List

I know two methods:

List<int> myList1 = new List<int>(myArray);

Or,

List<int> myList2 = myArray.ToList();

I'm assuming you know about data types and will change the types as you please.

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

//return timestamp, use to format month, year as per requirement
function getMonthYear($beforeMonth = '') {
    if($beforeMonth !="" && $beforeMonth >= 1) {
        $date = date('Y')."-".date('m')."-15";
        $timestamp_before = strtotime( $date . ' -'.$beforeMonth.' month' );
        return $timestamp_before;
    } else {
        $time= time();
        return $time;
    }
}


//call function
$month_year = date("Y-m",getMonthYear(1));// last month before  current month
$month_year = date("Y-m",getMonthYear(2)); // second last month before current month

Swift do-try-catch syntax

Create enum like this:

//Error Handling in swift
enum spendingError : Error{
case minus
case limit
}

Create method like:

 func calculateSpending(morningSpending:Double,eveningSpending:Double) throws ->Double{
if morningSpending < 0 || eveningSpending < 0{
    throw spendingError.minus
}
if (morningSpending + eveningSpending) > 100{
    throw spendingError.limit
}
return morningSpending + eveningSpending
}

Now check error is there or not and handle it:

do{
try calculateSpending(morningSpending: 60, eveningSpending: 50)
} catch spendingError.minus{
print("This is not possible...")
} catch spendingError.limit{
print("Limit reached...")
}

Pass Method as Parameter using C#

While the accepted answer is absolutely correct, I would like to provide an additional method.

I ended up here after doing my own searching for a solution to a similar question. I am building a plugin driven framework, and as part of it I wanted people to be able to add menu items to the applications menu to a generic list without exposing an actual Menu object because the framework may deploy on other platforms that don't have Menu UI objects. Adding general info about the menu is easy enough, but allowing the plugin developer enough liberty to create the callback for when the menu is clicked was proving to be a pain. Until it dawned on me that I was trying to re-invent the wheel and normal menus call and trigger the callback from events!

So the solution, as simple as it sounds once you realize it, eluded me until now.

Just create separate classes for each of your current methods, inherited from a base if you must, and just add an event handler to each.

Django optional url parameters

Django = 2.2

urlpatterns = [
    re_path(r'^project_config/(?:(?P<product>\w+)/(?:(?P<project_id>\w+)/)/)?$', tool.views.ProjectConfig, name='project_config')
]

Difference between two lists

bit late but here is working solution for me

 var myBaseProperty = (typeof(BaseClass)).GetProperties();//get base code properties
                    var allProperty = entity.GetProperties()[0].DeclaringType.GetProperties();//get derived class property plus base code as it is derived from it
                    var declaredClassProperties = allProperty.Where(x => !myBaseProperty.Any(l => l.Name == x.Name)).ToList();//get the difference

In above mention code I am getting the properties difference between my base class and derived class list

Volatile vs Static in Java

If we declare a variable as static, there will be only one copy of the variable. So, whenever different threads access that variable, there will be only one final value for the variable(since there is only one memory location allocated for the variable).

If a variable is declared as volatile, all threads will have their own copy of the variable but the value is taken from the main memory.So, the value of the variable in all the threads will be the same.

So, in both cases, the main point is that the value of the variable is same across all threads.

Bootstrap 3: Text overlay on image

try the following example. Image overlay with text on image. demo

<div class="thumbnail">
  <img src="https://s3.amazonaws.com/discount_now_staging/uploads/ed964a11-e089-4c61-b927-9623a3fe9dcb/direct_uploader_2F50cc1daf-465f-48f0-8417-b04ac68a999d_2FN_19_jewelry.jpg" alt="..."   />
  <div class="caption post-content">  
  </div> 
  <div class="details">
    <h3>Robots!</h3>
    <p>Lorem ipsum dolor sit amet</p>   
  </div>  
</div>

css

.post-content {
    background: rgba(0, 0, 0, 0.7) none repeat scroll 0 0;
    opacity: 0.5;
    top:0;
    left:0;
    min-width: 500px;
    min-height: 500px; 
    position: absolute;
    color: #ffffff; 
}

.thumbnail{
    position:relative;

}
.details {
    position: absolute; 
    z-index: 2; 
    top: 0;
    color: #ffffff; 
}

Using HTML5 file uploads with AJAX and jQuery

With jQuery (and without FormData API) you can use something like this:

function readFile(file){
   var loader = new FileReader();
   var def = $.Deferred(), promise = def.promise();

   //--- provide classic deferred interface
   loader.onload = function (e) { def.resolve(e.target.result); };
   loader.onprogress = loader.onloadstart = function (e) { def.notify(e); };
   loader.onerror = loader.onabort = function (e) { def.reject(e); };
   promise.abort = function () { return loader.abort.apply(loader, arguments); };

   loader.readAsBinaryString(file);

   return promise;
}

function upload(url, data){
    var def = $.Deferred(), promise = def.promise();
    var mul = buildMultipart(data);
    var req = $.ajax({
        url: url,
        data: mul.data,
        processData: false,
        type: "post",
        async: true,
        contentType: "multipart/form-data; boundary="+mul.bound,
        xhr: function() {
            var xhr = jQuery.ajaxSettings.xhr();
            if (xhr.upload) {

                xhr.upload.addEventListener('progress', function(event) {
                    var percent = 0;
                    var position = event.loaded || event.position; /*event.position is deprecated*/
                    var total = event.total;
                    if (event.lengthComputable) {
                        percent = Math.ceil(position / total * 100);
                        def.notify(percent);
                    }                    
                }, false);
            }
            return xhr;
        }
    });
    req.done(function(){ def.resolve.apply(def, arguments); })
       .fail(function(){ def.reject.apply(def, arguments); });

    promise.abort = function(){ return req.abort.apply(req, arguments); }

    return promise;
}

var buildMultipart = function(data){
    var key, crunks = [], bound = false;
    while (!bound) {
        bound = $.md5 ? $.md5(new Date().valueOf()) : (new Date().valueOf());
        for (key in data) if (~data[key].indexOf(bound)) { bound = false; continue; }
    }

    for (var key = 0, l = data.length; key < l; key++){
        if (typeof(data[key].value) !== "string") {
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"; filename=\""+data[key].value[1]+"\"\r\n"+
                "Content-Type: application/octet-stream\r\n"+
                "Content-Transfer-Encoding: binary\r\n\r\n"+
                data[key].value[0]);
        }else{
            crunks.push("--"+bound+"\r\n"+
                "Content-Disposition: form-data; name=\""+data[key].name+"\"\r\n\r\n"+
                data[key].value);
        }
    }

    return {
        bound: bound,
        data: crunks.join("\r\n")+"\r\n--"+bound+"--"
    };
};

//----------
//---------- On submit form:
var form = $("form");
var $file = form.find("#file");
readFile($file[0].files[0]).done(function(fileData){
   var formData = form.find(":input:not('#file')").serializeArray();
   formData.file = [fileData, $file[0].files[0].name];
   upload(form.attr("action"), formData).done(function(){ alert("successfully uploaded!"); });
});

With FormData API you just have to add all fields of your form to FormData object and send it via $.ajax({ url: url, data: formData, processData: false, contentType: false, type:"POST"})

How to append to a file in Node?

Try to use flags: 'a' to append data to a file

 var stream = fs.createWriteStream("udp-stream.log", {'flags': 'a'});
  stream.once('open', function(fd) {
    stream.write(msg+"\r\n");
  });

convert a char* to std::string

char* data;
std::string myString(data);

How to extract extension from filename string in Javascript?

I personally prefer to split the string by . and just return the last array element :)

var fileExt = filename.split('.').pop();

If there is no . in filename you get the entire string back.

Examples:

'some_value'                                   => 'some_value'
'.htaccess'                                    => 'htaccess'
'../images/something.cool.jpg'                 => 'jpg'
'http://www.w3schools.com/jsref/jsref_pop.asp' => 'asp'
'http://stackoverflow.com/questions/680929'    => 'com/questions/680929'

Linux / Bash, using ps -o to get process by specific name?

This is a bit old, but I guess what you want is: ps -o pid -C PROCESS_NAME, for example:

ps -o pid -C bash

EDIT: Dependening on the sort of output you expect, pgrep would be more elegant. This, in my knowledge, is Linux specific and result in similar output as above. For example:

pgrep bash

Get selected key/value of a combo box using jQuery

This works:

<select name="foo" id="foo">
<option value="1">a</option>
<option value="2">b</option>
<option value="3">c</option>
</select>
<input type="button" id="button" value="Button" />

$('#button').click(function() {
    alert($('#foo option:selected').text());
    alert($('#foo option:selected').val());
});

Compression/Decompression string with C#

With the advent of .NET 4.0 (and higher) with the Stream.CopyTo() methods, I thought I would post an updated approach.

I also think the below version is useful as a clear example of a self-contained class for compressing regular strings to Base64 encoded strings, and vice versa:

public static class StringCompression
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

Here’s another approach using the extension methods technique to extend the String class to add string compression and decompression. You can drop the class below into an existing project and then use thusly:

var uncompressedString = "Hello World!";
var compressedString = uncompressedString.Compress();

and

var decompressedString = compressedString.Decompress();

To wit:

public static class Extensions
{
    /// <summary>
    /// Compresses a string and returns a deflate compressed, Base64 encoded string.
    /// </summary>
    /// <param name="uncompressedString">String to compress</param>
    public static string Compress(this string uncompressedString)
    {
        byte[] compressedBytes;

        using (var uncompressedStream = new MemoryStream(Encoding.UTF8.GetBytes(uncompressedString)))
        {
            using (var compressedStream = new MemoryStream())
            { 
                // setting the leaveOpen parameter to true to ensure that compressedStream will not be closed when compressorStream is disposed
                // this allows compressorStream to close and flush its buffers to compressedStream and guarantees that compressedStream.ToArray() can be called afterward
                // although MSDN documentation states that ToArray() can be called on a closed MemoryStream, I don't want to rely on that very odd behavior should it ever change
                using (var compressorStream = new DeflateStream(compressedStream, CompressionLevel.Fastest, true))
                {
                    uncompressedStream.CopyTo(compressorStream);
                }

                // call compressedStream.ToArray() after the enclosing DeflateStream has closed and flushed its buffer to compressedStream
                compressedBytes = compressedStream.ToArray();
            }
        }

        return Convert.ToBase64String(compressedBytes);
    }

    /// <summary>
    /// Decompresses a deflate compressed, Base64 encoded string and returns an uncompressed string.
    /// </summary>
    /// <param name="compressedString">String to decompress.</param>
    public static string Decompress(this string compressedString)
    {
        byte[] decompressedBytes;

        var compressedStream = new MemoryStream(Convert.FromBase64String(compressedString));

        using (var decompressorStream = new DeflateStream(compressedStream, CompressionMode.Decompress))
        {
            using (var decompressedStream = new MemoryStream())
            {
                decompressorStream.CopyTo(decompressedStream);

                decompressedBytes = decompressedStream.ToArray();
            }
        }

        return Encoding.UTF8.GetString(decompressedBytes);
    }

How can you use php in a javascript function

In the above given code

assign the php value to javascript variable.

<html>
<?php
 $num = 1;
 echo $num;
?>
  <input type = "button" name = "lol" value = "Click to increment" onclick = "Inc()">
  <br>
  <script>
   var numeric = <?php echo $num; ?>"; //assigns value of the $num to javascript var             numeric 
  function Inc()
   {
     numeric = eVal(numeric) + 1;
     alert("Increamented value: "+numeric);
   }
  </script>
</html>

One thing in combination of PHP and Javsacript is you can not assign javascript value to PHP value. You can assign PHP value to javascript variable.

How to apply multiple transforms in CSS?

You can apply more than one transform like this:

li:nth-of-type(2){
    transform : translate(-20px, 0px) rotate(15deg);
}

SQL Not Like Statement not working

I just came across the same issue, and solved it, but not before I found this post. And seeing as your question wasn't really answered, here's my solution (which will hopefully work for you, or anyone else searching for the same thing I did;

Instead of;

... AND WPP.COMMENT NOT LIKE '%CORE%' ...

Try;

... AND NOT WPP.COMMENT LIKE '%CORE%' ...

Basically moving the "NOT" the other side of the field I was evaluating worked for me.

Converting Decimal to Binary Java

Well, you can use while loop, like this,

import java.util.Scanner;

public class DecimalToBinaryExample
{
    public static void main(String[] args)
    {
        int num;
        int a = 0;
        Scanner sc = new Scanner(System.in);
        System.out.println("Please enter a decimal number : ");
        num = sc.nextInt();
        int binary[] = new int[100];

        while(num != 0)
        {
            binary[a] = num % 2;
            num = num / 2;
            a++;
        }

        System.out.println("The binary value is : ");
        for(int b = a - 1; b >= 0; b--)
        {
            System.out.println("" + binary[b]);
        }
        sc.close();
    }
}

You can refer example below for some good explanation,

convert decimal to binary example.

When to use Spring Security`s antMatcher()?

I'm updating my answer...

antMatcher() is a method of HttpSecurity, it doesn't have anything to do with authorizeRequests(). Basically, http.antMatcher() tells Spring to only configure HttpSecurity if the path matches this pattern.

The authorizeRequests().antMatchers() is then used to apply authorization to one or more paths you specify in antMatchers(). Such as permitAll() or hasRole('USER3'). These only get applied if the first http.antMatcher() is matched.

Using jQuery Fancybox or Lightbox to display a contact form

you'll probably want to look into jquery-ui dialog. it's highly customizable and can be made to work exactly like lightbox/fancybox and supports everything you would need for a contact form from a regular link.

there is even an example with a form.

Generating Random Number In Each Row In Oracle Query

At first I thought that this would work:

select DBMS_Random.Value(1,9) output
from   ...

However, this does not generate an even distribution of output values:

select output,
       count(*)
from   (
       select round(dbms_random.value(1,9)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   62423
2   125302
3   125038
4   125207
5   124892
6   124235
7   124832
8   125514
9   62557

The reasons are pretty obvious I think.

I'd suggest using something like:

floor(dbms_random.value(1,10))

Hence:

select output,
       count(*)
from   (
       select floor(dbms_random.value(1,10)) output
       from   dual
       connect by level <= 1000000)
group by output
order by 1

1   111038
2   110912
3   111155
4   111125
5   111084
6   111328
7   110873
8   111532
9   110953

Print page numbers on pages when printing html

   **@page {
            margin-top:21% !important; 
            @top-left{
            content: element(header);

            }

            @bottom-left {
            content: element(footer
 }
 div.header {

            position: running(header);

            }
            div.footer {

            position: running(footer);
            border-bottom: 2px solid black;


            }
           .pagenumber:before {
            content: counter(page);
            }
            .pagecount:before {
            content: counter(pages);
            }      
 <div class="footer" style="font-size:12pt; font-family: Arial; font-family: Arial;">
                <span>Page <span class="pagenumber"/> of <span class="pagecount"/></span>
            </div >**

CASE .. WHEN expression in Oracle SQL

You can rewrite it to use the ELSE condition of a CASE:

SELECT status,
       CASE status
         WHEN 'i' THEN 'Inactive'
         WHEN 't' THEN 'Terminated'
         ELSE 'Active'
       END AS StatusText
FROM   stage.tst 

CXF: No message body writer found for class - automatically mapping non-simple resources

I encountered this problem while upgrading from CXF 2.7.0 to 3.0.2. Here is what I did to resolve it:

Included the following in my pom.xml

    <dependency>
        <groupId>org.apache.cxf</groupId>
        <artifactId>cxf-rt-rs-extension-providers</artifactId>
        <version>3.0.2</version>
    </dependency>

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-jaxrs</artifactId>
        <version>1.9.0</version>
    </dependency>

and added the following provider

    <jaxrs:providers>
        <bean class="org.codehaus.jackson.jaxrs.JacksonJaxbJsonProvider" />
    </jaxrs:providers>

Getting the error "Missing $ inserted" in LaTeX

My first guess is that LaTeX chokes on | outside a math environment. Missing $ inserted is usually a symptom of something like that.

How do you run a single test/spec file in RSpec?

http://github.com/grosser/single_test lets you do stuff like..

rake spec:user          #run spec/model/user_spec.rb (searches for user*_spec.rb)
rake test:users_c       #run test/functional/users_controller_test.rb
rake spec:user:token    #run the first spec in user_spec.rb that matches /token/
rake test:user:token    #run all tests in user_test.rb that match /token/
rake test:last
rake spec:last

set background color: Android

This question is a old one but it can help for others too.

Try this :

    li.setBackgroundColor(getResources().getColor(R.color.blue));

    or

    li.setBackgroundColor(getResources().getColor(android.R.color.red));

    or

    li.setBackgroundColor(Color.rgb(226, 11, 11));


    or
    li.setBackgroundColor(Color.RED)

How do I compile a .cpp file on Linux?

The compiler is telling you that there are problems starting at line 122 in the middle of that strange FBI-CIA warning message. That message is not valid C++ code and is NOT commented out so of course it will cause compiler errors. Try removing that entire message.

Also, I agree with In silico: you should always tell us what you tried and exactly what error messages you got.

Java: Simplest way to get last word in a string

String test =  "This is a sentence";
String lastWord = test.substring(test.lastIndexOf(" ")+1);

Get selected text from a drop-down list (select box) using jQuery

_x000D_
_x000D_
$(function () {_x000D_
  alert('.val() = ' + $('#selectnumber').val() + '  AND  html() = ' + $('#selectnumber option:selected').html() + '  AND .text() = ' + $('#selectnumber option:selected').text());_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
  <head runat="server">_x000D_
    <title></title>_x000D_
_x000D_
  </head>_x000D_
  <body>_x000D_
    <form id="form1" runat="server">_x000D_
      <div>_x000D_
        <select id="selectnumber">_x000D_
          <option value="1">one</option>_x000D_
          <option value="2">two</option>_x000D_
          <option value="3">three</option>_x000D_
          <option value="4">four</option>_x000D_
        </select>_x000D_
_x000D_
      </div>_x000D_
    </form>_x000D_
  </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Click to see OutPut Screen

How can I tail a log file in Python?

So, this is coming quite late, but I ran into the same problem again, and there's a much better solution now. Just use pygtail:

Pygtail reads log file lines that have not been read. It will even handle log files that have been rotated. Based on logcheck's logtail2 (http://logcheck.org)

How to convert a Kotlin source file to a Java source file

you can go to Tools > Kotlin > Show kotlin bytecode

enter image description here

enter image description here

enter image description here

How to run mysql command on bash?

This one worked, double quotes when $user and $password are outside single quotes. Single quotes when inside a single quote statement.

mysql --user="$user" --password="$password" --database="$user" --execute='DROP DATABASE '$user'; CREATE DATABASE '$user';'

Using Apache POI how to read a specific excel column

heikkim is right, here is some sample code adapted from some code I have:

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Row;
...
for (int rowIndex = 0; rowIndex <= sheet.getLastRowNum(); rowIndex++) {
  row = sheet.getRow(rowIndex);
  if (row != null) {
    Cell cell = row.getCell(colIndex);
    if (cell != null) {
      // Found column and there is value in the cell.
      cellValueMaybeNull = cell.getStringCellValue();
      // Do something with the cellValueMaybeNull here ...
      // break; ???
    }
  }
}

For the colCount use something like row.getPhysicalNumberOfCells()

Creating columns in listView and add items

I didn't see anyone answer this correctly. So I'm posting it here. In order to get columns to show up you need to specify the following line.

lvRegAnimals.View = View.Details;

And then add your columns after that.

lvRegAnimals.Columns.Add("Id", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Name", -2, HorizontalAlignment.Left);
lvRegAnimals.Columns.Add("Age", -2, HorizontalAlignment.Left);

Hope this helps anyone else looking for this answer in the future.

How to set the custom border color of UIView programmatically?

Swift 5*

I, always use view extension to make view corners round, set border color and width and it has been the most convenient way for me. just copy and paste this code and controlle these properties in attribute inspector.

extension UIView {
    @IBInspectable
    var cornerRadius: CGFloat {
        get {
            return layer.cornerRadius
        }
        set {
            layer.cornerRadius = newValue
        }
    }
    
    @IBInspectable
    var borderWidth: CGFloat {
        get {
            return layer.borderWidth
        }
        set {
            layer.borderWidth = newValue
        }
    }
    
    @IBInspectable
    var borderColor: UIColor? {
        get {
            if let color = layer.borderColor {
                return UIColor(cgColor: color)
            }
            return nil
        }
        set {
            if let color = newValue {
                layer.borderColor = color.cgColor
            } else {
                layer.borderColor = nil
            }
        }
    }
}

What is the reason for a red exclamation mark next to my project in Eclipse?

This is related to multiple versions of same depenendency in the local repository .m2

go to ur eclipse > problems tab > see the errors > go the local .m2 folder

delete all the non relevant versions of the the dependency which you have added recently.

then try to rebuild the project.

How do I format a date in Jinja2?

You can use it like this in jinja template {{ row.session_start_date_time.strftime('%d-%m-%Y %H:%M:%S')}}

In this code the field name is row.session_start_date_time.

Remote Connections Mysql Ubuntu

To expose MySQL to anything other than localhost you will have to have the following line

For mysql version 5.6 and below

uncommented in /etc/mysql/my.cnf and assigned to your computers IP address and not loopback

For mysql version 5.7 and above

uncommented in /etc/mysql/mysql.conf.d/mysqld.cnf and assigned to your computers IP address and not loopback

#Replace xxx with your IP Address 
bind-address        = xxx.xxx.xxx.xxx

Or add a bind-address = 0.0.0.0 if you don't want to specify the IP

Then stop and restart MySQL with the new my.cnf entry. Once running go to the terminal and enter the following command.

lsof -i -P | grep :3306

That should come back something like this with your actual IP in the xxx's

mysqld  1046  mysql  10u  IPv4  5203  0t0  TCP  xxx.xxx.xxx.xxx:3306 (LISTEN)

If the above statement returns correctly you will then be able to accept remote users. However for a remote user to connect with the correct priveleges you need to have that user created in both the localhost and '%' as in.

CREATE USER 'myuser'@'localhost' IDENTIFIED BY 'mypass';
CREATE USER 'myuser'@'%' IDENTIFIED BY 'mypass';

then,

GRANT ALL ON *.* TO 'myuser'@'localhost';
GRANT ALL ON *.* TO 'myuser'@'%';

and finally,

FLUSH PRIVILEGES; 
EXIT;

If you don't have the same user created as above, when you logon locally you may inherit base localhost privileges and have access issues. If you want to restrict the access myuser has then you would need to read up on the GRANT statement syntax HERE If you get through all this and still have issues post some additional error output and the my.cnf appropriate lines.

NOTE: If lsof does not return or is not found you can install it HERE based on your Linux distribution. You do not need lsof to make things work, but it is extremely handy when things are not working as expected.

UPDATE: If even after adding/changing the bind-address in my.cnf did not work, then go and change it in the place it was originally declared:

/etc/mysql/mariadb.conf.d/50-server.cnf

Chrome ignores autocomplete="off"

Whilst I agree autocomplete should be a user choice, there are times when Chrome is over-zealous with it (other browsers may be too). For instance, a password field with a different name is still auto-filled with a saved password and the previous field populated with the username. This particularly sucks when the form is a user management form for a web app and you don't want autofill to populate it with your own credentials.

Chrome completely ignores autocomplete="off" now. Whilst the JS hacks may well work, I found a simple way which works at the time of writing:

Set the value of the password field to the control character 8 ("\x08" in PHP or &#8; in HTML). This stops Chrome auto-filling the field because it has a value, but no actual value is entered because this is the backspace character.

Yes this is still a hack, but it works for me. YMMV.

Get bytes from std::string in C++

I dont think you want to use the c# code you have there. They provide System.Text.Encoding.ASCII(also UTF-*)

string str = "some text;
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(str);

your problems stem from ignoring the encoding in c# not your c++ code

Secondary axis with twinx(): how to add to legend?

I'm not sure if this functionality is new, but you can also use the get_legend_handles_labels() method rather than keeping track of lines and labels yourself:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib import rc
rc('mathtext', default='regular')

pi = np.pi

# fake data
time = np.linspace (0, 25, 50)
temp = 50 / np.sqrt (2 * pi * 3**2) \
        * np.exp (-((time - 13)**2 / (3**2))**2) + 15
Swdown = 400 / np.sqrt (2 * pi * 3**2) * np.exp (-((time - 13)**2 / (3**2))**2)
Rn = Swdown - 10

fig = plt.figure()
ax = fig.add_subplot(111)

ax.plot(time, Swdown, '-', label = 'Swdown')
ax.plot(time, Rn, '-', label = 'Rn')
ax2 = ax.twinx()
ax2.plot(time, temp, '-r', label = 'temp')

# ask matplotlib for the plotted objects and their labels
lines, labels = ax.get_legend_handles_labels()
lines2, labels2 = ax2.get_legend_handles_labels()
ax2.legend(lines + lines2, labels + labels2, loc=0)

ax.grid()
ax.set_xlabel("Time (h)")
ax.set_ylabel(r"Radiation ($MJ\,m^{-2}\,d^{-1}$)")
ax2.set_ylabel(r"Temperature ($^\circ$C)")
ax2.set_ylim(0, 35)
ax.set_ylim(-20,100)
plt.show()

How to determine the current iPhone/device model?

Using a Swift 'switch-case':

func platformString() -> String {

    var devSpec: String

    switch platform() {

    case "iPhone1,2": devSpec = "iPhone 3G"
    case "iPhone2,1": devSpec = "iPhone 3GS"
    case "iPhone3,1": devSpec = "iPhone 4"
    case "iPhone3,3": devSpec = "Verizon iPhone 4"
    case "iPhone4,1": devSpec = "iPhone 4S"
    case "iPhone5,1": devSpec = "iPhone 5 (GSM)"
    case "iPhone5,2": devSpec = "iPhone 5 (GSM+CDMA)"
    case "iPhone5,3": devSpec = "iPhone 5c (GSM)"
    case "iPhone5,4": devSpec = "iPhone 5c (GSM+CDMA)"
    case "iPhone6,1": devSpec = "iPhone 5s (GSM)"
    case "iPhone6,2": devSpec = "iPhone 5s (GSM+CDMA)"
    case "iPhone7,1": devSpec = "iPhone 6 Plus"
    case "iPhone7,2": devSpec = "iPhone 6"
    case "iPod1,1": devSpec = "iPod Touch 1G"
    case "iPod2,1": devSpec = "iPod Touch 2G"
    case "iPod3,1": devSpec = "iPod Touch 3G"
    case "iPod4,1": devSpec = "iPod Touch 4G"
    case "iPod5,1": devSpec = "iPod Touch 5G"
    case "iPad1,1": devSpec = "iPad"
    case "iPad2,1": devSpec = "iPad 2 (WiFi)"
    case "iPad2,2": devSpec = "iPad 2 (GSM)"
    case "iPad2,3": devSpec = "iPad 2 (CDMA)"
    case "iPad2,4": devSpec = "iPad 2 (WiFi)"
    case "iPad2,5": devSpec = "iPad Mini (WiFi)"
    case "iPad2,6": devSpec = "iPad Mini (GSM)"
    case "iPad2,7": devSpec = "iPad Mini (GSM+CDMA)"
    case "iPad3,1": devSpec = "iPad 3 (WiFi)"
    case "iPad3,2": devSpec = "iPad 3 (GSM+CDMA)"
    case "iPad3,3": devSpec = "iPad 3 (GSM)"
    case "iPad3,4": devSpec = "iPad 4 (WiFi)"
    case "iPad3,5": devSpec = "iPad 4 (GSM)"
    case "iPad3,6": devSpec = "iPad 4 (GSM+CDMA)"
    case "iPad4,1": devSpec = "iPad Air (WiFi)"
    case "iPad4,2": devSpec = "iPad Air (Cellular)"
    case "iPad4,4": devSpec = "iPad mini 2G (WiFi)"
    case "iPad4,5": devSpec = "iPad mini 2G (Cellular)"

    case "iPad4,7": devSpec = "iPad mini 3 (WiFi)"
    case "iPad4,8": devSpec = "iPad mini 3 (Cellular)"
    case "iPad4,9": devSpec = "iPad mini 3 (China Model)"

    case "iPad5,3": devSpec = "iPad Air 2 (WiFi)"
    case "iPad5,4": devSpec = "iPad Air 2 (Cellular)"

    case "i386": devSpec = "Simulator"
    case "x86_64": devSpec = "Simulator"

    default: devSpec = "Unknown"
    }

    return devSpec
}

How to get bean using application context in spring boot

If you are inside of Spring bean (in this case @Controller bean) you shouldn't use Spring context instance at all. Just autowire className bean directly.

BTW, avoid using field injection as it's considered as bad practice.

change type of input field with jQuery

It's very likely this action is prevented as part of the browser's security model.

Edit: indeed, testing right now in Safari, I get the error type property cannot be changed.

Edit 2: that seems to be an error straight out of jQuery. Using the following straight DOM code works just fine:

var pass = document.createElement('input');
pass.type = 'password';
document.body.appendChild(pass);
pass.type = 'text';
pass.value = 'Password';

Edit 3: Straight from the jQuery source, this seems to be related to IE (and could either be a bug or part of their security model, but jQuery isn't specific):

// We can't allow the type property to be changed (since it causes problems in IE)
if ( name == "type" && jQuery.nodeName( elem, "input" ) && elem.parentNode )
    throw "type property can't be changed";

Leave out quotes when copying from cell

  • if formula having multi line (means having line break in formula) then copy paste will work in that way
  • if can remove multi line then no quotes will appear while copy paste.
  • else use CLEAN function as said by @greg in previous answer

In Java, how do you determine if a thread is running?

You can use: Thread.currentThread().isAlive();. Returns true if this thread is alive; false otherwise.

How to use range-based for() loop with std::map?

From this paper: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2049.pdf

for( type-speci?er-seq simple-declarator : expression ) statement

is syntactically equivalent to

{
    typedef decltype(expression) C;
    auto&& rng(expression);
    for (auto begin(std::For<C>::begin(rng)), end(std::For<C>::end(rng)); begin != end; ++ begin) {
        type-speci?er-seq simple-declarator(*begin);
        statement
    }
}

So you can clearly see that what is abc in your case will be std::pair<key_type, value_type >. So for printing you can do access each element by abc.first and abc.second

Media query to detect if device is touchscreen

There is actually a property for this in the CSS4 media query draft.

The ‘pointer’ media feature is used to query about the presence and accuracy of a pointing device such as a mouse. If a device has multiple input mechanisms, it is recommended that the UA reports the characteristics of the least capable pointing device of the primary input mechanisms. This media query takes the following values:

‘none’
- The input mechanism of the device does not include a pointing device.

‘coarse’
- The input mechanism of the device includes a pointing device of limited accuracy.

‘fine’
- The input mechanism of the device includes an accurate pointing device.

This would be used as such:

/* Make radio buttons and check boxes larger if we have an inaccurate pointing device */
@media (pointer:coarse) {
    input[type="checkbox"], input[type="radio"] {
        min-width:30px;
        min-height:40px;
        background:transparent;
    }
}

I also found a ticket in the Chromium project related to this.

Browser compatibility can be tested at Quirksmode. These are my results (22 jan 2013):

  • Chrome/Win: Works
  • Chrome/iOS: Doesn't work
  • Safari/iOS6: Doesn't work

How to create a new column in a select query

SELECT field1, 
       field2,
       'example' AS newfield
FROM TABLE1

This will add a column called "newfield" to the output, and its value will always be "example".

printing a two dimensional array in python

There is always the easy way.

import numpy as np
print(np.matrix(A))

In VBA get rid of the case sensitivity when comparing words?

It is a bit of hack but will do the task.

Function equalsIgnoreCase(str1 As String, str2 As String) As Boolean
    equalsIgnoreCase = LCase(str1) = LCase(str2)
End Function

Javascript String to int conversion

If you are sure id.substring(indexPos) is a number, you can do it like so:

var number = Number(id.substring(indexPos)) + 1;

Otherwise I suggest checking if the Number function evaluates correctly.

How to find NSDocumentDirectory in Swift?

Usually I prefer to use this extension:

Swift 3.x and Swift 4.0:

extension FileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true) as [String]
        return paths[0]
    }
}

Swift 2.x:

extension NSFileManager {
    class func documentsDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
    
    class func cachesDir() -> String {
        var paths = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true) as [String]
        return paths[0]
    }
}

How to generate random float number in C

This generates a random float between two floats.

float RandomFloat(float min, float max){
   return ((max - min) * ((float)rand() / RAND_MAX)) + min;
}

.NET obfuscation tools/strategy

I've been obfuscating code in the same application since .Net 1, and it's been a major headache from a maintenance perspective. As you've mentioned, the serialization problem can be avoided, but it's really easy to make a mistake and obfuscate something you didn't want obfuscated. It's easy to break the build, or to change the obfuscation pattern and not be able to open old files. Plus it can be difficult to find out what went wrong and where.

Our choice was Xenocode, and were I to make the choice again today I would prefer to not obfuscate the code, or use Dotfuscator.

Passing arguments to "make run"

Here is my example. Note that I am writing under Windows 7, using mingw32-make.exe that comes with Dev-Cpp. (I have c:\Windows\System32\make.bat, so the command is still called "make".)

clean:
    $(RM) $(OBJ) $(BIN) 
    @echo off
    if "${backup}" NEQ "" ( mkdir ${backup} 2> nul && copy * ${backup} )

Usage for regular cleaning:

make clean

Usage for cleaning and creating a backup in mydir/:

make clean backup=mydir

Is multiplication and division using shift operators in C actually faster?

I think in the one case that you want to multiply or divide by a power of two, you can't go wrong with using bitshift operators, even if the compiler converts them to a MUL/DIV, because some processors microcode (really, a macro) them anyway, so for those cases you will achieve an improvement, especially if the shift is more than 1. Or more explicitly, if the CPU has no bitshift operators, it will be a MUL/DIV anyway, but if the CPU has bitshift operators, you avoid a microcode branch and this is a few instructions less.

I am writing some code right now that requires a lot of doubling/halving operations because it is working on a dense binary tree, and there is one more operation that I suspect might be more optimal than an addition - a left (power of two multiply) shift with an addition. This can be replaced with a left shift and an xor if the shift is wider than the number of bits you want to add, easy example is (i<<1)^1, which adds one to a doubled value. This does not of course apply to a right shift (power of two divide) because only a left (little endian) shift fills the gap with zeros.

In my code, these multiply/divide by two and powers of two operations are very intensively used and because the formulae are quite short already, each instruction that can be eliminated can be a substantial gain. If the processor does not support these bitshift operators, no gain will happen but neither will there be a loss.

Also, in the algorithms I am writing, they visually represent the movements that occur so in that sense they are in fact more clear. The left hand side of a binary tree is bigger, and the right is smaller. As well as that, in my code, odd and even numbers have a special significance, and all left-hand children in the tree are odd and all right hand children, and the root, are even. In some cases, which I haven't encountered yet, but may, oh, actually, I didn't even think of this, x&1 may be a more optimal operation compared to x%2. x&1 on an even number will produce zero, but will produce 1 for an odd number.

Going a bit further than just odd/even identification, if I get zero for x&3 I know that 4 is a factor of our number, and same for x%7 for 8, and so on. I know that these cases have probably got limited utility but it's nice to know that you can avoid a modulus operation and use a bitwise logic operation instead, because bitwise operations are almost always the fastest, and least likely to be ambiguous to the compiler.

I am pretty much inventing the field of dense binary trees so I expect that people may not grasp the value of this comment, as very rarely do people want to only perform factorisations on only powers of two, or only multiply/divide powers of two.

net::ERR_INSECURE_RESPONSE in Chrome

Don't know if this question is relevant anymore, but this happened to me on a client wich had an incorrect datetime set on Windows. This will be an alternative to watch. If is this case, it will reproduce on other browsers as well (at least, on firefox and chrome).

I fixed it updating datetime on Windows to actual's real datetime. Hope it helps somebody.

How to subtract days from a plain Date?

var my date = new Date().toISOString().substring(0, 10);

it can give you only date like 2014-06-20. hope will help

How do I copy items from list to list without foreach?

Easy to map different set of list by linq without for loop

var List1= new List<Entities1>();

var List2= new List<Entities2>();

var List2 = List1.Select(p => new Entities2
        {
            EntityCode = p.EntityCode,
            EntityId = p.EntityId,
            EntityName = p.EntityName
        }).ToList();

Import error No module named skimage

Hey this is pretty simple to solve this error.Just follow this steps:

First uninstall any existing installation:

pip uninstall scikit-image

or, on conda-based systems:

conda uninstall scikit-image

Now, clone scikit-image on your local computer, and install:

git clone https://github.com/scikit-image/scikit-image.git
cd scikit-image
pip install -e .

To update the installation:

git pull  # Grab latest source
pip install -e .  # Reinstall

For other os and manual process please check this Link.

How can I add new dimensions to a Numpy array?

This worked for me:

image = image[..., None]

Fixed GridView Header with horizontal and vertical scrolling in asp.net

// create this Js and add reference

var GridViewScrollOptions = /** @class */ (function () {
    function GridViewScrollOptions() {
    }
    return GridViewScrollOptions;
}());

var GridViewScroll = /** @class */ (function ()
 {

    function GridViewScroll(options) {
        this._initialized = false;
        if (options.elementID == null)
            options.elementID = "";
        if (options.width == null)
            options.width = "700";
        if (options.height == null)
            options.height = "350";
        if (options.freezeColumnCssClass == null)
            options.freezeColumnCssClass = "";
        if (options.freezeFooterCssClass == null)
            options.freezeFooterCssClass = "";
        if (options.freezeHeaderRowCount == null)
            options.freezeHeaderRowCount = 1;
        if (options.freezeColumnCount == null)
            options.freezeColumnCount = 1;
        this.initializeOptions(options);
    }
    GridViewScroll.prototype.initializeOptions = function (options) {
        this.GridID = options.elementID;
        this.GridWidth = options.width;
        this.GridHeight = options.height;
        this.FreezeColumn = options.freezeColumn;
        this.FreezeFooter = options.freezeFooter;
        this.FreezeColumnCssClass = options.freezeColumnCssClass;
        this.FreezeFooterCssClass = options.freezeFooterCssClass;
        this.FreezeHeaderRowCount = options.freezeHeaderRowCount;
        this.FreezeColumnCount = options.freezeColumnCount;
    };

    GridViewScroll.prototype.enhance = function () 
{

        this.FreezeCellWidths = [];
        this.IsVerticalScrollbarEnabled = false;
        this.IsHorizontalScrollbarEnabled = false;
        if (this.GridID == null || this.GridID == "")
 {

            return;
        }

        this.ContentGrid = document.getElementById(this.GridID);
        if (this.ContentGrid == null) {

            return;
        }
        if (this.ContentGrid.rows.length < 2) {


            return;
        }
        if (this._initialized) {

            this.undo();
        }

        this._initialized = true;
        this.Parent = this.ContentGrid.parentNode;
        this.ContentGrid.style.display = "none";
        if (typeof this.GridWidth == 'string' && this.GridWidth.indexOf("%") > -1) {
            var percentage = parseInt(this.GridWidth);
            this.Width = this.Parent.offsetWidth * percentage / 100;
        }
        else {

            this.Width = parseInt(this.GridWidth);
        }
        if (typeof this.GridHeight == 'string' && this.GridHeight.indexOf("%") > -1) {


            var percentage = parseInt(this.GridHeight);
            this.Height = this.Parent.offsetHeight * percentage / 100;
        }
        else {

            this.Height = parseInt(this.GridHeight);
        }

        this.ContentGrid.style.display = "";
        this.ContentGridHeaderRows = this.getGridHeaderRows();
        this.ContentGridItemRow = this.ContentGrid.rows.item(this.FreezeHeaderRowCount);
        var footerIndex = this.ContentGrid.rows.length - 1;
        this.ContentGridFooterRow = this.ContentGrid.rows.item(footerIndex);
        this.Content = document.createElement('div');
        this.Content.id = this.GridID + "_Content";
        this.Content.style.position = "relative";
        this.Content = this.Parent.insertBefore(this.Content, this.ContentGrid);
        this.ContentFixed = document.createElement('div');
        this.ContentFixed.id = this.GridID + "_Content_Fixed";
        this.ContentFixed.style.overflow = "auto";
        this.ContentFixed = this.Content.appendChild(this.ContentFixed);
        this.ContentGrid = this.ContentFixed.appendChild(this.ContentGrid);
        this.ContentFixed.style.width = String(this.Width) + "px";
        if (this.ContentGrid.offsetWidth > this.Width) {

            this.IsHorizontalScrollbarEnabled = true;
        }

        if (this.ContentGrid.offsetHeight > this.Height) {

            this.IsVerticalScrollbarEnabled = true;
        }

        this.Header = document.createElement('div');
        this.Header.id = this.GridID + "_Header";
        this.Header.style.backgroundColor = "#F0F0F0";
        this.Header.style.position = "relative";
        this.HeaderFixed = document.createElement('div');
        this.HeaderFixed.id = this.GridID + "_Header_Fixed";
        this.HeaderFixed.style.overflow = "hidden";
        this.Header = this.Parent.insertBefore(this.Header, this.Content);
        this.HeaderFixed = this.Header.appendChild(this.HeaderFixed);
        this.ScrollbarWidth = this.getScrollbarWidth();
        this.prepareHeader();
        this.calculateHeader();
        this.Header.style.width = String(this.Width) + "px";
        if (this.IsVerticalScrollbarEnabled) {

            this.HeaderFixed.style.width = String(this.Width - this.ScrollbarWidth) + "px";
            if (this.IsHorizontalScrollbarEnabled) {

                this.ContentFixed.style.width = this.HeaderFixed.style.width;
                if (this.isRTL()) {

                    this.ContentFixed.style.paddingLeft = String(this.ScrollbarWidth) + "px";
                }

                else {

                    this.ContentFixed.style.paddingRight = String(this.ScrollbarWidth) + "px";
                }

            }

            this.ContentFixed.style.height = String(this.Height - this.Header.offsetHeight) + "px";
        }

        else {

            this.HeaderFixed.style.width = this.Header.style.width;
            this.ContentFixed.style.width = this.Header.style.width;
        }

        if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {

            this.appendFreezeHeader();
            this.appendFreezeContent();
        }
        if (this.FreezeFooter && this.IsVerticalScrollbarEnabled) {

            this.appendFreezeFooter();
            if (this.FreezeColumn && this.IsHorizontalScrollbarEnabled) {


                this.appendFreezeFooterColumn();
            }
        }
        var self = this;
        this.ContentFixed.onscroll = function (event) {

            self.HeaderFixed.scrollLeft = self.ContentFixed.scrollLeft;
            if (self.ContentFreeze != null)
                self.ContentFreeze.scrollTop = self.ContentFixed.scrollTop;
            if (self.FooterFreeze != null)
                self.FooterFreeze.scrollLeft = self.ContentFixed.scrollLeft;
        };
    };
    GridViewScroll.prototype.getGridHeaderRows = function () {



        var gridHeaderRows = new Array();
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {

            gridHeaderRows.push(this.ContentGrid.rows.item(i));

        }
        return gridHeaderRows;
    };
    GridViewScroll.prototype.prepareHeader = function () {

        this.HeaderGrid = this.ContentGrid.cloneNode(false);
        this.HeaderGrid.id = this.GridID + "_Header_Fixed_Grid";
        this.HeaderGrid = this.HeaderFixed.appendChild(this.HeaderGrid);
        this.prepareHeaderGridRows();
        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            this.appendHelperElement(this.ContentGridItemRow.cells.item(i));
            this.appendHelperElement(this.HeaderGridHeaderCells[i]);
        }
    };
    GridViewScroll.prototype.prepareHeaderGridRows = function () {

        this.HeaderGridHeaderRows = new Array();
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {
            var gridHeaderRow = this.ContentGridHeaderRows[i];
            var headerGridHeaderRow = gridHeaderRow.cloneNode(true);
            this.HeaderGridHeaderRows.push(headerGridHeaderRow);
            this.HeaderGrid.appendChild(headerGridHeaderRow);
        }

        this.prepareHeaderGridCells();
    };
    GridViewScroll.prototype.prepareHeaderGridCells = function () {

        this.HeaderGridHeaderCells = new Array();
        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            for (var rowIndex in this.HeaderGridHeaderRows) {


                var cgridHeaderRow = this.HeaderGridHeaderRows[rowIndex];
                var fixedCellIndex = 0;
                for (var cellIndex = 0; cellIndex < cgridHeaderRow.cells.length; cellIndex++) {
                    var cgridHeaderCell = cgridHeaderRow.cells.item(cellIndex);
                    if (cgridHeaderCell.colSpan == 1 && i == fixedCellIndex) {

                        this.HeaderGridHeaderCells.push(cgridHeaderCell);
                    }
                    else {
                        fixedCellIndex += cgridHeaderCell.colSpan - 1;
                    }
                    fixedCellIndex++;
                }
            }
        }
    };
    GridViewScroll.prototype.calculateHeader = function () {

        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            var gridItemCell = this.ContentGridItemRow.cells.item(i);
            var helperElement = gridItemCell.firstChild;
            var helperWidth = parseInt(String(helperElement.offsetWidth));
            this.FreezeCellWidths.push(helperWidth);
            helperElement.style.width = helperWidth + "px";
            helperElement = this.HeaderGridHeaderCells[i].firstChild;
            helperElement.style.width = helperWidth + "px";
        }
        for (var i = 0; i < this.FreezeHeaderRowCount; i++) {

            this.ContentGridHeaderRows[i].style.display = "none";
        }
    };
    GridViewScroll.prototype.appendFreezeHeader = function () {

        this.HeaderFreeze = document.createElement('div');
        this.HeaderFreeze.id = this.GridID + "_Header_Freeze";
        this.HeaderFreeze.style.position = "absolute";
        this.HeaderFreeze.style.overflow = "hidden";
        this.HeaderFreeze.style.top = "0px";
        this.HeaderFreeze.style.left = "0px";
        this.HeaderFreeze.style.width = "";
        this.HeaderFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.HeaderFreezeGrid.id = this.GridID + "_Header_Freeze_Grid";
        this.HeaderFreezeGrid = this.HeaderFreeze.appendChild(this.HeaderFreezeGrid);
        this.HeaderFreezeGridHeaderRows = new Array();
        for (var i = 0; i < this.HeaderGridHeaderRows.length; i++) {

            var headerFreezeGridHeaderRow = this.HeaderGridHeaderRows[i].cloneNode(false);
            this.HeaderFreezeGridHeaderRows.push(headerFreezeGridHeaderRow);
            var columnIndex = 0;
            var columnCount = 0;
            while (columnCount < this.FreezeColumnCount) {

                var freezeColumn = this.HeaderGridHeaderRows[i].cells.item(columnIndex).cloneNode(true);
                headerFreezeGridHeaderRow.appendChild(freezeColumn);
                columnCount += freezeColumn.colSpan;
                columnIndex++;
            }
            this.HeaderFreezeGrid.appendChild(headerFreezeGridHeaderRow);
        }
        this.HeaderFreeze = this.Header.appendChild(this.HeaderFreeze);
    };
    GridViewScroll.prototype.appendFreezeContent = function () {

        this.ContentFreeze = document.createElement('div');
        this.ContentFreeze.id = this.GridID + "_Content_Freeze";
        this.ContentFreeze.style.position = "absolute";
        this.ContentFreeze.style.overflow = "hidden";
        this.ContentFreeze.style.top = "0px";
        this.ContentFreeze.style.left = "0px";
        this.ContentFreeze.style.width = "";
        this.ContentFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.ContentFreezeGrid.id = this.GridID + "_Content_Freeze_Grid";
        this.ContentFreezeGrid = this.ContentFreeze.appendChild(this.ContentFreezeGrid);
        var freezeCellHeights = [];
        var paddingTop = this.getPaddingTop(this.ContentGridItemRow.cells.item(0));
        var paddingBottom = this.getPaddingBottom(this.ContentGridItemRow.cells.item(0));
        for (var i = 0; i < this.ContentGrid.rows.length; i++) {

            var gridItemRow = this.ContentGrid.rows.item(i);
            var gridItemCell = gridItemRow.cells.item(0);
            var helperElement = void 0;
            if (gridItemCell.firstChild.className == "gridViewScrollHelper") {

                helperElement = gridItemCell.firstChild;
            }
            else {
                helperElement = this.appendHelperElement(gridItemCell);
            }
            var helperHeight = parseInt(String(gridItemCell.offsetHeight - paddingTop - paddingBottom));
            freezeCellHeights.push(helperHeight);
            var cgridItemRow = gridItemRow.cloneNode(false);
            var cgridItemCell = gridItemCell.cloneNode(true);
            if (this.FreezeColumnCssClass != null || this.FreezeColumnCssClass != "")
                cgridItemRow.className = this.FreezeColumnCssClass;
            var columnIndex = 0;
            var columnCount = 0;
            while (columnCount < this.FreezeColumnCount) {

                var freezeColumn = gridItemRow.cells.item(columnIndex).cloneNode(true);
                cgridItemRow.appendChild(freezeColumn);
                columnCount += freezeColumn.colSpan;
                columnIndex++;
            }
            this.ContentFreezeGrid.appendChild(cgridItemRow);
        }
        for (var i = 0; i < this.ContentGrid.rows.length; i++) {

            var gridItemRow = this.ContentGrid.rows.item(i);
            var gridItemCell = gridItemRow.cells.item(0);
            var cgridItemRow = this.ContentFreezeGrid.rows.item(i);
            var cgridItemCell = cgridItemRow.cells.item(0);
            var helperElement = gridItemCell.firstChild;
            helperElement.style.height = String(freezeCellHeights[i]) + "px";
            helperElement = cgridItemCell.firstChild;
            helperElement.style.height = String(freezeCellHeights[i]) + "px";
        }
        if (this.IsVerticalScrollbarEnabled) {
            this.ContentFreeze.style.height = String(this.Height - this.Header.offsetHeight - this.ScrollbarWidth) + "px";
        }
        else {
            this.ContentFreeze.style.height = String(this.ContentFixed.offsetHeight - this.ScrollbarWidth) + "px";
        }
        this.ContentFreeze = this.Content.appendChild(this.ContentFreeze);
    };
    GridViewScroll.prototype.appendFreezeFooter = function () {

        this.FooterFreeze = document.createElement('div');
        this.FooterFreeze.id = this.GridID + "_Footer_Freeze";
        this.FooterFreeze.style.position = "absolute";
        this.FooterFreeze.style.overflow = "hidden";
        this.FooterFreeze.style.left = "0px";
        this.FooterFreeze.style.width = String(this.ContentFixed.offsetWidth - this.ScrollbarWidth) + "px";
        this.FooterFreezeGrid = this.HeaderGrid.cloneNode(false);
        this.FooterFreezeGrid.id = this.GridID + "_Footer_Freeze_Grid";
        this.FooterFreezeGrid = this.FooterFreeze.appendChild(this.FooterFreezeGrid);
        this.FooterFreezeGridHeaderRow = this.ContentGridFooterRow.cloneNode(true);
        if (this.FreezeFooterCssClass != null || this.FreezeFooterCssClass != "")
            this.FooterFreezeGridHeaderRow.className = this.FreezeFooterCssClass;
        for (var i = 0; i < this.FooterFreezeGridHeaderRow.cells.length; i++) {

            var cgridHeaderCell = this.FooterFreezeGridHeaderRow.cells.item(i);
            var helperElement = this.appendHelperElement(cgridHeaderCell);
            helperElement.style.width = String(this.FreezeCellWidths[i]) + "px";
        }
        this.FooterFreezeGridHeaderRow = this.FooterFreezeGrid.appendChild(this.FooterFreezeGridHeaderRow);
        this.FooterFreeze = this.Content.appendChild(this.FooterFreeze);
        var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
        if (this.IsHorizontalScrollbarEnabled) {

            footerFreezeTop -= this.ScrollbarWidth;
        }
        this.FooterFreeze.style.top = String(footerFreezeTop) + "px";
    };
    GridViewScroll.prototype.appendFreezeFooterColumn = function () {

        this.FooterFreezeColumn = document.createElement('div');
        this.FooterFreezeColumn.id = this.GridID + "_Footer_FreezeColumn";
        this.FooterFreezeColumn.style.position = "absolute";
        this.FooterFreezeColumn.style.overflow = "hidden";
        this.FooterFreezeColumn.style.left = "0px";
        this.FooterFreezeColumn.style.width = "";
        this.FooterFreezeColumnGrid = this.HeaderGrid.cloneNode(false);
        this.FooterFreezeColumnGrid.id = this.GridID + "_Footer_FreezeColumn_Grid";
        this.FooterFreezeColumnGrid = this.FooterFreezeColumn.appendChild(this.FooterFreezeColumnGrid);
        this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeGridHeaderRow.cloneNode(false);
        this.FooterFreezeColumnGridHeaderRow = this.FooterFreezeColumnGrid.appendChild(this.FooterFreezeColumnGridHeaderRow);
        if (this.FreezeFooterCssClass != null)
            this.FooterFreezeColumnGridHeaderRow.className = this.FreezeFooterCssClass;
        var columnIndex = 0;
        var columnCount = 0;
        while (columnCount < this.FreezeColumnCount) {

            var freezeColumn = this.FooterFreezeGridHeaderRow.cells.item(columnIndex).cloneNode(true);
            this.FooterFreezeColumnGridHeaderRow.appendChild(freezeColumn);
            columnCount += freezeColumn.colSpan;
            columnIndex++;
        }
        var footerFreezeTop = this.ContentFixed.offsetHeight - this.FooterFreeze.offsetHeight;
        if (this.IsHorizontalScrollbarEnabled) {

            footerFreezeTop -= this.ScrollbarWidth;
        }
        this.FooterFreezeColumn.style.top = String(footerFreezeTop) + "px";
        this.FooterFreezeColumn = this.Content.appendChild(this.FooterFreezeColumn);
    };
    GridViewScroll.prototype.appendHelperElement = function (gridItemCell) {

        var helperElement = document.createElement('div');
        helperElement.className = "gridViewScrollHelper";
        while (gridItemCell.hasChildNodes()) {

            helperElement.appendChild(gridItemCell.firstChild);
        }
        return gridItemCell.appendChild(helperElement);
    };
    GridViewScroll.prototype.getScrollbarWidth = function () {

        var innerElement = document.createElement('p');
        innerElement.style.width = "100%";
        innerElement.style.height = "200px";
        var outerElement = document.createElement('div');
        outerElement.style.position = "absolute";
        outerElement.style.top = "0px";
        outerElement.style.left = "0px";
        outerElement.style.visibility = "hidden";
        outerElement.style.width = "200px";
        outerElement.style.height = "150px";
        outerElement.style.overflow = "hidden";
        outerElement.appendChild(innerElement);
        document.body.appendChild(outerElement);
        var innerElementWidth = innerElement.offsetWidth;
        outerElement.style.overflow = 'scroll';
        var outerElementWidth = innerElement.offsetWidth;
        if (innerElementWidth === outerElementWidth)
            outerElementWidth = outerElement.clientWidth;
        document.body.removeChild(outerElement);
        return innerElementWidth - outerElementWidth;
    };
    GridViewScroll.prototype.isRTL = function () {

        var direction = "";
        if (window.getComputedStyle) {

            direction = window.getComputedStyle(this.ContentGrid, null).getPropertyValue('direction');
        }
        else {
            direction = this.ContentGrid.currentStyle.direction;
        }
        return direction === "rtl";
    };
    GridViewScroll.prototype.getPaddingTop = function (element) {

        var value = "";
        if (window.getComputedStyle) {

            value = window.getComputedStyle(element, null).getPropertyValue('padding-Top');
        }
        else {

            value = element.currentStyle.paddingTop;
        }
        return parseInt(value);
    };
    GridViewScroll.prototype.getPaddingBottom = function (element) {
        var value = "";

        if (window.getComputedStyle) {

            value = window.getComputedStyle(element, null).getPropertyValue('padding-Bottom');
        }
        else {

            value = element.currentStyle.paddingBottom;
        }
        return parseInt(value);
    };
    GridViewScroll.prototype.undo = function () {

        this.undoHelperElement();
        for (var _i = 0, _a = this.ContentGridHeaderRows; _i < _a.length; _i++) {
            var contentGridHeaderRow = _a[_i];
            contentGridHeaderRow.style.display = "";
        }
        this.Parent.insertBefore(this.ContentGrid, this.Header);
        this.Parent.removeChild(this.Header);
        this.Parent.removeChild(this.Content);
        this._initialized = false;
    };
    GridViewScroll.prototype.undoHelperElement = function () {

        for (var i = 0; i < this.ContentGridItemRow.cells.length; i++) {

            var gridItemCell = this.ContentGridItemRow.cells.item(i);
            var helperElement = gridItemCell.firstChild;
            while (helperElement.hasChildNodes()) {

                gridItemCell.appendChild(helperElement.firstChild);
            }
            gridItemCell.removeChild(helperElement);
        }
        if (this.FreezeColumn) {

            for (var i = 2; i < this.ContentGrid.rows.length; i++) {

                var gridItemRow = this.ContentGrid.rows.item(i);
                var gridItemCell = gridItemRow.cells.item(0);
                var helperElement = gridItemCell.firstChild;
                while (helperElement.hasChildNodes()) {


                    gridItemCell.appendChild(helperElement.firstChild);
                }
                gridItemCell.removeChild(helperElement);
            }
        }
    };
    return GridViewScroll;
}());

//add On Head

<head runat="server">
    <title></title>

    <script src="client/js/jquery-3.1.1.min.js"></script>

    <script src="js/gridviewscroll.js"></script>

    <script type="text/javascript">
        window.onload = function () {

            var gridViewScroll = new GridViewScroll({
                elementID: "GridView1" // [Header is fix column will be Freeze ][1]Target Control
            });
            gridViewScroll.enhance();
        }
    </script>

</head>

//Add on Body

<body>
    <form id="form1" runat="server">

        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="true">

       // <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">

           <%-- <Columns>
                <asp:BoundField DataField="SHIPMENT_ID" HeaderText="SHIPMENT_ID"
                    ReadOnly="True" SortExpression="SHIPMENT_ID" />
                <asp:BoundField DataField="TypeValue" HeaderText="TypeValue"
                    SortExpression="TypeValue" />
                <asp:BoundField DataField="CHAId" HeaderText="CHAId"
                    SortExpression="CHAId" />
                <asp:BoundField DataField="Status" HeaderText="Status"
                    SortExpression="Status" />
            </Columns>--%>
        </asp:GridView>

How to parse dates in multiple formats using SimpleDateFormat

I was having multiple date formats into json, and was extracting csv with universal format. I looked multiple places, tried different ways, but at the end I'm able to convert with the following simple code.

private String getDate(String anyDateFormattedString) {
    @SuppressWarnings("deprecation")
    Date date = new Date(anyDateFormattedString);
    SimpleDateFormat dateFormat = new SimpleDateFormat(yourDesiredDateFormat);
        String convertedDate = dateFormat.format(date);
    return convertedDate;
}

Can't find/install libXtst.so.6?

Had that issue on Ubuntu 14.04, In my case I had also libXtst.so missing:

Could not open library 'libXtst.so': libXtst.so: cannot open shared object 
file: No such file or directory

Make sure your symbolic link is pointing to proper file, cd /usr/lib/x86_64-linux-gnu and list libXtst with:

 ll |grep libXtst                                                                                                                                                           
 lrwxrwxrwx   1 root root        16 Oct  7  2016 libXtst.so.6 -> libXtst.so.6.1.0
 -rw-r--r--   1 root root     22880 Aug 16  2013 libXtst.so.6.1.0

Then just create proper symbolic link using:

sudo ln -s libXtst.so.6 libXtst.so

List again:

ll | grep libXtst
lrwxrwxrwx   1 root root        12 Sep 20 10:23 libXtst -> libXtst.so.6
lrwxrwxrwx   1 root root        12 Sep 20 10:23 libXtst.so -> libXtst.so.6
lrwxrwxrwx   1 root root        16 Oct  7  2016 libXtst.so.6 -> libXtst.so.6.1.0
-rw-r--r--   1 root root     22880 Aug 16  2013 libXtst.so.6.1.0

all set!

How can I make a multipart/form-data POST request using Java?

Use this code to upload images or any other files to the server using post in multipart.

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class SimplePostRequestTest {

    public static void main(String[] args) throws UnsupportedEncodingException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.0.102/uploadtest/upload_photo");

        try {
            FileBody bin = new FileBody(new File("/home/ubuntu/cd.png"));
            StringBody id = new StringBody("3");
            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("upload_image", bin);
            reqEntity.addPart("id", id);
            reqEntity.addPart("image_title", new StringBody("CoolPic"));

            httppost.setEntity(reqEntity);
            System.out.println("Requesting : " + httppost.getRequestLine());
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost, responseHandler);
            System.out.println("responseBody : " + responseBody);

        } catch (ClientProtocolException e) {

        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

}

it requires below files to upload.

libraries are httpclient-4.1.2.jar, httpcore-4.1.2.jar, httpmime-4.1.2.jar, httpclient-cache-4.1.2.jar, commons-codec.jar and commons-logging-1.1.1.jar to be in classpath.

How to install and use "make" in Windows?

The accepted answer is a bad idea in general because the manually created make.exe will stick around and can potentially cause unexpected problems. It actually breaks RubyInstaller: https://github.com/oneclick/rubyinstaller2/issues/105

An alternative is installing make via Chocolatey (as pointed out by @Vasantha Ganesh K)

Another alternative is installing MSYS2 from Chocolatey and using make from C:\tools\msys64\usr\bin. If make isn't installed automatically with MSYS2 you need to install it manually via pacman -S make (as pointed out by @Thad Guidry and @Luke).

java.lang.ClassNotFoundException:com.mysql.jdbc.Driver

You can download the latest mysql driver jar from below path, and copy to your classpath or if you are using web server then copy to tomcat/lib or war/web-inf/lib folder.

http://dev.mysql.com/downloads/connector/j/ or

http://mirrors.ibiblio.org/pub/mirrors/maven2/mysql/mysql-connector-java/5.1.10/mysql-connector-java-5.1.10.jar

'dependencies.dependency.version' is missing error, but version is managed in parent

What just worked for was to delete the settings.xml in the .m2 folder: this file was telling the project to look for a versión of spring mvc and web that didn't exist.

using OR and NOT in solr query

Instead of "NOT [condition]" use "(*:* NOT [condition])"

Finding local maxima/minima with Numpy in a 1D numpy array

Another one:


def local_maxima_mask(vec):
    """
    Get a mask of all points in vec which are local maxima
    :param vec: A real-valued vector
    :return: A boolean mask of the same size where True elements correspond to maxima. 
    """
    mask = np.zeros(vec.shape, dtype=np.bool)
    greater_than_the_last = np.diff(vec)>0  # N-1
    mask[1:] = greater_than_the_last
    mask[:-1] &= ~greater_than_the_last
    return mask

Sending a JSON HTTP POST request from Android

Posting parameters Using POST:-

URL url;
URLConnection urlConn;
DataOutputStream printout;
DataInputStream  input;
url = new URL (getCodeBase().toString() + "env.tcgi");
urlConn = url.openConnection();
urlConn.setDoInput (true);
urlConn.setDoOutput (true);
urlConn.setUseCaches (false);
urlConn.setRequestProperty("Content-Type","application/json");   
urlConn.setRequestProperty("Host", "android.schoolportal.gr");
urlConn.connect();  
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
jsonParam.put("ID", "25");
jsonParam.put("description", "Real");
jsonParam.put("enable", "true");

The part which you missed is in the the following... i.e., as follows..

// Send POST output.
printout = new DataOutputStream(urlConn.getOutputStream ());
printout.writeBytes(URLEncoder.encode(jsonParam.toString(),"UTF-8"));
printout.flush ();
printout.close ();

The rest of the thing you can do it.

jQuery selector for inputs with square brackets in the name attribute

Per the jQuery documentation, try this:

$('input[inputName\\[\\]=someValue]')

[EDIT] However, I'm not sure that's the right syntax for your selector. You probably want:

$('input[name="inputName[]"][value="someValue"]')

Adjusting HttpWebRequest Connection Timeout in C#

From the documentation of the HttpWebRequest.Timeout property:

A Domain Name System (DNS) query may take up to 15 seconds to return or time out. If your request contains a host name that requires resolution and you set Timeout to a value less than 15 seconds, it may take 15 seconds or more before a WebException is thrown to indicate a timeout on your request.

Is it possible that your DNS query is the cause of the timeout?

How to output MySQL query results in CSV format?

If there is PHP installed on the machine you are using, you can write a PHP script to do that. It requires the PHP installation has the MySQL extension installed.

You can call the PHP interpreter from the command line like so:

php --php-ini path/to/php.ini your-script.php

I am including the --php-ini switch, because you may need to use your own PHP configuration that enables the MySQL extension. On PHP 5.3.0+ that extension is enabled by default, so that is no longer necessary to use the configuration to enable it.

Then you can write your export script like any normal PHP script:

<?php
    #mysql_connect("localhost", "username", "password") or die(mysql_error());
    mysql_select_db("mydb") or die(mysql_error());

    $result = mysql_query("SELECT * FROM table_with_the_data p WHERE p.type = $typeiwant");

    $result || die(mysql_error());

    while($row = mysql_fetch_row($result)) {
      $comma = false;
      foreach ($row as $item) {

        # Make it comma separated
        if ($comma) {
          echo ',';
        } else {
          $comma = true;
        }

        # Quote the quotes
        $quoted = str_replace("\"", "\"\"", $item);

        # Quote the string
        echo "\"$quoted\"";
      }
        echo "\n";
    }
?>

The advantage of this method is, that it has no problems with varchar and text fields, that have text containing newlines. Those fields are correctly quoted and those newlines in them will be interpreted by the CSV reader as a part of the text, not record separators. That is something that is hard to correct afterwards with sed or so.

Java string replace and the NUL (NULL, ASCII 0) character?

Should be probably changed to

firstName = firstName.trim().replaceAll("\\.", "");

Simulator or Emulator? What is the difference?

The distintion between the two terms is a bit fuzzy. Coming from a world where "Emulators" are pieces of hardware that allow you debug embedded systems. And remember products that allowed you to have ICE (In Circuit Emulation) capabilities to debug a PC platform, I find the use of the term "Emulation" to be a somewhat of a misnomer for software that SIMULATES the behaviour of a piece of hardware.

My justification for the current use of the term is Emulation is that it may "augment" the functionality, and only is concerned with a "reasonable" approximation of the behaviour of the system.

ICE: (In Circuit Emulation) A piece of hardware that is plugged into a board in place of the actual processor. It allows you to run the system as if the actual processor was present. Typically these have a variant of the processor on them to actually execute the software with glue logic to allow the user to break executation and single step under hardware control. Some would also provide logging capability. Most modern processors development systems have replace ICE type emulation with JTAG Emulation, where the JTAG just talks to the processor via a special purpose serial link and all execution is perform by the processor mounted on the board.

Software EMULATOR: An 0x86 emulator is only concerned with being able to execute 0x86 assembly language, not providing accurate cycle per cycle behaviourial model of a SPECIFIC 0x86 processor. Bochs is an example of this. QEMU does this, but also allows "virtualization" using special kernel modules.

SIMULATOR: Texas Instruments provides a CYCLE ACCURATE behaviourial model of there processors for software development that is intended to be a accurate SIMULATION of SPECIFIC processor cores behavior for the developers to use prior to having working hardware.

Software EMULATOR augmenting functionality: BLEEM not only allowed you to run Playstation Software, but also allowed the display to be output with higher resolution than the Playstation was able to provide, and also took advantage of more advanced capabilities of GPUs that were avaliable. (i.e. Better blending and smoothing of textures.)

C# DateTime to "YYYYMMDDHHMMSS" format

This site has great examples check it out

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

String.Format("{0:y yy yyy yyyy}",      dt);  // "8 08 008 2008"   year
String.Format("{0:M MM MMM MMMM}",      dt);  // "3 03 Mar March"  month
String.Format("{0:d dd ddd dddd}",      dt);  // "9 09 Sun Sunday" day
String.Format("{0:h hh H HH}",          dt);  // "4 04 16 16"      hour 12/24
String.Format("{0:m mm}",               dt);  // "5 05"            minute
String.Format("{0:s ss}",               dt);  // "7 07"            second
String.Format("{0:f ff fff ffff}",      dt);  // "1 12 123 1230"   sec.fraction
String.Format("{0:F FF FFF FFFF}",      dt);  // "1 12 123 123"    without zeroes
String.Format("{0:t tt}",               dt);  // "P PM"            A.M. or P.M.
String.Format("{0:z zz zzz}",           dt);  // "-6 -06 -06:00"   time zone

// month/day numbers without/with leading zeroes
String.Format("{0:M/d/yyyy}",           dt);  // "3/9/2008"
String.Format("{0:MM/dd/yyyy}",         dt);  // "03/09/2008"

// day/month names
String.Format("{0:ddd, MMM d, yyyy}",   dt);  // "Sun, Mar 9, 2008"
String.Format("{0:dddd, MMMM d, yyyy}", dt);  // "Sunday, March 9, 2008"

// two/four digit year
String.Format("{0:MM/dd/yy}",           dt);  // "03/09/08"
String.Format("{0:MM/dd/yyyy}",         dt);  // "03/09/2008"

Standard DateTime Formatting

String.Format("{0:t}", dt);  // "4:05 PM"                           ShortTime
String.Format("{0:d}", dt);  // "3/9/2008"                          ShortDate
String.Format("{0:T}", dt);  // "4:05:07 PM"                        LongTime
String.Format("{0:D}", dt);  // "Sunday, March 09, 2008"            LongDate
String.Format("{0:f}", dt);  // "Sunday, March 09, 2008 4:05 PM"    LongDate+ShortTime
String.Format("{0:F}", dt);  // "Sunday, March 09, 2008 4:05:07 PM" FullDateTime
String.Format("{0:g}", dt);  // "3/9/2008 4:05 PM"                  ShortDate+ShortTime
String.Format("{0:G}", dt);  // "3/9/2008 4:05:07 PM"               ShortDate+LongTime
String.Format("{0:m}", dt);  // "March 09"                          MonthDay
String.Format("{0:y}", dt);  // "March, 2008"                       YearMonth
String.Format("{0:r}", dt);  // "Sun, 09 Mar 2008 16:05:07 GMT"     RFC1123
String.Format("{0:s}", dt);  // "2008-03-09T16:05:07"               SortableDateTime
String.Format("{0:u}", dt);  // "2008-03-09 16:05:07Z"              UniversalSortableDateTime

/*
Specifier   DateTimeFormatInfo property     Pattern value (for en-US culture)
    t           ShortTimePattern                    h:mm tt
    d           ShortDatePattern                    M/d/yyyy
    T           LongTimePattern                     h:mm:ss tt
    D           LongDatePattern                     dddd, MMMM dd, yyyy
    f           (combination of D and t)            dddd, MMMM dd, yyyy h:mm tt
    F           FullDateTimePattern                 dddd, MMMM dd, yyyy h:mm:ss tt
    g           (combination of d and t)            M/d/yyyy h:mm tt
    G           (combination of d and T)            M/d/yyyy h:mm:ss tt
    m, M        MonthDayPattern                     MMMM dd
    y, Y        YearMonthPattern                    MMMM, yyyy
    r, R        RFC1123Pattern                      ddd, dd MMM yyyy HH':'mm':'ss 'GMT' (*)
    s           SortableDateTi­mePattern             yyyy'-'MM'-'dd'T'HH':'mm':'ss (*)
    u           UniversalSorta­bleDateTimePat­tern    yyyy'-'MM'-'dd HH':'mm':'ss'Z' (*)
                                                    (*) = culture independent   
*/

Update using c# 6 string interpolation format

// create date time 2008-03-09 16:05:07.123
DateTime dt = new DateTime(2008, 3, 9, 16, 5, 7, 123);

$"{dt:y yy yyy yyyy}";  // "8 08 008 2008"   year
$"{dt:M MM MMM MMMM}";  // "3 03 Mar March"  month
$"{dt:d dd ddd dddd}";  // "9 09 Sun Sunday" day
$"{dt:h hh H HH}";      // "4 04 16 16"      hour 12/24
$"{dt:m mm}";           // "5 05"            minute
$"{dt:s ss}";           // "7 07"            second
$"{dt:f ff fff ffff}";  // "1 12 123 1230"   sec.fraction
$"{dt:F FF FFF FFFF}";  // "1 12 123 123"    without zeroes
$"{dt:t tt}";           // "P PM"            A.M. or P.M.
$"{dt:z zz zzz}";       // "-6 -06 -06:00"   time zone

// month/day numbers without/with leading zeroes
$"{dt:M/d/yyyy}";    // "3/9/2008"
$"{dt:MM/dd/yyyy}";  // "03/09/2008"

// day/month names
$"{dt:ddd, MMM d, yyyy}";    // "Sun, Mar 9, 2008"
$"{dt:dddd, MMMM d, yyyy}";  // "Sunday, March 9, 2008"

// two/four digit year
$"{dt:MM/dd/yy}";    // "03/09/08"
$"{dt:MM/dd/yyyy}";  // "03/09/2008"

BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

This works well for specific articles where the text is all wrapped in <p> tags. Since the web is an ugly place, it's not always the case.

Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span> or a <div>, or an <li>).

To find all text nodes in the DOM, you can use soup.find_all(text=True).

This is going to return some undesired text, like the contents of <script> and <style> tags. You'll need to filter out the text contents of elements you don't want.

blacklist = [
  'style',
  'script',
  # other elements,
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]

If you are working with a known set of tags, you can tag the opposite approach:

whitelist = [
  'p'
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]

What does DIM stand for in Visual Basic and BASIC?

The Dim keyword is optional, when we are using it with modifiers- Public, Protected, Friend, Protected Friend,Private,Shared,Shadows,Static,ReadOnly etc. e.g. - Static nTotal As Integer

For reference type, we have to use new keyword to create the new instance of the class or structure. e.g. Dim lblTop As New System.Windows.Forms.Label.

Dim statement can be used with out a datatype when you set Option Infer to On. In that case the compiler infers the data type of a variable from the type of its initialization expression. Example :

Option Infer On

Module SampleMod

Sub Main()

 Dim nExpVar = 5

The above statement is equivalent to- Dim nExpVar As Integer

How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?

If you want to write a script to automate creation of jobs using the Jenkins API, you can use one of the API clients to do that. A ruby client for Jenkins is available at https://github.com/arangamani/jenkins_api_client

gem install jenkins_api_client

require "rubygems"
require "jenkins_api_client"

# Initialize the client by passing in the server information
# and credentials to communicate with the server
client = JenkinsApi::Client.new(
  :server_ip => "127.0.0.1",
  :username => "awesomeuser",
  :password => "awesomepassword"
)

# The following block will create 10 jobs in Jenkins
# test_job_0, test_job_1, test_job_2, ...
10.times do |num|
  client.job.create_freestyle(:name => "test_job_#{num}")
end

# The jobs in Jenkins can be listed using
client.job.list_all

The API client can be used to perform a lot of operations.

How can I convert a series of images to a PDF from the command line on linux?

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

How do I check if a string contains a specific word?

if (preg_match('/(are)/', $a)) {
   echo 'true';
}

Correctly ignore all files recursively under a specific folder except for a specific file type

Either I'm doing it wrongly, or the accepted answer does not work anymore with the current git.

I have actually found the proper solution and posted it under almost the same question here. For more details head there.

Solution:

# Ignore everything inside Resources/ directory
/Resources/**
# Except for subdirectories(won't be committed anyway if there is no committed file inside)
!/Resources/**/
# And except for *.foo files
!*.foo

Add JVM options in Tomcat

Set it in the JAVA_OPTS variable in [path to tomcat]/bin/catalina.sh. Under windows there is a console where you can set it up or you use the catalina.bat.

JAVA_OPTS=-agentpath:C:\calltracer\jvmti\calltracer5.dll=traceFile-C:\calltracer\call.trace,filterFile-C:\calltracer\filters.txt,outputType-xml,usage-uncontrolled -Djava.library.path=C:\calltracer\jvmti -Dcalltracerlib=calltracer5

Access to ES6 array element index inside for-of loop

Also you can use JavaScript to solve your problem

_x000D_
_x000D_
iterate(item, index) {
    console.log(`${item} has index ${index}`);
    //Do what you want...
}

readJsonList() {    
    jsonList.forEach(this.iterate);
    //it could be any array list.
}   
_x000D_
_x000D_
_x000D_

Loop inside React JSX

Think of it like you're just calling JavaScript functions. You can't use a for loop where the arguments to a function call would go:

return tbody(
    for (var i = 0; i < numrows; i++) {
        ObjectRow()
    } 
)

See how the function tbody is being passed a for loop as an argument – leading to a syntax error.

But you can make an array, and then pass that in as an argument:

var rows = [];
for (var i = 0; i < numrows; i++) {
    rows.push(ObjectRow());
}
return tbody(rows);

You can basically use the same structure when working with JSX:

var rows = [];
for (var i = 0; i < numrows; i++) {
    // note: we are adding a key prop here to allow react to uniquely identify each
    // element in this array. see: https://reactjs.org/docs/lists-and-keys.html
    rows.push(<ObjectRow key={i} />);
}
return <tbody>{rows}</tbody>;

Incidentally, my JavaScript example is almost exactly what that example of JSX transforms into. Play around with Babel REPL to get a feel for how JSX works.

docker run <IMAGE> <MULTIPLE COMMANDS>

You can also pipe commands inside Docker container, bash -c "<command1> | <command2>" for example:

docker run img /bin/bash -c "ls -1 | wc -l"

But, without invoking the shell in the remote the output will be redirected to the local terminal.

XAMPP on Windows - Apache not starting

my friend this the will fix ur problem ;)

in root of folder ( xampp ) just run this file ( setup_xampp.bat ) then press enter

and try to start the apache server

every things will work like charm ;)

Error "gnu/stubs-32.h: No such file or directory" while compiling Nachos source code

Try doing a sudo apt-get install libc6-dev.

apt-file tells me that the file in question belongs to that package.

How to represent e^(-t^2) in MATLAB?

If t is a matrix, you need to use the element-wise multiplication or exponentiation. Note the dot.

x = exp( -t.^2 )

or

x = exp( -t.*t )

Where to change the value of lower_case_table_names=2 on windows xampp

Do these steps:

  1. open your MySQL configuration file: [drive]\xampp\mysql\bin\my.ini
  2. look up for: # The MySQL server [mysqld]
  3. add this right below it: lower_case_table_names = 2
  4. save the file and restart MySQL service

From: http://webdev.issimplified.com/2010/03/02/mysql-on-windows-force-table-names-to-lowercase/

How should I print types like off_t and size_t?

You'll want to use the formatting macros from inttypes.h.

See this question: Cross platform format string for variables of type size_t?

How to copy a file from remote server to local machine?

The scp operation is separate from your ssh login. You will need to issue an ssh command similar to the following one assuming jdoe is account with which you log into the remote system and that the remote system is example.com:

scp [email protected]:/somedir/table /home/me/Desktop/.

The scp command issued from the system where /home/me/Desktop resides is followed by the userid for the account on the remote server. You then add a ":" followed by the directory path and file name on the remote server, e.g., /somedir/table. Then add a space and the location to which you want to copy the file. If you want the file to have the same name on the client system, you can indicate that with a period, i.e. "." at the end of the directory path; if you want a different name you could use /home/me/Desktop/newname, instead. If you were using a nonstandard port for SSH connections, you would need to specify that port with a "-P n" (capital P), where "n" is the port number. The standard port is 22 and if you aren't specifying it for the SSH connection then you won't need that.

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

You may also use element.insertAdjacentHTML('beforeend', data);

Please read the "Security considerations" on MDN.

How to set initial value and auto increment in MySQL?

Use this:

ALTER TABLE users AUTO_INCREMENT=1001;

or if you haven't already added an id column, also add it

ALTER TABLE users ADD id INT UNSIGNED NOT NULL AUTO_INCREMENT,
    ADD INDEX (id);

update package.json version automatically

As an addition to npm version you can use the --no-git-tag-version flag if you want a version bump but no tag or a new commit:

npm --no-git-tag-version version patch

https://docs.npmjs.com/cli/version

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

This is the proper way to access data in laravel :

@foreach($data-> ac as $link) 

   {{$link->url}}

@endforeach

Run automatically program on startup under linux ubuntu

sudo mv /filename /etc/init.d/
sudo chmod +x /etc/init.d/filename 
sudo update-rc.d filename defaults 

Script should now start on boot. Note that this method also works with both hard links and symbolic links (ln).

Edit

At this point in the boot process PATH isn't set yet, so it is critical that absolute paths are used throughout. BUT, as pointed out in the comments by Steve HHH, explicitly declaring the full file path (/etc/init.d/filename) for the update-rc.d command is not valid in most versions of Linux. Per the manpage for update-rc.d, the second parameter is a script located in /etc/init.d/*. Updated above code to reflect this.

Another Edit

Also as pointed out in the comments (by Charles Brandt), /filename must be an init style script. A good template was also provided - https://github.com/fhd/init-script-template.

Another link to another article just to avoid possible link rot (although it would be saddening if GitHub died) - http://www.linux.com/learn/tutorials/442412-managing-linux-daemons-with-init-scripts

yetAnother Edit

As pointed out in the comments (by Russell Yan), This works only on default mode of update-rc.d.

According to manual of update-rc.d, it can run on two modes, "the machines using the legacy mode will have a file /etc/init.d/.legacy-bootordering", in which case you have to pass sequence and runlevel configuration through command line arguments.

The equivalent argument set for the above example is

sudo update-rc.d filename start 20 2 3 4 5 . stop 20 0 1 6 .

How do you access the matched groups in a JavaScript regular expression?

JUST USE RegExp.$1...$n th group eg:

1.To match 1st group RegExp.$1

  1. To match 2nd group RegExp.$2

if you use 3 group in regex likey(note use after string.match(regex))

RegExp.$1 RegExp.$2 RegExp.$3

_x000D_
_x000D_
 var str = "The rain in ${india} stays safe"; _x000D_
  var res = str.match(/\${(.*?)\}/ig);_x000D_
  //i used only one group in above example so RegExp.$1_x000D_
console.log(RegExp.$1)
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
//easiest way is use RegExp.$1 1st group in regex and 2nd grounp like_x000D_
 //RegExp.$2 if exist use after match_x000D_
_x000D_
var regex=/\${(.*?)\}/ig;_x000D_
var str = "The rain in ${SPAIN} stays ${mainly} in the plain"; _x000D_
  var res = str.match(regex);_x000D_
for (const match of res) {_x000D_
  var res = match.match(regex);_x000D_
  console.log(match);_x000D_
  console.log(RegExp.$1)_x000D_
 _x000D_
}
_x000D_
_x000D_
_x000D_

How to convert a 3D point into 2D perspective projection?

All of the answers address the question posed in the title. However, I would like to add a caveat that is implicit in the text. Bézier patches are used to represent the surface, but you cannot just transform the points of the patch and tessellate the patch into polygons, because this will result in distorted geometry. You can, however, tessellate the patch first into polygons using a transformed screen tolerance and then transform the polygons, or you can convert the Bézier patches to rational Bézier patches, then tessellate those using a screen-space tolerance. The former is easier, but the latter is better for a production system.

I suspect that you want the easier way. For this, you would scale the screen tolerance by the norm of the Jacobian of the inverse perspective transformation and use that to determine the amount of tessellation that you need in model space (it might be easier to compute the forward Jacobian, invert that, then take the norm). Note that this norm is position-dependent, and you may want to evaluate this at several locations, depending on the perspective. Also remember that since the projective transformation is rational, you need to apply the quotient rule to compute the derivatives.

embedding image in html email

One additional hint to Pavel Perna's post which helped me very much (cannot comment with my reputation, that's why I post this as answer): In some versions of Microsoft Exchange, the inline contents disposition is removed (see this post by Microsoft). The image is simply not part in the mail the user sees in Outlook. As a workaround, use "Content-Disposition: attachement" instead. Outlook 2016 won't show images as attachement that are used in the mail message, although they use the "Content-Disposition: attachement".

How to programmatically get iOS status bar height

Don't forget that the status bar's frame will be in the screen's coordinate space! If you launch in landscape mode, you may find that width and height are swapped. I strongly recommend that you use this version of the code instead if you support landscape orientations:

CGRect statusBarFrame = [self.window convertRect:[UIApplication sharedApplication].statusBarFrame toView:view];

You can then read statusBarFrame's height property directly. 'View' in this instance should be the view in which you wish to make use of the measurements, most likely the application window's root view controller.

Incidentally, not only may the status bar be taller during phone calls, it can also be zero if the status bar has been deliberately hidden.

Can't bind to 'formGroup' since it isn't a known property of 'form'

I had the same issue and the problem was in fact only that I forgot to import and declare the component which holds the form in the module:

import { ContactFormComponent } from './contact-form/contact-form.component';

@NgModule({
    declarations: [..., ContactFormComponent, ...],
    imports: [CommonModule, HomeRoutingModule, SharedModule]
})
export class HomeModule {}

How do I serialize a Python dictionary into a string, and then back to a dictionary?

pyyaml should also be mentioned here. It is both human readable and can serialize any python object.
pyyaml is hosted here:
https://bitbucket.org/xi/pyyaml

How to include css files in Vue 2

As you can see, the import command did work but is showing errors because it tried to locate the resources in vendor.css and couldn't find them

You should also upload your project structure and ensure that there aren't any path issues. Also, you could include the css file in the index.html or the Component template and webpack loader would extract it when built

Get and Set Screen Resolution

in Winforms, there is a Screen class you can use to get data about screen dimensions and color depth for all displays connected to the computer. Here's the docs page: http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx

CHANGING the screen resolution is trickier. There is a Resolution third party class that wraps the native code you'd otherwise hook into. Use its CResolution nested class to set the screen resolution to a new height and width; but understand that doing this will only work for height/width combinations the display actually supports (800x600, 1024x768, etc, not 817x435).

Convert Date format into DD/MMM/YYYY format in SQL Server

Try this

select convert(varchar,getdate(),100)

third parameter is format, range is from 100 to 114, any one should work for you.

If you need date in dd/mmm/yyyy use this:

replace(convert(char(11),getdate(),113),' ','-')

Replace getdate() with your column name. This worked for me.

powershell - extract file name and extension

just do it:

$file=Get-Item "C:\temp\file.htm"
$file.Basename 
$file.Extension

day of the week to day number (Monday = 1, Tuesday = 2)

The date function can return this if you specify the format correctly:

$daynum = date("w", strtotime("wednesday"));

will return 0 for Sunday through to 6 for Saturday.

An alternative format is:

$daynum = date("N", strtotime("wednesday"));

which will return 1 for Monday through to 7 for Sunday (this is the ISO-8601 represensation).

Can git undo a checkout of unstaged files

Developing on OS X? Using Xcode? You're likely to be in luck!

As described in a comment by qungu, OS X maintains an autosaved version history of files, even if you're not using time machine.

So, if you've blown away your unstaged local changes with a careless git checkout ., here's how you can probably recover all your work.

If somebody finds this thread having destroyed some work in XCode, there is a way to get the AutoSave history. XCode itself does not have a menu entry to see the AutoSave history, but it does store it. If you open the files in question in TextEdit, you can revert and look through the AutoSave history under File > Revert.

Which is awesome, and recovered about a day of work for me, yesterday.


You might ask, "Why doesn't the git command-line UI, the premier VCS used for software engineering in 2016 2017 2018 2019 2020, at least back up files before just blowing them away? Like, you know, well written software tools for about the last three decades."

Or perhaps you ask, "Why is this insanely awesome file history feature accessible in TextEdit but not Xcode where I actually need it?"

… and both of those, I think, will tell you quite a lot about our industry. Or maybe you'll go and fix those tools. Which would be super.

how do I get a new line, after using float:left?

you can also use

<br style="clear:both" />

How to use underscore.js as a template engine?

Everything you need to know about underscore template is here. Only 3 things to keep in mind:

  1. <% %> - to execute some code
  2. <%= %> - to print some value in template
  3. <%- %> - to print some values HTML escaped

That's all about it.

Simple example:

var tpl = _.template("<h1>Some text: <%= foo %></h1>");

then tpl({foo: "blahblah"}) would be rendered to the string <h1>Some text: blahblah</h1>

node.js - request - How to "emitter.setMaxListeners()"?

I strongly advice NOT to use the code:

process.setMaxListeners(0);

The warning is not there without reason. Most of the time, it is because there is an error hidden in your code. Removing the limit removes the warning, but not its cause, and prevents you from being warned of a source of resource leakage.

If you hit the limit for a legitimate reason, put a reasonable value in the function (the default is 10).

Also, to change the default, it is not necessary to mess with the EventEmitter prototype. you can set the value of defaultMaxListeners attribute like so:

require('events').EventEmitter.defaultMaxListeners = 15;

How to change the color of a button?

Here is my code, to make different colors on button, and Linear, Constraint and Scroll Layout

First, you need to make a custom_button.xml on your drawable

  1. Go to res
  2. Expand it, right click on drawable
  3. New -> Drawable Resource File
  4. File Name : custom_button, Click OK

Custom_Button.xml Code

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true" android:drawable="@color/red"/> <!-- pressed -->
    <item android:state_focused="true" android:drawable="@color/blue"/> <!-- focused -->
    <item android:drawable="@color/black"/> <!-- default -->
</selector>

Second, go to res

  1. Expand values
  2. Double click on colors.xml
  3. Copy the code below

Colors.xml Code

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#3F51B5</color>
    <color name="colorPrimaryDark">#303F9F</color>
    <color name="colorAccent">#FF4081</color>

    <color name="black">#000</color>
    <color name="violet">#9400D3</color>
    <color name="indigo">#4B0082</color>
    <color name="blue">#0000FF</color>
    <color name="green">#00FF00</color>
    <color name="yellow">#FFFF00</color>
    <color name="orange">#FF7F00</color>
    <color name="red">#FF0000</color>
</resources>

Screenshots below

enter image description here XML Coding enter image description here Design Preview

Remote origin already exists on 'git push' to a new repository

The previous solutions seem to ignore origin, and they only suggest to use another name. When you just want to use git push origin, keep reading.

The problem appears because a wrong order of Git configuration is followed. You might have already added a 'git origin' to your .git configuration.

You can change the remote origin in your Git configuration with the following line:

git remote set-url origin [email protected]:username/projectname.git

This command sets a new URL for the Git repository you want to push to. Important is to fill in your own username and projectname

Difference between multitasking, multithreading and multiprocessing?

Basically Multi-programming is a concept where you run more than one program simultaneously, suppose you run two programs like chrome(browser) and calculator(system application).

Multi processing is where a user uses more than one processor to accomplish a task.

To know Multi threading we need to know what is a thread. A thread is basically a part of a program running within the program. Best example of thread is the tabs of a browser. If you have 5 tabs which are being opened and used then the program actually creates 5 threads of the program, this concept is called multi-threading.

What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone

Well considering there's no overhead difference between a varchar(30) and a varchar(100) if you're only storing 20 characters in each, err on the side of caution and just make it 50.

Simple insecure two-way data "obfuscation"?

Other answers here work fine, but AES is a more secure and up-to-date encryption algorithm. This is a class that I obtained a few years ago to perform AES encryption that I have modified over time to be more friendly for web applications (e,g. I've built Encrypt/Decrypt methods that work with URL-friendly string). It also has the methods that work with byte arrays.

NOTE: you should use different values in the Key (32 bytes) and Vector (16 bytes) arrays! You wouldn't want someone to figure out your keys by just assuming that you used this code as-is! All you have to do is change some of the numbers (must be <= 255) in the Key and Vector arrays (I left one invalid value in the Vector array to make sure you do this...). You can use https://www.random.org/bytes/ to generate a new set easily:

Using it is easy: just instantiate the class and then call (usually) EncryptToString(string StringToEncrypt) and DecryptString(string StringToDecrypt) as methods. It couldn't be any easier (or more secure) once you have this class in place.


using System;
using System.Data;
using System.Security.Cryptography;
using System.IO;


public class SimpleAES
{
    // Change these keys
    private byte[] Key = __Replace_Me__({ 123, 217, 19, 11, 24, 26, 85, 45, 114, 184, 27, 162, 37, 112, 222, 209, 241, 24, 175, 144, 173, 53, 196, 29, 24, 26, 17, 218, 131, 236, 53, 209 });

    // a hardcoded IV should not be used for production AES-CBC code
    // IVs should be unpredictable per ciphertext
    private byte[] Vector = __Replace_Me__({ 146, 64, 191, 111, 23, 3, 113, 119, 231, 121, 2521, 112, 79, 32, 114, 156 });


    private ICryptoTransform EncryptorTransform, DecryptorTransform;
    private System.Text.UTF8Encoding UTFEncoder;

    public SimpleAES()
    {
        //This is our encryption method
        RijndaelManaged rm = new RijndaelManaged();

        //Create an encryptor and a decryptor using our encryption method, key, and vector.
        EncryptorTransform = rm.CreateEncryptor(this.Key, this.Vector);
        DecryptorTransform = rm.CreateDecryptor(this.Key, this.Vector);

        //Used to translate bytes to text and vice versa
        UTFEncoder = new System.Text.UTF8Encoding();
    }

    /// -------------- Two Utility Methods (not used but may be useful) -----------
    /// Generates an encryption key.
    static public byte[] GenerateEncryptionKey()
    {
        //Generate a Key.
        RijndaelManaged rm = new RijndaelManaged();
        rm.GenerateKey();
        return rm.Key;
    }

    /// Generates a unique encryption vector
    static public byte[] GenerateEncryptionVector()
    {
        //Generate a Vector
        RijndaelManaged rm = new RijndaelManaged();
        rm.GenerateIV();
        return rm.IV;
    }


    /// ----------- The commonly used methods ------------------------------    
    /// Encrypt some text and return a string suitable for passing in a URL.
    public string EncryptToString(string TextValue)
    {
        return ByteArrToString(Encrypt(TextValue));
    }

    /// Encrypt some text and return an encrypted byte array.
    public byte[] Encrypt(string TextValue)
    {
        //Translates our text value into a byte array.
        Byte[] bytes = UTFEncoder.GetBytes(TextValue);

        //Used to stream the data in and out of the CryptoStream.
        MemoryStream memoryStream = new MemoryStream();

        /*
         * We will have to write the unencrypted bytes to the stream,
         * then read the encrypted result back from the stream.
         */
        #region Write the decrypted value to the encryption stream
        CryptoStream cs = new CryptoStream(memoryStream, EncryptorTransform, CryptoStreamMode.Write);
        cs.Write(bytes, 0, bytes.Length);
        cs.FlushFinalBlock();
        #endregion

        #region Read encrypted value back out of the stream
        memoryStream.Position = 0;
        byte[] encrypted = new byte[memoryStream.Length];
        memoryStream.Read(encrypted, 0, encrypted.Length);
        #endregion

        //Clean up.
        cs.Close();
        memoryStream.Close();

        return encrypted;
    }

    /// The other side: Decryption methods
    public string DecryptString(string EncryptedString)
    {
        return Decrypt(StrToByteArray(EncryptedString));
    }

    /// Decryption when working with byte arrays.    
    public string Decrypt(byte[] EncryptedValue)
    {
        #region Write the encrypted value to the decryption stream
        MemoryStream encryptedStream = new MemoryStream();
        CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
        decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
        decryptStream.FlushFinalBlock();
        #endregion

        #region Read the decrypted value from the stream.
        encryptedStream.Position = 0;
        Byte[] decryptedBytes = new Byte[encryptedStream.Length];
        encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
        encryptedStream.Close();
        #endregion
        return UTFEncoder.GetString(decryptedBytes);
    }

    /// Convert a string to a byte array.  NOTE: Normally we'd create a Byte Array from a string using an ASCII encoding (like so).
    //      System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
    //      return encoding.GetBytes(str);
    // However, this results in character values that cannot be passed in a URL.  So, instead, I just
    // lay out all of the byte values in a long string of numbers (three per - must pad numbers less than 100).
    public byte[] StrToByteArray(string str)
    {
        if (str.Length == 0)
            throw new Exception("Invalid string value in StrToByteArray");

        byte val;
        byte[] byteArr = new byte[str.Length / 3];
        int i = 0;
        int j = 0;
        do
        {
            val = byte.Parse(str.Substring(i, 3));
            byteArr[j++] = val;
            i += 3;
        }
        while (i < str.Length);
        return byteArr;
    }

    // Same comment as above.  Normally the conversion would use an ASCII encoding in the other direction:
    //      System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
    //      return enc.GetString(byteArr);    
    public string ByteArrToString(byte[] byteArr)
    {
        byte val;
        string tempStr = "";
        for (int i = 0; i <= byteArr.GetUpperBound(0); i++)
        {
            val = byteArr[i];
            if (val < (byte)10)
                tempStr += "00" + val.ToString();
            else if (val < (byte)100)
                tempStr += "0" + val.ToString();
            else
                tempStr += val.ToString();
        }
        return tempStr;
    }
}

How to replace comma (,) with a dot (.) using java

For the current information you are giving, it will be enought with this simple regex to do the replacement:

str.replaceAll(",", ".");

What is the meaning of polyfills in HTML5?

Here are some high level thoughts and info that might help, aside from the other answers.

Pollyfills are like a compatability patch for specific browsers. Shims are changes to specific arguments. Fallbacks can be used if say a @mediaquery is not compatible with a browser.

It kind of depends on the requirements of what your app/website needs to be compatible with.

You cna check this site out for compatability of specific libraries with specific browsers. https://caniuse.com/