Programs & Examples On #Lwip

lwIP (lightweight IP) is a widely used open source TCP/IP stack designed for embedded systems. lwIP was originally developed by Adam Dunkels. It is now maintained by a worldwide network of developers. The focus of the lwIP TCP/IP implementation is to reduce resource usage while still having a full-scale TCP stack.This makes lwIP suitable for use in embedded systems with tens of kilobytes of free RAM and room for around 40 kilobytes of code ROM.

ReadFile in Base64 Nodejs

var fs = require('fs');

function base64Encode(file) {
    var body = fs.readFileSync(file);
    return body.toString('base64');
}


var base64String = base64Encode('test.jpg');
console.log(base64String);

Shortest way to print current year in a website

according to chrome audit

For users on slow connections, external scripts dynamically injected via document.write() can delay page load by tens of seconds.

https://web.dev/no-document-write/?utm_source=lighthouse&utm_medium=devtools

so solution without errors is:

(new Date).getFullYear();

How do I pull my project from github?

Git clone is the command you're looking for:

git clone [email protected]:username/repo.git

Update: And this is the official guide: https://help.github.com/articles/fork-a-repo

Take a look at: https://help.github.com/

It has really useful content

Picasso v/s Imageloader v/s Fresco vs Glide

Fresco sources | off site
(-)

  • Huge size of library
  • No Callback with View, Bitmap parameters
  • SimpleDraweeView doesn't support wrap_content
  • Huge size of cache
    (+)
  • Pretty fast image loader (for small && medium images)
  • A lot of functionality(streaming, drawing tools, memory management, etc)
  • Possibility to setup directly in xml (for example round corners)
  • GIF support
  • WebP and Animated Webp support


Picasso sources | off site
(-)

  • Slow loading big images from internet into ListView
    (+)
  • Tinny size of library
  • Small size of cache
  • Simple to use
  • UI does not freeze
  • WebP support


Glide sources

(-)

  • Big size of library
    (+)
  • Tinny size of cache
  • Simple to use
  • GIF support
  • WebP support
  • Fast loading big images from internet into ListView
  • UI does not freeze
  • BitmapPool to re-use memory and thus lesser GC events


Universal Image Loader sources

(-)

  • Limited functionality (limited image processing)
  • Project support has stopped since 27.11.2015
    (+)
  • Tinny size of library
  • Simple to use

Tested by me on SGS2 (Android 4.1) (WiFi 8.43 Mbps)
Official versions for Java, not for Xamarin!
October 19 2015

I prefer to use Glide.
Read more here.
How to write cache to External Storage (SD Card) with Glide.

How to fix git error: RPC failed; curl 56 GnuTLS

Try to disable your IPV6 for that and disable after. I think this is your problem.

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;
}

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

The program can't start because api-ms-win-crt-runtime-l1-1-0.dll is missing while starting Apache server on my computer

I was facing the same issue. After many tries below solution worked for me.

Before installing VC++ install your windows updates. 1. Go to Start - Control Panel - Windows Update 2. Check for the updates. 3. Install all updates. 4. Restart your system.

After that you can follow the below steps.

@ABHI KUMAR

Download the Visual C++ Redistributable 2015

Visual C++ Redistributable for Visual Studio 2015 (64-bit)

Visual C++ Redistributable for Visual Studio 2015 (32-bit)

(Reinstal if already installed) then restart your computer or use windows updates for download auto.

For link download https://www.microsoft.com/de-de/download/details.aspx?id=48145.

Timing a command's execution in PowerShell

You can also get the last command from history and subtract its EndExecutionTime from its StartExecutionTime.

.\do_something.ps1  
$command = Get-History -Count 1  
$command.EndExecutionTime - $command.StartExecutionTime

How to use a table type in a SELECT FROM statement?

Thanks for all help at this issue. I'll post here my solution:

Package Header

CREATE OR REPLACE PACKAGE X IS
  TYPE exch_row IS RECORD(
    currency_cd VARCHAR2(9),
    exch_rt_eur NUMBER,
    exch_rt_usd NUMBER);
  TYPE exch_tbl IS TABLE OF X.exch_row;

  FUNCTION GetExchangeRate RETURN X.exch_tbl PIPELINED;
END X;

Package Body

CREATE OR REPLACE PACKAGE BODY X IS
  FUNCTION GetExchangeRate RETURN X.exch_tbl
    PIPELINED AS
    exch_rt_usd NUMBER := 1.0; --todo
    rw exch_row;
  BEGIN

    FOR rw IN (SELECT c.currency_cd AS currency_cd, e.exch_rt AS exch_rt_eur, (e.exch_rt / exch_rt_usd) AS exch_rt_usd
                 FROM exch e, currency c
                WHERE c.currency_key = e.currency_key
                  ) LOOP
      PIPE ROW(rw);
    END LOOP;
  END;


  PROCEDURE DoIt IS
  BEGIN
    DECLARE
      CURSOR c0 IS
        SELECT i.DOC,
               i.doc_currency,
               i.net_value,
               i.net_value / rt.exch_rt_usd AS net_value_in_usd,
               i.net_value / rt.exch_rt_eur AS net_value_in_euro,
          FROM item i, (SELECT * FROM TABLE(X.GetExchangeRate())) rt
         WHERE i.doc_currency = rt.currency_cd;

      TYPE c0_type IS TABLE OF c0%ROWTYPE;

      items c0_type;
    BEGIN
      OPEN c0;

      LOOP
        FETCH c0 BULK COLLECT
          INTO items LIMIT batchsize;

        EXIT WHEN items.COUNT = 0;
        FORALL i IN items.FIRST .. items.LAST SAVE EXCEPTIONS
          INSERT INTO detail_items VALUES items (i);

      END LOOP;

      CLOSE c0;

      COMMIT;

    EXCEPTION
      WHEN OTHERS THEN
        RAISE;
    END;
  END;

END X;

Please review.

Formula to check if string is empty in Crystal Reports

You can check for IsNull condition.

If IsNull({TABLE.FIELD}) or {TABLE.FIELD} = "" then
  // do something

How to order a data frame by one descending and one ascending column?

I used this code to produce your desired output. Is this what you were after?

rum <- read.table(textConnection("P1  P2  P3  T1  T2  T3  I1  I2
2   3   5   52  43  61  6   b
6   4   3   72  NA  59  1   a
1   5   6   55  48  60  6   f
2   4   4   65  64  58  2   b"), header = TRUE)
rum$I2 <- as.character(rum$I2)
rum[order(rum$I1, rev(rum$I2), decreasing = TRUE), ]

  P1 P2 P3 T1 T2 T3 I1 I2
1  2  3  5 52 43 61  6  b
3  1  5  6 55 48 60  6  f
4  2  4  4 65 64 58  2  b
2  6  4  3 72 NA 59  1  a

Transfer data from one database to another database

These solutions are working in case when target database is blank. In case when both databases already have some data you need something more complicated http://byalexblog.net/merge-sql-databases

how to find my angular version in my project?

you can use ng --version for angular version 7

How to resolve TypeError: can only concatenate str (not "int") to str

instead of using " + " operator

print( "Alireza" + 1980)

Use comma " , " operator

print( "Alireza" , 1980)

How to change symbol for decimal point in double.ToString()?

Some shortcut is to create a NumberFormatInfo class, set its NumberDecimalSeparator property to "." and use the class as parameter to ToString() method whenever u need it.

using System.Globalization;

NumberFormatInfo nfi = new NumberFormatInfo();
nfi.NumberDecimalSeparator = ".";

value.ToString(nfi);

how to send an array in url request

Separate with commas:

http://localhost:8080/MovieDB/GetJson?name=Actor1,Actor2,Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name=Actor1&name=Actor2&name=Actor3&startDate=20120101&endDate=20120505

or:

http://localhost:8080/MovieDB/GetJson?name[0]=Actor1&name[1]=Actor2&name[2]=Actor3&startDate=20120101&endDate=20120505

Either way, your method signature needs to be:

@RequestMapping(value = "/GetJson", method = RequestMethod.GET) 
public void getJson(@RequestParam("name") String[] ticker, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
   //code to get results from db for those params.
 }

Convert Xml to Table SQL Server

The sp_xml_preparedocument stored procedure will parse the XML and the OPENXML rowset provider will show you a relational view of the XML data.

For details and more examples check the OPENXML documentation.

As for your question,

DECLARE @XML XML
SET @XML = '<rows><row>
    <IdInvernadero>8</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>8</IdCaracteristica1>
    <IdCaracteristica2>8</IdCaracteristica2>
    <Cantidad>25</Cantidad>
    <Folio>4568457</Folio>
</row>
<row>
    <IdInvernadero>3</IdInvernadero>
    <IdProducto>3</IdProducto>
    <IdCaracteristica1>1</IdCaracteristica1>
    <IdCaracteristica2>2</IdCaracteristica2>
    <Cantidad>72</Cantidad>
    <Folio>4568457</Folio>
</row></rows>'

DECLARE @handle INT  
DECLARE @PrepareXmlStatus INT  

EXEC @PrepareXmlStatus= sp_xml_preparedocument @handle OUTPUT, @XML  

SELECT  *
FROM    OPENXML(@handle, '/rows/row', 2)  
    WITH (
    IdInvernadero INT,
    IdProducto INT,
    IdCaracteristica1 INT,
    IdCaracteristica2 INT,
    Cantidad INT,
    Folio INT
    )  


EXEC sp_xml_removedocument @handle 

Cannot implicitly convert type 'System.Collections.Generic.IEnumerable<AnonymousType#1>' to 'System.Collections.Generic.List<string>

If you have source as a string like "abcd" and want to produce a list like this:

{ "a.a" },
{ "b.b" },
{ "c.c" },
{ "d.d" }

then call:

List<string> list = source.Select(c => String.Concat(c, ".", c)).ToList();

Linux command for extracting war file?

You can use the unzip command.

convert string into array of integers

First split the string on spaces:

var result = '14 2'.split(' ');

Then convert the result array of strings into integers:

for (var i in result) {
    result[i] = parseInt(result[i], 10);
}

SQL server 2008 backup error - Operating system error 5(failed to retrieve text for this error. Reason: 15105)

I've faced this error, when there was no enough free space to create backup.

fork and exec in bash

How about:

(sleep 5; echo "Hello World") &

CSS get height of screen resolution

You can bind the current height and width of the screen to css variables: var(--screen-x) and var(--screen-y) with this javascript:

var root = document.documentElement;

document.addEventListener('resize', () => {
  root.style.setProperty('--screen-x', window.screenX)
  root.style.setProperty('--screen-y', window.screenY)
})

This was directly adapted from lea verou's example in her talk on css variables here: https://leaverou.github.io/css-variables/#slide31

how to run or install a *.jar file in windows?

The UnsupportedClassVersionError means that you are probably using (installed) an older version of Java as used to create the JAR.
Go to java.sun.com page, download and install a newer JRE (Java Runtime Environment).
if you want/need to develop with Java, you will need the JDK which includes the JRE.

Troubleshooting "program does not contain a static 'Main' method" when it clearly does...?

That's odd. Does your program compile and run successfully and only fail on 'Publish' or does it fail on every compile now?

Also, have you perhaps changed the file's properties' Build Action to something other than Compile?

Set up git to pull and push all branches

If you are pushing from one remote origin to another, you can use this:

git push newremote refs/remotes/oldremote/*:refs/heads/*

This worked for me. Reffer to this: https://www.metaltoad.com/blog/git-push-all-branches-new-remote

How to subtract date/time in JavaScript?

You can use getTime() method to convert the Date to the number of milliseconds since January 1, 1970. Then you can easy do any arithmetic operations with the dates. Of course you can convert the number back to the Date with setTime(). See here an example.

SQLException: No suitable driver found for jdbc:derby://localhost:1527

It's also possible that in persistence.xml, EmbeddedDriver was used while the jdbc url was pointing to Derby server. In this case just change the url to pointing a path of database.

Understanding ASP.NET Eval() and Bind()

For read-only controls they are the same. For 2 way databinding, using a datasource in which you want to update, insert, etc with declarative databinding, you'll need to use Bind.

Imagine for example a GridView with a ItemTemplate and EditItemTemplate. If you use Bind or Eval in the ItemTemplate, there will be no difference. If you use Eval in the EditItemTemplate, the value will not be able to be passed to the Update method of the DataSource that the grid is bound to.


UPDATE: I've come up with this example:

<%@ Page Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Data binding demo</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:GridView 
            ID="grdTest" 
            runat="server" 
            AutoGenerateEditButton="true" 
            AutoGenerateColumns="false" 
            DataSourceID="mySource">
            <Columns>
                <asp:TemplateField>
                    <ItemTemplate>
                        <%# Eval("Name") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox 
                            ID="edtName" 
                            runat="server" 
                            Text='<%# Bind("Name") %>' 
                        />
                    </EditItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>
    </form>

    <asp:ObjectDataSource 
        ID="mySource" 
        runat="server"
        SelectMethod="Select" 
        UpdateMethod="Update" 
        TypeName="MyCompany.CustomDataSource" />
</body>
</html>

And here's the definition of a custom class that serves as object data source:

public class CustomDataSource
{
    public class Model
    {
        public string Name { get; set; }
    }

    public IEnumerable<Model> Select()
    {
        return new[] 
        {
            new Model { Name = "some value" }
        };
    }

    public void Update(string Name)
    {
        // This method will be called if you used Bind for the TextBox
        // and you will be able to get the new name and update the
        // data source accordingly
    }

    public void Update()
    {
        // This method will be called if you used Eval for the TextBox
        // and you will not be able to get the new name that the user
        // entered
    }
}

How to get Database Name from Connection String using SqlConnectionStringBuilder

You can use InitialCatalog Property or builder["Database"] works as well. I tested it with different case and it still works.

How to run a bash script from C++ program

The only standard mandated implementation dependent way is to use the system() function from stdlib.h.

Also if you know how to make user become the super-user that would be nice also.

Do you want the script to run as super-user or do you want to elevate the privileges of the C executable? The former can be done with sudo but there are a few things you need to know before you can go off using sudo.

Java Error: "Your security settings have blocked a local application from running"

If you are using Linux, these settings are available using /usr/bin/jcontrol (or your path setting to get the current Java tools). You can also edit the files in ~/.java/deployment/deployment.properties to set "deployment.security.level=MEDIUM".

Surprisingly, this information is not readily available from the Oracle web site. I miss java.sun.com...

How to create a fix size list in python?

Note also that when you used arrays in C++ you might have had somewhat different needs, which are solved in different ways in Python:

  1. You might have needed just a collection of items; Python lists deal with this usecase just perfectly.
  2. You might have needed a proper array of homogenous items. Python lists are not a good way to store arrays.

Python solves the need in arrays by NumPy, which, among other neat things, has a way to create an array of known size:

from numpy import *

l = zeros(10)

How to set a ripple effect on textview or imageview on Android?

If you want the ripple to be bounded to the size of the TextView/ImageView use:

<TextView
android:background="?attr/selectableItemBackground"
android:clickable="true"/>

(I think it looks better)

Content Type application/soap+xml; charset=utf-8 was not supported by service

In my case one of the classes didn't have a default constructor - and class without default constructor can't be serialized.

Return first N key:value pairs from dict

For Python 3 and above,To select first n Pairs

n=4
firstNpairs = {k: Diction[k] for k in list(Diction.keys())[:n]}

How to check if activity is in foreground or in visible background?

Save a flag if you are paused or resumed. If you are resumed it means you are in the foreground

boolean  isResumed = false;

@Override
public void onPause() {
  super.onPause();    
  isResumed = false;
}

@Override
public void onResume() {
  super.onResume();    
  isResumed = true;
}

private void finishIfForeground() {
  if (isResumed) {
    finish();
  }
}

How to trigger SIGUSR1 and SIGUSR2?

terminal 1

dd if=/dev/sda of=debian.img

terminal 2

killall -SIGUSR1 dd

go back to terminal 1

34292201+0 records in
34292200+0 records out
17557606400 bytes (18 GB) copied, 1034.7 s, 17.0 MB/s

XMLHttpRequest cannot load file. Cross origin requests are only supported for HTTP

If you are doing something like writing HTML and Javascript in a code editor on your personal computer, and testing the output in your browser, you will probably get error messages about Cross Origin Requests. Your browser will render HTML and run Javascript, jQuery, angularJs in your browser without needing a server set up. But many web browsers are programed to watch for cross site attacks, and will block requests. You don't want just anyone being able to read your hard drive from your web browser. You can create a fully functioning web page using Notepad++ that will run Javascript, and frameworks like jQuery and angularJs; and test everything just by using the Notepad++ menu item, RUN, LAUNCH IN FIREFOX. That's a nice, easy way to start creating a web page, but when you start creating anything more than layout, css and simple page navigation, you need a local server set up on your machine.

Here are some options that I use.

  1. Test your web page locally on Firefox, then deploy to your host.
  2. or: Run a local server

Test on Firefox, Deploy to Host

  1. Firefox currently allows Cross Origin Requests from files served from your hard drive
  2. Your web hosting site will allow requests to files in folders as configured by the manifest file

Run a Local Server

  • Run a server on your computer, like Apache or Python
  • Python isn't a server, but it will run a simple server

Run a Local Server with Python

Get your IP address:

  • On Windows: Open up the 'Command Prompt'. All Programs, Accessories, Command Prompt
  • I always run the Command Prompt as Administrator. Right click the Command Prompt menu item and look for Run As Administrator
  • Type the command: ipconfig and hit Enter.
  • Look for: IPv4 Address . . . . . . . . 12.123.123.00
  • There are websites that will also display your IP address

If you don't have Python, download and install it.

Using the 'Command Prompt' you must go to the folder where the files are that you want to serve as a webpage.

  • If you need to get back to the C:\ Root directory - type cd/
  • type cd Drive:\Folder\Folder\etc to get to the folder where your .Html file is (or php, etc)
  • Check the path. type: path at the command prompt. You must see the path to the folder where python is located. For example, if python is in C:\Python27, then you must see that address in the paths that are listed.
  • If the path to the Python directory is not in the path, you must set the path. type: help path and hit Enter. You will see help for path.
  • Type something like: path c:\python27 %path%
  • %path% keeps all your current paths. You don't want to wipe out all your current paths, just add a new path.
  • Create the new path FROM the folder where you want to serve the files.
  • Start the Python Server: Type: python -m SimpleHTTPServer port Where 'port' is the number of the port you want, for example python -m SimpleHTTPServer 1337
  • If you leave the port empty, it defaults to port 8000
  • If the Python server starts successfully, you will see a msg.

Run You Web Application Locally

  • Open a browser
  • In the address line type: http://your IP address:port
  • http://xxx.xxx.x.x:1337 or http://xx.xxx.xxx.xx:8000 for the default
  • If the server is working, you will see a list of your files in the browser
  • Click the file you want to serve, and it should display.

More advanced solutions

  • Install a code editor, web server, and other services that are integrated.

You can install Apache, PHP, Python, SQL, Debuggers etc. all separately on your machine, and then spend lots of time trying to figure out how to make them all work together, or look for a solution that combines all those things.

I like using XAMPP with NetBeans IDE. You can also install WAMP which provides a User Interface for managing and integrating Apache and other services.

Error: getaddrinfo ENOTFOUND in nodejs for get call

Check host file which like this

##
# Host Database
#
# localhost is used to configure the loopback interface
# when the system is booting.  Do not change this entry.
##
127.0.0.1   localhost
255.255.255.255 broadcasthost

Using Pipes within ngModel on INPUT Elements in Angular

<input [ngModel]="item.value | currency" (ngModelChange)="item.value=$event"
name="name" type="text" />

I would like to add one more point to the accepted answer.

If the type of your input control is not text the pipe will not work.

Keep it in mind and save your time.

Paging with Oracle

Just want to summarize the answers and comments. There are a number of ways doing a pagination.

Prior to oracle 12c there were no OFFSET/FETCH functionality, so take a look at whitepaper as the @jasonk suggested. It's the most complete article I found about different methods with detailed explanation of advantages and disadvantages. It would take a significant amount of time to copy-paste them here, so I won't do it.

There is also a good article from jooq creators explaining some common caveats with oracle and other databases pagination. jooq's blogpost

Good news, since oracle 12c we have a new OFFSET/FETCH functionality. OracleMagazine 12c new features. Please refer to "Top-N Queries and Pagination"

You may check your oracle version by issuing the following statement

SELECT * FROM V$VERSION

Getting the computer name in Java

The computer "name" is resolved from the IP address by the underlying DNS (Domain Name System) library of the OS. There's no universal concept of a computer name across OSes, but DNS is generally available. If the computer name hasn't been configured so DNS can resolve it, it isn't available.

import java.net.InetAddress;
import java.net.UnknownHostException;

String hostname = "Unknown";

try
{
    InetAddress addr;
    addr = InetAddress.getLocalHost();
    hostname = addr.getHostName();
}
catch (UnknownHostException ex)
{
    System.out.println("Hostname can not be resolved");
}

Sql query to insert datetime in SQL Server

No need to use convert. Simply list it as a quoted date in ISO 8601 format.
Like so:

select * from table1 where somedate between '2000/01/01' and '2099/12/31'

The separator needs to be a / and it needs to be surrounded by single ' quotes.

Remove element of a regular array

Here's how I did it...

    public static ElementDefinitionImpl[] RemoveElementDefAt(
        ElementDefinition[] oldList,
        int removeIndex
    )
    {
        ElementDefinitionImpl[] newElementDefList = new ElementDefinitionImpl[ oldList.Length - 1 ];

        int offset = 0;
        for ( int index = 0; index < oldList.Length; index++ )
        {
            ElementDefinitionImpl elementDef = oldList[ index ] as ElementDefinitionImpl;
            if ( index == removeIndex )
            {
                //  This is the one we want to remove, so we won't copy it.  But 
                //  every subsequent elementDef will by shifted down by one.
                offset = -1;
            }
            else
            {
                newElementDefList[ index + offset ] = elementDef;
            }
        }
        return newElementDefList;
    }

SQL DELETE with INNER JOIN

Add .* to s in your first line.

Try:

DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");

C++ Double Address Operator? (&&)

&& is new in C++11. int&& a means "a" is an r-value reference. && is normally only used to declare a parameter of a function. And it only takes a r-value expression. If you don't know what an r-value is, the simple explanation is that it doesn't have a memory address. E.g. the number 6, and character 'v' are both r-values. int a, a is an l-value, however (a+2) is an r-value. For example:

void foo(int&& a)
{
    //Some magical code...
}

int main()
{
    int b;
    foo(b); //Error. An rValue reference cannot be pointed to a lValue.
    foo(5); //Compiles with no error.
    foo(b+3); //Compiles with no error.

    int&& c = b; //Error. An rValue reference cannot be pointed to a lValue.
    int&& d = 5; //Compiles with no error.
}

Hope that is informative.

What are the differences between the urllib, urllib2, urllib3 and requests module?

urllib2 provides some extra functionality, namely the urlopen() function can allow you to specify headers (normally you'd have had to use httplib in the past, which is far more verbose.) More importantly though, urllib2 provides the Request class, which allows for a more declarative approach to doing a request:

r = Request(url='http://www.mysite.com')
r.add_header('User-Agent', 'awesome fetcher')
r.add_data(urllib.urlencode({'foo': 'bar'})
response = urlopen(r)

Note that urlencode() is only in urllib, not urllib2.

There are also handlers for implementing more advanced URL support in urllib2. The short answer is, unless you're working with legacy code, you probably want to use the URL opener from urllib2, but you still need to import into urllib for some of the utility functions.

Bonus answer With Google App Engine, you can use any of httplib, urllib or urllib2, but all of them are just wrappers for Google's URL Fetch API. That is, you are still subject to the same limitations such as ports, protocols, and the length of the response allowed. You can use the core of the libraries as you would expect for retrieving HTTP URLs, though.

MySQL timezone change?

This works fine

<?php
      $con=mysqli_connect("localhost","my_user","my_password","my_db");
      $con->query("SET GLOBAL time_zone = 'Asia/Calcutta'");
      $con->query("SET time_zone = '+05:30'");
      $con->query("SET @@session.time_zone = '+05:30'");
?>

jQuery - Redirect with post data

Before document/window ready add "extend" to jQuery :

$.extend(
{
    redirectPost: function(location, args)
    {
        var form = '';
        $.each( args, function( key, value ) {

            form += '<input type="hidden" name="'+value.name+'" value="'+value.value+'">';
            form += '<input type="hidden" name="'+key+'" value="'+value.value+'">';
        });
        $('<form action="'+location+'" method="POST">'+form+'</form>').submit();
    }
});

Use :

$.redirectPost("someurl.com", $("#SomeForm").serializeArray());

Note : this method cant post files .

youtube: link to display HD video by default

via Is there a way to link someone to a YouTube Video in HD 1080p quality?

Yes there is:

https://www.youtube.com/embed/Susj4jVWs0s?version=3&vq=hd720

options are:

default|none: vq=auto;
Code for auto: vq=auto;
Code for 2160p: vq=hd2160;
Code for 1440p: vq=hd1440;
Code for 1080p: vq=hd1080;
Code for 720p: vq=hd720;
Code for 480p: vq=large;
Code for 360p: vq=medium;
Code for 240p: vq=small;

As mentioned, you have to use the /embed/ or /v/ URL.

Note: Some copyrighted content doesn't support be played in this way

Check whether a path is valid

The closest I have come is by trying to create it, and seeing if it succeeds.

async await return Task

Adding the async keyword is just syntactic sugar to simplify the creation of a state machine. In essence, the compiler takes your code;

public async Task MethodName()
{
     return null;
}

And turns it into;

public Task MethodName()
{
     return Task.FromResult<object>(null);
}

If your code has any await keywords, the compiler must take your method and turn it into a class to represent the state machine required to execute it. At each await keyword, the state of variables and the stack will be preserved in the fields of the class, the class will add itself as a completion hook to the task you are waiting on, then return.

When that task completes, your task will be executed again. So some extra code is added to the top of the method to restore the state of variables and jump into the next slab of your code.

See What does async & await generate? for a gory example.

This process has a lot in common with the way the compiler handles iterator methods with yield statements.

Loop through childNodes

The variable children is a NodeList instance and NodeLists are not true Array and therefore they do not inherit the forEach method.

Also some browsers actually support it nodeList.forEach


ES5

You can use slice from Array to convert the NodeList into a proper Array.

var array = Array.prototype.slice.call(children);

You could also simply use call to invoke forEach and pass it the NodeList as context.

[].forEach.call(children, function(child) {});


ES6

You can use the from method to convert your NodeList into an Array.

var array = Array.from(children);

Or you can also use the spread syntax ... like so

let array = [ ...children ];


A hack that can be used is NodeList.prototype.forEach = Array.prototype.forEach and you can then use forEach with any NodeList without having to convert them each time.

NodeList.prototype.forEach = Array.prototype.forEach
var children = element.childNodes;
children.forEach(function(item){
    console.log(item);
});

See A comprehensive dive into NodeLists, Arrays, converting NodeLists and understanding the DOM for a good explanation and other ways to do it.

How to add rows dynamically into table layout

The way you have added a row into the table layout you can add multiple TableRow instances into your tableLayout object

tl.addView(row1);
tl.addView(row2);

etc...

Creating self signed certificate for domain and subdomains - NET::ERR_CERT_COMMON_NAME_INVALID

Your wildcard *.example.com does not cover the root domain example.com but will cover any variant on a sub-domain such as www.example.com or test.example.com

The preferred method is to establish Subject Alternative Names like in Fabian's Answer but keep in mind that Chrome currently requires the Common Name to be listed additionally as one of the Subject Alternative Names (as it is correctly demonstrated in his answer). I recently discovered this problem because I had the Common Name example.com with SANs www.example.com and test.example.com, but got the NET::ERR_CERT_COMMON_NAME_INVALID warning from Chrome. I had to generate a new Certificate Signing Request with example.com as both the Common Name and one of the SANs. Then Chrome fully trusted the certificate. And don't forget to import the root certificate into Chrome as a trusted authority for identifying websites.

Python: For each list element apply a function across the list

>>> nums = [1, 2, 3, 4, 5]    
>>> min(map((lambda t: ((float(t[0])/t[1]), t)), ((x, y) for x in nums for y in nums)))[1]
(1, 5)

'str' object has no attribute 'decode'. Python 3 error?

You are trying to decode an object that is already decoded. You have a str, there is no need to decode from UTF-8 anymore.

Simply drop the .decode('utf-8') part:

header_data = data[1][0][1]

As for your fetch() call, you are explicitly asking for just the first message. Use a range if you want to retrieve more messages. See the documentation:

The message_set options to commands below is a string specifying one or more messages to be acted upon. It may be a simple message number ('1'), a range of message numbers ('2:4'), or a group of non-contiguous ranges separated by commas ('1:3,6:9'). A range can contain an asterisk to indicate an infinite upper bound ('3:*').

How do I see which version of Swift I'm using?

You will get this under the project setting

enter image description here

Calling Oracle stored procedure from C#?

Please visit this ODP site set up by oracle for Microsoft OracleClient Developers: http://www.oracle.com/technetwork/topics/dotnet/index-085703.html

Also below is a sample code that can get you started to call a stored procedure from C# to Oracle. PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT is the stored procedure built on Oracle accepting parameters PUNIT, POFFICE, PRECEIPT_NBR and returning the result in T_CURSOR.

using Oracle.DataAccess;
using Oracle.DataAccess.Client;

public DataTable GetHeader_BySproc(string unit, string office, string receiptno)
{
    using (OracleConnection cn = new OracleConnection(DatabaseHelper.GetConnectionString()))
    {
        OracleDataAdapter da = new OracleDataAdapter();
        OracleCommand cmd = new OracleCommand();
        cmd.Connection = cn;
        cmd.InitialLONGFetchSize = 1000;
        cmd.CommandText = DatabaseHelper.GetDBOwner() + "PKG_COLLECTION.CSP_COLLECTION_HDR_SELECT";
        cmd.CommandType = CommandType.StoredProcedure;
        cmd.Parameters.Add("PUNIT", OracleDbType.Char).Value = unit;
        cmd.Parameters.Add("POFFICE", OracleDbType.Char).Value = office;
        cmd.Parameters.Add("PRECEIPT_NBR", OracleDbType.Int32).Value = receiptno;
        cmd.Parameters.Add("T_CURSOR", OracleDbType.RefCursor).Direction = ParameterDirection.Output;

        da.SelectCommand = cmd;
        DataTable dt = new DataTable();
        da.Fill(dt);
        return dt;
    }
}

Change value of input placeholder via model?

As Wagner Francisco said, (in JADE)

input(type="text", ng-model="someModel", placeholder="{{someScopeVariable}}")`

And in your controller :

$scope.someScopeVariable = 'somevalue'

jQuery Validation plugin: disable validation for specified submit buttons

Add formnovalidate attribute to input

    <input type="submit" name="go" value="Submit"> 
    <input type="submit" formnovalidate name="cancel" value="Cancel"> 

Adding class="cancel" is now deprecated

See docs for Skipping validation on submit on this link

" netsh wlan start hostednetwork " command not working no matter what I try

If none of the above solution worked for you, locate the Wifi adapter from "Control Panel\Network and Internet\Network Connections", right click on it, and select "Diagnose", then follow the given instructions on the screen. It worked for me.

How to view query error in PDO PHP

I'm using this without any additional settings:

if (!$st->execute()) {
    print_r($st->errorInfo());
}

Can I update a component's props in React.js?

Trick to update props if they are array :

import React, { Component } from 'react';
import {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  Button
} from 'react-native';

class Counter extends Component {
  constructor(props) {
    super(props);
      this.state = {
        count: this.props.count
      }
    }
  increment(){
    console.log("this.props.count");
    console.log(this.props.count);
    let count = this.state.count
    count.push("new element");
    this.setState({ count: count})
  }
  render() {

    return (
      <View style={styles.container}>
        <Text>{ this.state.count.length }</Text>
        <Button
          onPress={this.increment.bind(this)}
          title={ "Increase" }
        />
      </View>
    );
  }
}

Counter.defaultProps = {
 count: []
}

export default Counter
const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
});

Python Remove last 3 characters of a string

It doesn't work as you expect because strip is character based. You need to do this instead:

foo = foo.replace(' ', '')[:-3].upper()

Random character generator with a range of (A..Z, 0..9) and punctuation

  1. Pick a random number between [0, x), where x is the number of different symbols. Hopefully the choice is uniformly chosen and not predictable :-)

  2. Now choose the symbol representing x.

  3. Profit!

I would start reading up Pseudorandomness and then some common Pseudo-random number generators. Of course, your language hopefully already has a suitable "random" function :-)

BadValue Invalid or no user locale set. Please ensure LANG and/or LC_* environment variables are set correctly

adding the following lines to my /etc/environment file worked

LC_ALL=en_US.UTF-8
LANG=en_US.UTF-8

Set default syntax to different filetype in Sublime Text 2

In ST2 there's a package you can install called Default FileType which does just that.

More info here.

python pandas remove duplicate columns

It sounds like you already know the unique column names. If that's the case, then df = df['Time', 'Time Relative', 'N2'] would work.

If not, your solution should work:

In [101]: vals = np.random.randint(0,20, (4,3))
          vals
Out[101]:
array([[ 3, 13,  0],
       [ 1, 15, 14],
       [14, 19, 14],
       [19,  5,  1]])

In [106]: df = pd.DataFrame(np.hstack([vals, vals]), columns=['Time', 'H1', 'N2', 'Time Relative', 'N2', 'Time'] )
          df
Out[106]:
   Time  H1  N2  Time Relative  N2  Time
0     3  13   0              3  13     0
1     1  15  14              1  15    14
2    14  19  14             14  19    14
3    19   5   1             19   5     1

In [107]: df.T.drop_duplicates().T
Out[107]:
   Time  H1  N2
0     3  13   0
1     1  15  14
2    14  19  14
3    19   5   1

You probably have something specific to your data that's messing it up. We could give more help if there's more details you could give us about the data.

Edit: Like Andy said, the problem is probably with the duplicate column titles.

For a sample table file 'dummy.csv' I made up:

Time    H1  N2  Time    N2  Time Relative
3   13  13  3   13  0
1   15  15  1   15  14
14  19  19  14  19  14
19  5   5   19  5   1

using read_table gives unique columns and works properly:

In [151]: df2 = pd.read_table('dummy.csv')
          df2
Out[151]:
         Time  H1  N2  Time.1  N2.1  Time Relative
      0     3  13  13       3    13              0
      1     1  15  15       1    15             14
      2    14  19  19      14    19             14
      3    19   5   5      19     5              1
In [152]: df2.T.drop_duplicates().T
Out[152]:
             Time  H1  Time Relative
          0     3  13              0
          1     1  15             14
          2    14  19             14
          3    19   5              1  

If your version doesn't let your, you can hack together a solution to make them unique:

In [169]: df2 = pd.read_table('dummy.csv', header=None)
          df2
Out[169]:
              0   1   2     3   4              5
        0  Time  H1  N2  Time  N2  Time Relative
        1     3  13  13     3  13              0
        2     1  15  15     1  15             14
        3    14  19  19    14  19             14
        4    19   5   5    19   5              1
In [171]: from collections import defaultdict
          col_counts = defaultdict(int)
          col_ix = df2.first_valid_index()
In [172]: cols = []
          for col in df2.ix[col_ix]:
              cnt = col_counts[col]
              col_counts[col] += 1
              suf = '_' + str(cnt) if cnt else ''
              cols.append(col + suf)
          cols
Out[172]:
          ['Time', 'H1', 'N2', 'Time_1', 'N2_1', 'Time Relative']
In [174]: df2.columns = cols
          df2 = df2.drop([col_ix])
In [177]: df2
Out[177]:
          Time  H1  N2 Time_1 N2_1 Time Relative
        1    3  13  13      3   13             0
        2    1  15  15      1   15            14
        3   14  19  19     14   19            14
        4   19   5   5     19    5             1
In [178]: df2.T.drop_duplicates().T
Out[178]:
          Time  H1 Time Relative
        1    3  13             0
        2    1  15            14
        3   14  19            14
        4   19   5             1 

How do I determine if my python shell is executing in 32bit or 64bit?

Grouping everything...

Considering that:

  • The question is asked for OSX (I have an old (and cracked) VM with an ancient Python version)
  • My main env is Win
  • I only have the 32bit version installed on Win (and I built a "crippled" one on Lnx)

I'm going to exemplify on all 3 platforms, using Python 3 and Python 2.

  1. Check [Python 3.Docs]: sys.maxsize value - compare it to 0x100000000 (2 ** 32): greater for 64bit, smaller for 32bit:
    • OSX 9 x64:
      • Python 2.7.10 x64:
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 2.7.10 (default, Oct 14 2015, 05:51:29) \n[GCC 4.8.2] on darwin'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffffffffffff', True)
        
    • Ubuntu 16 x64:
      • Python 3.5.2 x64:
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.5.2 (default, Nov 23 2017, 16:37:01) \n[GCC 5.4.0 20160609] on linux'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffffffffffff', True)
        
      • Python 3.6.4 x86:
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.6.4 (default, Apr 25 2018, 23:55:56) \n[GCC 5.4.0 20160609] on linux'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffff', False)
        
    • Win 10 x64:
      • Python 3.5.4 x64:
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.5.4 (v3.5.4:3f56838, Aug  8 2017, 02:17:05) [MSC v.1900 64 bit (AMD64)] on win32'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffffffffffff', True)
        
      • Python 3.6.2 x86:
        >>> import sys
        >>> "Python {0:s} on {1:s}".format(sys.version, sys.platform)
        'Python 3.6.2 (v3.6.2:5fd33b5, Jul  8 2017, 04:14:34) [MSC v.1900 32 bit (Intel)] on win32'
        >>> hex(sys.maxsize), sys.maxsize > 0x100000000
        ('0x7fffffff', False)
        


  1. Use [Python 3.Docs]: struct.calcsize(format) to determine the object size produced by the (pointer) format. In other words, determines the pointer size (sizeof(void*)):
    • OSX 9 x64:
      • Python 2.7.10 x64:
        >>> import struct
        >>> struct.calcsize("P") * 8
        64
        
    • Ubuntu 16 x64:
      • Python 3.5.2 x64:
        >>> import struct
        >>> struct.calcsize("P") * 8
        64
        
      • Python 3.6.4 x86:
        >>> import struct
        >>> struct.calcsize("P") * 8
        32
        
    • Win 10 x64:
      • Python 3.5.4 x64:
        >>> import struct
        >>> struct.calcsize("P") * 8
        64
        
      • Python 3.6.2 x86:
        >>> import struct
        >>> struct.calcsize("P") * 8
        32
        


  1. Use [Python 3.Docs]: ctypes - A foreign function library for Python. It also boils down to determining the size of a pointer (sizeof(void*)). As a note, ctypes uses #2. (not necessarily for this task) via "${PYTHON_SRC_DIR}/Lib/ctypes/__init__.py" (around line #15):
    • OSX 9 x64:
      • Python 2.7.10 x64:
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        64
        
    • Ubuntu 16 x64:
      • Python 3.5.2 x64:
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        64
        
      • Python 3.6.4 x86:
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        32
        
    • Win 10 x64:
      • Python 3.5.4 x64:
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        64
        
      • Python 3.6.2 x86:
        >>> import ctypes
        >>> ctypes.sizeof(ctypes.c_void_p) * 8
        32
        


  1. [Python 3.Docs]: platform.architecture(executable=sys.executable, bits='', linkage='') !!! NOT reliable on OSX !!! due to multi arch executable (or .dylib) format (in some cases, uses #2.):
    • OSX 9 x64:
      • Python 2.7.10 x64:
        >>> import platform
        >>> platform.architecture()
        ('64bit', '')
        
    • Ubuntu 16 x64:
      • Python 3.5.2 x64:
        >>> import platform
        >>> platform.architecture()
        ('64bit', 'ELF')
        
      • Python 3.6.4 x86:
        >>> import platform
        >>> platform.architecture()
        ('32bit', 'ELF')
        
    • Win 10 x64:
      • Python 3.5.4 x64:
        >>> import platform
        >>> platform.architecture()
        ('64bit', 'WindowsPE')
        
      • Python 3.6.2 x86:
        >>> import platform
        >>> platform.architecture()
        ('32bit', 'WindowsPE')
        


  1. Lame workaround (gainarie) - invoke an external command ([man7]: FILE(1)) via [Python 3.Docs]: os.system(command). The limitations of #4. apply (sometimes it might not even work):
    • OSX 9 x64:
      • Python 2.7.10 x64:
        >>> import os
        >>> os.system("file {0:s}".format(os.path.realpath(sys.executable)))
        /opt/OPSWbuildtools/2.0.6/bin/python2.7.global: Mach-O 64-bit executable x86_64
        
    • Ubuntu 16 x64:
      • Python 3.5.2 x64:
        >>> import os
        >>> os.system("file {0:s}".format(os.path.realpath(sys.executable)))
        /usr/bin/python3.5: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked, interpreter /lib64/ld-linux-x86-64.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=59a8ef36ca241df24686952480966d7bc0d7c6ea, stripped
        
      • Python 3.6.4 x86:
        >>> import os
        >>> os.system("file {0:s}".format(os.path.realpath(sys.executable)))
        /home/cfati/Work/Dev/Python-3.6.4/python: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked, interpreter /lib/ld-linux.so.2, for GNU/Linux 2.6.32, BuildID[sha1]=5c3d4eeadbd13cd91445d08f90722767b0747de2, not stripped
        
    • Win 10 x64:
      • file utility is not present, there are other 3rd Party tools that can be used, but I'm not going to insist on them


Win specific:

  1. Check env vars (e.g. %PROCESSOR_ARCHITECTURE% (or others)) via [Python 3.Docs]: os.environ:
    • Win 10 x64:
      • Python 3.5.4 x64:
        >>> import os
        >>> os.environ["PROCESSOR_ARCHITECTURE"]
        'AMD64'
        
      • Python 3.6.2 x86:
        >>> import os
        >>> os.environ["PROCESSOR_ARCHITECTURE"]
        'x86'
        


  1. [Python 3.Docs]: sys.version (also displayed in the 1st line when starting the interpreter)
    • Check #1.

Corrupted Access .accdb file: "Unrecognized Database Format"

WE had this problem on one machine and not another...the solution is to look in control panel at the VERSION of the Access Database Engine 2007 component. If it is version 12.0.45, you need to run the service pack 3 http://www.microsoft.com/en-us/download/confirmation.aspx?id=27835

The above link will install version 12.0.66...and this fixes the problem...thought I would post it since I haven't seen this solution on any other forum.

How do I implement onchange of <input type="text"> with jQuery?

<input id="item123" class="firstName" type="text" value="Hello there" data-someattr="CoolExample" />

$(".firstName").on('change keyup paste', function () {
   var element = $(this);
   console.log(element);
   var dataAttribute = $(element).attr("data-someattr");
   console.log("someattr: " + dataAttribute );
});

I recommend use this keyword in order to get access to the entire element so your are able do everything you need with this element.

Difference between dates in JavaScript

This answer, based on another one (link at end), is about the difference between two dates.
You can see how it works because it's simple, also it includes splitting the difference into
units of time (a function that I made) and converting to UTC to stop time zone problems.

_x000D_
_x000D_
function date_units_diff(a, b, unit_amounts) {_x000D_
    var split_to_whole_units = function (milliseconds, unit_amounts) {_x000D_
        // unit_amounts = list/array of amounts of milliseconds in a_x000D_
        // second, seconds in a minute, etc., for example "[1000, 60]"._x000D_
        time_data = [milliseconds];_x000D_
        for (i = 0; i < unit_amounts.length; i++) {_x000D_
            time_data.push(parseInt(time_data[i] / unit_amounts[i]));_x000D_
            time_data[i] = time_data[i] % unit_amounts[i];_x000D_
        }; return time_data.reverse();_x000D_
    }; if (unit_amounts == undefined) {_x000D_
        unit_amounts = [1000, 60, 60, 24];_x000D_
    };_x000D_
    var utc_a = new Date(a.toUTCString());_x000D_
    var utc_b = new Date(b.toUTCString());_x000D_
    var diff = (utc_b - utc_a);_x000D_
    return split_to_whole_units(diff, unit_amounts);_x000D_
}_x000D_
_x000D_
// Example of use:_x000D_
var d = date_units_diff(new Date(2010, 0, 1, 0, 0, 0, 0), new Date()).slice(0,-2);_x000D_
document.write("In difference: 0 days, 1 hours, 2 minutes.".replace(_x000D_
   /0|1|2/g, function (x) {return String( d[Number(x)] );} ));
_x000D_
_x000D_
_x000D_

How my code above works

A date/time difference, as milliseconds, can be calculated using the Date object:

var a = new Date(); // Current date now.
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // Start of 2010.

var utc_a = new Date(a.toUTCString());
var utc_b = new Date(b.toUTCString());
var diff = (utc_b - utc_a); // The difference as milliseconds.

Then to work out the number of seconds in that difference, divide it by 1000 to convert
milliseconds to seconds, then change the result to an integer (whole number) to remove
the milliseconds (fraction part of that decimal): var seconds = parseInt(diff/1000).
Also, I could get longer units of time using the same process, for example:
- (whole) minutes, dividing seconds by 60 and changing the result to an integer,
- hours, dividing minutes by 60 and changing the result to an integer.

I created a function for doing that process of splitting the difference into
whole units of time, named split_to_whole_units, with this demo:

console.log(split_to_whole_units(72000, [1000, 60]));
// -> [1,12,0] # 1 (whole) minute, 12 seconds, 0 milliseconds.

This answer is based on this other one.

Delete all rows in an HTML table

this would work iteration deletetion in HTML table in native

document.querySelectorAll("table tbody tr").forEach(function(e){e.remove()})

PHP removing a character in a string

While a regexp would suit here just fine, I'll present you with an alternative method. It might be a tad faster than the equivalent regexp, but life's all about choices (...or something).

$length = strlen($urlString);
for ($i=0; $i<$length; i++) {
  if ($urlString[$i] === '?') {
    $urlString[$i+1] = '';
    break;
  }
}

Weird, I know.

How do I send a POST request as a JSON?

You have to add header,or you will get http 400 error. The code works well on python2.6,centos5.4

code:

    import urllib2,json

    url = 'http://www.google.com/someservice'
    postdata = {'key':'value'}

    req = urllib2.Request(url)
    req.add_header('Content-Type','application/json')
    data = json.dumps(postdata)

    response = urllib2.urlopen(req,data)

Using LINQ to group by multiple properties and sum

Linus is spot on in the approach, but a few properties are off. It looks like 'AgencyContractId' is your Primary Key, which is unrelated to the output you want to give the user. I think this is what you want (assuming you change your ViewModel to match the data you say you want in your view).

var agencyContracts = _agencyContractsRepository.AgencyContracts
    .GroupBy(ac => new
                   {
                       ac.AgencyID,
                       ac.VendorID,
                       ac.RegionID
                   })
    .Select(ac => new AgencyContractViewModel
                   {
                       AgencyId = ac.Key.AgencyID,
                       VendorId = ac.Key.VendorID,
                       RegionId = ac.Key.RegionID,
                       Total = ac.Sum(acs => acs.Amount) + ac.Sum(acs => acs.Fee)
                   });

HTTP post XML data in C#

In General:

An example of an easy way to post XML data and get the response (as a string) would be the following function:

public string postXMLData(string destinationUrl, string requestXml)
{
    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(destinationUrl);
    byte[] bytes;
    bytes = System.Text.Encoding.ASCII.GetBytes(requestXml);
    request.ContentType = "text/xml; encoding='utf-8'";
    request.ContentLength = bytes.Length;
    request.Method = "POST";
    Stream requestStream = request.GetRequestStream();
    requestStream.Write(bytes, 0, bytes.Length);
    requestStream.Close();
    HttpWebResponse response;
    response = (HttpWebResponse)request.GetResponse();
    if (response.StatusCode == HttpStatusCode.OK)
    {
        Stream responseStream = response.GetResponseStream();
        string responseStr = new StreamReader(responseStream).ReadToEnd();
        return responseStr;
    }
    return null;
}

In your specific situation:

Instead of:

request.ContentType = "application/x-www-form-urlencoded";

use:

request.ContentType = "text/xml; encoding='utf-8'";

Also, remove:

string postData = "XMLData=" + Sendingxml;

And replace:

byte[] byteArray = Encoding.UTF8.GetBytes(postData);

with:

byte[] byteArray = Encoding.UTF8.GetBytes(Sendingxml.ToString());

File to byte[] in Java

If you don't have Java 8, and agree with me that including a massive library to avoid writing a few lines of code is a bad idea:

public static byte[] readBytes(InputStream inputStream) throws IOException {
    byte[] b = new byte[1024];
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    int c;
    while ((c = inputStream.read(b)) != -1) {
        os.write(b, 0, c);
    }
    return os.toByteArray();
}

Caller is responsible for closing the stream.

SQL exclude a column using SELECT * [except columnA] FROM tableA?

Sometimes the same program must handle different database stuctures. So I could not use a column list in the program to avoid errors in select statements.

* gives me all the optional fields. I check if the fields exist in the data table before use. This is my reason for using * in select.

This is how I handle excluded fields:

Dim da As New SqlDataAdapter("select * from table", cn)
da.FillSchema(dt, SchemaType.Source)
Dim fieldlist As String = ""
For Each DC As DataColumn In DT.Columns
   If DC.ColumnName.ToLower <> excludefield Then
    fieldlist = fieldlist &  DC.Columnname & ","
   End If
  Next

Replace Line Breaks in a String C#

Use replace with Environment.NewLine

myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;

As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of new line control characters.

Export DataBase with MySQL Workbench with INSERT statements

In MySQL Workbench 6.1.

I had to click on the Apply changes button in the insertion panel (only once, because twice and MWB crashes...).

You have to do it for each of your table.

Apply changes button

Then export your schema :

Export schema

Check Generate INSERT statements for table

Check INSERT

It is okay !

Inserts ok

How do I remove accents from characters in a PHP string?

I just created a removeAccents method based on the reading of this thread and this other one too (How to remove accents and turn letters into "plain" ASCII characters?).

The method is here: https://github.com/lingtalfi/Bat/blob/master/StringTool.md#removeaccents

Tests are here: https://github.com/lingtalfi/Bat/blob/master/btests/StringTool/removeAccents/stringTool.removeAccents.test.php,

and here is what was tested so far:

$a = [
    // easy
    '',
    'a',
    'après',
    'dédé fait la fête ?',
    // hard
    'àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ',
    'ZZCNASLEÓzzcnasleó',
    'qqqqZZCNASLEÓzzcnasleóqqq',
    'ŠŽšžŸÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïðñòóôõöøùúûüýÿ',       
    'ÀÁÂÃÄÅÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖØÙÚÛÜÝàáâãäåçèéêëìíîïñòóôõöøùúûüýÿ',
    'AaAaAaCcCcCcCcDdÐdEeEeEeEeEeGgGgGgGgHhHhIiIiIiIiIJjKk',
    'LlLlLl??LlNnNnNn?OoOoOoRrRrRrSsSsSsŠšTtTtTtUuUuUuUuUuUuWwYyŸZzZzŽž',
    '?ƒOoUuAaIiOoUuUuUuUuUu????',
    '??',
];

and it converts only accentuated things (letters/ligatures/cédilles/some letters with a line through/...?).

Here is the content of the method: (https://github.com/lingtalfi/Bat/blob/master/StringTool.php#L83)

public static function removeAccents($str)
{
    static $map = [
        // single letters
        'à' => 'a',
        'á' => 'a',
        'â' => 'a',
        'ã' => 'a',
        'ä' => 'a',
        'a' => 'a',
        'å' => 'a',
        'a' => 'a',
        'a' => 'a',
        'a' => 'a',
        '?' => 'a',
        'À' => 'A',
        'Á' => 'A',
        'Â' => 'A',
        'Ã' => 'A',
        'Ä' => 'A',
        'A' => 'A',
        'Å' => 'A',
        'A' => 'A',
        'A' => 'A',
        'A' => 'A',
        '?' => 'A',


        'ç' => 'c',
        'c' => 'c',
        'c' => 'c',
        'c' => 'c',
        'c' => 'c',
        'Ç' => 'C',
        'C' => 'C',
        'C' => 'C',
        'C' => 'C',
        'C' => 'C',

        'd' => 'd',
        'd' => 'd',
        'Ð' => 'D',
        'D' => 'D',
        'Ð' => 'D',


        'è' => 'e',
        'é' => 'e',
        'ê' => 'e',
        'ë' => 'e',
        'e' => 'e',
        'e' => 'e',
        'e' => 'e',
        'e' => 'e',
        'e' => 'e',
        'È' => 'E',
        'É' => 'E',
        'Ê' => 'E',
        'Ë' => 'E',
        'E' => 'E',
        'E' => 'E',
        'E' => 'E',
        'E' => 'E',
        'E' => 'E',

        'ƒ' => 'f',


        'g' => 'g',
        'g' => 'g',
        'g' => 'g',
        'g' => 'g',
        'G' => 'G',
        'G' => 'G',
        'G' => 'G',
        'G' => 'G',


        'h' => 'h',
        'h' => 'h',
        'H' => 'H',
        'H' => 'H',

        'ì' => 'i',
        'í' => 'i',
        'î' => 'i',
        'ï' => 'i',
        'i' => 'i',
        'i' => 'i',
        'i' => 'i',
        'i' => 'i',
        '?' => 'i',
        'i' => 'i',
        'Ì' => 'I',
        'Í' => 'I',
        'Î' => 'I',
        'Ï' => 'I',
        'I' => 'I',
        'I' => 'I',
        'I' => 'I',
        'I' => 'I',
        'I' => 'I',
        'I' => 'I',

        'j' => 'j',
        'J' => 'J',

        'k' => 'k',
        'K' => 'K',


        'l' => 'l',
        'l' => 'l',
        'l' => 'l',
        'l' => 'l',
        '?' => 'l',
        'L' => 'L',
        'L' => 'L',
        'L' => 'L',
        'L' => 'L',
        '?' => 'L',


        'ñ' => 'n',
        'n' => 'n',
        'n' => 'n',
        'n' => 'n',
        '?' => 'n',
        'Ñ' => 'N',
        'N' => 'N',
        'N' => 'N',
        'N' => 'N',

        'ò' => 'o',
        'ó' => 'o',
        'ô' => 'o',
        'õ' => 'o',
        'ö' => 'o',
        'ð' => 'o',
        'ø' => 'o',
        'o' => 'o',
        'o' => 'o',
        'o' => 'o',
        'o' => 'o',
        'o' => 'o',
        '?' => 'o',
        'Ò' => 'O',
        'Ó' => 'O',
        'Ô' => 'O',
        'Õ' => 'O',
        'Ö' => 'O',
        'Ø' => 'O',
        'O' => 'O',
        'O' => 'O',
        'O' => 'O',
        'O' => 'O',
        'O' => 'O',
        '?' => 'O',


        'r' => 'r',
        'r' => 'r',
        'r' => 'r',
        'R' => 'R',
        'R' => 'R',
        'R' => 'R',


        's' => 's',
        'š' => 's',
        's' => 's',
        's' => 's',
        'S' => 'S',
        'Š' => 'S',
        'S' => 'S',
        'S' => 'S',

        't' => 't',
        't' => 't',
        't' => 't',
        'T' => 'T',
        'T' => 'T',
        'T' => 'T',


        'ù' => 'u',
        'ú' => 'u',
        'û' => 'u',
        'ü' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'u' => 'u',
        'Ù' => 'U',
        'Ú' => 'U',
        'Û' => 'U',
        'Ü' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',
        'U' => 'U',


        'w' => 'w',
        'W' => 'W',

        'ý' => 'y',
        'ÿ' => 'y',
        'y' => 'y',
        'Ý' => 'Y',
        'Ÿ' => 'Y',
        'Y' => 'Y',

        'z' => 'z',
        'z' => 'z',
        'ž' => 'z',
        'Z' => 'Z',
        'Z' => 'Z',
        'Ž' => 'Z',


        // accentuated ligatures
        '?' => 'A',
        '?' => 'a',
    ];
    return strtr($str, $map);
}

Find if value in column A contains value from column B?

You could try this

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),FALSE, TRUE)

-or-

=IF(ISNA(VLOOKUP(<single column I value>,<entire column E range>,1,FALSE)),"FALSE", "File found in row "   & MATCH(<single column I value>,<entire column E range>,0))

you could replace <single column I value> and <entire column E range> with named ranged. That'd probably be the easiest.

Just drag that formula all the way down the length of your I column in whatever column you want.

How to set iframe size dynamically

If you use jquery, it can be done by using $(window).height();

<iframe src="html_intro.asp" width="100%" class="myIframe">
<p>Hi SOF</p>
</iframe>

<script type="text/javascript" language="javascript"> 
$('.myIframe').css('height', $(window).height()+'px');
</script>

Get the second highest value in a MySQL table

SELECT MAX(salary) salary
FROM tbl
WHERE salary <
  (SELECT MAX(salary)
   FROM tbl);

How to make sql-mode="NO_ENGINE_SUBSTITUTION" permanent in MySQL my.cnf

[Fixed] Server version: 10.1.38-MariaDB - mariadb.org binary distribution

Go to: C:\xampp\mysql\bin open my.ini in notepad and find [mysqld] (line number 27) then after this line(line no 28) just type: skip-grant-tables

save the file and then reload the phpmyadmin page.It worked for me.

Set Background color programmatically

If you just want to use some of the predefined Android colors, you can use Color.COLOR (where COLOR is BLACK, WHITE, RED, etc.):

myView.setBackgroundColor(Color.GREEN);

Otherwise you can do as others have suggested with

myView.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.myCustomGreen));

I don't recommend using a hex color directly. You should keep all of your custom colors in colors.xml.

Django URL Redirect

You can try the Class Based View called RedirectView

from django.views.generic.base import RedirectView

urlpatterns = patterns('',
    url(r'^$', 'macmonster.views.home'),
    #url(r'^macmon_home$', 'macmonster.views.home'),
    url(r'^macmon_output/$', 'macmonster.views.output'),
    url(r'^macmon_about/$', 'macmonster.views.about'),
    url(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')
)

Notice how as url in the <url_to_home_view> you need to actually specify the url.

permanent=False will return HTTP 302, while permanent=True will return HTTP 301.

Alternatively you can use django.shortcuts.redirect

Update for Django 2+ versions

With Django 2+, url() is deprecated and replaced by re_path(). Usage is exactly the same as url() with regular expressions. For replacements without the need of regular expression, use path().

from django.urls import re_path

re_path(r'^.*$', RedirectView.as_view(url='<url_to_home_view>', permanent=False), name='index')

Running an outside program (executable) in Python?

I'd try inserting an 'r' in front of your path if I were you, to indicate that it's a raw string - and then you won't have to use forward slashes. For example:

os.system(r"C:\Documents and Settings\flow_model\flow.exe")

AngularJS - Trigger when radio button is selected

Another approach is using Object.defineProperty to set valueas a getter setter property in the controller scope, then each change on the value property will trigger a function specified in the setter:

The HTML file:

<input type="radio" ng-model="value" value="one"/>
<input type="radio" ng-model="value" value="two"/>
<input type="radio" ng-model="value" value="three"/>

The javascript file:

var _value = null;
Object.defineProperty($scope, 'value', {
  get: function () {
    return _value;
  },         
  set: function (value) {
    _value = value;
    someFunction();
  }
});

see this plunker for the implementation

Numpy - add row to array

I use numpy.insert(arr, i, the_object_to_be_added, axis) in order to insert object_to_be_added at the i'th row(axis=0) or column(axis=1)

import numpy as np

a = np.array([[1, 2, 3], [5, 4, 6]])
# array([[1, 2, 3],
#        [5, 4, 6]])

np.insert(a, 1, [55, 66], axis=1)
# array([[ 1, 55,  2,  3],
#        [ 5, 66,  4,  6]])

np.insert(a, 2, [50, 60, 70], axis=0)
# array([[ 1,  2,  3],
#        [ 5,  4,  6],
#        [50, 60, 70]])

Too old discussion, but I hope it helps someone.

Update Fragment from ViewPager

You can update the fragment in two different ways,

First way

like @Sajmon

You need to implement getItemPosition(Object obj) method.

This method is called when you call

notifyDataSetChanged()

You can find a example in Github and more information in this post.

enter image description here

Second way

My approach to update fragments within the viewpager is to use the setTag() method for any instantiated view in the instantiateItem() method. So when you want to change the data or invalidate the view that you need, you can call the findViewWithTag() method on the ViewPager to retrieve the previously instantiated view and modify/use it as you want without having to delete/create a new view each time you want to update some value.

@Override
public Object instantiateItem(ViewGroup container, int position) {
    Object object = super.instantiateItem(container, position);
    if (object instanceof Fragment) {
        Fragment fragment = (Fragment) object;
        String tag = fragment.getTag();
        mFragmentTags.put(position, tag);
    }
    return object;
}

public Fragment getFragment(int position) {
    Fragment fragment = null;
    String tag = mFragmentTags.get(position);
    if (tag != null) {
        fragment = mFragmentManager.findFragmentByTag(tag);
    }
    return fragment;
}

You can find a example in Github or more information in this post:

enter image description here

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

size of NumPy array

This is called the "shape" in NumPy, and can be requested via the .shape attribute:

>>> a = zeros((2, 5))
>>> a.shape
(2, 5)

If you prefer a function, you could also use numpy.shape(a).

Convert ArrayList to String array in Android

You could make an array the same size as the ArrayList and then make an iterated for loop to index the items and insert them into the array.

Can't bind to 'ngForOf' since it isn't a known property of 'tr' (final release)

When use "app-routing.module" we forget import "CommonModule". Remember to import!

import { CommonModule } from "@angular/common";
@NgModule({  imports: [ CommonModule]})

What does @media screen and (max-width: 1024px) mean in CSS?

It means if the screen size is 1024 then only apply below CSS rules.

Add image to layout in ruby on rails

In a Ruby on Rails project by default the root of the HTML source for the server is the public directory. So your link would be:

<img src="images/rss.jpg" alt="rss feed" />

But it is best practice in a Rails project to use the built in helper:

<%= image_tag("rss.jpg", :alt => "rss feed") %>

That will create the correct image link plus if you ever add assert servers, etc it will work with those.

How to add extra whitespace in PHP?

for adding space character you can use

<? 
echo "\x20\x20\x20"; 
 ?>

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

Firstly, why doesn't your solution work. You mix up a lot of concepts. Mostly character class with other ones. In the first character class you use | which stems from alternation. In character classes you don't need the pipe. Just list all characters (and character ranges) you want:

[Uu]

Or simply write u if you use the case-insensitive modifier. If you write a pipe there, the character class will actually match pipes in your subject string.

Now in the second character class you use the comma to separate your characters for some odd reason. That does also nothing but include commas into the matchable characters. s and W are probably supposed to be the built-in character classes. Then escape them! Otherwise they will just match literal s and literal W. But then \W already includes everything else you listed there, so a \W alone (without square brackets) would have been enough. And the last part (^a-zA-Z) also doesn't work, because it will simply include ^, (, ) and all letters into the character class. The negation syntax only works for entire character classes like [^a-zA-Z].

What you actually want is to assert that there is no letter in front or after your u. You can use lookarounds for that. The advantage is that they won't be included in the match and thus won't be removed:

r'(?<![a-zA-Z])[uU](?![a-zA-Z])'

Note that I used a raw string. Is generally good practice for regular expressions, to avoid problems with escape sequences.

These are negative lookarounds that make sure that there is no letter character before or after your u. This is an important difference to asserting that there is a non-letter character around (which is similar to what you did), because the latter approach won't work at the beginning or end of the string.

Of course, you can remove the spaces around you from the replacement string.

If you don't want to replace u that are next to digits, you can easily include the digits into the character classes:

r'(?<![a-zA-Z0-9])[uU](?![a-zA-Z0-9])'

And if for some reason an adjacent underscore would also disqualify your u for replacement, you could include that as well. But then the character class coincides with the built-in \w:

r'(?<!\w)[uU](?!\w)'

Which is, in this case, equivalent to EarlGray's r'\b[uU]\b'.

As mentioned above you can shorten all of these, by using the case-insensitive modifier. Taking the first expression as an example:

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.I)

or

re.sub(r'(?<![a-z])u(?![a-z])', 'you', text, flags=re.IGNORECASE)

depending on your preference.

I suggest that you do some reading through the tutorial I linked several times in this answer. The explanations are very comprehensive and should give you a good headstart on regular expressions, which you will probably encounter again sooner or later.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Update using NuGet Package Manager Console in your Visual Studio

Update-Package -reinstall Microsoft.AspNet.Mvc

SQL WHERE condition is not equal to?

You can do like this

DELETE FROM table WHERE id NOT IN ( 2 )

OR

DELETE FROM table WHERE id <>  2 

As @Frank Schmitt noted, you might want to be careful about the NULL values too. If you want to delete everything which is not 2(including the NULLs) then add OR id IS NULL to the WHERE clause.

Groovy built-in REST/HTTP client?

HTTPBuilder is it. Very easy to use.

import groovyx.net.http.HTTPBuilder

def http = new HTTPBuilder('https://google.com')
def html = http.get(path : '/search', query : [q:'waffles'])

It is especially useful if you need error handling and generally more functionality than just fetching content with GET.

calling another method from the main method in java

You can do it multiple ways. Here are two. Cheers!

package learningjava;

public class helloworld {
    public static void main(String[] args) {
        new helloworld().go();
        // OR
        helloworld.get();
    }

    public void go(){
        System.out.println("Hello World");
    }
    public static void get(){
        System.out.println("Hello World, Again");
    }
}

How to delete the last row of data of a pandas dataframe

To drop last n rows:

df.drop(df.tail(n).index,inplace=True) # drop last n rows

By the same vein, you can drop first n rows:

df.drop(df.head(n).index,inplace=True) # drop first n rows

Unable to load AWS credentials from the /AwsCredentials.properties file on the classpath

In a Linux server, using default implementation of ses will expect files in .aws/credentials file. You can put following content in credential file at the location below and it will work. /home/local/<your service account>/.aws/credentials.

[default]
aws_access_key_id=<your access key>
aws_secret_access_key=<your secret access key>

Rename multiple columns by names

There are a few answers mentioning the functions dplyr::rename_with and rlang::set_names already. By they are separate. this answer illustrates the differences between the two and the use of functions and formulas to rename columns.

rename_with from the dplyr package can use either a function or a formula to rename a selection of columns given as the .cols argument. For example passing the function name toupper:

library(dplyr)
rename_with(head(iris), toupper, starts_with("Petal"))

Is equivalent to passing the formula ~ toupper(.x):

rename_with(head(iris), ~ toupper(.x), starts_with("Petal"))

When renaming all columns, you can also use set_names from the rlang package. To make a different example, let's use paste0 as a renaming function. pasteO takes 2 arguments, as a result there are different ways to pass the second argument depending on whether we use a function or a formula.

rlang::set_names(head(iris), paste0, "_hi")
rlang::set_names(head(iris), ~ paste0(.x, "_hi"))

The same can be achieved with rename_with by passing the data frame as first argument .data, the function as second argument .fn, all columns as third argument .cols=everything() and the function parameters as the fourth argument .... Alternatively you can place the second, third and fourth arguments in a formula given as the second argument.

rename_with(head(iris), paste0, everything(), "_hi")
rename_with(head(iris), ~ paste0(.x, "_hi"))

rename_with only works with data frames. set_names is more generic and can also perform vector renaming

rlang::set_names(1:4, c("a", "b", "c", "d"))

How Do I Convert an Integer to a String in Excel VBA?

The accepted answer is good for smaller numbers, most importantly while you are taking data from excel sheets. as the bigger numbers will automatically converted to scientific numbers i.e. e+10.
So I think this will give you more general answer. I didn't check if it have any downfall or not.

CStr(CDbl(#yourNumber#))

this will work for e+ converted numbers! as the just CStr(7.7685099559e+11) will be shown as "7.7685099559e+11" not as expected: "776850995590" So I rather to say my answer will be more generic result.

Regards, M

Django -- Template tag in {% if %} block

You try this.

I have already tried it in my django template.

It will work fine. Just remove the curly braces pair {{ and }} from {{source}}.

I have also added <table> tag and that's it.

After modification your code will look something like below.

{% for source in sources %}
   <table>
      <tr>
          <td>{{ source }}</td>
          <td>
              {% if title == source %}
                Just now! 
              {% endif %}
          </td>
      </tr>
   </table>
{% endfor %}

My dictionary looks like below,

{'title':"Rishikesh", 'sources':["Hemkesh", "Malinikesh", "Rishikesh", "Sandeep", "Darshan", "Veeru", "Shwetabh"]}

and OUTPUT looked like below once my template got rendered.

Hemkesh 
Malinikesh  
Rishikesh   Just now!
Sandeep 
Darshan 
Veeru   
Shwetabh    

I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

range() can only work with integers, but dividing with the / operator always results in a float value:

>>> 450 / 10
45.0
>>> range(450 / 10)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer

Make the value an integer again:

for i in range(int(c / 10)):

or use the // floor division operator:

for i in range(c // 10):

Executable directory where application is running from?

Dim strPath As String = System.IO.Path.GetDirectoryName( _
    System.Reflection.Assembly.GetExecutingAssembly().CodeBase)

Taken from HOW TO: Determine the Executing Application's Path (MSDN)

How can I Insert data into SQL Server using VBNet

Imports System.Data

Imports System.Data.SqlClient

Public Class Form2

Dim myconnection As SqlConnection

Dim mycommand As SqlCommand

Dim dr As SqlDataReader

Dim dr1 As SqlDataReader

Dim ra As Integer


Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click


    myconnection = New SqlConnection("server=localhost;uid=root;pwd=;database=simple")

    'you need to provide password for sql server

    myconnection.Open()

    mycommand = New SqlCommand("insert into tbl_cus([name],[class],[phone],[address]) values ('" & TextBox1.Text & "','" & TextBox2.Text & "','" & TextBox3.Text & "','" & TextBox4.Text & "')", myconnection)

    mycommand.ExecuteNonQuery()

    MessageBox.Show("New Row Inserted" & ra)

    myconnection.Close()

End Sub

End Class

Clear ComboBox selected text

Try specifying the actual index of the item you want erase the text from and set it's Text equal to "".

myComboBox[this.SelectedIndex].Text = ""

or

myComboBox.selectedIndex.Text = ""

I don't remember the exact syntax but it's something along those lines.

Angles between two n-dimensional vectors in Python

The other possibility is using just numpy and it gives you the interior angle

import numpy as np

p0 = [3.5, 6.7]
p1 = [7.9, 8.4]
p2 = [10.8, 4.8]

''' 
compute angle (in degrees) for p0p1p2 corner
Inputs:
    p0,p1,p2 - points in the form of [x,y]
'''

v0 = np.array(p0) - np.array(p1)
v1 = np.array(p2) - np.array(p1)

angle = np.math.atan2(np.linalg.det([v0,v1]),np.dot(v0,v1))
print np.degrees(angle)

and here is the output:

In [2]: p0, p1, p2 = [3.5, 6.7], [7.9, 8.4], [10.8, 4.8]

In [3]: v0 = np.array(p0) - np.array(p1)

In [4]: v1 = np.array(p2) - np.array(p1)

In [5]: v0
Out[5]: array([-4.4, -1.7])

In [6]: v1
Out[6]: array([ 2.9, -3.6])

In [7]: angle = np.math.atan2(np.linalg.det([v0,v1]),np.dot(v0,v1))

In [8]: angle
Out[8]: 1.8802197318858924

In [9]: np.degrees(angle)
Out[9]: 107.72865519428085

Error: Segmentation fault (core dumped)

"Segmentation fault (core dumped)" is the string that Linux prints when a program exits with a SIGSEGV signal and you have core creation enabled. This means some program has crashed.

If you're actually getting this error from running Python, this means the Python interpreter has crashed. There are only a few reasons this can happen:

  1. You're using a third-party extension module written in C, and that extension module has crashed.

  2. You're (directly or indirectly) using the built-in module ctypes, and calling external code that crashes.

  3. There's something wrong with your Python installation.

  4. You've discovered a bug in Python that you should report.

The first is by far the most common. If your q is an instance of some object from some third-party extension module, you may want to look at the documentation.

Often, when C modules crash, it's because you're doing something which is invalid, or at least uncommon and untested. But whether it's your "fault" in that sense or not - that doesn't matter. The module should raise a Python exception that you can debug, instead of crashing. So, you should probably report a bug to whoever wrote the extension. But meanwhile, rather than waiting 6 months for the bug to be fixed and a new version to come out, you need to figure out what you did that triggered the crash, and whether there's some different way to do what you want. Or switch to a different library.

On the other hand, since you're reading and printing out data from somewhere else, it's possible that your Python interpreter just read the line "Segmentation fault (core dumped)" and faithfully printed what it read. In that case, some other program upstream presumably crashed. (It's even possible that nobody crashed—if you fetched this page from the web and printed it out, you'd get that same line, right?) In your case, based on your comment, it's probably the Java program that crashed.

If you're not sure which case it is (and don't want to learn how to do process management, core-file inspection, or C-level debugging today), there's an easy way to test: After print line add a line saying print "And I'm OK". If you see that after the Segmentation fault line, then Python didn't crash, someone else did. If you don't see it, then it's probably Python that's crashed.

XPath to select multiple tags

One correct answer is:

/a/b/*[self::c or self::d or self::e]

Do note that this

a/b/*[local-name()='c' or local-name()='d' or local-name()='e']

is both too-long and incorrect. This XPath expression will select nodes like:

OhMy:c

NotWanted:d 

QuiteDifferent:e

How do I load a PHP file into a variable?

I suppose you want to get the content generated by PHP, if so use:

$Vdata = file_get_contents('http://YOUR_HOST/YOUR/FILE.php');

Otherwise if you want to get the source code of the PHP file, it's the same as a .txt file:

$Vdata = file_get_contents('path/to/YOUR/FILE.php');

How to "grep" for a filename instead of the contents of a file?

Also for multiple files.

tree /path/to/directory/ | grep -i "file1 \| file2 \| file3"

What is the difference between readonly="true" & readonly="readonly"?

Giving an element the attribute readonly will give that element the readonly status. It doesn't matter what value you put after it or if you put any value after it, it will still see it as readonly. Putting readonly="false" won't work.

Suggested is to use the W3C standard, which is readonly="readonly".

Updating the list view when the adapter data changes

invalidate(); calls the list view to invalidate itself (ie. background color)
invalidateViews(); calls all of its children to be invalidated. allowing you to update the children views

I assume its some type of efficiency thing preventing all of the items to constantly have to be redraw if not necessary.

How to change the background color on a input checkbox with css?

I always use pseudo elements :before and :after for changing the appearance of checkboxes and radio buttons. it's works like a charm.

Refer this link for more info

CODEPEN

Steps

  1. Hide the default checkbox using css rules like visibility:hidden or opacity:0 or position:absolute;left:-9999px etc.
  2. Create a fake checkbox using :before element and pass either an empty or a non-breaking space '\00a0';
  3. When the checkbox is in :checked state, pass the unicode content: "\2713", which is a checkmark;
  4. Add :focus style to make the checkbox accessible.
  5. Done

Here is how I did it.

_x000D_
_x000D_
.box {_x000D_
  background: #666666;_x000D_
  color: #ffffff;_x000D_
  width: 250px;_x000D_
  padding: 10px;_x000D_
  margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
  margin: 1.5em 0;_x000D_
  padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
  visibility: hidden;_x000D_
}_x000D_
label {_x000D_
  cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
  border: 1px solid #333;_x000D_
  content: "\00a0";_x000D_
  display: inline-block;_x000D_
  font: 16px/1em sans-serif;_x000D_
  height: 16px;_x000D_
  margin: 0 .25em 0 0;_x000D_
  padding: 0;_x000D_
  vertical-align: top;_x000D_
  width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
  background: #fff;_x000D_
  color: #333;_x000D_
  content: "\2713";_x000D_
  text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
  font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
    outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
  <div class="box">_x000D_
    <p>_x000D_
      <input type="checkbox" id="c1" name="cb">_x000D_
      <label for="c1">Option 01</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c2" name="cb">_x000D_
      <label for="c2">Option 02</label>_x000D_
    </p>_x000D_
    <p>_x000D_
      <input type="checkbox" id="c3" name="cb">_x000D_
      <label for="c3">Option 03</label>_x000D_
    </p>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Much more stylish using :before and :after

_x000D_
_x000D_
body{_x000D_
  font-family: sans-serif;  _x000D_
}_x000D_
_x000D_
.container {_x000D_
    margin-top: 50px;_x000D_
    margin-left: 20px;_x000D_
    margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
    width: 100%;_x000D_
    margin: 15px auto;_x000D_
    position: relative;_x000D_
    display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
    width: auto;_x000D_
    opacity: 0.00000001;_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
    position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    top: 0;_x000D_
    margin: 4px;_x000D_
    width: 22px;_x000D_
    height: 22px;_x000D_
    transition: transform 0.28s ease;_x000D_
    border-radius: 3px;_x000D_
    border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
  content: '';_x000D_
    display: block;_x000D_
    width: 10px;_x000D_
    height: 5px;_x000D_
    border-bottom: 2px solid #7bbe72;_x000D_
    border-left: 2px solid #7bbe72;_x000D_
    -webkit-transform: rotate(-45deg) scale(0);_x000D_
    transform: rotate(-45deg) scale(0);_x000D_
    transition: transform ease 0.25s;_x000D_
    will-change: transform;_x000D_
    position: absolute;_x000D_
    top: 12px;_x000D_
    left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
    color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
    -webkit-transform: rotate(-45deg) scale(1);_x000D_
    transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
    min-height: 34px;_x000D_
    display: block;_x000D_
    padding-left: 40px;_x000D_
    margin-bottom: 0;_x000D_
    font-weight: normal;_x000D_
    cursor: pointer;_x000D_
    vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    -webkit-transform: translateY(-50%);_x000D_
    transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
    outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox" name="" value="">_x000D_
     <label for="checkbox"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
_x000D_
  <div class="checkbox">_x000D_
     <input type="checkbox" id="checkbox2" name="" value="">_x000D_
     <label for="checkbox2"><span>Checkbox</span></label>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Can you animate a height change on a UITableViewCell when selected?

I resolved with reloadRowsAtIndexPaths.

I save in didSelectRowAtIndexPath the indexPath of cell selected and call reloadRowsAtIndexPaths at the end (you can send NSMutableArray for list of element's you want reload).

In heightForRowAtIndexPath you can check if indexPath is in the list or not of expandIndexPath cell's and send height.

You can check this basic example: https://github.com/ferminhg/iOS-Examples/tree/master/iOS-UITableView-Cell-Height-Change/celdascambiadetam It's a simple solution.

i add a sort of code if help you

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 20;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath*)indexPath
{
    if ([indexPath isEqual:_expandIndexPath])
        return 80;

    return 40;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Celda";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];

    [cell.textLabel setText:@"wopwop"];

    return cell;
}

#pragma mark -
#pragma mark Tableview Delegate Methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMutableArray *modifiedRows = [NSMutableArray array];
    // Deselect cell
    [tableView deselectRowAtIndexPath:indexPath animated:TRUE];
    _expandIndexPath = indexPath;
    [modifiedRows addObject:indexPath];

    // This will animate updating the row sizes
    [tableView reloadRowsAtIndexPaths:modifiedRows withRowAnimation:UITableViewRowAnimationAutomatic];
}

How to convert array into comma separated string in javascript

You can simply use JavaScripts join() function for that. This would simply look like a.value.join(','). The output would be a string though.

What is log4j's default log file dumping path

You can see the log info in the console view of your IDE if you are not using any log4j properties to generate log file. You can define log4j.properties in your project so that those properties would be used to generate log file. A quick sample is listed below.

# Global logging configuration
log4j.rootLogger=DEBUG, stdout, R

# SQL Map logging configuration...
log4j.logger.com.ibatis=INFO
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=INFO
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=INFO
log4j.logger.com.ibatis.SQLMap.engine.impl.SQL MapClientDelegate=INFO

log4j.logger.java.sql.Connection=INFO
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=INFO

log4j.logger.org.apache.http=ERROR

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=MyLog.log
log4j.appender.R.MaxFileSize=50000KB
log4j.appender.R.Encoding=UTF-8

# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d %5p [%t] (%F\:%L) - %m%n

Powershell: convert string to number

Since this topic never received a verified solution, I can offer a simple solution to the two issues I see you asked solutions for.

  1. Replacing the "." character when value is a string

The string class offers a replace method for the string object you want to update:

Example:

$myString = $myString.replace(".","") 
  1. Converting the string value to an integer

The system.int32 class (or simply [int] in powershell) has a method available called "TryParse" which will not only pass back a boolean indicating whether the string is an integer, but will also return the value of the integer into an existing variable by reference if it returns true.

Example:

[string]$convertedInt = "1500"
[int]$returnedInt = 0
[bool]$result = [int]::TryParse($convertedInt, [ref]$returnedInt)

I hope this addresses the issue you initially brought up in your question.

Excel VBA - How to Redim a 2D array?

Here ya go.

Public Function ReDimPreserve(ByRef Arr, ByVal idx1 As Integer, ByVal idx2 As Integer)

    Dim newArr()
    Dim x As Integer
    Dim y As Integer

    ReDim newArr(idx1, idx2)

    For x = 0 To UBound(Arr, 1)
        For y = 0 To UBound(Arr, 2)
            newArr(x, y) = Arr(x, y)
        Next
    Next

    Arr = newArr

End Function

Understanding MongoDB BSON Document size limit

Nested Depth for BSON Documents: MongoDB supports no more than 100 levels of nesting for BSON documents.

More more info vist

How to Check if value exists in a MySQL database

For Matching the ID:

Select * from table_name where 1=1

For Matching the Pattern:

Select * from table_name column_name Like '%string%'

Jackson Vs. Gson

Adding to other answers already given above. If case insensivity is of any importance to you, then use Jackson. Gson does not support case insensitivity for key names, while jackson does.

Here are two related links

(No) Case sensitivity support in Gson : GSON: How to get a case insensitive element from Json?

Case sensitivity support in Jackson https://gist.github.com/electrum/1260489

How to return history of validation loss in Keras

It's been solved.

The losses only save to the History over the epochs. I was running iterations instead of using the Keras built in epochs option.

so instead of doing 4 iterations I now have

model.fit(......, nb_epoch = 4)

Now it returns the loss for each epoch run:

print(hist.history)
{'loss': [1.4358016599558268, 1.399221191623641, 1.381293383180471, h1.3758836857303727]}

Laravel - Form Input - Multiple select for a one to many relationship

A multiple select is really just a select with a multiple attribute. With that in mind, it should be as easy as...

Form::select('sports[]', $sports, null, array('multiple'))

The first parameter is just the name, but post-fixing it with the [] will return it as an array when you use Input::get('sports').

The second parameter is an array of selectable options.

The third parameter is an array of options you want pre-selected.

The fourth parameter is actually setting this up as a multiple select dropdown by adding the multiple property to the actual select element..

How to define optional methods in Swift protocol?

A pure Swift approach with protocol inheritance:

//Required methods
protocol MyProtocol {
    func foo()
}

//Optional methods
protocol MyExtendedProtocol: MyProtocol {
    func bar()
}

class MyClass {
    var delegate: MyProtocol
    func myMethod() {
        (delegate as? MyExtendedProtocol).bar()
    }
}

A TypeScript GUID class?

I found this https://typescriptbcl.codeplex.com/SourceControl/latest

here is the Guid version they have in case the link does not work later.

module System {
    export class Guid {
        constructor (public guid: string) {
            this._guid = guid;
        }

        private _guid: string;

        public ToString(): string {
            return this.guid;
        }

        // Static member
        static MakeNew(): Guid {
            var result: string;
            var i: string;
            var j: number;

            result = "";
            for (j = 0; j < 32; j++) {
                if (j == 8 || j == 12 || j == 16 || j == 20)
                    result = result + '-';
                i = Math.floor(Math.random() * 16).toString(16).toUpperCase();
                result = result + i;
            }
            return new Guid(result);
        }
    }
}

$_SERVER["REMOTE_ADDR"] gives server IP rather than visitor IP

Replacing:

$_SERVER["REMOTE_ADDR"];

With:

$_SERVER["HTTP_X_REAL_IP"];

Worked for me.

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

Object-oriented version of the most up-voted solution

I've created an object-oriented solution based on Scott's answer:

<?php

namespace Utils;

/**
 * Class RandomStringGenerator
 * @package Utils
 *
 * Solution taken from here:
 * http://stackoverflow.com/a/13733588/1056679
 */
class RandomStringGenerator
{
    /** @var string */
    protected $alphabet;

    /** @var int */
    protected $alphabetLength;


    /**
     * @param string $alphabet
     */
    public function __construct($alphabet = '')
    {
        if ('' !== $alphabet) {
            $this->setAlphabet($alphabet);
        } else {
            $this->setAlphabet(
                  implode(range('a', 'z'))
                . implode(range('A', 'Z'))
                . implode(range(0, 9))
            );
        }
    }

    /**
     * @param string $alphabet
     */
    public function setAlphabet($alphabet)
    {
        $this->alphabet = $alphabet;
        $this->alphabetLength = strlen($alphabet);
    }

    /**
     * @param int $length
     * @return string
     */
    public function generate($length)
    {
        $token = '';

        for ($i = 0; $i < $length; $i++) {
            $randomKey = $this->getRandomInteger(0, $this->alphabetLength);
            $token .= $this->alphabet[$randomKey];
        }

        return $token;
    }

    /**
     * @param int $min
     * @param int $max
     * @return int
     */
    protected function getRandomInteger($min, $max)
    {
        $range = ($max - $min);

        if ($range < 0) {
            // Not so random...
            return $min;
        }

        $log = log($range, 2);

        // Length in bytes.
        $bytes = (int) ($log / 8) + 1;

        // Length in bits.
        $bits = (int) $log + 1;

        // Set all lower bits to 1.
        $filter = (int) (1 << $bits) - 1;

        do {
            $rnd = hexdec(bin2hex(openssl_random_pseudo_bytes($bytes)));

            // Discard irrelevant bits.
            $rnd = $rnd & $filter;

        } while ($rnd >= $range);

        return ($min + $rnd);
    }
}

Usage

<?php

use Utils\RandomStringGenerator;

// Create new instance of generator class.
$generator = new RandomStringGenerator;

// Set token length.
$tokenLength = 32;

// Call method to generate random string.
$token = $generator->generate($tokenLength);

Custom alphabet

You can use custom alphabet if required. Just pass a string with supported chars to the constructor or setter:

<?php

$customAlphabet = '0123456789ABCDEF';

// Set initial alphabet.
$generator = new RandomStringGenerator($customAlphabet);

// Change alphabet whenever needed.
$generator->setAlphabet($customAlphabet);

Here's the output samples

SRniGU2sRQb2K1ylXKnWwZr4HrtdRgrM
q1sRUjNq1K9rG905aneFzyD5IcqD4dlC
I0euIWffrURLKCCJZ5PQFcNUCto6cQfD
AKwPJMEM5ytgJyJyGqoD5FQwxv82YvMr
duoRF6gAawNOEQRICnOUNYmStWmOpEgS
sdHUkEn4565AJoTtkc8EqJ6cC4MLEHUx
eVywMdYXczuZmHaJ50nIVQjOidEVkVna
baJGt7cdLDbIxMctLsEBWgAw5BByP5V0
iqT0B2obq3oerbeXkDVLjZrrLheW4d8f
OUQYCny6tj2TYDlTuu1KsnUyaLkeObwa

I hope it will help someone. Cheers!

Use of String.Format in JavaScript?

Based on @roydukkey's answer, a bit more optimized for runtime (it caches the regexes):

(function () {
    if (!String.prototype.format) {
        var regexes = {};
        String.prototype.format = function (parameters) {
            for (var formatMessage = this, args = arguments, i = args.length; --i >= 0;)
                formatMessage = formatMessage.replace(regexes[i] || (regexes[i] = RegExp("\\{" + (i) + "\\}", "gm")), args[i]);
            return formatMessage;
        };
        if (!String.format) {
            String.format = function (formatMessage, params) {
                for (var args = arguments, i = args.length; --i;)
                    formatMessage = formatMessage.replace(regexes[i - 1] || (regexes[i - 1] = RegExp("\\{" + (i - 1) + "\\}", "gm")), args[i]);
                return formatMessage;
            };
        }
    }
})();

Fix columns in horizontal scrolling

Solved using JavaScript + jQuery! I just need similar solution to my project but current solution with HTML and CSS is not ok for me because there is issue with column height + I need more then one column to be fixed. So I create simple javascript solution using jQuery

You can try it here https://jsfiddle.net/kindrosker/ffwqvntj/

All you need is setup home many columsn will be fixed in data-count-fixed-columns parameter

<table class="table" data-count-fixed-columns="2" cellpadding="0" cellspacing="0">

and run js function

app_handle_listing_horisontal_scroll($('#table-listing'))

Does Python have an ordered set?

So i also had a small list where i clearly had the possibility of introducing non-unique values.

I searched for the existence of a unique list of some sort, but then realized that testing the existence of the element before adding it works just fine.

if(not new_element in my_list):
    my_list.append(new_element)

I don't know if there are caveats to this simple approach, but it solves my problem.

Best cross-browser method to capture CTRL+S with JQuery?

You could use a shortcut library to handle the browser specific stuff.

shortcut.add("Ctrl+S",function() {
    alert("Hi there!");
});

How to convert Java String into byte[]?

It is not necessary to change java as a String parameter. You have to change the c code to receive a String without a pointer and in its code:

Bool DmgrGetVersion (String szVersion);

Char NewszVersion [200];
Strcpy (NewszVersion, szVersion.t_str ());
.t_str () applies to builder c ++ 2010

Is it possible to preview stash contents in git?

You can view all stashes' list by the following command:

$ git stash list

stash@{0}: WIP on dev: ddd4d75 spelling fix

stash@{1}: WIP on dev: 40e65a8 setting width for messages

......

......

......


stash@{12}: WIP on dev: 264fdab added token based auth

Newest stash is the first one.

You can simply select index n of stash provided in the above list and use the following command to view stashed details

git stash show -p stash@{3}

Similarly,

git stash show -p stash@{n}

You can also check diff by using the command :

git diff HEAD stash@{n} -- /path/to/file

Correct way to pause a Python program

As pointed out by mhawke and steveha's comments, the best answer to this exact question would be:

For a long block of text, it is best to use input('Press <ENTER> to continue') (or raw_input('Press <ENTER> to continue') on Python 2.x) to prompt the user, rather than a time delay. Fast readers won't want to wait for a delay, slow readers might want more time on the delay, someone might be interrupted while reading it and want a lot more time, etc. Also, if someone uses the program a lot, he/she may become used to how it works and not need to even read the long text. It's just friendlier to let the user control how long the block of text is displayed for reading.

Python style - line continuation with strings?

Since adjacent string literals are automatically joint into a single string, you can just use the implied line continuation inside parentheses as recommended by PEP 8:

print("Why, hello there wonderful "
      "stackoverflow people!")

Google Chrome forcing download of "f.txt" file

Seems related to https://groups.google.com/forum/#!msg/google-caja-discuss/ite6K5c8mqs/Ayqw72XJ9G8J.

The so-called "Rosetta Flash" vulnerability is that allowing arbitrary yet identifier-like text at the beginning of a JSONP response is sufficient for it to be interpreted as a Flash file executing in that origin. See for more information: http://miki.it/blog/2014/7/8/abusing-jsonp-with-rosetta-flash/

JSONP responses from the proxy servlet now: * are prefixed with "/**/", which still allows them to execute as JSONP but removes requester control over the first bytes of the response. * have the response header Content-Disposition: attachment.

Selenium WebDriver and DropDown Boxes

You could try this:

IWebElement dropDownListBox = driver.findElement(By.Id("selection"));
SelectElement clickThis = new SelectElement(dropDownListBox);
clickThis.SelectByText("Germany");

Uncaught TypeError: Cannot read property 'msie' of undefined - jQuery tools

The $.browser method has been removed as of jQuery 1.9.

jQuery.browser() removed

The jQuery.browser() method has been deprecated since jQuery 1.3 and is removed in 1.9. If needed, it is available as part of the jQuery Migrate plugin. We recommend using feature detection with a library such as Modernizr.

jQuery Core 1.9 Upgrade Guide.

As stated in the Upgrade Guide you can try using the jQuery Migrate plugin to restore this functionality and let jQuery Tools work.

How can I control the speed that bootstrap carousel slides in items?

For Twitter Bootstrap 3:

You must change the CSS transition as specified in the other answer:

.carousel-inner > .item {
    position: relative;
    display: none;
    -webkit-transition: 0.6s ease-in-out left;
    -moz-transition: 0.6s ease-in-out left;
    -o-transition: 0.6s ease-in-out left;
    transition: 0.6s ease-in-out left;
}

From 0.6 seconds to 1.5 seconds (for example).

But also, there is some Javascript to change. In the bootstrap.js there is a line:

.emulateTransitionEnd(600)

This should be changed to the corresponding amount of milliseconds. So for 1.5 seconds you would change the number to 1500:

.emulateTransitionEnd(1500)

How do I get first name and last name as whole name in a MYSQL query?

When you have three columns : first_name, last_name, mid_name:

SELECT CASE 
    WHEN mid_name IS NULL OR TRIM(mid_name) ='' THEN
        CONCAT_WS( " ", first_name, last_name ) 
    ELSE 
        CONCAT_WS( " ", first_name, mid_name, last_name ) 
    END 
FROM USER;

how to end ng serve or firebase serve

ctrl + c OR ctrl + Pause/Break

Both will ask for Terminate batch job, then press Y or y and click enter.

Android Studio build fails with "Task '' not found in root project 'MyProject'."

Though late in answering, this is a hard one to Google (the single quotes) and it’s not clear what’s happening. I don't have the reputation yet to comment or ask for scope (or post 3 links), so this answer may be a little tedious.

To answer fast, you may have multiple Gradle plugins in your project.

Synchronize Gradle Wrapper and Plugins

My issue seemed to start with a corrupted IML file. Android Studio (between closing and reopening a project) began complaining an IML was gone (it wasn’t) and a module should be deleted, which I declined. It persisted, I upgraded to AS 0.8.7 (canary channel) and got stuck on the OP issue (Task '' not found in root project). This completely blocked builds so I had to dig in to Gradle.

My repair steps on OSX (please adjust for Windows):

  1. Upgrade Android Studio to 0.8.7
    • Preferences | Updates | Switch "Beta Channel" to "Canary Channel", then do a Check Now.
    • You might be able to skip this.
  2. Checked the Gradle wrapper (currently 1.12.2; don’t try to use 2.0 at this time).

    • Assuming you don’t need a particular version, use the latest supported distribution

      $ vi ~/project/gradle-wrapper.properties ... distributionUrl=http\://services.gradle.org/distributions/gradle-1.12-all.zip

    • This can be set in Android Studio at Preferences | Gradle (but 0.8.7 was giving me ‘invalid location’ errors).

    • The 'wrapper' is just a copy of Gradle for each Android Studio project. It allows you to have Gradle 2 in your OS, and different versions in your projects. The Android Developer docs explain that here.
    • Then adjust your build.gradle files for the plugin. The Gradle plugin version must be compatible with the distribution/wrapper version, for the whole project. As the Tools documentation (tools.android.com/tech-docs/new-build-system/user-guide#TOC-Requirements) is slightly out of date, you can set the plugin version too low (like 0.8.0) and Android Studio will throw an error with the acceptable range for the wrapper.

Example, in build.gradle, you have this plugin:

dependencies {
    classpath "com.android.tools.build:gradle:0.12.+"
}

You can try switching it to the exact version, like this:

dependencies {
    classpath "com.android.tools.build:gradle:0.12.2"
}

and (after recording what version you’re changing from in each case) verifying that every build.gradle file in your project pulls in the same plugin version. Keeping the “+” should work (for 0.12.0, 0.12.1, 0.12.2, etc), but my build succeeded when I updated Google’s Volley library (originally gradle:0.8.+) and my main project (originally 0.12.+) to the fixed version: gradle:0.12.2.

Other checks

  1. Ensure you don’t have two Android Application modules in the same Project

    • This may interact with the final solution (different Gradle versions, above), and cause

      UNEXPECTED TOP-LEVEL EXCEPTION: com.android.dex.DexException: Multiple dex files define (various classes)

    • To check, Build | Make Project should not pop up a window asking what application you want to make.

  2. Invalidate your caches
    • File | Invalidate Caches / Restart (stackoverflow.com/a/19223269/513413)
  3. If step 2 doesn't work, delete ~/.gradle/ (www.wuttech.com/index.php/tag/groovy-lang-closure/)
    • Quit Android Studio
    • $ rm -rf ~/.gradle/
    • Start Android Studio, then sync:
      • Tools | Android | Sync Project with Gradle Files
    • Repeat this entire sequence (quit...sync) a few times before giving up.
  4. Clean the project
    • Build | Clean Project

If You See This...

In my recent builds, I kept seeing horrible fails (pages of exceptions) but within seconds the messages would clear, build succeeded and the app deployed. Since I could never explain it and the app worked, I never noticed that I had two Gradle plugins in my project. So I think the Gradle plugins fought each other; one crashed, the other lost its state and reported the error.

If you have time, the 1-hour video "A Gentle Introduction to Gradle" (www.youtube.com/watch?v=OFUEb7pLLXw) really helped me approach the Gradle build files, tasks, build decisions, etc.

Disclaimer

I'm learning this entire stack, on a foreign OS, after working a different career...all at the same time and under pressure. In the last few months I have hit every wall I think Android has; I've been here quite often and this is my first post. I thought this was a hard fix, so I sincerely apologize if the quality of my answer reflects the difficulty I had in getting to it.

"While .. End While" doesn't work in VBA?

VBA is not VB/VB.NET

The correct reference to use is Do..Loop Statement (VBA). Also see the article Excel VBA For, Do While, and Do Until. One way to write this is:

Do While counter < 20
    counter = counter + 1
Loop

(But a For..Next might be more appropriate here.)

Happy coding.

Inserting a value into all possible locations in a list

If l is your list and X is your value:

for i in range(len(l) + 1):
    print l[:i] + [X] + l[i:]

R dplyr: Drop multiple columns

Another way is to mutate the undesired columns to NULL, this avoids the embedded parentheses :

head(iris,2) %>% mutate_at(drop.cols, ~NULL)
#   Petal.Length Petal.Width Species
# 1          1.4         0.2  setosa
# 2          1.4         0.2  setosa

Find duplicate values in R

Here's a data.table solution that will list the duplicates along with the number of duplications (will be 1 if there are 2 copies, and so on - you can adjust that to suit your needs):

library(data.table)
dt = data.table(vocabulary)

dt[duplicated(id), cbind(.SD[1], number = .N), by = id]

How to use numpy.genfromtxt when first column is string and the remaining columns are numbers?

data=np.genfromtxt(csv_file, delimiter=',', dtype='unicode')

It works fine for me.

Function not defined javascript

I just went through the same problem. And found out once you have a syntax or any type of error in you javascript, the whole file don't get loaded so you cannot use any of the other functions at all.

How to run code after some delay in Flutter?

(Adding response on old q as this is the top result on google)

I tried yielding a new state in the callback within a bloc, and it didn't work. Tried with Timer and Future.delayed.

However, what did work was...

await Future.delayed(const Duration(milliseconds: 500));

yield newState;

Awaiting an empty future then running the function afterwards.

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

In my case, I was actually missing my web.config altogether, which had the appropriate binding redirects. Restoring the web.config resolved the error.

C++ float array initialization

No, it sets all members/elements that haven't been explicitly set to their default-initialisation value, which is zero for numeric types.

How can I configure Logback to log different levels for a logger to different destinations?

The simplest solution is to use ThresholdFilter on the appenders:

    <appender name="..." class="...">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>

Full example:

<configuration>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>INFO</level>
        </filter>
        <encoder>
            <pattern>%d %-5level: %msg%n</pattern>
        </encoder>
    </appender>

    <appender name="STDERR" class="ch.qos.logback.core.ConsoleAppender">
        <filter class="ch.qos.logback.classic.filter.ThresholdFilter">
            <level>ERROR</level>
        </filter>
        <target>System.err</target>
        <encoder>
            <pattern>%d %-5level: %msg%n</pattern>
        </encoder>
    </appender>

    <root>
        <appender-ref ref="STDOUT" />
        <appender-ref ref="STDERR" />
    </root>
</configuration>

Update: As Mike pointed out in the comment, messages with ERROR level are printed here both to STDOUT and STDERR. Not sure what was the OP's intent, though. You can try Mike's answer if this is not what you wanted.

How to get datas from List<Object> (Java)?

Thanks All for your responses. Good solution was to use 'brain`s' method:

List<Object> list = getHouseInfo();
for (int i=0; i<list.size; i++){
Object[] row = (Object[]) list.get(i);
System.out.println("Element "+i+Arrays.toString(row));
}

Problem solved. Thanks again.

how to put image in a bundle and pass it to another activity

So you can do it like this, but the limitation with the Parcelables is that the payload between activities has to be less than 1MB total. It's usually better to save the Bitmap to a file and pass the URI to the image to the next activity.

 protected void onCreate(Bundle savedInstanceState) {     setContentView(R.layout.my_layout);     Bitmap bitmap = getIntent().getParcelableExtra("image");     ImageView imageView = (ImageView) findViewById(R.id.imageview);     imageView.setImageBitmap(bitmap);  } 

Using SUMIFS with multiple AND OR conditions

Quote_Month (Worksheet!$D:$D) contains a formula (=TEXT(Worksheet!$E:$E,"mmm-yy"))to convert a date/time number from another column into a text based month reference.

You can use OR by adding + in Sumproduct. See this

=SUMPRODUCT((Quote_Value)*(Salesman="JBloggs")*(Days_To_Close<=90)*((Quote_Month="Cond1")+(Quote_Month="Cond2")+(Quote_Month="Cond3")))

ScreenShot

enter image description here

What is The difference between ListBox and ListView

A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView, but you can easily create your own.

Another difference is the default selection mode: it's Single for a ListBox, but Extended for a ListView

How to export data to CSV in PowerShell?

what you are searching for is the Export-Csv file.csv

try using Get-Help Export-Csv to see whats possible

also Out-File -FilePath "file.csv" will work

Proxy with express.js

I don't have have an express sample, but one with plain http-proxy package. A very strip down version of the proxy I used for my blog.

In short, all nodejs http proxy packages work at the http protocol level, not tcp(socket) level. This is also true for express and all express middleware. None of them can do transparent proxy, nor NAT, which means keeping incoming traffic source IP in the packet sent to backend web server.

However, web server can pickup original IP from http x-forwarded headers and add it into the log.

The xfwd: true in proxyOption enable x-forward header feature for http-proxy.

const url = require('url');
const proxy = require('http-proxy');

proxyConfig = {
    httpPort: 8888,
    proxyOptions: {
        target: {
            host: 'example.com',
            port: 80
        },
        xfwd: true // <--- This is what you are looking for.
    }
};

function startProxy() {

    proxy
        .createServer(proxyConfig.proxyOptions)
        .listen(proxyConfig.httpPort, '0.0.0.0');

}

startProxy();

Reference for X-Forwarded Header: https://en.wikipedia.org/wiki/X-Forwarded-For

Full version of my proxy: https://github.com/J-Siu/ghost-https-nodejs-proxy

making matplotlib scatter plots from dataframes in Python's pandas

I will recommend to use an alternative method using seaborn which more powerful tool for data plotting. You can use seaborn scatterplot and define colum 3 as hue and size.

Working code:

import pandas as pd
import seaborn as sns
import numpy as np

#creating sample data 
sample_data={'col_name_1':np.random.rand(20),
      'col_name_2': np.random.rand(20),'col_name_3': np.arange(20)*100}
df= pd.DataFrame(sample_data)
sns.scatterplot(x="col_name_1", y="col_name_2", data=df, hue="col_name_3",size="col_name_3")

enter image description here

can you host a private repository for your organization to use with npm?

https://github.com/isaacs/npmjs.org/ : In npm version v1.0.26 you can specify private git repositories urls as a dependency in your package.json files. I have not used it but would love feedback. Here is what you need to do:

{
    "name": "my-app",
    "dependencies": {
        "private-repo": "git+ssh://[email protected]:my-app.git#v0.0.1",
    }
}

The following post talks about this: Debuggable: Private npm modules

Writing a Python list of lists to a csv file

Using csv.writer in my very large list took quite a time. I decided to use pandas, it was faster and more easy to control and understand:

 import pandas

 yourlist = [[...],...,[...]]
 pd = pandas.DataFrame(yourlist)
 pd.to_csv("mylist.csv")

The good part you can change somethings to make a better csv file:

 yourlist = [[...],...,[...]]
 columns = ["abcd","bcde","cdef"] #a csv with 3 columns
 index = [i[0] for i in yourlist] #first element of every list in yourlist
 not_index_list = [i[1:] for i in yourlist]
 pd = pandas.DataFrame(not_index_list, columns = columns, index = index)

 #Now you have a csv with columns and index:
 pd.to_csv("mylist.csv")

How can I use jQuery in Greasemonkey?

If you are using chrome you have to opt for an alternative as Chromium does not support @require.

Source: The Chromium Project - User scripts

More details and alternatives on How can I use jQuery in Greasemonkey scripts in Google Chrome?

Check whether variable is number or string in JavaScript

@BitOfUniverse's answer is good, and I come up with a new way:

function isNum(n) {
    return !isNaN(n/0);
}

isNum('')  // false
isNum(2)   // true
isNum('2k') // false
isNum('2')  //true

I know 0 can't be dividend, but here the function works perfectly.

How to throw RuntimeException ("cannot find symbol")

You need to create the instance of the RuntimeException, using new the same way you would to create an instance of most other classes:

throw new RuntimeException(msg);

Unable to start the mysql server in ubuntu

Yes, should try reinstall mysql, but use the --reinstall flag to force a package reconfiguration. So the operating system service configuration is not skipped:

sudo apt --reinstall install mysql-server

How to make a .jar out from an Android Studio project

the way i found was to find the project compiler output (project structure > project). then find the complied folder of the module you wish to turn to a jar, compress it with zip and change the extension of the output from zip to jar.

How to find GCD, LCM on a set of numbers

for gcd you cad do as below:

    String[] ss = new Scanner(System.in).nextLine().split("\\s+");
    BigInteger bi,bi2 = null;
    bi2 = new BigInteger(ss[1]);
    for(int i = 0 ; i<ss.length-1 ; i+=2 )
    {
        bi = new BigInteger(ss[i]);
        bi2 = bi.gcd(bi2);
    }
    System.out.println(bi2.toString());

CSS endless rotation animation

@keyframes rotate {
    100% {
        transform: rotate(1turn);
    }
}

div{
   animation: rotate 4s linear infinite;
}

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Your problem is here:

2013-11-14 17:57:20 5180 [ERROR] InnoDB: .\ibdata1 can't be opened in read-write mode

There's some problem with the ibdata1 file - maybe the permissions have changed on it? Perhaps some other process has it open. Does it even exist?

Fix this and possibly everything else will fall into place.

What does API level mean?

An API is ready-made source code library.

In Java for example APIs are a set of related classes and interfaces that come in packages. This picture illustrates the libraries included in the Java Standard Edition API. Packages are denoted by their color.

This pictures illustrates the libraries included in the Java Standard Edition API

Difference between "or" and || in Ruby?

or is NOT the same as ||. Use only || operator instead of the or operator.

Here are some reasons. The:

  • or operator has a lower precedence than ||.
  • or has a lower precedence than the = assignment operator.
  • and and or have the same precedence, while && has a higher precedence than ||.

When does Java's Thread.sleep throw InterruptedException?

The Java Specialists newsletter (which I can unreservedly recommend) had an interesting article on this, and how to handle the InterruptedException. It's well worth reading and digesting.

Problem in running .net framework 4.0 website on iis 7.0

In our case the solution to this problem did not involve the "ISAPI and CGI Restrictions" settings. The error started occuring after operations staff had upgraded the server to .NET 4.5 by accident, then downgraded to .NET 4.0 again. This caused some of the IIS websites to forget their respective correct application pools, and it caused some of the application pools to switch from .NET Framework 4.0 to 2.0. Changing these settings back fixed the problem.

How to convert IPython notebooks to PDF and HTML?

I combined some answers above in inline python that u can add to ~/.bashrc or ~/.zshrc to compile and convert many notebooks to a single pdf file

function convert_notebooks(){
  # read anything on this folder that ends on ipynb and run pdf formatting for it  
  python -c 'import os; [os.system("jupyter nbconvert --to pdf " + f) for f in os.listdir (".") if f.endswith("ipynb")]'
  # to convert to pdf u must have installed latex and that means u have pdfjam installed
  pdfjam * 
}

Parsing JSON string in Java

Looks like for both of your objects (inside the array), you have an extra closing brace after "Longitude".

Update div with jQuery ajax response html

Almost 5 years later, I think my answer can reduce a little bit the hard work of many people.

Update an element in the DOM with the HTML from the one from the ajax call can be achieved that way

$('#submitform').click(function() {
     $.ajax({
     url: "getinfo.asp",
     data: {
         txtsearch: $('#appendedInputButton').val()
     },
     type: "GET",
     dataType : "html",
     success: function (data){
         $('#showresults').html($('#showresults',data).html());
         // similar to $(data).find('#showresults')
     },
});

or with replaceWith()

// codes

success: function (data){
   $('#showresults').replaceWith($('#showresults',data));
},

Selected value for JSP drop down using JSTL

If you don't mind using jQuery you can use the code bellow:

    <script>
     $(document).ready(function(){
           $("#department").val("${requestScope.selectedDepartment}").attr('selected', 'selected');
     });
     </script>


    <select id="department" name="department">
      <c:forEach var="item" items="${dept}">
        <option value="${item.key}">${item.value}</option>
      </c:forEach>
    </select>

In the your Servlet add the following:

        request.setAttribute("selectedDepartment", YOUR_SELECTED_DEPARTMENT );

How to make an inline-block element fill the remainder of the line?

I've used flex-grow property to achieve this goal. You'll have to set display: flex for parent container, then you need to set flex-grow: 1 for the block you want to fill remaining space, or just flex: 1 as tanius mentioned in the comments.

How can I set an SQL Server connection string?

Actually you can use the SqlConnectionStringBuilder class to build your connection string. To build the connection string, you need to instantiate an object from that SqlConnectionStringBuilder and set their properties with the parameters you use to connect to the database. Then you can get the connection string from the ConnectionString property from the SqlConnectionStringBuilder object, as is shown in this example:

For example:

SqlConnectionStringBuilder sConnB = new SqlConnectionStringBuilder ()
    {
        DataSource = "ServerName",
        InitialCatalog = "DatabaseName",
        UserID = "UserName",
        Password = "UserPassword"
    }.ConnectionString

SqlConnection conn = new SqlConnection(sConnB.ConnectionString);

You can either use the new operator to make that directly.

For example:

SqlConnection conn = new SqlConnection(
    new SqlConnectionStringBuilder ()
    {
        DataSource = "ServerName",
        InitialCatalog = "DatabaseName",
        UserID = "UserName",
        Password = "UserPassword"
    }.ConnectionString
);

You can add more parameters to build your connection string. Remember that the parameters are defined by the values setted in the SqlConnectionStringBuilder object properties.

Also you can get the database connection string from the connection of Microsoft Visual Studio with the attached database. When you select the database, in the properties panel is shown the connection string.

The complete list of properties of the SqlConnectionStringBuilder class is listed in this page from the Microsoft MSDN site.

About the default user of SQL Server, sa means "system administrator" and its password varies according the SQL Server version. On this page you can see how the password varies.

SQL Server 2008/R2 Express User: sa Password: [blank password - leave field empty to connect]
SQL Server 201x Express User: sa Password: Password123
SQL Server 20xx Web or Standard User: sa Password: will be the same as your administrator or root user password at the time the VDS was provisioned.

You can log in with the sa user in this login window at the start of SQL Server Database Manager. Like in this image:

Log in example

jQuery remove all list items from an unordered list

If you have multiple ul and want to empty specific ul then use id eg:

<ul id="randomName">
   <li>1</li>
   <li>2</li>
   <li>3</li>
</ul>


<script>
  $('#randomName').empty();
</script>

_x000D_
_x000D_
$('input').click(function() {_x000D_
  $('#randomName').empty()_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
_x000D_
<ul id="randomName">_x000D_
  <li>1</li>_x000D_
  <li>2</li>_x000D_
  <li>3</li>_x000D_
</ul>_x000D_
_x000D_
<ul>_x000D_
  <li>4</li>_x000D_
  <li>5</li>_x000D_
</ul>_x000D_
<input type="button" value="click me" />
_x000D_
_x000D_
_x000D_

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

In my case none of the other answers worked because I previously downgraded to node8. So instead of doing above, following worked for me:

which node

which returned /usr/local/bin/node@8 instead of /usr/local/bin/node

so i executed this command:

brew uninstall node@8

which worked and then downloaded latest pkg from official site and installed. After that I had to close my terminal and start again to access new version

How to secure the ASP.NET_SessionId cookie?

Here is a code snippet taken from a blog article written by Anubhav Goyal:

// this code will mark the forms authentication cookie and the
// session cookie as Secure.
if (Response.Cookies.Count > 0)
{
    foreach (string s in Response.Cookies.AllKeys)
    {
        if (s == FormsAuthentication.FormsCookieName || "asp.net_sessionid".Equals(s, StringComparison.InvariantCultureIgnoreCase))
        {
             Response.Cookies[s].Secure = true;
        }
    }
}

Adding this to the EndRequest event handler in the global.asax should make this happen for all page calls.

Note: An edit was proposed to add a break; statement inside a successful "secure" assignment. I've rejected this edit based on the idea that it would only allow 1 of the cookies to be forced to secure and the second would be ignored. It is not inconceivable to add a counter or some other metric to determine that both have been secured and to break at that point.

Download File Using Javascript/jQuery

To improve Imagine Breaker 's answer, this is supported on FF & IE :

var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);

function downloadURI(uri, name) {
    var link = document.createElement("a");
    link.download = name;
    link.href = uri;
    link.dispatchEvent(evt);
}

In other words, just use a dispatchEvent function instead of click();

Create patch or diff file from git repository and apply it to another different git repository

You can just use git diff to produce a unified diff suitable for git apply:

git diff tag1..tag2 > mypatch.patch

You can then apply the resulting patch with:

git apply mypatch.patch

Loading and parsing a JSON file with multiple JSON objects

That is ill-formatted. You have one JSON object per line, but they are not contained in a larger data structure (ie an array). You'll either need to reformat it so that it begins with [ and ends with ] with a comma at the end of each line, or parse it line by line as separate dictionaries.

Textarea that can do syntax highlighting on the fly?

Here is the response I've done to a similar question (Online Code Editor) on programmers:

First, you can take a look to this article:
Wikipedia - Comparison of JavaScript-based source code editors.

For more, here is some tools that seem to fit with your request:

  • EditArea - Demo as FileEditor who is a Yii Extension - (Apache Software License, BSD, LGPL)

    Here is EditArea, a free javascript editor for source code. It allow to write well formated source code with line numerotation, tab support, search & replace (with regexp) and live syntax highlighting (customizable).

  • CodePress - Demo of Joomla! CodePress Plugin - (LGPL) - It doesn't work in Chrome and it looks like development has ceased.

    CodePress is web-based source code editor with syntax highlighting written in JavaScript that colors text in real time while it's being typed in the browser.

  • CodeMirror - One of the many demo - (MIT-style license + optional commercial support)

    CodeMirror is a JavaScript library that can be used to create a relatively pleasant editor interface for code-like content - computer programs, HTML markup, and similar. If a mode has been written for the language you are editing, the code will be coloured, and the editor will optionally help you with indentation

  • Ace Ajax.org Cloud9 Editor - Demo - (Mozilla tri-license (MPL/GPL/LGPL))

    Ace is a standalone code editor written in JavaScript. Our goal is to create a web based code editor that matches and extends the features, usability and performance of existing native editors such as TextMate, Vim or Eclipse. It can be easily embedded in any web page and JavaScript application. Ace is developed as the primary editor for Cloud9 IDE and the successor of the Mozilla Skywriter (Bespin) Project.

Can jQuery check whether input content has changed?

function checkChange($this){
    var value = $this.val();      
    var sv=$this.data("stored");            
        if(value!=sv)
            $this.trigger("simpleChange");    
}

$(document).ready(function(){
    $(this).data("stored",$(this).val());   
        $("input").bind("keyup",function(e){  
        checkChange($(this));
    });        
    $("input").bind("simpleChange",function(e){
        alert("the value is chaneged");
    });        
});

here is the fiddle http://jsfiddle.net/Q9PqT/1/