Programs & Examples On #Response.contenttype

Window.Open with PDF stream instead of PDF location

Note: I have verified this in the latest version of IE, and other browsers like Mozilla and Chrome and this works for me. Hope it works for others as well.

if (data == "" || data == undefined) {
    alert("Falied to open PDF.");
} else { //For IE using atob convert base64 encoded data to byte array
    if (window.navigator && window.navigator.msSaveOrOpenBlob) {
        var byteCharacters = atob(data);
        var byteNumbers = new Array(byteCharacters.length);
        for (var i = 0; i < byteCharacters.length; i++) {
            byteNumbers[i] = byteCharacters.charCodeAt(i);
        }
        var byteArray = new Uint8Array(byteNumbers);
        var blob = new Blob([byteArray], {
            type: 'application/pdf'
        });
        window.navigator.msSaveOrOpenBlob(blob, fileName);
    } else { // Directly use base 64 encoded data for rest browsers (not IE)
        var base64EncodedPDF = data;
        var dataURI = "data:application/pdf;base64," + base64EncodedPDF;
        window.open(dataURI, '_blank');
    }

}

How to Avoid Response.End() "Thread was being aborted" Exception during the Excel file download

Looks to be the same question as:

When an ASP.NET System.Web.HttpResponse.End() is called, the current thread is aborted?

So it's by design. You need to add a catch for that exception and gracefully "ignore" it.

Add Header and Footer for PDF using iTextsharp

This link will help you out completely(the Shortest and Most Elegant way):

Header Footer with PageEvent

        PdfPTable tbheader = new PdfPTable(3);
        tbheader.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
        tbheader.DefaultCell.Border = 0;
        tbheader.AddCell(new Paragraph());
        tbheader.AddCell(new Paragraph());
        var _cell2 = new PdfPCell(new Paragraph("This is my header", arial_italic));
        _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
        _cell2.Border = 0;
        tbheader.AddCell(_cell2);
        float[] widths = new float[] { 20f, 20f, 60f };
        tbheader.SetWidths(widths);
        tbheader.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetTop(document.TopMargin), writer.DirectContent);

        PdfPTable tbfooter = new PdfPTable(3);
        tbfooter.TotalWidth = document.PageSize.Width - document.LeftMargin - document.RightMargin;
        tbfooter.DefaultCell.Border = 0;
        tbfooter.AddCell(new Paragraph());
        tbfooter.AddCell(new Paragraph());
        var _cell2 = new PdfPCell(new Paragraph("This is my footer", arial_italic));
        _cell2.HorizontalAlignment = Element.ALIGN_RIGHT;
        _cell2.Border = 0;
        tbfooter.AddCell(_cell2);
        tbfooter.AddCell(new Paragraph());
        tbfooter.AddCell(new Paragraph());
        var _celly = new PdfPCell(new Paragraph(writer.PageNumber.ToString()));//For page no.
        _celly.HorizontalAlignment = Element.ALIGN_RIGHT;
        _celly.Border = 0;
        tbfooter.AddCell(_celly);
        float[] widths1 = new float[] { 20f, 20f, 60f };
        tbfooter.SetWidths(widths1);
        tbfooter.WriteSelectedRows(0, -1, document.LeftMargin, writer.PageSize.GetBottom(document.BottomMargin), writer.DirectContent);

ASP.NET file download from server

You can use an HTTP Handler (.ashx) to download a file, like this:

DownloadFile.ashx:

public class DownloadFile : IHttpHandler 
{
    public void ProcessRequest(HttpContext context)
    {   
        System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
        response.ClearContent();
        response.Clear();
        response.ContentType = "text/plain";
        response.AddHeader("Content-Disposition", 
                           "attachment; filename=" + fileName + ";");
        response.TransmitFile(Server.MapPath("FileDownload.csv"));
        response.Flush();    
        response.End();
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Then you can call the HTTP Handler from the button click event handler, like this:

Markup:

<asp:Button ID="btnDownload" runat="server" Text="Download File" 
            OnClick="btnDownload_Click"/>

Code-Behind:

protected void btnDownload_Click(object sender, EventArgs e)
{
    Response.Redirect("PathToHttpHandler/DownloadFile.ashx");
}

Passing a parameter to the HTTP Handler:

You can simply append a query string variable to the Response.Redirect(), like this:

Response.Redirect("PathToHttpHandler/DownloadFile.ashx?yourVariable=yourValue");

Then in the actual handler code you can use the Request object in the HttpContext to grab the query string variable value, like this:

System.Web.HttpRequest request = System.Web.HttpContext.Current.Request;
string yourVariableValue = request.QueryString["yourVariable"];

// Use the yourVariableValue here

Note - it is common to pass a filename as a query string parameter to suggest to the user what the file actually is, in which case they can override that name value with Save As...

Export data to Excel file with ASP.NET MVC 4 C# is rendering into view

I used a list in my controller class to set data into grid view. The code works fine for me:

public ActionResult ExpExcl()
{
  List<PersonModel> person= new List<PersonModel>
   { 
    new PersonModel() {FirstName= "Jenny", LastName="Mathew", Age= 23},
    new PersonModel() {FirstName= "Paul", LastName="Meehan", Age=25}
   };
   var grid= new GridView();
   grid.DataSource= person;
   grid.DataBind();

   Response.ClearContent();
   Response.AddHeader("content-disposition","attachement; filename=data.xls");
   Response.ContentType="application/excel";
   StringWriter sw= new StringWriter();
   HtmlTextWriter htw= new HtmlTextWriter(sw); 
   grid.RenderControl(htw);
   Response.Output.Write(sw.ToString());
   Response.Flush();
   Response.End();
   return View();
 }

gridview data export to excel in asp.net

I think it will help you

string filename = String.Format("Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
        if (!string.IsNullOrEmpty(GRIDVIEWNAME.Page.Title))
            filename = GRIDVIEWNAME.Page.Title + ".xls";

        HttpContext.Current.Response.Clear();

        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + filename);


        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.Charset = "";

        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);



        System.Web.UI.HtmlControls.HtmlForm form = new System.Web.UI.HtmlControls.HtmlForm();
        GRIDVIEWNAME.Parent.Controls.Add(form);
        form.Controls.Add(GRIDVIEWNAME);
        form.RenderControl(htmlWriter);

        HttpContext.Current.Response.Write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />");
        HttpContext.Current.Response.Write(stringWriter.ToString());
        HttpContext.Current.Response.End();

Writing an Excel file in EPPlus

Have you looked at the samples provided with EPPlus?

This one shows you how to create a file http://epplus.codeplex.com/wikipage?title=ContentSheetExample

This one shows you how to use it to stream back a file http://epplus.codeplex.com/wikipage?title=WebapplicationExample

This is how we use the package to generate a file.

var newFile = new FileInfo(ExportFileName);
using (ExcelPackage xlPackage = new ExcelPackage(newFile))
{                       
    // do work here                            
    xlPackage.Save();
}

Duplicate headers received from server

The server SHOULD put double quotes around the filename, as mentioned by @cusman and @Touko in their replies.

For example:

Response.AddHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");

Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

What worked for me was setting aspnet:MaxHttpCollectionKeys to a high value on appSettings tag on the inetpub VirtualDirectories\443\web.config file:

<configuration>
    <appSettings>
        <add key="aspnet:MaxHttpCollectionKeys" value="100000" />
    </appSettings>
</configuration>

How to convert DataSet to DataTable

A DataSet already contains DataTables. You can just use:

DataTable firstTable = dataSet.Tables[0];

or by name:

DataTable customerTable = dataSet.Tables["Customer"];

Note that you should have using statements for your SQL code, to ensure the connection is disposed properly:

using (SqlConnection conn = ...)
{
    // Code here...
}

ASP.Net Download file to client browser

Just a slight addition to the above solution if you are having problem with downloaded file's name...

Response.AddHeader("Content-Disposition", "attachment; filename=\"" + file.Name + "\"");

This will return the exact file name even if it contains spaces or other characters.

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

Use this code. This works like a champ.

Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();

Download/Stream file from URL - asp.net

The accepted solution from Dallas was working for us if we use Load Balancer on the Citrix Netscaler (without WAF policy).

The download of the file doesn't work through the LB of the Netscaler when it is associated with WAF as the current scenario (Content-length not being correct) is a RFC violation and AppFW resets the connection, which doesn't happen when WAF policy is not associated.

So what was missing was:

Response.End();

See also: Trying to stream a PDF file with asp.net is producing a "damaged file"

Export to CSV using MVC, C# and jQuery

In addition to Biff MaGriff's answer. To export the file using JQuery, redirect the user to a new page.

$('#btn_export').click(function () {
    window.location.href = 'NewsLetter/Export';
});

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

It is not an issue it is because of caching...

To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').

After timestamp it should be axios.get(/api/products?${Date.now()}.

It will resolve your 304 status code.

How to Generate Unique Public and Private Key via RSA

The RSACryptoServiceProvider(CspParameters) constructor creates a keypair which is stored in the keystore on the local machine. If you already have a keypair with the specified name, it uses the existing keypair.

It sounds as if you are not interested in having the key stored on the machine.

So use the RSACryptoServiceProvider(Int32) constructor:

public static void AssignNewKey(){
    RSA rsa = new RSACryptoServiceProvider(2048); // Generate a new 2048 bit RSA key

    string publicPrivateKeyXML = rsa.ToXmlString(true);
    string publicOnlyKeyXML = rsa.ToXmlString(false);
    // do stuff with keys...
}

EDIT:

Alternatively try setting the PersistKeyInCsp to false:

public static void AssignNewKey(){
    const int PROVIDER_RSA_FULL = 1;
    const string CONTAINER_NAME = "KeyContainer";
    CspParameters cspParams;
    cspParams = new CspParameters(PROVIDER_RSA_FULL);
    cspParams.KeyContainerName = CONTAINER_NAME;
    cspParams.Flags = CspProviderFlags.UseMachineKeyStore;
    cspParams.ProviderName = "Microsoft Strong Cryptographic Provider";
    rsa = new RSACryptoServiceProvider(cspParams);

    rsa.PersistKeyInCsp = false;

    string publicPrivateKeyXML = rsa.ToXmlString(true);
    string publicOnlyKeyXML = rsa.ToXmlString(false);
    // do stuff with keys...
}

How can I present a file for download from an MVC controller?

You can do the same in Razor or in the Controller, like so..

@{
    //do this on the top most of your View, immediately after `using` statement
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");
}

Or in the Controller..

public ActionResult Receipt() {
    Response.ContentType = "application/pdf";
    Response.AddHeader("Content-Disposition", "attachment; filename=receipt.pdf");

    return View();
}

I tried this in Chrome and IE9, both is downloading the pdf file.

I probably should add I am using RazorPDF to generate my PDFs. Here is a blog about it: http://nyveldt.com/blog/post/Introducing-RazorPDF

How to return XML in ASP.NET?

Below is the way a handler will returns stream data that would contain xml data in the server side.

Here is the handler code that would returns the data.

    public void ProcessRequest(HttpContext context)
    {

        StringBuilder xmlBuilder = new StringBuilder();

        xmlBuilder.Append("<Names>");
        xmlBuilder.Append("<Name>");
        xmlBuilder.Append("Sheo");
        xmlBuilder.Append("</Name>");
        xmlBuilder.Append("</Names>");
        context.Response.ContentType = "application/octet-stream";
        context.Response.BinaryWrite(Encoding.UTF8.GetBytes(xmlBuilder.ToString()));
        context.Response.End();

    }

How to output an Excel *.xls file from classic ASP

You must specify the file to be downloaded (attachment) by the client in the http header:

Response.ContentType = "application/vnd.ms-excel"
Response.AppendHeader "content-disposition", "attachment: filename=excelTest.xls"

http://classicasp.aspfaq.com/general/how-do-i-prompt-a-save-as-dialog-for-an-accepted-mime-type.html

Response Content type as CSV

Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )

  • text/comma-separated-values
  • text/csv
  • application/csv
  • application/excel
  • application/vnd.ms-excel
  • application/vnd.msexcel

Also, the mime-type might be case sensitive...

Set database from SINGLE USER mode to MULTI USER

This worked fine for me

  1. Take a backup
  2. Create new database and restore the backup to it
  3. Then Properties > Options > [Scroll down] State > RestrictAccess > select Multi_user and click OK
  4. Delete the old database

Hope this work for all Thank you Ramesh Kumar

How do I read an image file using Python?

The word "read" is vague, but here is an example which reads a jpeg file using the Image class, and prints information about it.

from PIL import Image
jpgfile = Image.open("picture.jpg")

print(jpgfile.bits, jpgfile.size, jpgfile.format)

Annotation @Transactional. How to rollback?

For me rollbackFor was not enough, so I had to put this and it works as expected:

@Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class)

I hope it helps :-)

How to copy file from one location to another location?

Copy a file from one location to another location means,need to copy the whole content to another location.Files.copy(Path source, Path target, CopyOption... options) throws IOException this method expects source location which is original file location and target location which is a new folder location with destination same type file(as original). Either Target location needs to exist in our system otherwise we need to create a folder location and then in that folder location we need to create a file with the same name as original filename.Then using copy function we can easily copy a file from one location to other.

 public static void main(String[] args) throws IOException {
                String destFolderPath = "D:/TestFile/abc";
                String fileName = "pqr.xlsx";
                String sourceFilePath= "D:/TestFile/xyz.xlsx";
                File f = new File(destFolderPath);
                if(f.mkdir()){
                    System.out.println("Directory created!!!!");
                }
                else {
                    System.out.println("Directory Exists!!!!");
                }
                f= new File(destFolderPath,fileName);
                if(f.createNewFile())   {

                    System.out.println("File Created!!!!");
                }   else {
                    System.out.println("File exists!!!!");
                }

                Files.copy(Paths.get(sourceFilePath), Paths.get(destFolderPath, fileName),REPLACE_EXISTING);
                System.out.println("Copy done!!!!!!!!!!!!!!");


            }

Shell Script Syntax Error: Unexpected End of File

In my case, I found that placing a here document (like sqplus ... << EOF) statements indented also raise the same error as shown below:

./dbuser_case.ksh: line 25: syntax error: unexpected end of file

So after removing the indentation for this, then it went fine.

Hope it helps...

Highlighting Text Color using Html.fromHtml() in Android?

This can be achieved using a Spannable String. You will need to import the following

import android.text.SpannableString; 
import android.text.style.BackgroundColorSpan; 
import android.text.style.StyleSpan;

And then you can change the background of the text using something like the following:

TextView text = (TextView) findViewById(R.id.text_login);
text.setText("");
text.append("Add all your funky text in here");
Spannable sText = (Spannable) text.getText();
sText.setSpan(new BackgroundColorSpan(Color.RED), 1, 4, 0);

Where this will highlight the charecters at pos 1 - 4 with a red color. Hope this helps!

Word wrapping in phpstorm

For all files (default setting for opened file): Settings/Preferences | Editor | General | Use soft wraps in editor

For currently opened file in editor: Menu | View | Active Editor | Use Soft Wraps


In latest IDE versions you can also access this option via context menu for the editor gutter area (the area with line numbers on the left side of the editor).

Search Everywhere (Shift 2x times) or Help | Find Action... ( Ctrl + Shift+ A on Windows using Default keymap) can also be used to quickly change this option (instead of going into Settings/Preferences).

Using strtok with a std::string

#include <iostream>
#include <string>
#include <sstream>
int main(){
    std::string myText("some-text-to-tokenize");
    std::istringstream iss(myText);
    std::string token;
    while (std::getline(iss, token, '-'))
    {
        std::cout << token << std::endl;
    }
    return 0;
}

Or, as mentioned, use boost for more flexibility.

SQL - Update multiple records in one query

in my case I have to update the records which are more than 1000, for this instead of hitting the update query each time I preferred this,

   UPDATE mst_users 
   SET base_id = CASE user_id 
   WHEN 78 THEN 999 
   WHEN 77 THEN 88 
   ELSE base_id END WHERE user_id IN(78, 77)

78,77 are the user Ids and for those user id I need to update the base_id 999 and 88 respectively.This works for me.

Android Studio rendering problems

In build.gradle below dependencies add:

configurations.all {
    resolutionStrategy.eachDependency { DependencyResolveDetails details ->
        def requested = details.requested
        if (requested.group == "com.android.support") {
            if (!requested.name.startsWith("multidex")) {
                details.useVersion "27.+"
            }
        }
    }
}

This worked for me, I found it on stack, addressed as the "Theme Error solution": Theme Error - how to fix?

Change arrow colors in Bootstraps carousel

In bootstrap 4 if you are just changing the colour of the controls you can use the sass variables, typically in custom.scss:

$carousel-control-color: #7b277d;

As highlighted in this github issue note: https://github.com/twbs/bootstrap/issues/21985#issuecomment-281402443

Are iframes considered 'bad practice'?

I have seen IFRAMEs applied very successfully as an easy way to make dynamic context menus, but the target audience of that web-app was only Internet Explorer users.

I would say that it all depends on your requirements. If you wish to make sure your page works equally well on every browser, avoid IFRAMEs. If you are targeting a narrow and well-known audience (eg. on the local Intranet) and you see a benefit in using IFRAMEs then I would say it's OK to do so.

How to write std::string to file?

remove the ios::binary from your modes in your ofstream and use studentPassword.c_str() instead of (char *)&studentPassword in your write.write()

Converting string to byte array in C#

use this

byte[] myByte= System.Text.ASCIIEncoding.Default.GetBytes(myString);

Best way to reset an Oracle sequence to the next value in an existing column?

With oracle 10.2g:

select  level, sequence.NEXTVAL
from  dual 
connect by level <= (select max(pk) from tbl);

will set the current sequence value to the max(pk) of your table (i.e. the next call to NEXTVAL will give you the right result); if you use Toad, press F5 to run the statement, not F9, which pages the output (thus stopping the increment after, usually, 500 rows). Good side: this solution is only DML, not DDL. Only SQL and no PL-SQL. Bad side : this solution prints max(pk) rows of output, i.e. is usually slower than the ALTER SEQUENCE solution.

Web Reference vs. Service Reference

If I understand your question right:

To add a .net 2.0 Web Service Reference instead of a WCF Service Reference, right-click on your project and click 'Add Service Reference.'

Then click "Advanced.." at the bottom left of the dialog.

Then click "Add Web Reference.." on the bottom left of the next dialog.

Now you can add a regular SOAP web reference like you are looking for.

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

As stated in this other answer:

This error message... implies that the ChromeDriver was unable to initiate/spawn a new WebBrowser i.e. Chrome Browser session.

Among the possible causes, I would like to mention the fact that, in case you are running an headless Chromium via Xvfb, you might need to export the DISPLAY variable: in my case, I had in place (as recommended) the --disable-dev-shm-usage and --no-sandbox options, everything was running fine, but in a new installation running the latest (at the time of writing) Ubuntu 18.04 this error started to occurr, and the only possible fix was to execute an export DISPLAY=":20" (having previously started Xvfb with Xvfb :20&).

install / uninstall APKs programmatically (PackageManager vs Intents)

API level 14 introduced two new actions: ACTION_INSTALL_PACKAGE and ACTION_UNINSTALL_PACKAGE. Those actions allow you to pass EXTRA_RETURN_RESULT boolean extra to get an (un)installation result notification.

Example code for invoking the uninstall dialog:

String app_pkg_name = "com.example.app";
int UNINSTALL_REQUEST_CODE = 1;

Intent intent = new Intent(Intent.ACTION_UNINSTALL_PACKAGE);  
intent.setData(Uri.parse("package:" + app_pkg_name));  
intent.putExtra(Intent.EXTRA_RETURN_RESULT, true);
startActivityForResult(intent, UNINSTALL_REQUEST_CODE);

And receive the notification in your Activity#onActivityResult method:

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == UNINSTALL_REQUEST_CODE) {
        if (resultCode == RESULT_OK) {
            Log.d("TAG", "onActivityResult: user accepted the (un)install");
        } else if (resultCode == RESULT_CANCELED) {
            Log.d("TAG", "onActivityResult: user canceled the (un)install");
        } else if (resultCode == RESULT_FIRST_USER) {
            Log.d("TAG", "onActivityResult: failed to (un)install");
        }
    }
}

Run PowerShell command from command prompt (no ps1 script)

Run it on a single command line like so:

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile 
  -WindowStyle Hidden -Command "Get-AppLockerFileInformation -Directory <folderpath> 
  -Recurse -FileType <type>"

How to get DataGridView cell value in messagebox?

   private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)
    {
        MessageBox.Show(Convert.ToString(dataGridView1.CurrentCell.Value));
    }

a bit late but hope it helps

JavaScript error: "is not a function"

I also hit this error. In my case the root cause was async related (during a codebase refactor): An asynchronous function that builds the object to which the "not a function" function belongs was not awaited, and the subsequent attempt to invoke the function throws the error, example below:

const car = carFactory.getCar();
car.drive() //throws TypeError: drive is not a function

The fix was:

const car = await carFactory.getCar();
car.drive()

Posting this incase it helps anyone else facing this error.

Android: Access child views from a ListView

See: Android ListView: get data index of visible item and combine with part of Feet's answer above, can give you something like:

int wantedPosition = 10; // Whatever position you're looking for
int firstPosition = listView.getFirstVisiblePosition() - listView.getHeaderViewsCount(); // This is the same as child #0
int wantedChild = wantedPosition - firstPosition;
// Say, first visible position is 8, you want position 10, wantedChild will now be 2
// So that means your view is child #2 in the ViewGroup:
if (wantedChild < 0 || wantedChild >= listView.getChildCount()) {
  Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
  return;
}
// Could also check if wantedPosition is between listView.getFirstVisiblePosition() and listView.getLastVisiblePosition() instead.
View wantedView = listView.getChildAt(wantedChild);

The benefit is that you aren't iterating over the ListView's children, which could take a performance hit.

Programmatically navigate using React router

If happen to pair RR4 w/ redux through react-router-redux, use the routing action creators from react-router-redux is a option as well.

import { push, replace, ... } from 'react-router-redux'

class WrappedComponent extends React.Component {
  handleRedirect(url, replaceState = true) { 
    replaceState 
      ? this.props.dispatch(replace(url)) 
      : this.props.dispatch(push(url)) 
  }
  render() { ... }
}

export default connect(null)(WrappedComponent)

If use redux thunk/saga to manage async flow, import the above action creators in redux actions and hook to react components using mapDispatchToProps might be better.

SQL to search objects, including stored procedures, in Oracle

I would use DBA_SOURCE (if you have access to it) because if the object you require is not owned by the schema under which you are logged in you will not see it.

If you need to know the functions and Procs inside the packages try something like this:

select * from all_source
 where type = 'PACKAGE'
   and (upper(text) like '%FUNCTION%' or upper(text) like '%PROCEDURE%')
   and owner != 'SYS';

The last line prevents all the sys stuff (DBMS_ et al) from being returned. This will work in user_source if you just want your own schema stuff.

Parse HTML table to Python list?

If the HTML is not XML you can't do it with etree. But even then, you don't have to use an external library for parsing a HTML table. In python 3 you can reach your goal with HTMLParser from html.parser. I've the code of the simple derived HTMLParser class here in a github repo.

You can use that class (here named HTMLTableParser) the following way:

import urllib.request
from html_table_parser import HTMLTableParser

target = 'http://www.twitter.com'

# get website content
req = urllib.request.Request(url=target)
f = urllib.request.urlopen(req)
xhtml = f.read().decode('utf-8')

# instantiate the parser and feed it
p = HTMLTableParser()
p.feed(xhtml)
print(p.tables)

The output of this is a list of 2D-lists representing tables. It looks maybe like this:

[[['   ', ' Anmelden ']],
 [['Land', 'Code', 'Für Kunden von'],
  ['Vereinigte Staaten', '40404', '(beliebig)'],
  ['Kanada', '21212', '(beliebig)'],
  ...
  ['3424486444', 'Vodafone'],
  ['  Zeige SMS-Kurzwahlen für andere Länder ']]]

PDO::__construct(): Server sent charset (255) unknown to the client. Please, report to the developers

The accepted answer saved me (thanks, Bill!!!), but I ran into another related issue, just wanted to provide some details on my experience -

After upgrading to MySQL 8.0.11, I experienced the same problem as the OP when using PHP's mysqli_connect() function. In my MySQL directory (in my case, usr/local/mysql), I created the my.cnf file, added the content in the accepted answer, then restarted the MySQL server. However, this produced a new error:

mysqli_connect(): The server requested authentication method unknown to the client [caching_sha2_password]

I added the line default_authentication_plugin = mysql_native_password, so my.cnf now looked like:

[client]
default-character-set=utf8

[mysql]
default-character-set=utf8

[mysqld]
collation-server = utf8_unicode_ci
character-set-server = utf8
default_authentication_plugin = mysql_native_password

and I was good to go!

For additional reference: https://github.com/laradock/laradock/issues/1392

how to fire event on file select

<input type="file" @change="onFileChange" class="input upload-input" ref="inputFile"/>

onFileChange(e) {
    //upload file and then delete it from input 
    self.$refs.inputFile.value = ''
}

Loop in Jade (currently known as "Pug") template engine

Here is a very simple jade file that have a loop in it. Jade is very sensitive about white space. After loop definition line (for) you should give an indent(tab) to stuff that want to go inside the loop. You can do this without {}:

- var arr=['one', 'two', 'three'];
- var s = 'string';
doctype html
html
    head
    body
        section= s
        - for (var i=0; i<3; i++)
            div= arr[i]

Getting a link to go to a specific section on another page

You can simply use

 <a href="directry/filename.html#section5" >click me</a>

to link to a section/id of another page by

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

Permission denied (publickey) when SSH Access to Amazon EC2 instance

My private key was set to permission 400 and was resulting in Permission denied setting it to '644' helped me .

key_load_private_type: Permission denied is the specific error I was getting

Solution: Sudo chmod 644 <key.pem>

Note: set to 644 is must, it was not working with 400

how to upload file using curl with php

Use:

if (function_exists('curl_file_create')) { // php 5.5+
  $cFile = curl_file_create($file_name_with_full_path);
} else { // 
  $cFile = '@' . realpath($file_name_with_full_path);
}
$post = array('extra_info' => '123456','file_contents'=> $cFile);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,$target_url);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
$result=curl_exec ($ch);
curl_close ($ch);

You can also refer:

http://blog.derakkilgo.com/2009/06/07/send-a-file-via-post-with-curl-and-php/

Important hint for PHP 5.5+:

Now we should use https://wiki.php.net/rfc/curl-file-upload but if you still want to use this deprecated approach then you need to set curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);

Check an integer value is Null in c#

Nullable<T> (or ?) exposes a HasValue flag to denote if a value is set or the item is null.

Also, nullable types support ==:

if (Age == null)

The ?? is the null coalescing operator and doesn't result in a boolean expression, but a value returned:

int i = Age ?? 0;

So for your example:

if (age == null || age == 0)

Or:

if (age.GetValueOrDefault(0) == 0)

Or:

if ((age ?? 0) == 0)

Or ternary:

int i = age.HasValue ? age.Value : 0;

Spring MVC 4: "application/json" Content Type is not being set correctly

Use jackson library and @ResponseBody annotation on return type for the Controller.

This works if you wish to return POJOs represented as JSon. If you woud like to return String and not POJOs as JSon please refer to Sotirious answer.

How to replace special characters in a string?

I am using this.

s = s.replaceAll("\\W", ""); 

It replace all special characters from string.

Here

\w : A word character, short for [a-zA-Z_0-9]

\W : A non-word character

Read XLSX file in Java

docx4j now covers xlsx as well.

"Why would you use docx4j to do this", I hear you ask, "rather than POI, which focuses on xlsx and binary xls?"

Probably because you like JAXB (as opposed to XML Beans), or you are already using docx4j for docx or pptx, and need to be able to do some stuff with xlsx as well.

Another possible reason is that the jar XML Beans generates from the OpenXML schemas is too big for your purposes. (To get around this, POI offers a 'lite' subset: the 'big' ooxml-schemas-1.0.jar is 14.5 MB! But if you need to support arbitrary spreadsheets, you'll probably need the complete jar). In contrast, the whole of docx4j/pptx4j/xlsx4j weighs in at about the same as POI's lite subset.

If you are processing spreadsheets only (ie not docx or pptx), and preceding paragraph is not a concern for you, then you would probably be best off using POI.

How do I make a div full screen?

This is the simplest one.

#divid {
   position: fixed;
   top: 0;
   right: 0;
   bottom: 0;
   left: 0;
}

Delete dynamically-generated table row using jQuery

A simple solution is encapsulate code of button event in a function, and call it when you add TRs too:

 var i = 1;
$("#addbutton").click(function() {
  $("table tr:first").clone().find("input").each(function() {
    $(this).val('').attr({
      'id': function(_, id) {return id + i },
      'name': function(_, name) { return name + i },
      'value': ''               
    });
  }).end().appendTo("table");
  i++;

  applyRemoveEvent();  
});


function applyRemoveEvent(){
    $('button.removebutton').on('click',function() {
        alert("aa");
      $(this).closest( 'tr').remove();
      return false;
    });
};

applyRemoveEvent();

http://jsfiddle.net/Z7fG7/2/

Can I write native iPhone apps using Python?

Yes, nowadays you can develop apps for iOS in Python.

There are two frameworks that you may want to checkout: Kivy and PyMob.

Please consider the answers to this question too, as they are more up-to-date than this one.

How to determine if .NET Core is installed

After all the other answers, this might prove useful.

Open your application in Visual Studio. In Solutions Explorer, right click your project. Click Properties. Click Application. Under "Target Framework" click the dropdown button and there you are, all of the installed frameworks.

BTW - you may now choose which framework you want.

Find the number of employees in each department - SQL Oracle

select count(e.empno), d.deptno, d.dname 
from emp e, dep d
where e.DEPTNO = d.DEPTNO 
group by d.deptno, d.dname;

Summarizing multiple columns with dplyr?

We can summarize by using summarize_at, summarize_all and summarize_if on dplyr 0.7.4. We can set the multiple columns and functions by using vars and funs argument as below code. The left-hand side of funs formula is assigned to suffix of summarized vars. In the dplyr 0.7.4, summarise_each(and mutate_each) is already deprecated, so we cannot use these functions.

options(scipen = 100, dplyr.width = Inf, dplyr.print_max = Inf)

library(dplyr)
packageVersion("dplyr")
# [1] ‘0.7.4’

set.seed(123)
df <- data_frame(
  a = sample(1:5, 10, replace=T), 
  b = sample(1:5, 10, replace=T), 
  c = sample(1:5, 10, replace=T), 
  d = sample(1:5, 10, replace=T), 
  grp = as.character(sample(1:3, 10, replace=T)) # For convenience, specify character type
)

df %>% group_by(grp) %>% 
  summarise_each(.vars = letters[1:4],
                 .funs = c(mean="mean"))
# `summarise_each()` is deprecated.
# Use `summarise_all()`, `summarise_at()` or `summarise_if()` instead.
# To map `funs` over a selection of variables, use `summarise_at()`
# Error: Strings must match column names. Unknown columns: mean

You should change to the following code. The following codes all have the same result.

# summarise_at
df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = names(.)[1:4],
               .funs = c(mean="mean"))

df %>% group_by(grp) %>% 
  summarise_at(.vars = vars(a,b,c,d),
               .funs = c(mean="mean"))

# summarise_all
df %>% group_by(grp) %>% 
  summarise_all(.funs = c(mean="mean"))

# summarise_if
df %>% group_by(grp) %>% 
  summarise_if(.predicate = function(x) is.numeric(x),
               .funs = funs(mean="mean"))
# A tibble: 3 x 5
# grp a_mean b_mean c_mean d_mean
# <chr>  <dbl>  <dbl>  <dbl>  <dbl>
# 1     1   2.80   3.00    3.6   3.00
# 2     2   4.25   2.75    4.0   3.75
# 3     3   3.00   5.00    1.0   2.00

You can also have multiple functions.

df %>% group_by(grp) %>% 
  summarise_at(.vars = letters[1:2],
               .funs = c(Mean="mean", Sd="sd"))
# A tibble: 3 x 5
# grp a_Mean b_Mean      a_Sd     b_Sd
# <chr>  <dbl>  <dbl>     <dbl>    <dbl>
# 1     1   2.80   3.00 1.4832397 1.870829
# 2     2   4.25   2.75 0.9574271 1.258306
# 3     3   3.00   5.00        NA       NA

Is there a command to list all Unix group names?

On Linux, macOS and Unix to display the groups to which you belong, use:

id -Gn

which is equivalent to groups utility which has been obsoleted on Unix (as per Unix manual).

On macOS and Unix, the command id -p is suggested for normal interactive.

Explanation of the parameters:

-G, --groups - print all group IDs

-n, --name - print a name instead of a number, for -ugG

-p - Make the output human-readable.

How can I read a whole file into a string variable

Use ioutil.ReadFile:

func ReadFile(filename string) ([]byte, error)

ReadFile reads the file named by filename and returns the contents. A successful call returns err == nil, not err == EOF. Because ReadFile reads the whole file, it does not treat an EOF from Read as an error to be reported.

You will get a []byte instead of a string. It can be converted if really necessary:

s := string(buf)

Is Java RegEx case-insensitive?

RegexBuddy is telling me if you want to include it at the beginning, this is the correct syntax:

"(?i)\\b(\\w+)\\b(\\s+\\1)+\\b"

What is the most efficient way to store tags in a database?

One item is going to have many tags. And one tag will belong to many items. This implies to me that you'll quite possibly need an intermediary table to overcome the many-to-many obstacle.

Something like:

Table: Items
Columns: Item_ID, Item_Title, Content

Table: Tags
Columns: Tag_ID, Tag_Title

Table: Items_Tags
Columns: Item_ID, Tag_ID

It might be that your web app is very very popular and need de-normalizing down the road, but it's pointless muddying the waters too early.

Label encoding across multiple columns in scikit-learn

Mainly used @Alexander answer but had to make some changes -

cols_need_mapped = ['col1', 'col2']

mapper = {col: {cat: n for n, cat in enumerate(df[col].astype('category').cat.categories)} 
     for col in df[cols_need_mapped]}

for c in cols_need_mapped :
    df[c] = df[c].map(mapper[c])

Then to re-use in the future you can just save the output to a json document and when you need it you read it in and use the .map() function like I did above.

select2 onchange event only works once

Apparently the change event is not fired if a selection already exists when using data. I ended up updating the data manually on select to resolve the problem.

$("#search_code").on("select2-selecting", function(e) {
    $("#search_code").select2("data",e.choice);
});

I know this is pretty late but hopefully this answer will save others time.

Restart android machine

adb reboot should not reboot your linux box.

But in any case, you can redirect the command to a specific adb device using adb -s <device_id> command , where

Device ID can be obtained from the command adb devices
command in this case is reboot

Apply jQuery datepicker to multiple instances

I just had the same problem.

The correct way to use date pick is $('.my_class').datepicker(); but you need to make sure you don't assign the same ID to multiple datepickers.

error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup

try using return 0;

if it keeps failing change your solution platform to 64x instead of 86x and go to configuration manager(that's were you change the 86x to 64x) and in platform set it to 64 bits

that works for me, hope it work to you

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

Here is the solution I found:

How to fix the missing MSVCR711.dll problem

You can find MSVCR71.dll file in following location of your installed SQL Developer 2.1 directory:

sqldeveloper-2.1.0.63.10\sqldeveloper\jdk\jre\bin\MSVCR71.dll

Only allow specific characters in textbox

As mentioned in a comment (and another answer as I typed) you need to register an event handler to catch the keydown or keypress event on a text box. This is because TextChanged is only fired when the TextBox loses focus

The below regex lets you match those characters you want to allow

Regex regex = new Regex(@"[0-9+\-\/\*\(\)]");
MatchCollection matches = regex.Matches(textValue);

and this does the opposite and catches characters that aren't allowed

Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
MatchCollection matches = regex.Matches(textValue);

I'm not assuming there'll be a single match as someone could paste text into the textbox. in which case catch textchanged

textBox1.TextChanged += new TextChangedEventHandler(textBox1_TextChanged);
private void textBox1_TextChanged(object sender, EventArgs e)
{
    Regex regex = new Regex(@"[^0-9^+^\-^\/^\*^\(^\)]");
    MatchCollection matches = regex.Matches(textBox1.Text);
    if (matches.Count > 0) {
       //tell the user
    }
}

and to validate single key presses

textBox1.KeyPress += new KeyPressEventHandler(textBox1_KeyPress);
private void textBox1_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
{
    // Check for a naughty character in the KeyDown event.
    if (System.Text.RegularExpressions.Regex.IsMatch(e.KeyChar.ToString(), @"[^0-9^+^\-^\/^\*^\(^\)]"))
    {
        // Stop the character from being entered into the control since it is illegal.
        e.Handled = true;
    }
}

Android emulator failed to allocate memory 8

Try this if other answers did not work for you.

For me This happened for API 27 Emulator.

API 26 Emulator worked just fine. So I started API 26 Emulator first and then closed it.

Then I started API 27 Emulator and It worked with No errors at all.

Programmatically change input type of the EditText from PASSWORD to NORMAL & vice versa

use this code to change password to text and vice versa

mCbShowPwd.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                // checkbox status is changed from uncheck to checked.
                if (!isChecked) {
                        // hide password
                    mEtPwd.setTransformationMethod(PasswordTransformationMethod.getInstance());
                } else {
                        // show password
                    mEtPwd.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
                }
            }
        });

for full sample code refer http://www.codeproject.com/Tips/518641/Show-hide-password-in-a-edit-text-view-password-ty

Do conditional INSERT with SQL?

If you're looking to do an "upsert" one of the most efficient ways currently in SQL Server for single rows is this:

UPDATE myTable ...


IF @@ROWCOUNT=0
    INSERT INTO myTable ....

You can also use the MERGE syntax if you're doing this with sets of data rather than single rows.

If you want to INSERT and not UPDATE then you can just write your single INSERT statement and use WHERE NOT EXISTS (SELECT ...)

How to get 2 digit year w/ Javascript?

The specific answer to this question is found in this one line below:

_x000D_
_x000D_
//pull the last two digits of the year_x000D_
//logs to console_x000D_
//creates a new date object (has the current date and time by default)_x000D_
//gets the full year from the date object (currently 2017)_x000D_
//converts the variable to a string_x000D_
//gets the substring backwards by 2 characters (last two characters)    _x000D_
console.log(new Date().getFullYear().toString().substr(-2));
_x000D_
_x000D_
_x000D_

Formatting Full Date Time Example (MMddyy): jsFiddle

JavaScript:

_x000D_
_x000D_
//A function for formatting a date to MMddyy_x000D_
function formatDate(d)_x000D_
{_x000D_
    //get the month_x000D_
    var month = d.getMonth();_x000D_
    //get the day_x000D_
    //convert day to string_x000D_
    var day = d.getDate().toString();_x000D_
    //get the year_x000D_
    var year = d.getFullYear();_x000D_
    _x000D_
    //pull the last two digits of the year_x000D_
    year = year.toString().substr(-2);_x000D_
    _x000D_
    //increment month by 1 since it is 0 indexed_x000D_
    //converts month to a string_x000D_
    month = (month + 1).toString();_x000D_
_x000D_
    //if month is 1-9 pad right with a 0 for two digits_x000D_
    if (month.length === 1)_x000D_
    {_x000D_
        month = "0" + month;_x000D_
    }_x000D_
_x000D_
    //if day is between 1-9 pad right with a 0 for two digits_x000D_
    if (day.length === 1)_x000D_
    {_x000D_
        day = "0" + day;_x000D_
    }_x000D_
_x000D_
    //return the string "MMddyy"_x000D_
    return month + day + year;_x000D_
}_x000D_
_x000D_
var d = new Date();_x000D_
console.log(formatDate(d));
_x000D_
_x000D_
_x000D_

Setting TIME_WAIT TCP

TIME_WAIT might not be the culprit.

int listen(int sockfd, int backlog);

According to Unix Network Programming Volume1, backlog is defined to be the sum of completed connection queue and incomplete connection queue.

Let's say the backlog is 5. If you have 3 completed connections (ESTABLISHED state), and 2 incomplete connections (SYN_RCVD state), and there is another connect request with SYN. The TCP stack just ignores the SYN packet, knowing it'll be retransmitted some other time. This might be causing the degradation.

At least that's what I've been reading. ;)

How to pass all arguments passed to my bash script to a function of mine?

abc "$@" is generally the correct answer. But I was trying to pass a parameter through to an su command, and no amount of quoting could stop the error su: unrecognized option '--myoption'. What actually worked for me was passing all the arguments as a single string :

abc "$*"

My exact case (I'm sure someone else needs this) was in my .bashrc

# run all aws commands as Jenkins user
aws ()
{
    sudo su jenkins -c "aws $*"
}

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

Can I get JSON to load into an OrderedDict?

In addition to dumping the ordered list of keys alongside the dictionary, another low-tech solution, which has the advantage of being explicit, is to dump the (ordered) list of key-value pairs ordered_dict.items(); loading is a simple OrderedDict(<list of key-value pairs>). This handles an ordered dictionary despite the fact that JSON does not have this concept (JSON dictionaries have no order).

It is indeed nice to take advantage of the fact that json dumps the OrderedDict in the correct order. However, it is in general unnecessarily heavy and not necessarily meaningful to have to read all JSON dictionaries as an OrderedDict (through the object_pairs_hook argument), so an explicit conversion of only the dictionaries that must be ordered makes sense too.

What are the rules for calling the superclass constructor?

In C++ there is a concept of constructor's initialization list, which is where you can and should call the base class' constructor and where you should also initialize the data members. The initialization list comes after the constructor signature following a colon, and before the body of the constructor. Let's say we have a class A:


class A : public B
{
public:
  A(int a, int b, int c);
private:
  int b_, c_;
};

Then, assuming B has a constructor which takes an int, A's constructor may look like this:


A::A(int a, int b, int c) 
  : B(a), b_(b), c_(c) // initialization list
{
  // do something
}

As you can see, the constructor of the base class is called in the initialization list. Initializing the data members in the initialization list, by the way, is preferable to assigning the values for b_, and c_ inside the body of the constructor, because you are saving the extra cost of assignment.

Keep in mind, that data members are always initialized in the order in which they are declared in the class definition, regardless of their order in the initialization list. To avoid strange bugs, which may arise if your data members depend on each other, you should always make sure that the order of the members is the same in the initialization list and the class definition. For the same reason the base class constructor must be the first item in the initialization list. If you omit it altogether, then the default constructor for the base class will be called automatically. In that case, if the base class does not have a default constructor, you will get a compiler error.

Python 2,3 Convert Integer to "bytes" Cleanly

from int to byte:

bytes_string = int_v.to_bytes( lenth, endian )

where the lenth is 1/2/3/4...., and endian could be 'big' or 'little'

form bytes to int:

data_list = list( bytes );

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

document.getElementsByClassName returns a NodeList, not a single element, I'd recommend either using jQuery, since you'd only have to use something like $('.new').toggle()

or if you want plain JS try :

function toggle_by_class(cls, on) {
    var lst = document.getElementsByClassName(cls);
    for(var i = 0; i < lst.length; ++i) {
        lst[i].style.display = on ? '' : 'none';
    }
}

What is 'PermSize' in Java?

A quick definition of the "permanent generation":

"The permanent generation is used to hold reflective data of the VM itself such as class objects and method objects. These reflective objects are allocated directly into the permanent generation, and it is sized independently from the other generations." [ref]

In other words, this is where class definitions go (and this explains why you may get the message OutOfMemoryError: PermGen space if an application loads a large number of classes and/or on redeployment).

Note that PermSize is additional to the -Xmx value set by the user on the JVM options. But MaxPermSize allows for the JVM to be able to grow the PermSize to the amount specified. Initially when the VM is loaded, the MaxPermSize will still be the default value (32mb for -client and 64mb for -server) but will not actually take up that amount until it is needed. On the other hand, if you were to set BOTH PermSize and MaxPermSize to 256mb, you would notice that the overall heap has increased by 256mb additional to the -Xmx setting.

How to avoid pressing Enter with getchar() for reading a single character only?

By default, the C library buffers the output until it sees a return. To print out the results immediately, use fflush:

while((c=getchar())!= EOF)      
{
    putchar(c);
    fflush(stdout);
}

Redirect stderr to stdout in C shell

What about just

xxx >& /dev/stdout

???

What is the usefulness of PUT and DELETE HTTP request methods?

Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times

According to your requirement :

1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD

What is the difference between POST and GET?

A POST, unlike a GET, typically has relevant information in the body of the request. (A GET should not have a body, so aside from cookies, the only place to pass info is in the URL.) Besides keeping the URL relatively cleaner, POST also lets you send much more information (as URLs are limited in length, for all practical purposes), and lets you send just about any type of data (file upload forms, for example, can't use GET -- they have to use POST plus a special content type/encoding).

Aside from that, a POST connotes that the request will change something, and shouldn't be redone willy-nilly. That's why you sometimes see your browser asking you if you want to resubmit form data when you hit the "back" button.

GET, on the other hand, should be idempotent -- meaning you could do it a million times and the server will do the same thing (and show basically the same result) each and every time.

Java Inheritance - calling superclass method

It is possible to use super to call the method from mother class, but this would mean you probably have a design problem. Maybe B.alphaMethod1() shouldn't override A's method and be called B.betaMethod1().

If it depends on the situation, you can put some code logic like :

public void alphaMethod1(){
    if (something) {
        super.alphaMethod1();
        return;
    }
    // Rest of the code for other situations
}

Like this it will only call A's method when needed and will remain invisible for the class user.

HashMap allows duplicates?

HashMap don't allow duplicate keys,but since it's not thread safe,it might occur duplicate keys. eg:

 while (true) {
            final HashMap<Object, Object> map = new HashMap<Object, Object>(2);
            map.put("runTimeType", 1);
            map.put("title", 2);
            map.put("params", 3);
            final AtomicInteger invokeCounter = new AtomicInteger();

            for (int i = 0; i < 100; i++) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        map.put("formType", invokeCounter.incrementAndGet());
                    }
                }).start();
            }
            while (invokeCounter.intValue() != 100) {
                Thread.sleep(10);
            }
            if (map.size() > 4) {
// this means you insert two or more formType key to the map
               System.out.println( JSONObject.fromObject(map));
            }
        }

Android app unable to start activity componentinfo

Your null pointer exception seems to be on this line:

String url = intent.getExtras().getString("userurl");

because intent.getExtras() returns null when the intent doesn't have any extras.

You have to realize that this piece of code:

Intent Main = new Intent(this, ToClass.class);
Main.putExtra("userurl", url);
startActivity(Main);

doesn't start the activity you wrote in Main.java, it will attempt to start an activity called ToClass and if that doesn't exist, your app crashes.

Also, there is no such thing as "android.intent.action.start" so the manifest should look more like:

<activity android:name=".start" android:label="@string/app_name">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>
<activity android:name= ".Main">
</activity>

I hope this fixes some of the issues you are encountering but I strongly suggest you check out some "getting started" tutorials for android development and build up from there.

Format ints into string of hex

Similar to my other answer, except repeating the format string:

>>> numbers = [1, 15, 255]
>>> fmt = '{:02X}' * len(numbers)
>>> fmt.format(*numbers)
'010FFF'

'float' vs. 'double' precision

float : 23 bits of significand, 8 bits of exponent, and 1 sign bit.

double : 52 bits of significand, 11 bits of exponent, and 1 sign bit.

Two models in one view in ASP MVC 3

In fact there is a way to use two or more models on one view without wrapping them in a class that contains both.

Using Employee as an example model:

@model Employee

Is actually treated like.

@{ var Model = ViewBag.model as Employee; }

So the View(employee) method is setting your model to the ViewBag and then the ViewEngine is casting it.

This means that,

ViewBag.departments = GetListOfDepartments();
    return View(employee);

Can be used like,

            @model  Employee
        @{
                var DepartmentModel = ViewBag.departments as List<Department>;
        }

Essentially, you can use whatever is in your ViewBag as a "Model" because that's how it works anyway. I'm not saying that this is architecturally ideal, but it is possible.

JavaScript Chart.js - Custom data formatting to display on tooltip

You want to specify a custom tooltip template in your chart options, like this :

 // String - Template string for single tooltips
 tooltipTemplate: "<%if (label){%><%=label %>: <%}%><%= value + ' %' %>",
 // String - Template string for multiple tooltips
 multiTooltipTemplate: "<%= value + ' %' %>",

This way you can add a '%' sign after your values if that's what you want.

Here's a jsfiddle to illustrate this.

Note that tooltipTemplate applies if you only have one dataset, multiTooltipTemplate applies if you have several datasets.

This options are mentioned in the global chart configuration section of the documentation. Do have a look, it's worth checking for all the other options that can be customized in there.

Note that Your datasets should only contain numeric values. (No % signs or other stuff there).

Load resources from relative path using local html in uiwebview

Swift answer 2.

The UIWebView Class Reference advises against using webView.loadRequest(request):

Don’t use this method to load local HTML files; instead, use loadHTMLString:baseURL:.

In this solution, the html is read into a string. The html's url is used to work out the path, and passes that as a base url.

let url = bundle.URLForResource("index", withExtension: "html", subdirectory: "htmlFileFolder")
let html = try String(contentsOfURL: url)
let base = url.URLByDeletingLastPathComponent
webView.loadHTMLString(html, baseURL: base)

java.io.IOException: Invalid Keystore format

go to build clean the project then rebuild your project it worked for me.

Named parameters in JDBC

Plain vanilla JDBC does not support named parameters.

If you are using DB2 then using DB2 classes directly:

  1. Using named parameter markers with PreparedStatement objects
  2. Using named parameter markers with CallableStatement objects

Select distinct values from a list using LINQ in C#

You can use GroupBy with anonymous type, and then get First:

list.GroupBy(e => new { 
                          empLoc = e.empLoc, 
                          empPL = e.empPL, 
                          empShift = e.empShift 
                       })

    .Select(g => g.First());

How can I get the active screen dimensions?

Adding a solution that doesn't use WinForms but NativeMethods instead. First you need to define the native methods needed.

public static class NativeMethods
{
    public const Int32 MONITOR_DEFAULTTOPRIMERTY = 0x00000001;
    public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;


    [DllImport( "user32.dll" )]
    public static extern IntPtr MonitorFromWindow( IntPtr handle, Int32 flags );


    [DllImport( "user32.dll" )]
    public static extern Boolean GetMonitorInfo( IntPtr hMonitor, NativeMonitorInfo lpmi );


    [Serializable, StructLayout( LayoutKind.Sequential )]
    public struct NativeRectangle
    {
        public Int32 Left;
        public Int32 Top;
        public Int32 Right;
        public Int32 Bottom;


        public NativeRectangle( Int32 left, Int32 top, Int32 right, Int32 bottom )
        {
            this.Left = left;
            this.Top = top;
            this.Right = right;
            this.Bottom = bottom;
        }
    }


    [StructLayout( LayoutKind.Sequential, CharSet = CharSet.Auto )]
    public sealed class NativeMonitorInfo
    {
        public Int32 Size = Marshal.SizeOf( typeof( NativeMonitorInfo ) );
        public NativeRectangle Monitor;
        public NativeRectangle Work;
        public Int32 Flags;
    }
}

And then get the monitor handle and the monitor info like this.

        var hwnd = new WindowInteropHelper( this ).EnsureHandle();
        var monitor = NativeMethods.MonitorFromWindow( hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST );

        if ( monitor != IntPtr.Zero )
        {
            var monitorInfo = new NativeMonitorInfo();
            NativeMethods.GetMonitorInfo( monitor, monitorInfo );

            var left = monitorInfo.Monitor.Left;
            var top = monitorInfo.Monitor.Top;
            var width = ( monitorInfo.Monitor.Right - monitorInfo.Monitor.Left );
            var height = ( monitorInfo.Monitor.Bottom - monitorInfo.Monitor.Top );
        }

PHP 7 simpleXML

my experience

  1. get your php version

    php --version

  2. Instal package for your php version

    sudo apt-get install php7.4-xml

  3. Restart apache

    sudo systemctl reload apache2

Getting the name of a variable as a string

You can try the following to retrieve the name of a function you defined (does not work for built-in functions though):

import re
def retrieve_name(func):
    return re.match("<function\s+(\w+)\s+at.*", str(func)).group(1)

def foo(x):
    return x**2

print(retrieve_name(foo))
# foo

Oracle SQL query for Date format

if you are using same date format and have select query where date in oracle :

   select count(id) from Table_name where TO_DATE(Column_date)='07-OCT-2015';

To_DATE provided by oracle

drag drop files into standard html file input

This is the "DTHML" HTML5 way to do it. Normal form input (which IS read only as Ricardo Tomasi pointed out). Then if a file is dragged in, it is attached to the form. This WILL require modification to the action page to accept the file uploaded this way.

_x000D_
_x000D_
function readfiles(files) {_x000D_
  for (var i = 0; i < files.length; i++) {_x000D_
    document.getElementById('fileDragName').value = files[i].name_x000D_
    document.getElementById('fileDragSize').value = files[i].size_x000D_
    document.getElementById('fileDragType').value = files[i].type_x000D_
    reader = new FileReader();_x000D_
    reader.onload = function(event) {_x000D_
      document.getElementById('fileDragData').value = event.target.result;}_x000D_
    reader.readAsDataURL(files[i]);_x000D_
  }_x000D_
}_x000D_
var holder = document.getElementById('holder');_x000D_
holder.ondragover = function () { this.className = 'hover'; return false; };_x000D_
holder.ondragend = function () { this.className = ''; return false; };_x000D_
holder.ondrop = function (e) {_x000D_
  this.className = '';_x000D_
  e.preventDefault();_x000D_
  readfiles(e.dataTransfer.files);_x000D_
}
_x000D_
#holder.hover { border: 10px dashed #0c0 !important; }
_x000D_
<form method="post" action="http://example.com/">_x000D_
  <input type="file"><input id="fileDragName"><input id="fileDragSize"><input id="fileDragType"><input id="fileDragData">_x000D_
  <div id="holder" style="width:200px; height:200px; border: 10px dashed #ccc"></div>_x000D_
</form>
_x000D_
_x000D_
_x000D_

It is even more boss if you can make the whole window a drop zone, see How do I detect a HTML5 drag event entering and leaving the window, like Gmail does?

What are differences between AssemblyVersion, AssemblyFileVersion and AssemblyInformationalVersion?

AssemblyVersion

Where other assemblies that reference your assembly will look. If this number changes, other assemblies have to update their references to your assembly! Only update this version, if it breaks backward compatibility. The AssemblyVersion is required.

I use the format: major.minor. This would result in:

[assembly: AssemblyVersion("1.0")]

If you're following SemVer strictly then this means you only update when the major changes, so 1.0, 2.0, 3.0, etc.

AssemblyFileVersion

Used for deployment. You can increase this number for every deployment. It is used by setup programs. Use it to mark assemblies that have the same AssemblyVersion, but are generated from different builds.

In Windows, it can be viewed in the file properties.

The AssemblyFileVersion is optional. If not given, the AssemblyVersion is used.

I use the format: major.minor.patch.build, where I follow SemVer for the first three parts and use the buildnumber of the buildserver for the last part (0 for local build). This would result in:

[assembly: AssemblyFileVersion("1.3.2.254")]

Be aware that System.Version names these parts as major.minor.build.revision!

AssemblyInformationalVersion

The Product version of the assembly. This is the version you would use when talking to customers or for display on your website. This version can be a string, like '1.0 Release Candidate'.

The AssemblyInformationalVersion is optional. If not given, the AssemblyFileVersion is used.

I use the format: major.minor[.patch] [revision as string]. This would result in:

[assembly: AssemblyInformationalVersion("1.0 RC1")]

Passing an array as parameter in JavaScript

JavaScript is a dynamically typed language. This means that you never need to declare the type of a function argument (or any other variable). So, your code will work as long as arrayP is an array and contains elements with a value property.

What's the best way to add a full screen background image in React Native

Since 0.14 this method won't work, so I built a static component that will make this simple for you guys. You can just paste this in or reference it as a component.

This should be re-useable and it will allow you to add additional styles and properties as-if it were a standard <Image /> component

const BackgroundImage = ({ source, children, style, ...props }) => {
  return (
      <Image
        source={source}
        style={{flex: 1, width: null, height: null, ...style}}
        {...props}>
        {children}
      </Image>
  );
}

just paste this in and then you can use it like image and it should fit the entire size of the view it is in (so if it's the top view it will fill your screen.

<BackgroundImage source={require('../../assets/backgrounds/palms.jpg')}>
    <Scene styles={styles} {...store} />
</BackgroundImage>

Click here for a Preview Image

Getting "net::ERR_BLOCKED_BY_CLIENT" error on some AJAX calls

AdBlockers usually have some rules, i.e. they match the URIs against some type of expression (sometimes they also match the DOM against expressions, not that this matters in this case).

Having rules and expressions that just operate on a tiny bit of text (the URI) is prone to create some false-positives...

Besides instructing your users to disable their extensions (at least on your site) you can also get the extension and test which of the rules/expressions blocked your stuff, provided the extension provides enough details about that. Once you identified the culprit, you can either try to avoid triggering the rule by using different URIs, report the rule as incorrect or overly-broad to the team that created it, or both. Check the docs for a particular add-on on how to do that.

For example, AdBlock Plus has a Blockable items view that shows all blocked items on a page and the rules that triggered the block. And those items also including XHR requests.

Blockable items

How to create Select List for Country and States/province in MVC

Thank You All! I am able to to load Select List as per MVC now My Working Code is below:

HTML+MVC Code in View:-

    <tr>
        <th>@Html.Label("Country")</th>
        <td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetCountryList())<span class="required">*</span></td>
    </tr>
    <tr>
        <th>@Html.LabelFor(x=>x.Province)</th>
        <td>@Html.DropDownListFor(x =>x.Province,SelectListItemHelper.GetProvincesList())<span class="required">*</span></td>
    </tr>

Created a Controller under "UTIL" folder: Code:-

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MedAvail.Applications.MedProvision.Web.Util
{
    public class SelectListItemHelper
    {
        public static IEnumerable<SelectListItem> GetProvincesList()
        {
            IList<SelectListItem> items = new List<SelectListItem>
            {
                new SelectListItem{Text = "California", Value = "B"},
                new SelectListItem{Text = "Alaska", Value = "B"},
                new SelectListItem{Text = "Illinois", Value = "B"},
                new SelectListItem{Text = "Texas", Value = "B"},
                new SelectListItem{Text = "Washington", Value = "B"}

            };
            return items;
        }


        public static IEnumerable<SelectListItem> GetCountryList()
        {
            IList<SelectListItem> items = new List<SelectListItem>
            {
                new SelectListItem{Text = "United States", Value = "B"},
                new SelectListItem{Text = "Canada", Value = "B"},
                new SelectListItem{Text = "United Kingdom", Value = "B"},
                new SelectListItem{Text = "Texas", Value = "B"},
                new SelectListItem{Text = "Washington", Value = "B"}

            };
            return items;
        }


    }
}

And its working COOL now :-)

Thank you!!

How do I "decompile" Java class files?

There are a few decompilers out there... A quick search yields:

  1. Procyon: open-source (Apache 2) and actively developed
  2. Krakatau: open-source (GPLv3) and actively developed
  3. CFR: open-source (MIT) and actively developed
  4. JAD
  5. DJ Java Decompiler
  6. Mocha

And many more.

These produce Java code. Java comes with something that lets you see JVM byte code (javap).

How to loop through each and every row, column and cells in a GridView and get its value

The easiest would be using a foreach:

foreach(GridViewRow row in GridView2.Rows)
{
    // here you'll get all rows with RowType=DataRow
    // others like Header are omitted in a foreach
}

Edit: According to your edits, you are accessing the column incorrectly, you should start with 0:

foreach(GridViewRow row in GridView2.Rows)
{
    for(int i = 0; i < GridView2.Columns.Count; i++)
    {
        String header = GridView2.Columns[i].HeaderText;
        String cellText = row.Cells[i].Text;
    }
}

Key value pairs using JSON

var object = {
    key1 : {
        name : 'xxxxxx',
        value : '100.0'
    },
    key2 : {
        name : 'yyyyyyy',
        value : '200.0'
    },
    key3 : {
        name : 'zzzzzz',
        value : '500.0'
    },
}

If thats how your object looks and you want to loop each name and value then I would try and do something like.

$.each(object,function(key,innerjson){
    /*
        key would be key1,key2,key3
        innerjson would be the name and value **
    */

    //Alerts and logging of the variable.
    console.log(innerjson); //should show you the value    
    alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});

Get current index from foreach loop

Use Enumerable.Select<TSource, TResult> Method (IEnumerable<TSource>, Func<TSource, Int32, TResult>)

list = list.Cast<object>().Select( (v, i) => new {Value= v, Index = i});

foreach(var row in list)
{
    bool IsChecked = (bool)((CheckBox)DataGridDetail.Columns[0].GetCellContent(row.Value)).IsChecked;
    row.Index ...
}

jquery ajax get responsetext from http url

As Karim said, cross domain ajax doesn't work unless the server allows for it. In this case Google does not, BUT, there is a simple trick to get around this in many cases. Just have your local server pass the content retrieved through HTTP or HTTPS.

For example, if you were using PHP, you could:

Create the file web_root/ajax_responders/google.php with:

<?php
  echo file_get_contents('http://www.google.de');
?>

And then alter your code to connect to that instead of to Google's domain directly in the javascript:

var response = $.ajax({ type: "GET",   
                        url: "/ajax_responders/google.php",   
                        async: false
                      }).responseText;
alert(response);

Finding first and last index of some value in a list in Python

Perhaps the two most efficient ways to find the last index:

def rindex(lst, value):
    lst.reverse()
    i = lst.index(value)
    lst.reverse()
    return len(lst) - i - 1
def rindex(lst, value):
    return len(lst) - operator.indexOf(reversed(lst), value) - 1

Both take only O(1) extra space and the two in-place reversals of the first solution are much faster than creating a reverse copy. Let's compare it with the other solutions posted previously:

def rindex(lst, value):
    return len(lst) - lst[::-1].index(value) - 1

def rindex(lst, value):
    return len(lst) - next(i for i, val in enumerate(reversed(lst)) if val == value) - 1

Benchmark results, my solutions are the red and green ones: unshuffled, full range

This is for searching a number in a list of a million numbers. The x-axis is for the location of the searched element: 0% means it's at the start of the list, 100% means it's at the end of the list. All solutions are fastest at location 100%, with the two reversed solutions taking pretty much no time for that, the double-reverse solution taking a little time, and the reverse-copy taking a lot of time.

A closer look at the right end: unshuffled, tail part

At location 100%, the reverse-copy solution and the double-reverse solution spend all their time on the reversals (index() is instant), so we see that the two in-place reversals are about seven times as fast as creating the reverse copy.

The above was with lst = list(range(1_000_000, 2_000_001)), which pretty much creates the int objects sequentially in memory, which is extremely cache-friendly. Let's do it again after shuffling the list with random.shuffle(lst) (probably less realistic, but interesting):

shuffled list, full range

shuffled list, tail part

All got a lot slower, as expected. The reverse-copy solution suffers the most, at 100% it now takes about 32 times (!) as long as the double-reverse solution. And the enumerate-solution is now second-fastest only after location 98%.

Overall I like the operator.indexOf solution best, as it's the fastest one for the last half or quarter of all locations, which are perhaps the more interesting locations if you're actually doing rindex for something. And it's only a bit slower than the double-reverse solution in earlier locations.

All benchmarks done with CPython 3.9.0 64-bit on Windows 10 Pro 1903 64-bit.

How to get query parameters from URL in Angular 5?

/*
Example below url with two param (type and name) 
URL : http://localhost:4200/updatePolicy?type=Medicare%20Insurance&name=FutrueInsurance
*/ 
  constructor(private route: ActivatedRoute) {
    //Read url query parameter `enter code here`
  this.route.queryParams.subscribe(params => {
    this.name= params['type'];
    this.type= params['name'];
    alert(this.type);
    alert(this.name);

 });

  }

Python List & for-each access (Find/Replace in built-in list)

Python is not Java, nor C/C++ -- you need to stop thinking that way to really utilize the power of Python.

Python does not have pass-by-value, nor pass-by-reference, but instead uses pass-by-name (or pass-by-object) -- in other words, nearly everything is bound to a name that you can then use (the two obvious exceptions being tuple- and list-indexing).

When you do spam = "green", you have bound the name spam to the string object "green"; if you then do eggs = spam you have not copied anything, you have not made reference pointers; you have simply bound another name, eggs, to the same object ("green" in this case). If you then bind spam to something else (spam = 3.14159) eggs will still be bound to "green".

When a for-loop executes, it takes the name you give it, and binds it in turn to each object in the iterable while running the loop; when you call a function, it takes the names in the function header and binds them to the arguments passed; reassigning a name is actually rebinding a name (it can take a while to absorb this -- it did for me, anyway).

With for-loops utilizing lists, there are two basic ways to assign back to the list:

for i, item in enumerate(some_list):
    some_list[i] = process(item)

or

new_list = []
for item in some_list:
    new_list.append(process(item))
some_list[:] = new_list

Notice the [:] on that last some_list -- it is causing a mutation of some_list's elements (setting the entire thing to new_list's elements) instead of rebinding the name some_list to new_list. Is this important? It depends! If you have other names besides some_list bound to the same list object, and you want them to see the updates, then you need to use the slicing method; if you don't, or if you do not want them to see the updates, then rebind -- some_list = new_list.

'import' and 'export' may only appear at the top level

I got this error when I was missing a closing bracket.

Simplified recreation:

const foo = () => {
  return (
    'bar'
  );
}; <== this bracket was missing

export default foo;

How can I specify working directory for popen

subprocess.Popen takes a cwd argument to set the Current Working Directory; you'll also want to escape your backslashes ('d:\\test\\local'), or use r'd:\test\local' so that the backslashes aren't interpreted as escape sequences by Python. The way you have it written, the \t part will be translated to a tab.

So, your new line should look like:

subprocess.Popen(r'c:\mytool\tool.exe', cwd=r'd:\test\local')

To use your Python script path as cwd, import os and define cwd using this:

os.path.dirname(os.path.realpath(__file__)) 

Change the maximum upload file size

If you edited the right php.ini file, restarted Apache or Nginx and still doesn't work, then you have to restart php-fpm too:

sudo service php-fpm restart 

Changing the action of a form with JavaScript/jQuery

Use Java script to change action url dynamically Works for me well

function chgAction( action_name )
{

 {% for data in sidebar_menu_data %}

     if( action_name== "ABC"){ document.forms.action = "/ABC/";
     }
     else if( action_name== "XYZ"){ document.forms.action = "/XYZ/";
     }

}

<form name="forms" method="post" action="<put default url>" onSubmit="return checkForm(this);">{% csrf_token %} 

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

As mobrule indicates, you could use the following instead for a small savings:

if (defined $name && $name ne '') {
    # do something with $name
}

You could ditch the defined check and get something even shorter, e.g.:

if ($name ne '') {
    # do something with $name
}

But in the case where $name is not defined, although the logic flow will work just as intended, if you are using warnings (and you should be), then you'll get the following admonishment:

Use of uninitialized value in string ne

So, if there's a chance that $name might not be defined, you really do need to check for definedness first and foremost in order to avoid that warning. As Sinan Ünür points out, you can use Scalar::MoreUtils to get code that does exactly that (checks for definedness, then checks for zero length) out of the box, via the empty() method:

use Scalar::MoreUtils qw(empty);
if(not empty($name)) {
    # do something with $name 
}

Highcharts - how to have a chart with dynamic height?

When using percentage, the height it relative to the width and will dynamically change along with it:

chart: {
    height: (9 / 16 * 100) + '%' // 16:9 ratio
},

JSFiddle Highcharts with percentage height

How do I make a WinForms app go Full Screen

On the Form Move Event add this:

private void Frm_Move (object sender, EventArgs e)
{
    Top = 0; Left = 0;
    Size = new System.Drawing.Size(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
}

Prevent PDF file from downloading and printing

If you encrypt the PDF you can control how printable and changeable it is.

Print settings:

  1. None
  2. Low res (150 dpi)
  3. high res (max dpi)

You can also prevent folks from copying/pasting from your PDF, and even do that while allowing screen readers access (visually impaired folks can still read your PDFs).

You haven't mentioned what you're using to build the PDFs so the details are up to you.

Alternative: You can create annotations that are only visible when printing. Create a solid box over the entire page that only shows up when printed -> No useful printing.

You might be able to do the same thing with layers (Optional Content Groups) as well, not sure.

How to run an awk commands in Windows?

Quoting is an issue if you're running awk from the command line. You'll sometimes need to use \, e.g. to quote ", but most of the time you'll use ^:

w:\srv>dir | grep ".txt" | awk "{ printf(\"echo %s@%s ^> %s.tstamp^\n\", $1, $2, $4); }"
echo 2014-09-07@22:21 > requirements-dev.txt.tstamp
echo 2014-11-28@18:14 > syncspec.txt.tstamp

Click in OK button inside an Alert (Selenium IDE)

Try Selenium 2.0b1. It has different core than the first version. It should support popup dialogs according to documentation:

Popup Dialogs

Starting with Selenium 2.0 beta 1, there is built in support for handling popup dialog boxes. After you’ve triggered and action that would open a popup, you can access the alert with the following:

Java

Alert alert = driver.switchTo().alert();

Ruby

driver.switch_to.alert

This will return the currently open alert object. With this object you can now accept, dismiss, read it’s contents or even type into a prompt. This interface works equally well on alerts, confirms, prompts. Refer to the JavaDocs for more information.

What are the performance characteristics of sqlite with very large database files?

Much of the reason that it took > 48 hours to do your inserts is because of your indexes. It is incredibly faster to:

1 - Drop all indexes 2 - Do all inserts 3 - Create indexes again

Pandas: rolling mean by time interval

To keep it basic, I used a loop and something like this to get you started (my index are datetimes):

import pandas as pd
import datetime as dt

#populate your dataframe: "df"
#...

df[df.index<(df.index[0]+dt.timedelta(hours=1))] #gives you a slice. you can then take .sum() .mean(), whatever

and then you can run functions on that slice. You can see how adding an iterator to make the start of the window something other than the first value in your dataframes index would then roll the window (you could use a > rule for the start as well for example).

Note, this may be less efficient for SUPER large data or very small increments as your slicing may become more strenuous (works for me well enough for hundreds of thousands of rows of data and several columns though for hourly windows across a few weeks)

Windows batch script launch program and exit console

start "" ExeToExecute

method does not work for me in the case of Xilinx xsdk, because as pointed out by @jeb in the comments below it is actaully a bat file.

so what does not work de-facto is

start "" BatToExecute

I am trying to open xsdk like that and it opens a separate cmd that needs to be closed and xsdk can run on its own

Before launching xsdk I run (source) the Env / Paths (with settings64.bat) so that xsdk.bat command gets recognized (simply as xsdk, withoitu the .bat)

what works with .bat

call BatToExecute

Take a char input from the Scanner

you just need to write this for getting value in char type.

char c = reader.next().charAt(0);

Python Function to test ping

Try this

def ping(server='example.com', count=1, wait_sec=1):
    """

    :rtype: dict or None
    """
    cmd = "ping -c {} -W {} {}".format(count, wait_sec, server).split(' ')
    try:
        output = subprocess.check_output(cmd).decode().strip()
        lines = output.split("\n")
        total = lines[-2].split(',')[3].split()[1]
        loss = lines[-2].split(',')[2].split()[0]
        timing = lines[-1].split()[3].split('/')
        return {
            'type': 'rtt',
            'min': timing[0],
            'avg': timing[1],
            'max': timing[2],
            'mdev': timing[3],
            'total': total,
            'loss': loss,
        }
    except Exception as e:
        print(e)
        return None

JavaScript query string

If you have the querystring on hand, use this:

 /**
 * @param qry the querystring
 * @param name name of parameter
 * @returns the parameter specified by name
 * @author [email protected]
 */

function getQueryStringParameter(qry,name){
    if(typeof qry !== undefined && qry !== ""){
        var keyValueArray = qry.split("&");
        for ( var i = 0; i < keyValueArray.length; i++) {
            if(keyValueArray[i].indexOf(name)>-1){
                return keyValueArray[i].split("=")[1];
            }
        }
    }
    return "";
}

Multiple definition of ... linker error

Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)

Table row and column number in jQuery

$('td').click(function() {
    var myCol = $(this).index();
    var $tr = $(this).closest('tr');
    var myRow = $tr.index();
});

Pandas column of lists, create a row for each list element

Trying to work through Roman Pekar's solution step-by-step to understand it better, I came up with my own solution, which uses melt to avoid some of the confusing stacking and index resetting. I can't say that it's obviously a clearer solution though:

items_as_cols = df.apply(lambda x: pd.Series(x['samples']), axis=1)
# Keep original df index as a column so it's retained after melt
items_as_cols['orig_index'] = items_as_cols.index

melted_items = pd.melt(items_as_cols, id_vars='orig_index', 
                       var_name='sample_num', value_name='sample')
melted_items.set_index('orig_index', inplace=True)

df.merge(melted_items, left_index=True, right_index=True)

Output (obviously we can drop the original samples column now):

                 samples  subject  trial_num sample_num  sample
0    [1.84, 1.05, -0.66]        1          1          0    1.84
0    [1.84, 1.05, -0.66]        1          1          1    1.05
0    [1.84, 1.05, -0.66]        1          1          2   -0.66
1    [-0.24, -0.9, 0.65]        1          2          0   -0.24
1    [-0.24, -0.9, 0.65]        1          2          1   -0.90
1    [-0.24, -0.9, 0.65]        1          2          2    0.65
2    [1.15, -0.87, -1.1]        1          3          0    1.15
2    [1.15, -0.87, -1.1]        1          3          1   -0.87
2    [1.15, -0.87, -1.1]        1          3          2   -1.10
3   [-0.8, -0.62, -0.68]        2          1          0   -0.80
3   [-0.8, -0.62, -0.68]        2          1          1   -0.62
3   [-0.8, -0.62, -0.68]        2          1          2   -0.68
4    [0.91, -0.47, 1.43]        2          2          0    0.91
4    [0.91, -0.47, 1.43]        2          2          1   -0.47
4    [0.91, -0.47, 1.43]        2          2          2    1.43
5  [-1.14, -0.24, -0.91]        2          3          0   -1.14
5  [-1.14, -0.24, -0.91]        2          3          1   -0.24
5  [-1.14, -0.24, -0.91]        2          3          2   -0.91

What's the difference between a Python module and a Python package?

First, keep in mind that, in its precise definition, a module is an object in the memory of a Python interpreter, often created by reading one or more files from disk. While we may informally call a disk file such as a/b/c.py a "module," it doesn't actually become one until it's combined with information from several other sources (such as sys.path) to create the module object.

(Note, for example, that two modules with different names can be loaded from the same file, depending on sys.path and other settings. This is exactly what happens with python -m my.module followed by an import my.module in the interpreter; there will be two module objects, __main__ and my.module, both created from the same file on disk, my/module.py.)

A package is a module that may have submodules (including subpackages). Not all modules can do this. As an example, create a small module hierarchy:

$ mkdir -p a/b
$ touch a/b/c.py

Ensure that there are no other files under a. Start a Python 3.4 or later interpreter (e.g., with python3 -i) and examine the results of the following statements:

import a
a                ? <module 'a' (namespace)>
a.b              ? AttributeError: module 'a' has no attribute 'b'
import a.b.c
a.b              ? <module 'a.b' (namespace)>
a.b.c            ? <module 'a.b.c' from '/home/cjs/a/b/c.py'>

Modules a and a.b are packages (in fact, a certain kind of package called a "namespace package," though we wont' worry about that here). However, module a.b.c is not a package. We can demonstrate this by adding another file, a/b.py to the directory structure above and starting a fresh interpreter:

import a.b.c
? ImportError: No module named 'a.b.c'; 'a.b' is not a package
import a.b
a                ? <module 'a' (namespace)>
a.__path__       ? _NamespacePath(['/.../a'])
a.b              ? <module 'a.b' from '/home/cjs/tmp/a/b.py'>
a.b.__path__     ? AttributeError: 'module' object has no attribute '__path__'

Python ensures that all parent modules are loaded before a child module is loaded. Above it finds that a/ is a directory, and so creates a namespace package a, and that a/b.py is a Python source file which it loads and uses to create a (non-package) module a.b. At this point you cannot have a module a.b.c because a.b is not a package, and thus cannot have submodules.

You can also see here that the package module a has a __path__ attribute (packages must have this) but the non-package module a.b does not.

How stable is the git plugin for eclipse?

There is also gitclipse(based on JavaGit), but seems dead.

Lookup City and State by Zip Google Geocode Api

function getCityState($zip, $blnUSA = true) {
    $url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";

    $address_info = file_get_contents($url);
    $json = json_decode($address_info);
    $city = "";
    $state = "";
    $country = "";
    if (count($json->results) > 0) {
        //break up the components
        $arrComponents = $json->results[0]->address_components;

        foreach($arrComponents as $index=>$component) {
            $type = $component->types[0];

            if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
                $city = trim($component->short_name);
            }
            if ($state == "" && $type=="administrative_area_level_1") {
                $state = trim($component->short_name);
            }
            if ($country == "" && $type=="country") {
                $country = trim($component->short_name);

                if ($blnUSA && $country!="US") {
                    $city = "";
                    $state = "";
                    break;
                }
            }
            if ($city != "" && $state != "" && $country != "") {
                //we're done
                break;
            }
        }
    }
    $arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);

    die(json_encode($arrReturn));
}

How do I convert from int to String?

Personally I think that "" + i does look as the original question poster states "smelly". I have used a lot of OO languages besides Java. If that syntax was intended to be appropriate then Java would just interpret the i alone without needing the "" as desired to be converted to a string and do it since the destination type is unambiguous and only a single value would be being supplied on the right. The other seems like a 'trick" to fool the compiler, bad mojo when different versions of Javac made by other manufacturers or from other platforms are considered if the code ever needs to be ported. Heck for my money it should like many other OOL's just take a Typecast: (String) i. winks

Given my way of learning and for ease of understanding such a construct when reading others code quickly I vote for the Integer.toString(i) method. Forgetting a ns or two in how Java implements things in the background vs. String.valueOf(i) this method feels right to me and says exactly what is happening: I have and Integer and I wish it converted to a String.

A good point made a couple times is perhaps just using StringBuilder up front is a good answer to building Strings mixed of text and ints or other objects since thats what will be used in the background anyways right?

Just my two cents thrown into the already well paid kitty of the answers to the Mans question... smiles

EDIT TO MY OWN ANSWER AFTER SOME REFLECTION:

Ok, Ok, I was thinking on this some more and String.valueOf(i) is also perfectly good as well it says: I want a String that represents the value of an Integer. lol, English is by far more difficult to parse then Java! But, I leave the rest of my answer/comment... I was always taught to use the lowest level of a method/function chain if possible and still maintains readablity so if String.valueOf calls Integer.toString then Why use a whole orange if your just gonna peel it anyways, Hmmm?

To clarify my comment about StringBuilder, I build a lot of strings with combos of mostly literal text and int's and they wind up being long and ugly with calls to the above mentioned routines imbedded between the +'s, so seems to me if those become SB objects anyways and the append method has overloads it might be cleaner to just go ahead and use it... So I guess I am up to 5 cents on this one now, eh? lol...

How can I make Bootstrap 4 columns all the same height?

You can use the new Bootstrap cards:

_x000D_
_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js" integrity="sha384-A7FZj7v+d/sdmMqp/nOQwliLvUsJfDHW+k9Omg/a/EheAdgtzNs3hpfag6Ed950n" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>_x000D_
_x000D_
<div class="card-group">_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This content is a little bit longer.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This card has supporting text below as a natural lead-in to additional content.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="card">_x000D_
    <img class="card-img-top" src="..." alt="Card image cap">_x000D_
    <div class="card-block">_x000D_
      <h4 class="card-title">Card title</h4>_x000D_
      <p class="card-text">This is a wider card with supporting text below as a natural lead-in to additional content. This card has even longer content than the first to show that equal height action.</p>_x000D_
    </div>_x000D_
    <div class="card-footer">_x000D_
      <small class="text-muted">Last updated 3 mins ago</small>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Link: Click here

regards,

Get and Set a Single Cookie with Node.js HTTP Server

Using Some ES5/6 Sorcery & RegEx Magic

Here is an option to read the cookies and turn them into an object of Key, Value pairs for client side, could also use it server side.

Note: If there is a = in the value, no worries. If there is an = in the key, trouble in paradise.

More Notes: Some may argue readability so break it down as you like.

I Like Notes: Adding an error handler (try catch) wouldn't hurt.

const iLikeCookies = () => {
    return Object.fromEntries(document.cookie.split('; ').map(v => v.split(/=(.+)/))); 
}

const main = () => {
    // Add Test Cookies
    document.cookie = `name=Cookie Monster;expires=false;domain=localhost`
    document.cookie = `likesCookies=yes=withARandomEquals;expires=false;domain=localhost`;

    // Show the Objects
    console.log(document.cookie)
    console.log('The Object:', iLikeCookies())

    // Get a value from key
    console.log(`Username: ${iLikeCookies().name}`)
    console.log(`Enjoys Cookies: ${iLikeCookies().likesCookies}`)
}

enter image description here

What is going on?

iLikeCookies() will split the cookies by ; (space after ;):

["name=Cookie Monster", "likesCookies=yes=withARandomEquals"]

Then we map that array and split by first occurrence of = using regex capturing parens:

[["name", "Cookie Monster"], ["likesCookies", "yes=withARandomEquals"]]

Then use our friend `Object.fromEntries to make this an object of key, val pairs.

Nooice.

jQuery xml error ' No 'Access-Control-Allow-Origin' header is present on the requested resource.'

There's a kind of hack-tastic way to do it if you have php enabled on your server. Change this line:

url:   'http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml',

to this line:

url: '/path/to/phpscript.php',

and then in the php script (if you have permission to use the file_get_contents() function):

<?php

header('Content-type: application/xml');
echo file_get_contents("http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml");

?>

Php doesn't seem to mind if that url is from a different origin. Like I said, this is a hacky answer, and I'm sure there's something wrong with it, but it works for me.

Edit: If you want to cache the result in php, here's the php file you would use:

<?php

$cacheName = 'somefile.xml.cache';
// generate the cache version if it doesn't exist or it's too old!
$ageInSeconds = 3600; // one hour
if(!file_exists($cacheName) || filemtime($cacheName) > time() + $ageInSeconds) {
  $contents = file_get_contents('http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml');
  file_put_contents($cacheName, $contents);
}

$xml = simplexml_load_file($cacheName);

header('Content-type: application/xml');
echo $xml;

?>

Caching code take from here.

How to properly add cross-site request forgery (CSRF) token using PHP

CSRF protection

TYPES OF CSRF USAGE

IN FORM

<form>
   @csrf
</form>

or

<input type="hidden" name="token" value="{{ form_token() }}" />

META TAG

<meta name="csrf-token" content="{{ csrf_token() }}">

AJAX

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

SESSION

use Illuminate\Http\Request;

Route::get('/token', function (Request $request) {
    $token = $request->session()->token();

    $token = csrf_token();

    // ...
});

MIDDLEWARE

 App\Providers\RouteServiceProvider

<?php

namespace App\Http\Middleware;

use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;

class VerifyCsrfToken extends Middleware
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'stripe/*',
        'http://example.com/foo/bar',
        'http://example.com/foo/*',
    ];
}

ERROR 1044 (42000): Access denied for 'root' With All Privileges

Try to comment string "sql-mode=..." in file my.cnf and than restart mysql.

how to fetch data from database in Hibernate

Hibernate has its own sql features that is known as hibernate query language. for retriving data from database using hibernate.

String sql_query = "from employee"//user table name which is in database.
Query query = session.createQuery(sql_query);
//for fetch we need iterator
Iterator it=query.iterator();
while(it.hasNext())
    {
         s=(employee) it.next();
System.out.println("Id :"+s.getId()+"FirstName"+s.getFirstName+"LastName"+s.getLastName);

   }

for fetch we need Iterator for that define and import package.

Link to Flask static files with url_for

In my case I had special instruction into nginx configuration file:

location ~ \.(js|css|png|jpg|gif|swf|ico|pdf|mov|fla|zip|rar)$ {
            try_files $uri =404;
    }

All clients have received '404' because nginx nothing known about Flask.

I hope it help someone.

HTML5 textarea placeholder not appearing

I know this post has been (very well) answered by Aquarelle but just in case somebody is having this issue with other tag forms with no text such as inputs i'll leave this here:

If you have an input in your form and placeholder is not showing because a white space at the beginning, this may be caused for you "value" attribute. In case you are using variables to fill the value of an input check that there are no white spaces between the commas and the variables.

example using twig for php framework symfony :

<input type="text" name="subject" value="{{ subject }}" placeholder="hello" />       <-- this is ok
<input type="text" name="subject" value" {{ subject }} " placeholder="hello" />      <-- this will not show placeholder 

In this case the tag between {{ }} is the variable, just make sure you are not leaving spaces between the commas because white space is also a valid character.

How do you view ALL text from an ntext or nvarchar(max) in SSMS?

I was successful with this method today. It's similar to the other answers in that it also converts the contents to XML, just using a different method. As I didn't see FOR XML PATH mentioned amongst the answers, I thought I'd add it for completeness:

SELECT [COL_NVARCHAR_MAX]
  FROM [SOME_TABLE]
  FOR XML PATH(''), ROOT('ROOT')

This will deliver a valid XML containing the contents of all rows, nested in an outer <ROOT></ROOT> element. The contents of the individual rows will each be contained within an element that, for this example, is called <COL_NVARCHAR_MAX>. The name of that can be changed using an alias via AS.

Special characters like &, < or > or similar will be converted to their respective entities. So you may have to convert &lt;, &gt; and &amp; back to their original character, depending on what you need to do with the result.

EDIT

I just realized that CDATA can be specified using FOR XML too. I find it a bit cumbersome though. This would do it:

SELECT 1 as tag, 0 as parent, [COL_NVARCHAR_MAX] as [COL_NVARCHAR_MAX!1!!CDATA]
  FROM [SOME_TABLE]
  FOR XML EXPLICIT, ROOT('ROOT')

Where are shared preferences stored?

SharedPreferences are stored in an xml file in the app data folder, i.e.

/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PREFS_NAME.xml

or the default preferences at:

/data/data/YOUR_PACKAGE_NAME/shared_prefs/YOUR_PACKAGE_NAME_preferences.xml

SharedPreferences added during runtime are not stored in the Eclipse project.

Note: Accessing /data/data/<package_name> requires superuser privileges

Echo tab characters in bash script

Use the verbatim keystroke, ^V (CTRL+V, C-v, whatever).

When you type ^V into the terminal (or in most Unix editors), the following character is taken verbatim. You can use this to type a literal tab character inside a string you are echoing.

Something like the following works:

echo "^V<tab>"     # CTRL+V, TAB

Bash docs (q.v., "quoted-insert")

quoted-insert (C-q, C-v) Add the next character that you type to the line verbatim. This is how to insert key sequences like C-q, for example.

side note: according to this, ALT+TAB should do the same thing, but we've all bound that sequence to window switching so we can't use it

tab-insert (M-TAB) Insert a tab character.

--

Note: you can use this strategy with all sorts of unusual characters. Like a carriage return:

echo "^V^M"        # CTRL+V, CTRL+M

This is because carriage return is ASCII 13, and M is the 13th letter of the alphabet, so when you type ^M, you get the 13th ASCII character. You can see it in action using ls^M, at an empty prompt, which will insert a carriage return, causing the prompt to act just like you hit return. When these characters are normally interpreted, verbatim gets you get the literal character.

What .NET collection provides the fastest search

If you don't need ordering, try HashSet<Record> (new to .Net 3.5)

If you do, use a List<Record> and call BinarySearch.

Delete all rows in an HTML table

This works in IE without even having to declare a var for the table and will delete all rows:

for(var i = 0; i < resultsTable.rows.length;)
{   
   resultsTable.deleteRow(i);
}

How can I show line numbers in Eclipse?

Window ? Preferences ? General ? Editors ? Text Editors ? Show line numbers.


Edit: I wrote this long ago but as @ArtOfWarfar and @voidstate mentioned you can now simply:

Right click the gutter and select "Show Line Numbers":

Unable to connect to any of the specified mysql hosts. C# MySQL

In my case by removing portion "port=3306;" from the connection string solved the problem.

How do I get rid of the "cannot empty the clipboard" error?

check this tip. worked for here http://mobeer.blogspot.com/2009/01/excel-2007-cannot-empty-clipboard.html:

This might save somebody some time and headaches if google picks it up. I was getting a 'Cannot empty the Clipboard' error every time I moved cells around in Excel - eventually I mucked around with the settings and made it go away. Here's how; In the excel main menu (glass globe w/logo), click Excel options, then Advanced, then turn off 'Show paste options buttons'

How exciting was this as my first post of the year?

Update: I still haven't found a permanent solution but I found another thing that seems to help. In Excel 2007, from the "home" tab, the first thing on the left is the clipboard tool panel. Expand the panel to view the clipboard and in the clipboard you might find "cannot empty clipboard" as an entry. Empty the clipboard, keep the panel open for a second or two while you do a few cut and pastes/drags etc. and then the bogey seems to go away.

I call this the cable dance because back in the day I had a printer that only worked if you unplugged the cable, shook it out and plugged it back in.

How to stop flask application without using ctrl-c

As others have pointed out, you can only use werkzeug.server.shutdown from a request handler. The only way I've found to shut down the server at another time is to send a request to yourself. For example, the /kill handler in this snippet will kill the dev server unless another request comes in during the next second:

import requests
from threading import Timer
from flask import request
import time

LAST_REQUEST_MS = 0
@app.before_request
def update_last_request_ms():
    global LAST_REQUEST_MS
    LAST_REQUEST_MS = time.time() * 1000


@app.route('/seriouslykill', methods=['POST'])
def seriouslykill():
    func = request.environ.get('werkzeug.server.shutdown')
    if func is None:
        raise RuntimeError('Not running with the Werkzeug Server')
    func()
    return "Shutting down..."


@app.route('/kill', methods=['POST'])
def kill():
    last_ms = LAST_REQUEST_MS
    def shutdown():
        if LAST_REQUEST_MS <= last_ms:  # subsequent requests abort shutdown
            requests.post('http://localhost:5000/seriouslykill')
        else:
            pass

    Timer(1.0, shutdown).start()  # wait 1 second
    return "Shutting down..."

Hide console window from Process.Start C#

This doesn't show the window:

Process cmd = new Process();
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
cmd.StartInfo.CreateNoWindow = true;

...
cmd.Start();

How can I color a UIImage in Swift?

I have modified the extension found here: Github Gist, for Swift 3 which I have tested in the context of an extension for UIImage.

func tint(with color: UIColor) -> UIImage 
{
   UIGraphicsBeginImageContext(self.size)
   guard let context = UIGraphicsGetCurrentContext() else { return self }

   // flip the image
   context.scaleBy(x: 1.0, y: -1.0)
   context.translateBy(x: 0.0, y: -self.size.height)

   // multiply blend mode
   context.setBlendMode(.multiply)

   let rect = CGRect(x: 0, y: 0, width: self.size.width, height: self.size.height)
   context.clip(to: rect, mask: self.cgImage!)
   color.setFill()
   context.fill(rect)

   // create UIImage
   guard let newImage = UIGraphicsGetImageFromCurrentImageContext() else { return self }
   UIGraphicsEndImageContext()

   return newImage
}

How do I remove duplicate items from an array in Perl?

You can do something like this as demonstrated in perlfaq4:

sub uniq {
    my %seen;
    grep !$seen{$_}++, @_;
}

my @array = qw(one two three two three);
my @filtered = uniq(@array);

print "@filtered\n";

Outputs:

one two three

If you want to use a module, try the uniq function from List::MoreUtils

Determine the size of an InputStream

You can't determine the amount of data in a stream without reading it; you can, however, ask for the size of a file:

http://java.sun.com/javase/6/docs/api/java/io/File.html#length()

If that isn't possible, you can write the bytes you read from the input stream to a ByteArrayOutputStream which will grow as required.

How do I edit a file after I shell to a Docker container?

If you use Windows container and you want change any file, you can get and use Vim in Powershell console easily.

To shelled to the Windows Docker container with PowerShell:

docker exec -it <name> powershell

  • First install Chocolatey package manager

    Invoke-WebRequest https://chocolatey.org/install.ps1 -UseBasicParsing | Invoke-Expression;

  • Install Vim

    choco install vim

  • Refresh ENVIRONMENTAL VARIABLE You can just exit and shell back to the container

  • Go to file location and Vim it vim file.txt

How to reduce a huge excel file

I save files in .XLSB format to cut size. The XLSB also allows for VBA and macros to stay with the file. I've seen 50 meg files down to less than 10 with the Binary formatting.

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

http://jsbeautifier.org/ is helpful to indent your minified JS code.

Also, with Google Chrome you can use "pretty print". See the example screenshot below showing jquery.min.js from Stack Overflow nicely indented right from my browser :)

enter image description here

Do fragments really need an empty constructor?

As noted by CommonsWare in this question https://stackoverflow.com/a/16064418/1319061, this error can also occur if you are creating an anonymous subclass of a Fragment, since anonymous classes cannot have constructors.

Don't make anonymous subclasses of Fragment :-)

Saving plots (AxesSubPlot) generated from python pandas with matplotlib's savefig

You can use ax.figure.savefig(), as suggested in a comment on the question:

import pandas as pd

df = pd.DataFrame([0, 1])
ax = df.plot.line()
ax.figure.savefig('demo-file.pdf')

This has no practical benefit over ax.get_figure().savefig() as suggested in other answers, so you can pick the option you find the most aesthetically pleasing. In fact, get_figure() simply returns self.figure:

# Source from snippet linked above
def get_figure(self):
    """Return the `.Figure` instance the artist belongs to."""
    return self.figure

AJAX post error : Refused to set unsafe header "Connection"

Remove these two lines:

xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");

XMLHttpRequest isn't allowed to set these headers, they are being set automatically by the browser. The reason is that by manipulating these headers you might be able to trick the server into accepting a second request through the same connection, one that wouldn't go through the usual security checks - that would be a security vulnerability in the browser.

How to use split?

According to MDN, the split() method divides a String into an ordered set of substrings, puts these substrings into an array, and returns the array.

Example

var str = 'Hello my friend'

var split1 = str.split(' ') // ["Hello", "my", "friend"]
var split2 = str.split('') // ["H", "e", "l", "l", "o", " ", "m", "y", " ", "f", "r", "i", "e", "n", "d"]

In your case

var str = 'something -- something_else'
var splitArr = str.split(' -- ') // ["something", "something_else"]

console.log(splitArr[0]) // something
console.log(splitArr[1]) // something_else

How to get the xml node value in string

You should use .Load and not .LoadXML

MSDN Link

"The LoadXml method is for loading an XML string directly. You want to use the Load method instead."

ref : Link

Proper way to handle multiple forms on one page in Django

Based on this answer by @ybendana:

Again, we use is_bound to check if the form is capable of validation. See this section of the documentation:

Bound and unbound forms

A Form instance is either bound to a set of data, or unbound.

  • If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the HTML.
  • If it’s unbound, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.

We use a list of tuples for form objects and their details allowing for more extensibility and less repetition.

However, instead of overriding get(), we override get_context_data() to make inserting a new, blank instance of the form (with prefix) into the response the default action for any request. In the context of a POST request, we override the post() method to:

  1. Use the prefix to check if each form has been submitted
  2. Validate the forms that have been submitted
  3. Process the valid forms using the cleaned_data
  4. Return any invalid forms to the response by overwriting the context data
# views.py

class MultipleForms(TemplateResponseMixin, ContextMixin, View):

    form_list = [ # (context_key, formcls, prefix)
        ("form_a", FormA, "prefix_a"),
        ("form_b", FormB, "prefix_b"),
        ("form_c", FormC, "prefix_c"),
        ...
        ("form_x", FormX, "prefix_x"),
    ]

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        # Add blank forms to context with prefixes
        for context_key, formcls, prefix in self.form_list:
            context[context_key] = formcls(prefix=prefix)
        return context

    def post(self, request, *args, **kwargs):
        # Get object and context
        self.object = self.get_object()
        context = self.get_context_data(object=self.object)
        # Process forms
        for context_key, formcls, prefix in self.form_list:
            if prefix in request.POST:
                # Get the form object with prefix and pass it the POST data to \
                # validate and clean etc.
                form = formcls(request.POST, prefix=prefix)
                if form.is_bound:
                    # If the form is bound (i.e. it is capable of validation)  \
                    # check the validation
                    if form.is_valid():
                        # call the form's save() method or do whatever you     \
                        # want with form.cleaned_data
                        form.save()
                    else:
                        # overwrite context data for this form so that it is   \
                        # returned to the page with validation errors
                        context[context_key] = form
        # Pass context back to render_to_response() including any invalid forms
        return self.render_to_response(context)
        

This method allows repeated form entries on the same page, something I found did not work with @ybendana's answer.

I believe it wouldn't be masses more work to fold this method into a Mixin class, taking the form_list object as an attribute and hooking get_context_data() and post() as above.

Edit: This already exists. See this repository.

NB: This method required TemplateResponseMixin for render_to_response() and ContextMixin for get_context_data() to work. Either use these Mixins or a CBV that descends from them.

Guzzle 6: no more json() method for responses

I use $response->getBody()->getContents() to get JSON from response. Guzzle version 6.3.0.

How to clear gradle cache?

Command: rm -rf ~/.gradle/caches/

Sublime Text 2: How do I change the color that the row number is highlighted?

tmtheme-editor.herokuapp.com seems pretty nice.

On the mac, the default theme files are in ~/Library/Application\ Support/Sublime\ Text\ 2/Packages/Color\ Scheme\ -\ Default

On Win7, the default theme files are in %appdata%\Sublime Text 2\Packages\Color Scheme - Default

Can you break from a Groovy "each" closure?

Replace each loop with any closure.

def list = [1, 2, 3, 4, 5]
list.any { element ->
    if (element == 2)
        return // continue

    println element

    if (element == 3)
        return true // break
}

Output

1
3

How to get the previous url using PHP

$_SERVER['HTTP_REFERER'] will give you incomplete url.

If you want http://bawse.3owl.com/jayz__magna_carta_holy_grail.php, $_SERVER['HTTP_REFERER'] will give you http://bawse.3owl.com/ only.

Can two or more people edit an Excel document at the same time?

yes if it is SharePoint 2010 and above by using the Office feature co-authoring

Excluding files/directories from Gulp task

Gulp uses micromatch under the hood for matching globs, so if you want to exclude any of the .min.js files, you can achieve the same by using an extended globbing feature like this:

src("'js/**/!(*.min).js")

Basically what it says is: grab everything at any level inside of js that doesn't end with *.min.js

What's the best visual merge tool for Git?

Meld is a free, open-source, and cross-platform (UNIX/Linux, OSX, Windows) diff/merge tool.

Here's how to install it on:

JAVA How to remove trailing zeros from a double

Use a DecimalFormat object with a format string of "0.#".

error : expected unqualified-id before return in c++

if (chapeau) {

You forgot the ending brace to this if statement, so the subsequent else if is considered a syntax error. You need to add the brace when the if statement body is complete:

if (chapeau) {
    cout << "le Professeur Violet";
}
else if (moustaches) {
    cout << "le Colonel Moutarde";
}
// ...

Encoding Error in Panda read_csv

This works in Mac as well you can use

df= pd.read_csv('Region_count.csv', encoding ='latin1')

PHP Connection failed: SQLSTATE[HY000] [2002] Connection refused

Using MAMP ON Mac, I solve my problem by renaming

/Applications/MAMP/tmp/mysql/mysql.sock.lock

to

/Applications/MAMP/tmp/mysql/mysql.sock

Set a variable if undefined in JavaScript

In our days you actually can do your approach with JS:

// Your variable is null
// or '', 0, false, undefined
let x = null;

// Set default value
x = x || 'default value';

console.log(x); // default value

So your example WILL work:

const setVariable = localStorage.getItem('value') || 0;

'numpy.float64' object is not iterable

numpy.linspace() gives you a one-dimensional NumPy array. For example:

>>> my_array = numpy.linspace(1, 10, 10)
>>> my_array
array([  1.,   2.,   3.,   4.,   5.,   6.,   7.,   8.,   9.,  10.])

Therefore:

for index,point in my_array

cannot work. You would need some kind of two-dimensional array with two elements in the second dimension:

>>> two_d = numpy.array([[1, 2], [4, 5]])
>>> two_d
array([[1, 2], [4, 5]])

Now you can do this:

>>> for x, y in two_d:
    print(x, y)

1 2
4 5

How to remove leading and trailing spaces from a string

String.Trim

Removes all leading and trailing white-space characters from the current String object.

Usage:

txt = txt.Trim();

If this isn't working then it highly likely that the "spaces" aren't spaces but some other non printing or white space character, possibly tabs. In this case you need to use the String.Trim method which takes an array of characters:

  char[] charsToTrim = { ' ', '\t' };
  string result = txt.Trim(charsToTrim);

Source

You can add to this list as and when you come across more space like characters that are in your input data. Storing this list of characters in your database or configuration file would also mean that you don't have to rebuild your application each time you come across a new character to check for.

NOTE

As of .NET 4 .Trim() removes any character that Char.IsWhiteSpace returns true for so it should work for most cases you come across. Given this, it's probably not a good idea to replace this call with the one that takes a list of characters you have to maintain.

It would be better to call the default .Trim() and then call the method with your list of characters.

How to run a shell script in OS X by double-clicking?

The easy way is to change the extension to .command or no extension.

But that will open the Terminal, and you will have to close it. If you don't want to see any output, you can use Automator to create a Mac Application that you can double click, add to the dock, etc.

  1. Open Automator application
  2. Choose "Application" type
  3. Type "run" in the Actions search box
  4. Double click "Run Shell Script"
  5. Click the Run button in upper right corner to test it.
  6. File > Save to create the Application.

enter image description here

bootstrap datepicker today as default

It works fine for me...

$(document).ready(function() {
        var date = new Date();
        var today = new Date(date.getFullYear(), date.getMonth(), date.getDate());

        $('#datepicker1').datepicker({
            format: 'dd-mm-yyyy',
            orientation: 'bottom'
        });

        $('#datepicker1').datepicker('setDate', today);

    });

Calling a function when ng-repeat has finished

Very easy, this is how I did it.

_x000D_
_x000D_
.directive('blockOnRender', function ($blockUI) {_x000D_
    return {_x000D_
        restrict: 'A',_x000D_
        link: function (scope, element, attrs) {_x000D_
            _x000D_
            if (scope.$first) {_x000D_
                $blockUI.blockElement($(element).parent());_x000D_
            }_x000D_
            if (scope.$last) {_x000D_
                $blockUI.unblockElement($(element).parent());_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
})
_x000D_
_x000D_
_x000D_

java.lang.NoClassDefFoundError in junit

  1. Right click your project in Package Explorer > click Properties
  2. go to Java Build Path > Libraries tab
  3. click on 'Add Library' button
  4. select JUnit
  5. click Next.
  6. select in dropdown button JUnit4 or other new versions.
  7. click finish.
  8. Then Ok.

How do I instantiate a JAXBElement<String> object?

ObjectFactory fact = new ObjectFactory();   
JAXBElement<String> str = fact.createCompositeTypeStringValue("vik");    
comp.setStringValue(str);
CompositeType retcomp = service.getDataUsingDataContract(comp);
System.out.println(retcomp.getStringValue().getValue());

H2 in-memory database. Table not found

The H2 in-memory database stores data in memory inside the JVM. When the JVM exits, this data is lost.

I suspect that what you are doing is similar to the two Java classes below. One of these classes creates a table and the other tries to insert into it:

import java.sql.*;

public class CreateTable {
    public static void main(String[] args) throws Exception {
        DriverManager.registerDriver(new org.h2.Driver());
        Connection c = DriverManager.getConnection("jdbc:h2:mem:test");
        PreparedStatement stmt = c.prepareStatement("CREATE TABLE PERSON (ID INT PRIMARY KEY, FIRSTNAME VARCHAR(64), LASTNAME VARCHAR(64))");
        stmt.execute();
        stmt.close();
        c.close();
    }
}

and

import java.sql.*;

public class InsertIntoTable {
    public static void main(String[] args) throws Exception {
        DriverManager.registerDriver(new org.h2.Driver());
        Connection c = DriverManager.getConnection("jdbc:h2:mem:test");
        PreparedStatement stmt = c.prepareStatement("INSERT INTO PERSON (ID, FIRSTNAME, LASTNAME) VALUES (1, 'John', 'Doe')");
        stmt.execute();
        stmt.close();
        c.close();
    }
}

When I ran these classes one after the other, I got the following output:

C:\Users\Luke\stuff>java CreateTable

C:\Users\Luke\stuff>java InsertIntoTable
Exception in thread "main" org.h2.jdbc.JdbcSQLException: Table "PERSON" not found; SQL statement:
INSERT INTO PERSON (ID, FIRSTNAME, LASTNAME) VALUES (1, 'John', 'Doe') [42102-154]
        at org.h2.message.DbException.getJdbcSQLException(DbException.java:327)
        at org.h2.message.DbException.get(DbException.java:167)
        at org.h2.message.DbException.get(DbException.java:144)
        ...

As soon as the first java process exits, the table created by CreateTable no longer exists. So, when the InsertIntoTable class comes along, there's no table for it to insert into.

When I changed the connection strings to jdbc:h2:test, I found that there was no such error. I also found that a file test.h2.db had appeared. This was where H2 had put the table, and since it had been stored on disk, the table was still there for the InsertIntoTable class to find.

TypeError: unsupported operand type(s) for -: 'str' and 'int'

For future reference Python is strongly typed. Unlike other dynamic languages, it will not automagically cast objects from one type or the other (say from str to int) so you must do this yourself. You'll like that in the long-run, trust me!

Null pointer Exception on .setOnClickListener

android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference

Because Submit button is inside login_modal so you need to use loginDialog view to access button:

Submit = (Button)loginDialog.findViewById(R.id.Submit);

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

How to create a HTTP server in Android?

If you are using kotlin,consider these library. It's build for kotlin language.

AndroidHttpServer is a simple demo using ServerSocket to handle http request

https://github.com/weeChanc/AndroidHttpServer

https://github.com/ktorio/ktor

AndroidHttpServer is very small , but the feature is less as well.

Ktor is a very nice library,and the usage is simple too

Controller not a function, got undefined, while defining controllers globally

I got this problem because I had wrapped a controller-definition file in a closure:

(function() {
   ...stuff...
});

But I had forgotten to actually invoke that closure to execute that definition code and actually tell Javascript my controller existed. I.e., the above needs to be:

(function() {
   ...stuff...
})();

Note the () at the end.

Android: java.lang.SecurityException: Permission Denial: start Intent

You have to add android:exported="true" in the manifest file in the activity you are trying to start.

From the android:exported documentation:

android:exported
Whether or not the activity can be launched by components of other applications — "true" if it can be, and "false" if not. If "false", the activity can be launched only by components of the same application or applications with the same user ID.

The default value depends on whether the activity contains intent filters. The absence of any filters means that the activity can be invoked only by specifying its exact class name. This implies that the activity is intended only for application-internal use (since others would not know the class name). So in this case, the default value is "false". On the other hand, the presence of at least one filter implies that the activity is intended for external use, so the default value is "true".

This attribute is not the only way to limit an activity's exposure to other applications. You can also use a permission to limit the external entities that can invoke the activity (see the permission attribute).

Is there a way to delete created variables, functions, etc from the memory of the interpreter?

You can delete individual names with del:

del x

or you can remove them from the globals() object:

for name in dir():
    if not name.startswith('_'):
        del globals()[name]

This is just an example loop; it defensively only deletes names that do not start with an underscore, making a (not unreasoned) assumption that you only used names without an underscore at the start in your interpreter. You could use a hard-coded list of names to keep instead (whitelisting) if you really wanted to be thorough. There is no built-in function to do the clearing for you, other than just exit and restart the interpreter.

Modules you've imported (import os) are going to remain imported because they are referenced by sys.modules; subsequent imports will reuse the already imported module object. You just won't have a reference to them in your current global namespace.

how to get selected row value in the KendoUI

I think it needs to be checked if any row is selected or not? The below code would check it:

var entityGrid = $("#EntitesGrid").data("kendoGrid");
            var selectedItem = entityGrid.dataItem(entityGrid.select());
            if (selectedItem != undefined)
                alert("The Row Is SELECTED");
            else
                alert("NO Row Is SELECTED")

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

What exactly does Perl's "bless" do?

Short version: it's marking that hash as attached to the current package namespace (so that that package provides its class implementation).

Access to the requested object is only available from the local network phpmyadmin

On Xampp 5.6.3 Windows Path C:\xampp\apache\conf\extra\httpd-xampp.conf comment in this: #Require local

New XAMPP security concept ... #Require local ...

Convert MFC CString to integer

Define in msdn: https://msdn.microsoft.com/en-us/library/yd5xkb5c.aspx

int atoi(
   const char *str 
);
int _wtoi(
   const wchar_t *str 
);
int _atoi_l(
   const char *str,
   _locale_t locale
);
int _wtoi_l(
   const wchar_t *str,
   _locale_t locale
);

CString is wchar_t string. So, if you want convert Cstring to int, you can use:

 CString s;  
int test = _wtoi(s)

How to configure Git post commit hook

As mentioned in "Polling must die: triggering Jenkins builds from a git hook", you can notify Jenkins of a new commit:

With the latest Git plugin 1.1.14 (that I just release now), you can now do this more >easily by simply executing the following command:

curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>

This will scan all the jobs that’s configured to check out the specified URL, and if they are also configured with polling, it’ll immediately trigger the polling (and if that finds a change worth a build, a build will be triggered in turn.)

This allows a script to remain the same when jobs come and go in Jenkins.
Or if you have multiple repositories under a single repository host application (such as Gitosis), you can share a single post-receive hook script with all the repositories. Finally, this URL doesn’t require authentication even for secured Jenkins, because the server doesn’t directly use anything that the client is sending. It runs polling to verify that there is a change, before it actually starts a build.

As mentioned here, make sure to use the right address for your Jenkins server:

since we're running Jenkins as standalone Webserver on port 8080 the URL should have been without the /jenkins, like this:

http://jenkins:8080/git/notifyCommit?url=git@gitserver:tools/common.git

To reinforce that last point, ptha adds in the comments:

It may be obvious, but I had issues with:

curl http://yourserver/jenkins/git/notifyCommit?url=<URL of the Git repository>. 

The url parameter should match exactly what you have in Repository URL of your Jenkins job.
When copying examples I left out the protocol, in our case ssh://, and it didn't work.


You can also use a simple post-receive hook like in "Push based builds using Jenkins and GIT"

#!/bin/bash
/usr/bin/curl --user USERNAME:PASS -s \

http://jenkinsci/job/PROJECTNAME/build?token=1qaz2wsx

Configure your Jenkins job to be able to “Trigger builds remotely” and use an authentication token (1qaz2wsx in this example).

However, this is a project-specific script, and the author mentions a way to generalize it.
The first solution is easier as it doesn't depend on authentication or a specific project.


I want to check in change set whether at least one java file is there the build should start.
Suppose the developers changed only XML files or property files, then the build should not start.

Basically, your build script can:

  • put a 'build' notes (see git notes) on the first call
  • on the subsequent calls, grab the list of commits between HEAD of your branch candidate for build and the commit referenced by the git notes 'build' (git show refs/notes/build): git diff --name-only SHA_build HEAD.
  • your script can parse that list and decide if it needs to go on with the build.
  • in any case, create/move your git notes 'build' to HEAD.

May 2016: cwhsu points out in the comments the following possible url:

you could just use curl --user USER:PWD http://JENKINS_SERVER/job/JOB_NAME/build?token=YOUR_TOKEN if you set trigger config in your item

http://i.imgur.com/IolrOOj.png


June 2016, polaretto points out in the comments:

I wanted to add that with just a little of shell scripting you can avoid manual url configuration, especially if you have many repositories under a common directory.
For example I used these parameter expansions to get the repo name

repository=${PWD%/hooks}; 
repository=${repository##*/} 

and then use it like:

curl $JENKINS_URL/git/notifyCommit?url=$GIT_URL/$repository

How do pointer-to-pointer's work in C? (and when might you use them?)

Let's assume an 8 bit computer with 8 bit addresses (and thus only 256 bytes of memory). This is part of that memory (the numbers at the top are the addresses):

  54   55   56   57   58   59   60   61   62   63   64   65   66   67   68   69
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+
|    | 58 |    |    | 63 |    | 55 |    |    | h  | e  | l  | l  | o  | \0 |    |
+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+----+

What you can see here, is that at address 63 the string "hello" starts. So in this case, if this is the only occurrence of "hello" in memory then,

const char *c = "hello";

... defines c to be a pointer to the (read-only) string "hello", and thus contains the value 63. c must itself be stored somewhere: in the example above at location 58. Of course we can not only point to characters, but also to other pointers. E.g.:

const char **cp = &c;

Now cp points to c, that is, it contains the address of c (which is 58). We can go even further. Consider:

const char ***cpp = &cp;

Now cpp stores the address of cp. So it has value 55 (based on the example above), and you guessed it: it is itself stored at address 60.


As to why one uses pointers to pointers:

  • The name of an array usually yields the address of its first element. So if the array contains elements of type t, a reference to the array has type t *. Now consider an array of arrays of type t: naturally a reference to this 2D array will have type (t *)* = t **, and is hence a pointer to a pointer.
  • Even though an array of strings sounds one-dimensional, it is in fact two-dimensional, since strings are character arrays. Hence: char **.
  • A function f will need to accept an argument of type t ** if it is to alter a variable of type t *.
  • Many other reasons that are too numerous to list here.

How to style UITextview to like Rounded Rect text field?

You may want to check out my library called DCKit.

You'd be able to make a rounded corner text view (as well as text field/button/plain UIView) from the Interface Builder directly:

DCKit: bordered UITextView

It also has many other useful features, such as text fields with validation, controls with borders, dashed borders, circle and hairline views etc.

Confirm Password with jQuery Validate

jQuery('.validatedForm').validate({
        rules : {
            password : {
                minlength : 5
            },
            password_confirm : {
                minlength : 5,
                equalTo : '[name="password"]'
            }
        }

In general, you will not use id="password" like this. So, you can use [name="password"] instead of "#password"

What does it mean when an HTTP request returns status code 0?

I believe the error code indicates that the response was empty, (as not even headers were returned). This means the connection was accepted and then closed gracefully (TCP FIN). There are a number of things which could cause this, but based off of your description, some form of firewall seems the most likely culprit.

Is there a Wikipedia API?

If you want to extract structured data from Wikipedia, you may consider using DbPedia http://dbpedia.org/

It provides means to query data using given criteria using SPARQL and returns data from parsed Wikipedia infobox templates

Here is a quick example how it could be done in .NET http://www.kozlenko.info/blog/2010/07/20/executing-sparql-query-on-wikipedia-in-net/

There are some SPARQL libraries available for multiple platforms to make queries easier

fatal: early EOF fatal: index-pack failed

I tried pretty much all the suggestions made here but none worked. For us the issue was temperamental and became worse and worse the larger the repos became (on our Jenkins Windows build slave).

It ended up being the version of ssh being used by git. Git was configured to use some version of Open SSH, specified in the users .gitconfig file via the core.sshCommand variable. Removing that line fixed it. I believe this is because Windows now ships with a more reliable / compatible version of SSH which gets used by default.

Microsoft Excel mangles Diacritics in .csv files?

open the file csv with notepad++ clic on Encode, select convert to UTF-8 (not convert to UTF-8(without BOM)) Save open by double clic with excel Hope that help Christophe GRISON

How to clear APC cache entries?

My work-around for Symfony build having loot of instances at the same server:

Step 1. Create trigger or something to set a file flag (eg. Symfony command) then create marker file ..

file_put_contents('clearAPCU','yes sir i can buggy')

Step 2. On index file at start add clearing code and remove marker file.

if(file_exists('clearAPCU')){
    apcu_clear_cache();
    unlink('clearAPCU');
}

Step 2. Run app.

editing PATH variable on mac

use

~/.bash_profile

or

~/.MacOSX/environment.plist

(see Runtime Configuration Guidelines)

Java - Convert int to Byte Array of 4 Bytes?

public static  byte[] my_int_to_bb_le(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_le(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.LITTLE_ENDIAN).getInt();
}

public static  byte[] my_int_to_bb_be(int myInteger){
    return ByteBuffer.allocate(4).order(ByteOrder.BIG_ENDIAN).putInt(myInteger).array();
}

public static int my_bb_to_int_be(byte [] byteBarray){
    return ByteBuffer.wrap(byteBarray).order(ByteOrder.BIG_ENDIAN).getInt();
}

Build Error - missing required architecture i386 in file

This happens when you add a framework to your project and unintentionally copy the framework into your project directory.

The fix is to check your project directory (where you store your project on disk) for any iphone SDK *.Framework files and delete them.

Project will build fine afterwards.