Programs & Examples On #Sinatra

Sinatra is a Domain Specific Language (DSL) for quickly creating web applications in Ruby with minimal effort. It is an alternative to other Ruby web application frameworks such as Ruby on Rails, Nitro, Camping, and Rango.

Which Ruby version am I really running?

If you have access to a console in the context you are investigating, you can determine which version you are running by printing the value of the global constant RUBY_VERSION.

Why is nginx responding to any domain name?

Little comment to answer:

if you have several virtual hosts on several IPs in several config files in sites-available/, than "default" domain for IP will be taken from first file by alphabetic order.

And as Pavel said, there is "default_server" argument for "listen" directive http://nginx.org/en/docs/http/ngx_http_core_module.html#listen

Dealing with nginx 400 "The plain HTTP request was sent to HTTPS port" error

The above answers are incorrect in that most over-ride the 'is this connection HTTPS' test to allow serving the pages over http irrespective of connection security.

The secure answer using an error-page on an NGINX specific http 4xx error code to redirect the client to retry the same request to https. (as outlined here https://serverfault.com/questions/338700/redirect-http-mydomain-com12345-to-https-mydomain-com12345-in-nginx )

The OP should use:

server {
  listen        12345;
  server_name   php.myadmin.com;

  root         /var/www/php;

  ssl           on;

  # If they come here using HTTP, bounce them to the correct scheme
  error_page 497 https://$server_name:$server_port$request_uri;

  [....]
}

Javascript Array Alert

If you want to see the array as an array, you can say

alert(JSON.stringify(aCustomers));

instead of all those document.writes.

http://jsfiddle.net/5b2eb/

However, if you want to display them cleanly, one per line, in your popup, do this:

alert(aCustomers.join("\n"));

http://jsfiddle.net/5b2eb/1/

How to write to a JSON file in the correct format

This question is for ruby 1.8 but it still comes on top when googling.

in ruby >= 1.9 you can use

File.write("public/temp.json",tempHash.to_json)

other than what mentioned in other answers, in ruby 1.8 you can also use one liner form

File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }

Variable name as a string in Javascript

Probably pop would be better than indexing with [0], for safety (variable might be null).

const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${variable}'`);

// returns "Variable myFirstName with value 'John'"

Generate an HTML Response in a Java Servlet

You need to have a doGet method as:

public void doGet(HttpServletRequest request,
        HttpServletResponse response)
throws IOException, ServletException
{
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    out.println("<html>");
    out.println("<head>");
    out.println("<title>Hola</title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");
    out.println("</body>");
    out.println("</html>");
}

You can see this link for a simple hello world servlet

Assigning the output of a command to a variable

Try:

output=$(ps -ef | awk '/siebsvc –s siebsrvr/ && !/awk/ { a++ } END { print a }'); echo $output

Wrapping your command in $( ) tells the shell to run that command, instead of attempting to set the command itself to the variable named "output". (Note that you could also use backticks `command`.)

I can highly recommend http://tldp.org/LDP/abs/html/commandsub.html to learn more about command substitution.

Also, as 1_CR correctly points out in a comment, the extra space between the equals sign and the assignment is causing it to fail. Here is a simple example on my machine of the behavior you are experiencing:

jed@MBP:~$ foo=$(ps -ef |head -1);echo $foo
UID PID PPID C STIME TTY TIME CMD

jed@MBP:~$ foo= $(ps -ef |head -1);echo $foo
-bash: UID: command not found
UID PID PPID C STIME TTY TIME CMD

How do I find the location of Python module sources?

If you're using pip to install your modules, just pip show $module the location is returned.

How to check if a variable is NULL, then set it with a MySQL stored procedure?

@last_run_time is a 9.4. User-Defined Variables and last_run_time datetime one 13.6.4.1. Local Variable DECLARE Syntax, are different variables.

Try: SELECT last_run_time;

UPDATE

Example:

/* CODE FOR DEMONSTRATION PURPOSES */
DELIMITER $$

CREATE PROCEDURE `sp_test`()
BEGIN
    DECLARE current_procedure_name CHAR(60) DEFAULT 'accounts_general';
    DECLARE last_run_time DATETIME DEFAULT NULL;
    DECLARE current_run_time DATETIME DEFAULT NOW();

    -- Define the last run time
    SET last_run_time := (SELECT MAX(runtime) FROM dynamo.runtimes WHERE procedure_name = current_procedure_name);

    -- if there is no last run time found then use yesterday as starting point
    IF(last_run_time IS NULL) THEN
        SET last_run_time := DATE_SUB(NOW(), INTERVAL 1 DAY);
    END IF;

    SELECT last_run_time;

    -- Insert variables in table2
    INSERT INTO table2 (col0, col1, col2) VALUES (current_procedure_name, last_run_time, current_run_time);
END$$

DELIMITER ;

jQuery UI Dialog OnBeforeUnload

this works for me

$(window).bind('beforeunload', function() {
      return 'Do you really want to leave?' ;
});

What is the point of the diamond operator (<>) in Java 7?

The issue with

List<String> list = new LinkedList();

is that on the left hand side, you are using the generic type List<String> where on the right side you are using the raw type LinkedList. Raw types in Java effectively only exist for compatibility with pre-generics code and should never be used in new code unless you absolutely have to.

Now, if Java had generics from the beginning and didn't have types, such as LinkedList, that were originally created before it had generics, it probably could have made it so that the constructor for a generic type automatically infers its type parameters from the left-hand side of the assignment if possible. But it didn't, and it must treat raw types and generic types differently for backwards compatibility. That leaves them needing to make a slightly different, but equally convenient, way of declaring a new instance of a generic object without having to repeat its type parameters... the diamond operator.

As far as your original example of List<String> list = new LinkedList(), the compiler generates a warning for that assignment because it must. Consider this:

List<String> strings = ... // some list that contains some strings

// Totally legal since you used the raw type and lost all type checking!
List<Integer> integers = new LinkedList(strings);

Generics exist to provide compile-time protection against doing the wrong thing. In the above example, using the raw type means you don't get this protection and will get an error at runtime. This is why you should not use raw types.

// Not legal since the right side is actually generic!
List<Integer> integers = new LinkedList<>(strings);

The diamond operator, however, allows the right hand side of the assignment to be defined as a true generic instance with the same type parameters as the left side... without having to type those parameters again. It allows you to keep the safety of generics with almost the same effort as using the raw type.

I think the key thing to understand is that raw types (with no <>) cannot be treated the same as generic types. When you declare a raw type, you get none of the benefits and type checking of generics. You also have to keep in mind that generics are a general purpose part of the Java language... they don't just apply to the no-arg constructors of Collections!

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

In app.module.ts add this:

import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@NgModule({
    declarations: [AppComponent],
    imports: [FormsModule],
})

How to format date with hours, minutes and seconds when using jQuery UI Datepicker?

Using jQuery UI in combination with the excellent datetimepicker plugin from http://trentrichardson.com/examples/timepicker/

You can specify the dateFormat and timeFormat

$('#datepicker').datetimepicker({
    dateFormat: "yy-mm-dd",
    timeFormat:  "hh:mm:ss"
});

Regex date format validation on Java

Use the following regular expression:

^\d{4}-\d{2}-\d{2}$

as in

if (str.matches("\\d{4}-\\d{2}-\\d{2}")) {
    ...
}

With the matches method, the anchors ^ and $ (beginning and end of string, respectively) are present implicitly.

MassAssignmentException in Laravel

I am using Laravel 4.2.

the error you are seeing

[Illuminate\Database\Eloquent\MassAssignmentException]
username

indeed is because the database is protected from filling en masse, which is what you are doing when you are executing a seeder. However, in my opinion, it's not necessary (and might be insecure) to declare which fields should be fillable in your model if you only need to execute a seeder.

In your seeding folder you have the DatabaseSeeder class:

class DatabaseSeeder extends Seeder {

    /**
    * Run the database seeds.
    *
    * @return void
    */

    public function run()
    {
        Eloquent::unguard();

        //$this->call('UserTableSeeder');
    }
}

This class acts as a facade, listing all the seeders that need to be executed. If you call the UsersTableSeeder seeder manually through artisan, like you did with the php artisan db:seed --class="UsersTableSeeder" command, you bypass this DatabaseSeeder class.

In this DatabaseSeeder class the command Eloquent::unguard(); allows temporary mass assignment on all tables, which is exactly what you need when you are seeding a database. This unguard method is only executed when you run the php aristan db:seed command, hence it being temporary as opposed to making the fields fillable in your model (as stated in the accepted and other answers).

All you need to do is add the $this->call('UsersTableSeeder'); to the run method in the DatabaseSeeder class and run php aristan db:seed in your CLI which by default will execute DatabaseSeeder.

Also note that you are using a plural classname Users, while Laraval uses the the singular form User. If you decide to change your class to the conventional singular form, you can simply uncomment the //$this->call('UserTableSeeder'); which has already been assigned but commented out by default in the DatabaseSeeder class.

How to find and replace string?

Do we really need a Boost library for seemingly such a simple task?

To replace all occurences of a substring use this function:

std::string ReplaceString(std::string subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
    return subject;
}

If you need performance, here is an optimized function that modifies the input string, it does not create a copy of the string:

void ReplaceStringInPlace(std::string& subject, const std::string& search,
                          const std::string& replace) {
    size_t pos = 0;
    while ((pos = subject.find(search, pos)) != std::string::npos) {
         subject.replace(pos, search.length(), replace);
         pos += replace.length();
    }
}

Tests:

std::string input = "abc abc def";
std::cout << "Input string: " << input << std::endl;

std::cout << "ReplaceString() return value: " 
          << ReplaceString(input, "bc", "!!") << std::endl;
std::cout << "ReplaceString() input string not modified: " 
          << input << std::endl;

ReplaceStringInPlace(input, "bc", "??");
std::cout << "ReplaceStringInPlace() input string modified: " 
          << input << std::endl;

Output:

Input string: abc abc def
ReplaceString() return value: a!! a!! def
ReplaceString() input string not modified: abc abc def
ReplaceStringInPlace() input string modified: a?? a?? def

XPath Query: get attribute href from a tag

The answer shared by @mockinterface is correct. Although I would like to add my 2 cents to it.

If someone is using frameworks like scrapy the you will have to use /html/body//a[contains(@href,'com')][2]/@href along with get() like this:

response.xpath('//a[contains(@href,'com')][2]/@href').get()

How do I get first element rather than using [0] in jQuery?

You can use .get(0) as well but...you shouldn't need to do that with an element found by ID, that should always be unique. I'm hoping this is just an oversight in the example...if this is the case on your actual page, you'll need to fix it so your IDs are unique, and use a class (or another attribute) instead.

.get() (like [0]) gets the DOM element, if you want a jQuery object use .eq(0) or .first() instead :)

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

Use its value directly:

In [79]: df[df.c > 0.5][['b', 'e']].values
Out[79]: 
array([[ 0.98836259,  0.82403141],
       [ 0.337358  ,  0.02054435],
       [ 0.29271728,  0.37813099],
       [ 0.70033513,  0.69919695]])

MVC 4 - Return error message from Controller - Show in View

The Return View(model) returns you error because you don't fill the model with the values in your post method and the model data for the dropdown is empty. Please provide the Get method to explain further how to manage displaying the error. In order to the error to be shown you should use this:

[HttpPost]
public ActionResult form_edit(FormModels model)
{          
   if(ModelState.IsValid())
   {
      --- operations 
      return Redirect("OtherAction", "SomeController");
   }

   // here you can use a little trick
   //fill the model property that holds the information for the dropdown with the data 

   // you haven't provided the get method but it should look something like this
   model.Countries = ... some data goes here;
   model.dd_value = ... some other data;
   model.dd_text = ... other data;

   ModelState.AddModelError("", "adfdghdghgdhgdhdgda");
   return View(model);
}

and then in the view just use :

@model mvc_cs.Models.FormModels
@using ctrlr = mvc_cs.Controllers.FormController


@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{

    <table>
    <tr>
    <td>       
    @Html.ValidationSummary(true)             
    </td>
    </tr>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.content_name)
        @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")

    </th>
</tr>
</table>

<table>
<tr>
    <td>
        <input  type="submit" value="Submit" />
    </td>
</tr>
</table>
}

This should work okay.

If you just use RedirectToAction it will redirect you to the get method --> you will have no error but the view will be just reloaded and no error would be shown.

other way around is that you can pass the error not by ModelState.AddError, but with ViewData["error"] like this:

[HttpPost]
public ActionResult form_edit(FormModels model)
{          
   TempData["error"] = "someErrorMessage";
   return RedirectToAction("form_Post", "Form");
}

[HttpGet]
public ActionResult form_edit()
{
    do stuff here ----
    ViewData["error"] = TempData["error"];
    return View();
}

@model mvc_cs.Models.FormModels
@using ctrlr = mvc_cs.Controllers.FormController


@using (Html.BeginForm("form_edit", "Form", FormMethod.Post))
{

    <table>
    <tr>
    <td>       
    <div>@ViewData["error"]</div>             
    </td>
    </tr>
<tr>
    <th>
        @Html.DisplayNameFor(model => model.content_name)
        @Html.DropDownListFor(x => x.selectedvalue, new SelectList(Model.Countries, Model.dd_value, Model.dd_text), "-- Select Product--")

    </th>
</tr>
</table>

<table>
<tr>
    <td>
        <input  type="submit" value="Submit" />
    </td>
</tr>
</table>
}

Understanding Popen.communicate

Do not use communicate(input=""). It writes input to the process, closes its stdin and then reads all output.

Do it like this:

p=subprocess.Popen(["python","1st.py"],stdin=PIPE,stdout=PIPE)

# get output from process "Something to print"
one_line_output = p.stdout.readline()

# write 'a line\n' to the process
p.stdin.write('a line\n')

# get output from process "not time to break"
one_line_output = p.stdout.readline() 

# write "n\n" to that process for if r=='n':
p.stdin.write('n\n') 

# read the last output from the process  "Exiting"
one_line_output = p.stdout.readline()

What you would do to remove the error:

all_the_process_will_tell_you = p.communicate('all you will ever say to this process\nn\n')[0]

But since communicate closes the stdout and stdin and stderr, you can not read or write after you called communicate.

How to add Active Directory user group as login in SQL Server

Go to the SQL Server Management Studio, navigate to Security, go to Logins and right click it. A Menu will come up with a button saying "New Login". There you will be able to add users and/or groups from Active Directory to your SQL Server "permissions". Hope this helps

How do I combine two dataframes?

You can also use pd.concat, which is particularly helpful when you are joining more than two dataframes:

bigdata = pd.concat([data1, data2], ignore_index=True, sort=False)

Maven2: Best practice for Enterprise Project (EAR file)

NetBeans IDE automatically defines the structure which is almost similar to one suggested by Patrick Garner. For NetBeans users

File->New Project ->In left side select Maven and In right side select Maven Enterprise Application and press Next -> Asks for project names for both war,ejb and settings.

The IDE will automatically create the structure for you.

What is the default boolean value in C#?

It can be treated as defensive programming approach from the compiler - the variables must be assigned before it can be used.

Does Visual Studio have code coverage for unit tests?

If you are using Visual Studio 2017 and come across this question, you might consider AxoCover. It's a free VS extension that integrates OpenCover, but supports VS2017 (it also appears to be under active development. +1).

VS Extension page

https://github.com/axodox/AxoTools

how to save canvas as png image?

Submit a form that contains an input with value of canvas toDataURL('image/png') e.g

//JAVASCRIPT

    var canvas = document.getElementById("canvas");
    var url = canvas.toDataUrl('image/png');

Insert the value of the url to your hidden input on form element.

//PHP

    $data = $_POST['photo'];
    $data = str_replace('data:image/png;base64,', '', $data);
    $data = base64_decode($data);
    file_put_contents("i".  rand(0, 50).".png", $data);

Adobe Reader Command Line Reference

You can find something about this in the Adobe Developer FAQ. (It's a PDF document rather than a web page, which I guess is unsurprising in this particular case.)

The FAQ notes that the use of the command line switches is unsupported.

To open a file it's:

AcroRd32.exe <filename>

The following switches are available:

  • /n - Launch a new instance of Reader even if one is already open
  • /s - Don't show the splash screen
  • /o - Don't show the open file dialog
  • /h - Open as a minimized window
  • /p <filename> - Open and go straight to the print dialog
  • /t <filename> <printername> <drivername> <portname> - Print the file the specified printer.

Numpy: Get random set of rows from 2D array

This is a similar answer to the one Hezi Rasheff provided, but simplified so newer python users understand what's going on (I noticed many new datascience students fetch random samples in the weirdest ways because they don't know what they are doing in python).

You can get a number of random indices from your array by using:

indices = np.random.choice(A.shape[0], amount_of_samples, replace=False)

You can then use fancy indexing with your numpy array to get the samples at those indices:

A[indices]

This will get you the specified number of random samples from your data.

Get DOM content of cross-domain iframe

There is a simple way.

  1. You create an iframe which have for source something like "http://your-domain.com/index.php?url=http://the-site-you-want-to-get.com/unicorn

  2. Then, you just get this url with $_GET and display the contents with file_get_contents($_GET['url']);

You will obtain an iframe which has a domain same than yours, then you will be able to use the $("iframe").contents().find("body") to manipulate the content.

How to add number of days to today's date?

Pure JS solution, with date formatted YYYY-mm-dd format

_x000D_
_x000D_
var someDate = new Date('2014-05-14');_x000D_
someDate.setDate(someDate.getDate() + 15); //number  of days to add, e.x. 15 days_x000D_
var dateFormated = someDate.toISOString().substr(0,10);_x000D_
console.log(dateFormated);
_x000D_
_x000D_
_x000D_

If Cell Starts with Text String... Formula

As of Excel 2019 you could do this. The "Error" at the end is the default.

SWITCH(LEFT(A1,1), "A", "Pick Up", "B", "Collect", "C", "Prepaid", "Error")

Microsoft Excel Switch Documentation

How to access the ith column of a NumPy multidimensional array?

You could also transpose and return a row:

In [4]: test.T[0]
Out[4]: array([1, 3, 5])

enumerate() for dictionary in python

  1. Iterating over a Python dict means to iterate over its keys exactly the same way as with dict.keys()
  2. The order of the keys is determined by the implementation code and you cannot expect some specific order:

    Keys and values are iterated over in an arbitrary order which is non-random, varies across Python implementations, and depends on the dictionary’s history of insertions and deletions. If keys, values and items views are iterated over with no intervening modifications to the dictionary, the order of items will directly correspond.

That's why you see the indices 0 to 7 in the first column. They are produced by enumerate and are always in the correct order. Further you see the dict's keys 0 to 7 in the second column. They are not sorted.

How to split and modify a string in NodeJS?

If you're using lodash and in the mood for a too-cute-for-its-own-good one-liner:

_.map(_.words('123, 124, 234,252'), _.add.bind(1, 1));

It's surprisingly robust thanks to lodash's powerful parsing capabilities.

If you want one that will also clean non-digit characters out of the string (and is easier to follow...and not quite so cutesy):

_.chain('123, 124, 234,252, n301')
   .replace(/[^\d,]/g, '')
   .words()
   .map(_.partial(_.add, 1))
   .value();

2017 edit:

I no longer recommend my previous solution. Besides being overkill and already easy to do without a third-party library, it makes use of _.chain, which has a variety of issues. Here's the solution I would now recommend:

const str = '123, 124, 234,252';
const arr = str.split(',').map(n => parseInt(n, 10) + 1);

My old answer is still correct, so I'll leave it for the record, but there's no need to use it nowadays.

Proper use cases for Android UserManager.isUserAGoat()?

Android R Update:

From Android R, this method always returns false. Google says that this is done "to protect goat privacy":

/**
 * Used to determine whether the user making this call is subject to
 * teleportations.
 *
 * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
 * now automatically identify goats using advanced goat recognition technology.</p>
 *
 * <p>As of {@link android.os.Build.VERSION_CODES#R}, this method always returns
 * {@code false} in order to protect goat privacy.</p>
 *
 * @return Returns whether the user making this call is a goat.
 */
public boolean isUserAGoat() {
    if (mContext.getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.R) {
        return false;
    }
    return mContext.getPackageManager()
            .isPackageAvailable("com.coffeestainstudios.goatsimulator");
}

Previous answer:

From their source, the method used to return false until it was changed in API 21.

/**
 * Used to determine whether the user making this call is subject to
 * teleportations.
 * @return whether the user making this call is a goat 
 */
public boolean isUserAGoat() {
    return false;
}

It looks like the method has no real use for us as developers. Someone has previously stated that it might be an Easter egg.

In API 21 the implementation was changed to check if there is an installed app with the package com.coffeestainstudios.goatsimulator

/**
 * Used to determine whether the user making this call is subject to
 * teleportations.
 *
 * <p>As of {@link android.os.Build.VERSION_CODES#LOLLIPOP}, this method can
 * now automatically identify goats using advanced goat recognition technology.</p>
 *
 * @return Returns true if the user making this call is a goat.
 */
public boolean isUserAGoat() {
    return mContext.getPackageManager()
            .isPackageAvailable("com.coffeestainstudios.goatsimulator");
}

Here is the source and the change.

ALTER TABLE DROP COLUMN failed because one or more objects access this column

I had the same problem and this was the script that worked for me with a table with a two part name separated by a period ".".

USE [DATABASENAME] GO ALTER TABLE [TableNamePart1].[TableNamePart2] DROP CONSTRAINT [DF__ TableNamePart1D__ColumnName__5AEE82B9] GO ALTER TABLE [TableNamePart1].[ TableNamePart1] DROP COLUMN [ColumnName] GO

Get remote registry value

Try the Remote Registry Module, the registry provider cannot operate remotely:

Import-Module PSRemoteRegistry
Get-RegValue -ComputerName $Computer1 -Key SOFTWARE\Veritas\NetBackup\CurrentVersion -Value PackageVersion 

How to write connection string in web.config file and read from it?

Try to use WebConfigurationManager instead of ConfigurationManager

Writing Python lists to columns in csv

You can use izip to combine your lists, and then iterate them

for val in itertools.izip(l1,l2,l3,l4,l5):
    writer.writerow(val)

How to fix libeay32.dll was not found error

Please check if the dll in application is of the same version as that in the sys32 or wow64 folder depending on your version of windows.

You can check that from the filesize of the dlls.

Eg: I faced this issue because my libeay32.dll and ssleay32.dll file in system32 had a different dll than my libeay32.dll and ssleay32.dll file in openssl application.

I copied the one in sys32 into openssl and everything worked well.

Using malloc for allocation of multi-dimensional arrays with different row lengths

The typical form for dynamically allocating an NxM array of type T is

T **a = malloc(sizeof *a * N);
if (a)
{
  for (i = 0; i < N; i++)
  {
    a[i] = malloc(sizeof *a[i] * M);
  }
}

If each element of the array has a different length, then replace M with the appropriate length for that element; for example

T **a = malloc(sizeof *a * N);
if (a)
{
  for (i = 0; i < N; i++)
  {
    a[i] = malloc(sizeof *a[i] * length_for_this_element);
  }
}

Does VBScript have a substring() function?

As Tmdean correctly pointed out you can use the Mid() function. The MSDN Library also has a great reference section on VBScript which you can find here:

VBScript Language Reference (MSDN Library)

Multiple conditions in WHILE loop

You need to change || to && so that both conditions must be true to enter the loop.

while(myChar != 'n' && myChar != 'N')

How do I use a C# Class Library in a project?

You need to add a reference to your class library from your project. Right click on the references folder and click add reference. You can either browse for the DLL or, if your class libaray is a project in your solution you can add a project reference.

How to toggle boolean state of react component?

You should use this.state.check instead of check.value here:

this.setState({check: !this.state.check})

But anyway it is bad practice to do it this way. Much better to move it to separate method and don't write callbacks directly in markup.

Is HTML considered a programming language?

I think not exactly a programming language, but exactly what its name says: a markup language. We cannot program using just pure, HTML. But just annotate how to present content.

But if you consider programming the act of tell the computer how to present contents, it is a programming language.

boundingRectWithSize for NSAttributedString returning wrong size

My final decision after long investigation:
- boundingRectWithSize function returns correct size for uninterrupted sequence of characters only! In case string contains spaces or something else (called by Apple "Some of the glyphs" ) - it is impossible to get actual size of rect needed to display text!
I have replaced spaces in my strings by letters and immediately got correct result.

Apple says here: https://developer.apple.com/documentation/foundation/nsstring/1524729-boundingrectwithsize

"This method returns the actual bounds of the glyphs in the string. Some of the glyphs (spaces, for example) are allowed to overlap the layout constraints specified by the size passed in, so in some cases the width value of the size component of the returned CGRect can exceed the width value of the size parameter."

So it is necessary to find some another way to calculate actual rect...


After long investigation process solution finally found!!! I am not sure it will work good for all cases related to UITextView, but main and important thing was detected!

boundingRectWithSize function as well as CTFramesetterSuggestFrameSizeWithConstraints (and many other methods) will calculate size and text portion correct when correct rectangle used. For example - UITextView has textView.bounds.size.width - and this value not actual rectangle used by system when text drawing on UITextView.

I found very interesting parameter and performed simple calculation in code:

CGFloat padding = textView.textContainer.lineFragmentPadding;  
CGFloat  actualPageWidth = textView.bounds.size.width - padding * 2;

And magic works - all my texts calculated correct now! Enjoy!

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

input[type='text'] CSS selector does not apply to default-type text inputs?

To be compliant with all browsers you should always declare the input type.

Some browsers will assume default type as 'text', but this isn't a good practice.

get the margin size of an element with jquery

You'll want to use...

alert(parseInt($this.parents("div:.item-form").css("marginTop").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginRight").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginBottom").replace('px', '')));
alert(parseInt($this.parents("div:.item-form").css("marginLeft").replace('px', '')));

HTML button calling an MVC Controller and Action method

Try this:

@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)

This should work for you.

Show a leading zero if a number is less than 10

Try this

function pad (str, max) {
  return str.length < max ? pad("0" + str, max) : str;
}

alert(pad("5", 2));

Example

http://jsfiddle.net/

Or

var number = 5;
var i;
if (number < 10) {
    alert("0"+number);
}

Example

http://jsfiddle.net/

Deleting records before a certain date

This is another example using defined column/table names.

DELETE FROM jos_jomres_gdpr_optins WHERE `date_time` < '2020-10-21 08:21:22';

How can I get the request URL from a Java Filter?

Is this what you're looking for?

if (request instanceof HttpServletRequest) {
 String url = ((HttpServletRequest)request).getRequestURL().toString();
 String queryString = ((HttpServletRequest)request).getQueryString();
}

To Reconstruct:

System.out.println(url + "?" + queryString);

Info on HttpServletRequest.getRequestURL() and HttpServletRequest.getQueryString().

Laravel Pagination links not including other GET parameters

Use this construction, to keep all input params but page

{!! $myItems->appends(Request::capture()->except('page'))->render() !!}

Why?

1) you strip down everything that added to request like that

  $request->request->add(['variable' => 123]);

2) you don't need $request as input parameter for the function

3) you are excluding "page"

PS) and it works for Laravel 5.1

Why does Lua have no "continue" statement?

I've never used Lua before, but I Googled it and came up with this:

http://www.luafaq.org/

Check question 1.26.

This is a common complaint. The Lua authors felt that continue was only one of a number of possible new control flow mechanisms (the fact that it cannot work with the scope rules of repeat/until was a secondary factor.)

In Lua 5.2, there is a goto statement which can be easily used to do the same job.

What is LD_LIBRARY_PATH and how to use it?

Typically you must set java.library.path on the JVM's command line:

java -Djava.library.path=/path/to/my/dll -cp /my/classpath/goes/here MainClass

MySQL maximum memory usage

MySQL's maximum memory usage very much depends on hardware, your settings and the database itself.

Hardware

The hardware is the obvious part. The more RAM the merrier, faster disks ftw. Don't believe those monthly or weekly news letters though. MySQL doesn't scale linear - not even on Oracle hardware. It's a little trickier than that.

The bottom line is: there is no general rule of thumb for what is recommend for your MySQL setup. It all depends on the current usage or the projections.

Settings & database

MySQL offers countless variables and switches to optimize its behavior. If you run into issues, you really need to sit down and read the (f'ing) manual.

As for the database -- a few important constraints:

  • table engine (InnoDB, MyISAM, ...)
  • size
  • indices
  • usage

Most MySQL tips on stackoverflow will tell you about 5-8 so called important settings. First off, not all of them matter - e.g. allocating a lot of resources to InnoDB and not using InnoDB doesn't make a lot of sense because those resources are wasted.

Or - a lot of people suggest to up the max_connection variable -- well, little do they know it also implies that MySQL will allocate more resources to cater those max_connections -- if ever needed. The more obvious solution might be to close the database connection in your DBAL or to lower the wait_timeout to free those threads.

If you catch my drift -- there's really a lot, lot to read up on and learn.

Engines

Table engines are a pretty important decision, many people forget about those early on and then suddenly find themselves fighting with a 30 GB sized MyISAM table which locks up and blocks their entire application.

I don't mean to say MyISAM sucks, but InnoDB can be tweaked to respond almost or nearly as fast as MyISAM and offers such thing as row-locking on UPDATE whereas MyISAM locks the entire table when it is written to.

If you're at liberty to run MySQL on your own infrastructure, you might also want to check out the percona server because among including a lot of contributions from companies like Facebook and Google (they know fast), it also includes Percona's own drop-in replacement for InnoDB, called XtraDB.

See my gist for percona-server (and -client) setup (on Ubuntu): http://gist.github.com/637669

Size

Database size is very, very important -- believe it or not, most people on the Intarwebs have never handled a large and write intense MySQL setup but those do really exist. Some people will troll and say something like, "Use PostgreSQL!!!111", but let's ignore them for now.

The bottom line is: judging from the size, decision about the hardware are to be made. You can't really make a 80 GB database run fast on 1 GB of RAM.

Indices

It's not: the more, the merrier. Only indices needed are to be set and usage has to be checked with EXPLAIN. Add to that that MySQL's EXPLAIN is really limited, but it's a start.

Suggested configurations

About these my-large.cnf and my-medium.cnf files -- I don't even know who those were written for. Roll your own.

Tuning primer

A great start is the tuning primer. It's a bash script (hint: you'll need linux) which takes the output of SHOW VARIABLES and SHOW STATUS and wraps it into hopefully useful recommendation. If your server has ran some time, the recommendation will be better since there will be data to base them on.

The tuning primer is not a magic sauce though. You should still read up on all the variables it suggests to change.

Reading

I really like to recommend the mysqlperformanceblog. It's a great resource for all kinds of MySQL-related tips. And it's not just MySQL, they also know a lot about the right hardware or recommend setups for AWS, etc.. These guys have years and years of experience.

Another great resource is planet-mysql, of course.

How do you pass a function as a parameter in C?

I am gonna explain with a simple example code which takes a compare function as parameter to another sorting function. Lets say I have a bubble sort function that takes a custom compare function and uses it instead of a fixed if statement.

Compare Function

bool compare(int a, int b) {
    return a > b;
}

Now , the Bubble sort that takes another function as its parameter to perform comparison

Bubble sort function

void bubble_sort(int arr[], int n, bool (&cmp)(int a, int b)) {

    for (int i = 0;i < n - 1;i++) {
        for (int j = 0;j < (n - 1 - i);j++) {
            
            if (cmp(arr[j], arr[j + 1])) {
                swap(arr[j], arr[j + 1]);
            }
        }
    }
}

Finally , the main which calls the Bubble sort function by passing the boolean compare function as argument.

int main()
{
    int i, n = 10, key = 11;
    int arr[10] = { 20, 22, 18, 8, 12, 3, 6, 12, 11, 15 };

    bubble_sort(arr, n, compare);
    cout<<"Sorted Order"<<endl;
    for (int i = 0;i < n;i++) {
        cout << arr[i] << " ";
    }
}

Output:

Sorted Order
3 6 8 11 12 12 15 18 20 22

How can I select all children of an element except the last child?

How to select all children of an element except the last child using CSS?

Answer: this code will work

<style>
.parent *:not(:last-child) { 
  color:red;
}
</style>

<div class='parent'>
  <p>this is paragraph</p>
  <h1>this is heading</h1>
  <b>text is bold</b>
</div>

Regular Expression to match valid dates

To control a date validity under the following format :

YYYY/MM/DD or YYYY-MM-DD

I would recommand you tu use the following regular expression :

(((19|20)([2468][048]|[13579][26]|0[48])|2000)[/-]02[/-]29|((19|20)[0-9]{2}[/-](0[4678]|1[02])[/-](0[1-9]|[12][0-9]|30)|(19|20)[0-9]{2}[/-](0[1359]|11)[/-](0[1-9]|[12][0-9]|3[01])|(19|20)[0-9]{2}[/-]02[/-](0[1-9]|1[0-9]|2[0-8])))

Matches

2016-02-29 | 2012-04-30 | 2019/09/31

Non-Matches

2016-02-30 | 2012-04-31 | 2019/09/35

You can customise it if you wants to allow only '/' or '-' separators. This RegEx strictly controls the validity of the date and verify 28,30 and 31 days months, even leap years with 29/02 month.

Try it, it works very well and prevent your code from lot of bugs !

FYI : I made a variant for the SQL datetime. You'll find it there (look for my name) : Regular Expression to validate a timestamp

Feedback are welcomed :)

Android splash screen image sizes to fit all devices

** If you are looking for screen details for all kind of major devices **

go to material.io

Efficient way to Handle ResultSet in Java

A couple of things to enhance the other answers. First, you should never return a HashMap, which is a specific implementation. Return instead a plain old java.util.Map. But that's actually not right for this example, anyway. Your code only returns the last row of the ResultSet as a (Hash)Map. You instead want to return a List<Map<String,Object>>. Think about how you should modify your code to do that. (Or you could take Dave Newton's suggestion).

Format numbers to strings in Python

You can use following to achieve desired functionality

"%d:%d:d" % (hours, minutes, seconds)

Hash String via SHA-256 in Java

Java 8: Base64 available:

    MessageDigest md = MessageDigest.getInstance( "SHA-512" );
    md.update( inbytes );
    byte[] aMessageDigest = md.digest();

    String outEncoded = Base64.getEncoder().encodeToString( aMessageDigest );
    return( outEncoded );

Find which version of package is installed with pip

There's also a tool called pip-check which gives you a quick overview of all installed packages and their update status:

enter image description here

Haven't used it myself; just stumbled upon it and this SO question in quick succession, and since it wasn't mentioned...

Edit and Continue: "Changes are not allowed when..."

Couple of things to check

  • Make sure your compile is set to Debug vs. Release
  • Make sure you're not launching a mixed mode process
  • If on a 64 bit machine Make sure to set the CPU target to x86 rather than AnyCPU

EDIT

I don't believe this should matter but make sure that the hosting process is enabled for the target platform. Probably won't help.

If it repros for new projects then it might be something even more subtle. I would try the following.

  • Backup HKCU:\Software\Wow6432Node\VisualStudio\9.0 (maybe just rename it)
  • Delete the same key
  • Try the repro again

Compare a string using sh shell

-eq is used to compare integers. Use = instead.

Convert base-2 binary number string to int

For the record to go back and forth in basic python3:

a = 10
bin(a)
# '0b1010'

int(bin(a), 2)
# 10
eval(bin(a))
# 10

How to append strings using sprintf?

Are you simply appending string literals? Or are you going to be appending various data types (ints, floats, etc.)?

It might be easier to abstract this out into its own function (the following assumes C99):

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

int appendToStr(char *target, size_t targetSize, const char * restrict format, ...)
{
  va_list args;
  char temp[targetSize];
  int result;

  va_start(args, format);
  result = vsnprintf(temp, targetSize, format, args);
  if (result != EOF)
  {
    if (strlen(temp) + strlen(target) > targetSize)
    {
      fprintf(stderr, "appendToStr: target buffer not large enough to hold additional string");
      return 0;
    }
    strcat(target, temp);
  }
  va_end(args);
  return result;
}

And you would use it like so:

char target[100] = {0};
...
appendToStr(target, sizeof target, "%s %d %f\n", "This is a test", 42, 3.14159);
appendToStr(target, sizeof target, "blah blah blah");

etc.

The function returns the value from vsprintf, which in most implementations is the number of bytes written to the destination. There are a few holes in this implementation, but it should give you some ideas.

https connection using CURL from command line

having dignosed the problem I was able to use the existing system default CA file, on debian6 this is:

/etc/ssl/certs/ca-certificates.crt

as root this can be done like:

echo curl.cainfo=/etc/ssl/certs/ca-certificates.crt >> /etc/php5/mods-available/curl.ini

then re-start the web-server.

Python NLTK: SyntaxError: Non-ASCII character '\xc3' in file (Sentiment Analysis -NLP)

Add the following to the top of your file # coding=utf-8

If you go to the link in the error you can seen the reason why:

Defining the Encoding

Python will default to ASCII as standard encoding if no other encoding hints are given. To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as: # coding=

Calculate Pandas DataFrame Time Difference Between Two Columns in Hours and Minutes

This was driving me bonkers as the .astype() solution above didn't work for me. But I found another way. Haven't timed it or anything, but might work for others out there:

t1 = pd.to_datetime('1/1/2015 01:00')
t2 = pd.to_datetime('1/1/2015 03:30')

print pd.Timedelta(t2 - t1).seconds / 3600.0

...if you want hours. Or:

print pd.Timedelta(t2 - t1).seconds / 60.0

...if you want minutes.

How to do SELECT MAX in Django?

See this. Your code would be something like the following:

from django.db.models import Max
# Generates a "SELECT MAX..." query
Argument.objects.aggregate(Max('rating')) # {'rating__max': 5}

You can also use this on existing querysets:

from django.db.models import Max
args = Argument.objects.filter(name='foo') # or whatever arbitrary queryset
args.aggregate(Max('rating')) # {'rating__max': 5}

If you need the model instance that contains this max value, then the code you posted is probably the best way to do it:

arg = args.order_by('-rating')[0]

Note that this will error if the queryset is empty, i.e. if no arguments match the query (because the [0] part will raise an IndexError). If you want to avoid that behavior and instead simply return None in that case, use .first():

arg = args.order_by('-rating').first() # may return None

C# DateTime.ParseExact

That's because you have the Date in American format in line[i] and UK format in the FormatString.

11/20/2011
M / d/yyyy

I'm guessing you might need to change the FormatString to:

"M/d/yyyy h:mm"

Flask Value error view function did not return a response

You are not returning a response object from your view my_form_post. The function ends with implicit return None, which Flask does not like.

Make the function my_form_post return an explicit response, for example

return 'OK'

at the end of the function.

preferredStatusBarStyle isn't called

Possible root cause

I had the same problem, and figured out it was happening because I wasn't setting the root view controller in my application window.

The UIViewController in which I had implemented the preferredStatusBarStyle was used in a UITabBarController, which controlled the appearance of the views on the screen.

When I set the root view controller to point to this UITabBarController, the status bar changes started to work correctly, as expected (and the preferredStatusBarStyle method was getting called).

(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    ... // other view controller loading/setup code

    self.window.rootViewController = rootTabBarController;
    [self.window makeKeyAndVisible];
    return YES;
}

Alternative method (Deprecated in iOS 9)

Alternatively, you can call one of the following methods, as appropriate, in each of your view controllers, depending on its background color, instead of having to use setNeedsStatusBarAppearanceUpdate:

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

or

[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];

Note that you'll also need to set UIViewControllerBasedStatusBarAppearance to NO in the plist file if you use this method.

jQuery remove selected option from this

 $('#some_select_box').click(function() {
     $(this).find('option:selected').remove();
 });

Using the find method.

How to force browser to download file?

You are setting the response headers after writing the contents of the file to the output stream. This is quite late in the response lifecycle to be setting headers. The correct sequence of operations should be to set the headers first, and then write the contents of the file to the servlet's outputstream.

Therefore, your method should be written as follows (this won't compile as it is a mere representation):

response.setContentType("application/force-download");
response.setContentLength((int)f.length());
        //response.setContentLength(-1);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName);
...
...
File f= new File(fileName);

InputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);

while(din.available() > 0){
    out.print(din.readLine());
    out.print("\n");
}

The reason for the failure is that it is possible for the actual headers sent by the servlet would be different from what you are intending to send. After all, if the servlet container does not know what headers (which appear before the body in the HTTP response), then it may set appropriate headers to ensure that the response is valid; setting the headers after the file has been written is therefore futile and redundant as the container might have already set the headers. You could confirm this by looking at the network traffic using Wireshark or a HTTP debugging proxy like Fiddler or WebScarab.

You may also refer to the Java EE API documentation for ServletResponse.setContentType to understand this behavior:

Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response's character encoding is only set from the given content type if this method is called before getWriter is called.

This method may be called repeatedly to change content type and character encoding. This method has no effect if called after the response has been committed.

...

How to discard uncommitted changes in SourceTree?

Do as follow,

  • Click on commit
  • Select all by pressing CMD+A that you want to delete or discard
  • Right click on the selected uncommitted files that you want to delete
  • Select Remove from the drop-down list

How to create friendly URL in php?

It's actually not PHP, it's apache using mod_rewrite. What happens is the person requests the link, www.example.com/profile/12345 and then apache chops it up using a rewrite rule making it look like this, www.example.com/profile.php?u=12345, to the server. You can find more here: Rewrite Guide

Open new Terminal Tab from command line (Mac OS X)

What about this simple snippet, based on a standard script command (echo):

# set mac osx's terminal title to "My Title"
echo -n -e "\033]0;My Title\007"

Could not resolve '...' from state ''

I've just had this same issue with Ionic.

It turns out nothing was wrong with my code, I simply had to quit the ionic serve session and run ionic serve again.

After going back into the app, my states worked fine.

I would also suggest pressing save on your app.js file a few times if you are running gulp, to make sure everything gets re-compiled.

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

This happens when your result is not a result (but a "false" instead). You should change this line

$sql = 'SELECT * FROM $usertable WHERE PartNumber = $partid';

to this:

$sql = "SELECT * FROM $usertable WHERE PartNumber = $partid";

because the " can interprete $variables while ' cannot.

Works fine with integers (numbers), for strings you need to put the $variable in single quotes, like

$sql = "SELECT * FROM $usertable WHERE PartNumber = '$partid' ";

If you want / have to work with single quotes, then php CAN NOT interprete the variables, you will have to do it like this:

 $sql = 'SELECT * FROM '.$usertable.' WHERE string_column = "'.$string.'" AND integer_column = '.$number.';

How to set 00:00:00 using moment.js

var time = moment().toDate();  // This will return a copy of the Date that the moment uses

time.setHours(0);
time.setMinutes(0);
time.setSeconds(0);
time.setMilliseconds(0);

Redirect pages in JSP?

Just define the target page in the action attribute of the <form> containing the submit button.

So, in page1.jsp:

<form action="page2.jsp">
    <input type="submit">
</form>

Unrelated to the problem, a JSP is not the best place to do business stuff, if you need to do any. Consider learning servlets.

When should static_cast, dynamic_cast, const_cast and reinterpret_cast be used?

It might help if you know little bit of internals...

static_cast

  • C++ compiler already knows how to convert between scaler types such as float to int. Use static_cast for them.
  • When you ask compiler to convert from type A to B, static_cast calls B's constructor passing A as param. Alternatively, A could have a conversion operator (i.e. A::operator B()). If B doesn't have such constructor, or A doesn't have a conversion operator, then you get compile time error.
  • Cast from A* to B* always succeeds if A and B are in inheritance hierarchy (or void) otherwise you get compile error.
  • Gotcha: If you cast base pointer to derived pointer but if actual object is not really derived type then you don't get error. You get bad pointer and very likely a segfault at runtime. Same goes for A& to B&.
  • Gotcha: Cast from Derived to Base or viceversa creates new copy! For people coming from C#/Java, this can be a huge surprise because the result is basically a chopped off object created from Derived.

dynamic_cast

  • dynamic_cast uses runtime type information to figure out if cast is valid. For example, (Base*) to (Derived*) may fail if pointer is not actually of derived type.
  • This means, dynamic_cast is very expensive compared to static_cast!
  • For A* to B*, if cast is invalid then dynamic_cast will return nullptr.
  • For A& to B& if cast is invalid then dynamic_cast will throw bad_cast exception.
  • Unlike other casts, there is runtime overhead.

const_cast

  • While static_cast can do non-const to const it can't go other way around. The const_cast can do both ways.
  • One example where this comes handy is iterating through some container like set<T> which only returns its elements as const to make sure you don't change its key. However if your intent is to modify object's non-key members then it should be ok. You can use const_cast to remove constness.
  • Another example is when you want to implement T& SomeClass::foo() as well as const T& SomeClass::foo() const. To avoid code duplication, you can apply const_cast to return value of one function from another.

reinterpret_cast

  • This basically says that take these bytes at this memory location and think of it as given object.
  • For example, you can load 4 bytes of float to 4 bytes of int to see how bits in float looks like.
  • Obviously, if data is not correct for the type, you may get segfault.
  • There is no runtime overhead for this cast.

What is "String args[]"? parameter in main method Java

When you finish your code, you will turn it into a file with the extension .java, which can be run by double clicking it, but also throughout a console (terminal on a mac, cmd.exe on windows) which lets the user do many things. One thing is they can see console messages (System.out.print or System.out.println) which they can't see if they double click. Another thing they can do is specify parameters, so normally you would use the line

java -jar MyCode.jar

after navigating to the folder of the program with

cd C:My/Code/Location

on windows or

cd My/Code/Location

on Mac (notice that mac is less clunky) to run code, but to specify parameters you would use

java -jar MyCode.jar parameter1 parameter2

These parameters stored in the args array, which you can use in your program is you want to allow the user to control special parameters such as what file to use or how much memory the program can have. If you want to know how to use an array, you could probably find a topic on this site or just google it. Note that any number of parameters can be used.

MySQL Multiple Left Joins

You're missing a GROUP BY clause:

SELECT news.id, users.username, news.title, news.date, news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id

The left join is correct. If you used an INNER or RIGHT JOIN then you wouldn't get news items that didn't have comments.

Converting HTML element to string in JavaScript / JQuery

(document.body.outerHTML).constructor will return String. (take off .constructor and that's your string)

That aughta do it :)

How do I reference a cell within excel named range?

Add a column to the left so that B10 to B20 is your named range Age.

Set A10 to A20 so that A10 = 1, A11= 2,... A20 = 11 and give the range A10 to A20 a name e.g. AgeIndex.

The 5th element can be then found by using an array formula:

=sum( Age * (1 * (AgeIndex = 5) )

As it's an array formula you'll need to press Ctrl + Shift + Return to make it work and not just return. Doing that, the formula will be turned into an array formula:

{=sum( Age * (1 * (AgeIndex = 5) )}

Increasing the timeout value in a WCF service

Under the Tools menu in Visual Studio 2008 (or 2005 if you have the right WCF stuff installed) there is an options called 'WCF Service Configuration Editor'.

From there you can change the binding options for both the client and the services, one of these options will be for time-outs.

node.js remove file

I don't think you have to check if file exists or not, fs.unlink will check it for you.

fs.unlink('fileToBeRemoved', function(err) {
    if(err && err.code == 'ENOENT') {
        // file doens't exist
        console.info("File doesn't exist, won't remove it.");
    } else if (err) {
        // other errors, e.g. maybe we don't have enough permission
        console.error("Error occurred while trying to remove file");
    } else {
        console.info(`removed`);
    }
});

pandas: best way to select all columns whose names start with X

The simplest way is to use str directly on column names, there is no need for pd.Series

df.loc[:,df.columns.str.startswith("foo")]


Error in model.frame.default: variable lengths differ

Joran suggested to first remove the NAs before running the model. Thus, I removed the NAs, run the model and obtained the residuals. When I updated model2 by inclusion of the lagged residuals, the error message did not appear again.

Remove NAs

df2<-df1[complete.cases(df1),]

Run the main model

model2<-gam(death ~ pm10 + s(trend,k=14*7)+ s(temp,k=5), data=df2, family=poisson)

Obtain residuals

resid2 <- residuals(model2,type="deviance")

Update model2 by including the lag 1 residuals

model2_1 <- update(model2,.~.+ Lag(resid2,1),  na.action=na.omit)

How to run java application by .bat file

It's the same way you run it from command line. Just put that "command line" into a ".bat" file.

So, if you use java -cp .;foo.jar Bar, put that into a .bat file as

@echo off

java -cp .;foo.jar Bar

How to "properly" print a list?

Here's an interactive session showing some of the steps in @TokenMacGuy's one-liner. First he uses the map function to convert each item in the list to a string (actually, he's making a new list, not converting the items in the old list). Then he's using the string method join to combine those strings with ', ' between them. The rest is just string formatting, which is pretty straightforward. (Edit: this instance is straightforward; string formatting in general can be somewhat complex.)

Note that using join is a simple and efficient way to build up a string from several substrings, much more efficient than doing it by successively adding strings to strings, which involves a lot of copying behind the scenes.

>>> mylist = ['x', 3, 'b']
>>> m = map(str, mylist)
>>> m
['x', '3', 'b']
>>> j = ', '.join(m)
>>> j
'x, 3, b'

Return file in ASP.Net Core Web API

Here is a simplistic example of streaming a file:

using System.IO;
using Microsoft.AspNetCore.Mvc;
[HttpGet("{id}")]
public async Task<FileStreamResult> Download(int id)
{
    var path = "<Get the file path using the ID>";
    var stream = File.OpenRead(path);
    return new FileStreamResult(stream, "application/octet-stream");
}

Note:

Be sure to use FileStreamResult from Microsoft.AspNetCore.Mvc and not from System.Web.Mvc.

how to convert long date value to mm/dd/yyyy format

Refer below code for formatting date

long strDate1 = 1346524199000;
Date date=new Date(strDate1);

try {
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        date = df2.format(format.parse("yourdate");
    } catch (java.text.ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

cast class into another class or convert class to another

Use JSON serialization and deserialization:

using Newtonsoft.Json;

Class1 obj1 = new Class1();
Class2 obj2 = JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj1));

Or:

public class Class1
{
    public static explicit operator Class2(Class1 obj)
    {
        return JsonConvert.DeserializeObject<Class2>(JsonConvert.SerializeObject(obj));
    }
}

Which then allows you to do something like

Class1 obj1 = new Class1();
Class2 obj2 = (Class2)obj1;

Converting JSON data to Java object

Depending on the input JSON format(string/file) create a jSONString. Sample Message class object corresponding to JSON can be obtained as below:

Message msgFromJSON = new ObjectMapper().readValue(jSONString, Message.class);

How to uninstall Apache with command line

If Apache was installed using NSIS installer it should have left an uninstaller. You should search inside Apache installation directory for executable named unistaller.exe or something like that. NSIS uninstallers support /S flag by default for silent uninstall. So you can run something like "C:\Program Files\<Apache installation dir here>\uninstaller.exe" /S

From NSIS documentation:

3.2.1 Common Options

/NCRC disables the CRC check, unless CRCCheck force was used in the script. /S runs the installer or uninstaller silently. See section 4.12 for more information. /D sets the default installation directory ($INSTDIR), overriding InstallDir and InstallDirRegKey. It must be the last parameter used in the command line and must not contain any quotes, even if the path contains spaces. Only absolute paths are supported.

Change the content of a div based on selection from dropdown menu

There are many ways to perform your task, but the most elegant are, I believe, using css. Here are basic steps

  1. Listening option selection event, biding adding/removing some class to container action, which contains all divs you are interested in (for example, body)
  2. Adding styles for hiding all divs except one.
  3. Well done, sir.

This works pretty well if there a few divs, since more elements you want to toggle, more css rules should be written. Here is more general solution, binding action, base on following steps: 1. find all elements using some selector (usually it looks like '.menu-container .menu-item') 2. find one of found elements, which is current visible, hide it 3. make visible another element, the one you desire to be visible under new circumstances.

javascript it a rather timtoady language )

How to change the CHARACTER SET (and COLLATION) throughout a database?

change database collation:

ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change table collation:

ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

change column collation:

ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci;

What do the parts of utf8mb4_0900_ai_ci mean?

3 bytes -- utf8
4 bytes -- utf8mb4 (new)
v4.0 --   _unicode_
v5.20 --  _unicode_520_
v9.0 --   _0900_ (new)
_bin      -- just compare the bits; don't consider case folding, accents, etc
_ci       -- explicitly case insensitive (A=a) and implicitly accent insensitive (a=á)
_ai_ci    -- explicitly case insensitive and accent insensitive
_as (etc) -- accent-sensitive (etc)
_bin         -- simple, fast
_general_ci  -- fails to compare multiple letters; eg ss=ß, somewhat fast
...          -- slower
_0900_       -- (8.0) much faster because of a rewrite

More info:

How to properly and completely close/reset a TcpClient connection?

Have you tried calling TcpClient.Dispose() explicitly?

And are you sure that you have TcpClient.Close() and TcpClient.Dispose()-ed ALL connections?

What is the difference between int, Int16, Int32 and Int64?

A very important note on the 16, 32 and 64 types:

if you run this query... Array.IndexOf(new Int16[]{1,2,3}, 1)

you are suppose to get zero(0) because you are asking... is 1 within the array of 1, 2 or 3. if you get -1 as answer, it means 1 is not within the array of 1, 2 or 3.

Well check out what I found: All the following should give you 0 and not -1 (I've tested this in all framework versions 2.0, 3.0, 3.5, 4.0)

C#:

Array.IndexOf(new Int16[]{1,2,3}, 1) = -1 (not correct)
Array.IndexOf(new Int32[]{1,2,3}, 1) = 0 (correct)
Array.IndexOf(new Int64[]{1,2,3}, 1) = 0 (correct)

VB.NET:

Array.IndexOf(new Int16(){1,2,3}, 1) = -1 (not correct)
Array.IndexOf(new Int32(){1,2,3}, 1) = 0 (correct)
Array.IndexOf(new Int64(){1,2,3}, 1) = -1 (not correct)

So my point is, for Array.IndexOf comparisons, only trust Int32!

Counting Chars in EditText Changed Listener

little few change in your code :

TextView tv = (TextView)findViewById(R.id.charCounts);
textMessage = (EditText)findViewById(R.id.textMessage);
textMessage.addTextChangedListener(new TextWatcher(){
    public void afterTextChanged(Editable s) {
        tv.setText(String.valueOf(s.toString().length()));
    }
    public void beforeTextChanged(CharSequence s, int start, int count, int after){}
    public void onTextChanged(CharSequence s, int start, int before, int count){}
}); 

Automatically start a Windows Service on install

You can use the GetServices method of ServiceController class to get an array of all the services. Then, find your service by checking the ServiceName property of each service. When you've found your service, call the Start method to start it.

You should also check the Status property to see what state it is already in before calling start (it may be running, paused, stopped, etc..).

jQuery posting JSON

'data' should be a stringified JavaScript object:

data: JSON.stringify({ "userName": userName, "password" : password })

To send your formData, pass it to stringify:

data: JSON.stringify(formData)

Some servers also require the application/json content type:

contentType: 'application/json'

There's also a more detailed answer to a similar question here: Jquery Ajax Posting json to webservice

Change limit for "Mysql Row size too large"

I would like to share an awesome answer, it might be helpful. Credits Bill Karwin see here https://dba.stackexchange.com/questions/6598/innodb-create-table-error-row-size-too-large

They vary by InnoDB file format.At present there are 2 formats called Antelope and Barracuda.

The central tablespace file (ibdata1) is always in Antelope format. If you use file-per-table, you can make the individual files use Barracuda format by setting innodb_file_format=Barracuda in my.cnf.

Basic points:

  1. One 16KB page of InnoDB data must hold at least two rows of data. Plus each page has a header and a footer containing page checksums and log sequence number and so on. That's where you get your limit of a bit less than 8KB per row.

  2. Fixed-size data types like INTEGER, DATE, FLOAT, CHAR are stored on this primary data page and count toward the row size limit.

  3. Variable-sized data types like VARCHAR, TEXT, BLOB are stored on overflow pages, so they don't count fully toward the row size limit. In Antelope, up to 768 bytes of such columns are stored on the primary data page in addition to being stored on the overflow page. Barracuda supports a dynamic row format, so it may store only a 20-byte pointer on the primary data page.

  4. Variable-size data types are also prefixed with 1 or more bytes to encode the length. And InnoDB row format also has an array of field offsets. So there's an internal structure more or less documented in their wiki.

Barracuda also supports a ROW_FORMAT=COMPRESSED to gain further storage efficiency for overflow data.

I also have to comment that I've never seen a well-designed table exceed the row size limit. It's a strong "code smell" that you're violating the repeating groups condition of First Normal Form.

Run a Python script from another Python script, passing in arguments

import subprocess
subprocess.call(" python script2.py 1", shell=True)

'gulp' is not recognized as an internal or external command

I had similar issue when I installed locally initially(w/o -g). I reinstalled with -g (global) and then it worked.

npm install -g gulp

you should run gulp from folder where gulpfile.js is available.

Found a swap file by the name

.MERGE_MSG.swp is open in your git, you just need to delete this .swp file. In my case I used following command and it worked fine.

rm .MERGE_MSG.swp

Is there a Social Security Number reserved for testing/examples?

I used this 457-55-5462 as testing SSN and it worked for me. I used it at paypal sandbox account. Hope it helps somebody

Structure of a PDF file?

I'm trying to do pretty much the same thing. The PDF reference is a very difficult document to read. This tutorial is a better start I think.

Writing html form data to a txt file without the use of a webserver

I know this is old, but it's the first example of saving form data to a txt file I found in a quick search. So I've made a couple edits to the above code that makes it work more smoothly. It's now easier to add more fields, including the radio button as @user6573234 requested.

https://jsfiddle.net/cgeiser/m0j7Lwyt/1/

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download() {
  var filename = window.document.myform.docname.value;
  var name =  window.document.myform.name.value;
  var text =  window.document.myform.text.value;
  var problem =  window.document.myform.problem.value;
  
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
    "Your Name: " + encodeURIComponent(name) + "\n\n" +
    "Problem: " + encodeURIComponent(problem) + "\n\n" +
    encodeURIComponent(text)); 

  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>
<form name="myform" method="post" >
  <input type="text" id="docname" value="test.txt" />
  <input type="text" id="name" placeholder="Your Name" />
  <div style="display:unblock">
    Option 1 <input type="radio" value="Option 1" onclick="getElementById('problem').value=this.value; getElementById('problem').show()" style="display:inline" />
    Option 2 <input type="radio" value="Option 2" onclick="getElementById('problem').value=this.value;" style="display:inline" />
    <input type="text" id="problem" />
  </div>
  <textarea rows=3 cols=50 id="text" />Please type in this box. 
When you click the Download button, the contents of this box will be downloaded to your machine at the location you specify. Pretty nifty. </textarea>
  
  <input id="download_btn" type="submit" class="btn" style="width: 125px" onClick="download();" />
  
</form>
</body>
</html>

How to compare variables to undefined, if I don’t know whether they exist?

if (document.getElementById('theElement')) // do whatever after this

For undefined things that throw errors, test the property name of the parent object instead of just the variable name - so instead of:

if (blah) ...

do:

if (window.blah) ...

Why doesn't document.addEventListener('load', function) work in a greasemonkey script?

According to HTML living standard specification, the load event is

Fired at the Window when the document has finished loading; fired at an element containing a resource (e.g. img, embed) when its resource has finished loading

I.e. load event is not fired on document object.

Credit: Why does document.addEventListener(‘load’, handler) not work?

How to use multiprocessing queue in Python?

We implemented two versions of this, one a simple multi thread pool that can execute many types of callables, making our lives much easier and the second version that uses processes, which is less flexible in terms of callables and requires and extra call to dill.

Setting frozen_pool to true will freeze execution until finish_pool_queue is called in either class.

Thread Version:

'''
Created on Nov 4, 2019

@author: Kevin
'''
from threading import Lock, Thread
from Queue import Queue
import traceback
from helium.loaders.loader_retailers import print_info
from time import sleep
import signal
import os

class ThreadPool(object):
    def __init__(self, queue_threads, *args, **kwargs):
        self.frozen_pool = kwargs.get('frozen_pool', False)
        self.print_queue = kwargs.get('print_queue', True)
        self.pool_results = []
        self.lock = Lock()
        self.queue_threads = queue_threads
        self.queue = Queue()
        self.threads = []

        for i in range(self.queue_threads):
            t = Thread(target=self.make_pool_call)
            t.daemon = True
            t.start()
            self.threads.append(t)

    def make_pool_call(self):
        while True:
            if self.frozen_pool:
                #print '--> Queue is frozen'
                sleep(1)
                continue

            item = self.queue.get()
            if item is None:
                break

            call = item.get('call', None)
            args = item.get('args', [])
            kwargs = item.get('kwargs', {})
            keep_results = item.get('keep_results', False)

            try:
                result = call(*args, **kwargs)

                if keep_results:
                    self.lock.acquire()
                    self.pool_results.append((item, result))
                    self.lock.release()

            except Exception as e:
                self.lock.acquire()
                print e
                traceback.print_exc()
                self.lock.release()
                os.kill(os.getpid(), signal.SIGUSR1)

            self.queue.task_done()

    def finish_pool_queue(self):
        self.frozen_pool = False

        while self.queue.unfinished_tasks > 0:
            if self.print_queue:
                print_info('--> Thread pool... %s' % self.queue.unfinished_tasks)
            sleep(5)

        self.queue.join()

        for i in range(self.queue_threads):
            self.queue.put(None)

        for t in self.threads:
            t.join()

        del self.threads[:]

    def get_pool_results(self):
        return self.pool_results

    def clear_pool_results(self):
        del self.pool_results[:]

Process Version:

  '''
Created on Nov 4, 2019

@author: Kevin
'''
import traceback
from helium.loaders.loader_retailers import print_info
from time import sleep
import signal
import os
from multiprocessing import Queue, Process, Value, Array, JoinableQueue, Lock,\
    RawArray, Manager
from dill import dill
import ctypes
from helium.misc.utils import ignore_exception
from mem_top import mem_top
import gc

class ProcessPool(object):
    def __init__(self, queue_processes, *args, **kwargs):
        self.frozen_pool = Value(ctypes.c_bool, kwargs.get('frozen_pool', False))
        self.print_queue = kwargs.get('print_queue', True)
        self.manager = Manager()
        self.pool_results = self.manager.list()
        self.queue_processes = queue_processes
        self.queue = JoinableQueue()
        self.processes = []

        for i in range(self.queue_processes):
            p = Process(target=self.make_pool_call)
            p.start()
            self.processes.append(p)

        print 'Processes', self.queue_processes

    def make_pool_call(self):
        while True:
            if self.frozen_pool.value:
                sleep(1)
                continue

            item_pickled = self.queue.get()

            if item_pickled is None:
                #print '--> Ending'
                self.queue.task_done()
                break

            item = dill.loads(item_pickled)

            call = item.get('call', None)
            args = item.get('args', [])
            kwargs = item.get('kwargs', {})
            keep_results = item.get('keep_results', False)

            try:
                result = call(*args, **kwargs)

                if keep_results:
                    self.pool_results.append(dill.dumps((item, result)))
                else:
                    del call, args, kwargs, keep_results, item, result

            except Exception as e:
                print e
                traceback.print_exc()
                os.kill(os.getpid(), signal.SIGUSR1)

            self.queue.task_done()

    def finish_pool_queue(self, callable=None):
        self.frozen_pool.value = False

        while self.queue._unfinished_tasks.get_value() > 0:
            if self.print_queue:
                print_info('--> Process pool... %s' % (self.queue._unfinished_tasks.get_value()))

            if callable:
                callable()

            sleep(5)

        for i in range(self.queue_processes):
            self.queue.put(None)

        self.queue.join()
        self.queue.close()

        for p in self.processes:
            with ignore_exception: p.join(10)
            with ignore_exception: p.terminate()

        with ignore_exception: del self.processes[:]

    def get_pool_results(self):
        return self.pool_results

    def clear_pool_results(self):
        del self.pool_results[:]
def test(eg):
        print 'EG', eg

Call with either:

tp = ThreadPool(queue_threads=2)
tp.queue.put({'call': test, 'args': [random.randint(0, 100)]})
tp.finish_pool_queue()

or

pp = ProcessPool(queue_processes=2)
pp.queue.put(dill.dumps({'call': test, 'args': [random.randint(0, 100)]}))
pp.queue.put(dill.dumps({'call': test, 'args': [random.randint(0, 100)]}))
pp.finish_pool_queue()

Fetch API with Cookie

Just adding to the correct answers here for .net webapi2 users.

If you are using cors because your client site is served from a different address as your webapi then you need to also include SupportsCredentials=true on the server side configuration.

        // Access-Control-Allow-Origin
        // https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api
        var cors = new EnableCorsAttribute(Settings.CORSSites,"*", "*");
        cors.SupportsCredentials = true;
        config.EnableCors(cors);

dispatch_after - GCD in Swift?

A clearer idea of the structure:

dispatch_after(when: dispatch_time_t, queue: dispatch_queue_t, block: dispatch_block_t?)

dispatch_time_t is a UInt64. The dispatch_queue_t is actually type aliased to an NSObject, but you should just use your familiar GCD methods to get queues. The block is a Swift closure. Specifically, dispatch_block_t is defined as () -> Void, which is equivalent to () -> ().

Example usage:

let delayTime = dispatch_time(DISPATCH_TIME_NOW, Int64(1 * Double(NSEC_PER_SEC)))
dispatch_after(delayTime, dispatch_get_main_queue()) {
    print("test")
}

EDIT:

I recommend using @matt's really nice delay function.

EDIT 2:

In Swift 3, there will be new wrappers for GCD. See here: https://github.com/apple/swift-evolution/blob/master/proposals/0088-libdispatch-for-swift3.md

The original example would be written as follows in Swift 3:

let deadlineTime = DispatchTime.now() + .seconds(1)
DispatchQueue.main.asyncAfter(deadline: deadlineTime) {
    print("test")
}

Note that you can write the deadlineTime declaration as DispatchTime.now() + 1.0 and get the same result because the + operator is overridden as follows (similarly for -):

  • func +(time: DispatchTime, seconds: Double) -> DispatchTime
  • func +(time: DispatchWalltime, interval: DispatchTimeInterval) -> DispatchWalltime

This means that if you don't use the DispatchTimeInterval enum and just write a number, it is assumed that you are using seconds.

is it possible to evenly distribute buttons across the width of an android linearlayout

For evenly spacing out two buttons in a horizontal linear layout, I used 3 LinearLayout objects to act as spaces which are going to be automatically resized. I positioned these LinearLayout objects as follow:

[] Button1 [] Button2 []

([] represents a LinearLayout object used for spacing)

then I set each of these [] LinearLayout objects' weights to 1, and I get evenly spaced out buttons.

Hope this helps.

How to manually trigger click event in ReactJS?

Using React Hooks and the useRef hook.

import React, { useRef } from 'react';

const MyComponent = () => {
    const myInput = useRef(null);

    const clickElement = () => {
        // To simulate a user focusing an input you should use the
        // built in .focus() method.
        myInput.current?.focus();

        // To simulate a click on a button you can use the .click()
        // method.
        // myInput.current?.click();
    }

    return (
        <div>
            <button onClick={clickElement}>
                Trigger click inside input
            </button>
            <input ref={myInput} />
        </div>
    );
}

How to select into a variable in PL/SQL when the result might be null?

From all the answers above, Björn's answer seems to be the most elegant and short. I personally used this approach many times. MAX or MIN function will do the job equally well. Complete PL/SQL follows, just the where clause should be specified.

declare v_column my_table.column%TYPE;
begin
    select MIN(column) into v_column from my_table where ...;
    DBMS_OUTPUT.PUT_LINE('v_column=' || v_column);
end;

What is the difference between JSF, Servlet and JSP?

JSPs are the View component of MVC (Model View Controller). The Controller takes the incoming request and passes it to the Model, which might be a bean that does some database access. The JSP then formats the output using HTML, CSS and JavaScript, and the output then gets sent back to the requester.

Regular expression for matching HH:MM time format

As you asked the left most bit optional, I have done left most and right most bit optional too, check it out

^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]?$

It matches with

0:0 
00:00
00:0 
0:00
23:59
01:00
00:59

The live link is available here

How do you copy the contents of an array to a std::vector in C++ without looping?

Yet another answer, since the person said "I don't know how many times my function will be called", you could use the vector insert method like so to append arrays of values to the end of the vector:

vector<int> x;

void AddValues(int* values, size_t size)
{
   x.insert(x.end(), values, values+size);
}

I like this way because the implementation of the vector should be able to optimize for the best way to insert the values based on the iterator type and the type itself. You are somewhat replying on the implementation of stl.

If you need to guarantee the fastest speed and you know your type is a POD type then I would recommend the resize method in Thomas's answer:

vector<int> x;

void AddValues(int* values, size_t size)
{
   size_t old_size(x.size());
   x.resize(old_size + size, 0);
   memcpy(&x[old_size], values, size * sizeof(int));
}

How to integrate Dart into a Rails app

If you run pub build --mode=debug the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug is used.

Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline

Script to Change Row Color when a cell changes text

I think simpler (though without a script) assuming the Status column is ColumnS.

Select ColumnS and clear formatting from it. Select entire range to be formatted and Format, Conditional formatting..., Format cells if... Custom formula is and:

=and($S1<>"",search("Complete",$S1)>0)

with fill of choice and Done.

This is not case sensitive (change search to find for that) and will highlight a row where ColumnS contains the likes of Now complete (though also Not yet complete).

Android and setting width and height programmatically in dp units

simplest way(and even works from api 1) that tested is:

getResources().getDimensionPixelSize(R.dimen.example_dimen);

From documentations:

Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This is the same as getDimension(int), except the returned value is converted to integer pixels for use as a size. A size conversion involves rounding the base value, and ensuring that a non-zero base value is at least one pixel in size.

Yes it rounding the value but it's not very bad(just in odd values on hdpi and ldpi devices need to add a little value when ldpi is not very common) I tested in a xxhdpi device that converts 4dp to 16(pixels) and that is true.

Print the address or pointer for value in C

char c = 'A';
printf("ptr: %p,\tvalue: %c,\tand also address: %zu", &c, c, &c);

Result:

ptr: 0x7ffc48e5105f,    value: A,    and also address: 140721531457631

How to use delimiter for csv in python

ok, here is what i understood from your question. You are writing a csv file from python but when you are opening that file into some other application like excel or open office they are showing the complete row in one cell rather than each word in individual cell. I am right??

if i am then please try this,

import csv

with open(r"C:\\test.csv", "wb") as csv_file:
    writer = csv.writer(csv_file, delimiter =",",quoting=csv.QUOTE_MINIMAL)
    writer.writerow(["a","b"])

you have to set the delimiter = ","

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

For Webdriverjs (node.js), the following maximizes chrome window.

var webdriver = require('selenium-webdriver');
var driver = new webdriver.Builder().
withCapabilities(webdriver.Capabilities.chrome()).build();
driver.manage().window().maximize();
driver.get('hxxp://localhost:8888');

PHP 7 simpleXML

For Alpine (in docker), you can use apk add php7-simplexml.

If that doesn't work for you, you can run apk add --no-cache php7-simplexml. This is in case you aren't updating the package index first.

how to make div click-able?

If this div is a function I suggest use cursor:pointer in your style like style="cursor:pointer" and can use onclick function.

like this

<div onclick="myfunction()" style="cursor:pointer"></div>

but I suggest you use a JS framework like jquery or extjs

SQL Server table creation date query

For SQL Server 2005 upwards:

SELECT [name] AS [TableName], [create_date] AS [CreatedDate] FROM sys.tables

For SQL Server 2000 upwards:

SELECT so.[name] AS [TableName], so.[crdate] AS [CreatedDate]
FROM INFORMATION_SCHEMA.TABLES AS it, sysobjects AS so 
WHERE it.[TABLE_NAME] = so.[name]

Unable to copy ~/.ssh/id_rsa.pub

DISPLAY=:0 xclip -sel clip < ~/.ssh/id_rsa.pub didn't work for me (ubuntu 14.04), but you can use :

cat ~/.ssh/id_rsa.pub

to get your public key

Insert variable into Header Location PHP

like this?

<?php
$url_endpoint = get_permalink();
$url_endpoint = parse_url( $url_endpoint );
$url_endpoint = $url_endpoint['path'];

header('Location: http://linkhere.com/'. $url_endpoint);

?>

OS X cp command in Terminal - No such file or directory

I know this question has already been answered, but another option is simply to open the destination and source folders in Finder and then drag and drop them into the terminal. The paths will automatically be copied and properly formatted (thus negating the need to actually figure out proper file names/extensions).

I have to do over-network copies between Mac and Windows machines, sometimes fairly deep down in filetrees, and have found this the most effective way to do so.

So, as an example:

cp -r [drag and drop source folder from finder] [drag and drop destination folder from finder]

How to check if a char is equal to an empty space?

My suggestion would be:

if (c == ' ')

Input length must be multiple of 16 when decrypting with padded cipher

This is a very old question, but my answer may help someone.

  • In the encrypt method, don't forget to encode your string to Base64
  • In the decrypt method, don't forget to decode your string to Base64

Below is the working code

    import java.util.Arrays;
    import java.util.Base64;

    import javax.crypto.Cipher;
    import javax.crypto.SecretKey;
    import javax.crypto.spec.SecretKeySpec;

    public class EncryptionDecryptionUtil {

    public static String encrypt(final String secret, final String data) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.ENCRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while encrypting data", e);
        }

    }

    public static String decrypt(final String secret,
            final String encryptedString) {


        byte[] decodedKey = Base64.getDecoder().decode(secret);

        try {
            Cipher cipher = Cipher.getInstance("AES");
            // rebuild key using SecretKeySpec
            SecretKey originalKey = new SecretKeySpec(Arrays.copyOf(decodedKey, 16), "AES");
            cipher.init(Cipher.DECRYPT_MODE, originalKey);
            byte[] cipherText = cipher.doFinal(Base64.getDecoder().decode(encryptedString));
            return new String(cipherText);
        } catch (Exception e) {
            throw new RuntimeException(
                    "Error occured while decrypting data", e);
        }
    }


    public static void main(String[] args) {

        String data = "This is not easy as you think";
        String key = "---------------------------------";
        String encrypted = encrypt(key, data);
        System.out.println(encrypted);
        System.out.println(decrypt(key, encrypted));
      }
  }

For Generating Key you can use below class

    import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;

public class SecretKeyGenerator {

    public static void main(String[] args) throws NoSuchAlgorithmException {

        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");

        SecureRandom secureRandom = new SecureRandom();
        int keyBitSize = 256;
        keyGenerator.init(keyBitSize, secureRandom);

        SecretKey secretKey = keyGenerator.generateKey();

 System.out.println(Base64.getEncoder().encodeToString(secretKey.getEncoded()));
    }

}

Round double value to 2 decimal places

I was going to go with Jason's answer but I noticed that in My version of Xcode (4.3.3) I couldn't do that. so after a bit of research I found they had recently changed the class methods and removed all the old ones. so here's how I had to do it:

NSNumberFormatter *fmt = [[NSNumberFormatter alloc] init];

[fmt setMaximumFractionDigits:2];
NSLog(@"%@", [fmt stringFromNumber:[NSNumber numberWithFloat:25.342]]);

C# with MySQL INSERT parameters

I was facing very similar problem while trying to insert data using mysql-connector-net-5.1.7-noinstall and Visual Studio(2015) in Windows Form Application. I am not a C# guru. So, it takes around 2 hours to resolve everything.

The following code works lately:

string connetionString = null;
connetionString = "server=localhost;database=device_db;uid=root;pwd=123;";

using (MySqlConnection cn = new MySqlConnection(connetionString))
{
    try
    {
        string query = "INSERT INTO test_table(user_id, user_name) VALUES (?user_id,?user_name);";
        cn.Open();
        using (MySqlCommand cmd = new MySqlCommand(query, cn))
        {
            cmd.Parameters.Add("?user_id", MySqlDbType.Int32).Value = 123;
            cmd.Parameters.Add("?user_name", MySqlDbType.VarChar).Value = "Test username";
            cmd.ExecuteNonQuery();
        }
    }
    catch (MySqlException ex)
    {
        MessageBox.Show("Error in adding mysql row. Error: "+ex.Message);
    }
}

Excel VBA Open a Folder

If you want to open a windows file explorer, you should call explorer.exe

Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)

Equivalent syxntax

Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus

What is the difference between CHARACTER VARYING and VARCHAR in PostgreSQL?

Varying is an alias for varchar, so no difference, see documentation :)

The notations varchar(n) and char(n) are aliases for character varying(n) and character(n), respectively. character without length specifier is equivalent to character(1). If character varying is used without length specifier, the type accepts strings of any size. The latter is a PostgreSQL extension.

DLL and LIB files - what and why?

Another aspect is security (obfuscation). Once a piece of code is extracted from the main application and put in a "separated" Dynamic-Link Library, it is easier to attack, analyse (reverse-engineer) the code, since it has been isolated. When the same piece of code is kept in a LIB Library, it is part of the compiled (linked) target application, and this thus harder to isolate (differentiate) that piece of code from the rest of the target binaries.

Difference between npx and npm?

NPM is a package manager, you can install node.js packages using NPM

NPX is a tool to execute node.js packages.

It doesn't matter whether you installed that package globally or locally. NPX will temporarily install it and run it. NPM also can run packages if you configure a package.json file and include it in the script section.

So remember this, if you want to check/run a node package quickly without installing locally or globally use NPX.

npM - Manager

npX - Execute - easy to remember

Using Python's os.path, how do I go up one directory?

I think the easiest thing to do is just to reuse dirname() So you can call

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

if you file is at /Users/hobbes3/Sites/mysite/templates/method.py

This will return "/Users/hobbes3/Sites/mysite"

ComboBox: Adding Text and Value to an Item (no Binding Source)

If anyone is still interested in this, here is a simple and flexible class for a combobox item with a text and a value of any type (very similar to Adam Markowitz's example):

public class ComboBoxItem<T>
{
    public string Name;
    public T value = default(T);

    public ComboBoxItem(string Name, T value)
    {
        this.Name = Name;
        this.value = value;
    }

    public override string ToString()
    {
        return Name;
    }
}

Using the <T> is better than declaring the value as an object, because with object you'd then have to keep track of the type you used for each item, and cast it in your code to use it properly.

I've been using it on my projects for quite a while now. It is really handy.

What's the best way to determine the location of the current PowerShell script?

I use the automatic variable $ExecutionContext. It will work from PowerShell 2 and later.

 $ExecutionContext.SessionState.Path.GetUnresolvedProviderPathFromPSPath('.\')

$ExecutionContext Contains an EngineIntrinsics object that represents the execution context of the Windows PowerShell host. You can use this variable to find the execution objects that are available to cmdlets.

Simple PowerShell LastWriteTime compare

Slightly easier - use the new-timespan cmdlet, which creates a time interval from the current time.

ls | where-object {(new-timespan $_.LastWriteTime).days -ge 1}

shows all files not written to today.

How do I parse JSON from a Java HTTPResponse?

There is no need to do the reader loop yourself. The JsonTokener has this built in. E.g.

ttpResponse response; // some response object
BufferedReader reader = new BufferedReader(new    
JSONTokener tokener = new JSONTokener(reader);
JSONArray finalResult = new JSONArray(tokener);

Is it bad practice to use break to exit a loop in Java?

Using break in loops can be perfectly legitimate and it can even be the only way to solve some problems.

However, it's bad reputation comes from the fact that new programmers usually abuse it, leading to confusing code, especially by using break to stop the loop in conditions that could have been written in the loop condition statement in the first place.

Serializing list to JSON

You can use pure Python to do it:

import json
list = [1, 2, (3, 4)] # Note that the 3rd element is a tuple (3, 4)
json.dumps(list) # '[1, 2, [3, 4]]'

accessing a variable from another class

I hope I'm understanding the problem correctly, but it looks like you don't have a reference back to your DrawFrame object from DrawCircle.

Try this:

Change your constructor signature for DrawCircle to take in a DrawFrame object. Within the constructor, set the class variable "d" to the DrawFrame object you just took in. Now add the getWidth/getHeight methods to DrawFrame as mentioned in previous answers. See if that allows you to get what you're looking for.

Your DrawCircle constructor should be changed to something like:

public DrawCircle(DrawFrame frame)
{
    d = frame;
    w = 400;
    h = 400;
    diBig = 300;
    diSmall = 10;
    maxRad = (diBig/2) - diSmall;
    xSq = 50;
    ySq = 50;
    xPoint = 200;
    yPoint = 200;
}

The last line of code in DrawFrame should look something like:

contentPane.add(new DrawCircle(this));

Then, try using d.getheight(), d.getWidth() and so on within DrawCircle. This assumes you still have those methods available on DrawFrame to access them, of course.

What is the JUnit XML format specification that Hudson supports?

I've decided to post a new answer, because some existing answers are outdated or incomplete.

First of all: there is nothing like JUnit XML Format Specification, simply because JUnit doesn't produce any kind of XML or HTML report.

The XML report generation itself comes from the Ant JUnit task/ Maven Surefire Plugin/ Gradle (whichever you use for running your tests). The XML report format was first introduced by Ant and later adapted by Maven (and Gradle).

If somebody just needs an official XML format then:

  1. There exists a schema for a maven surefire-generated XML report and it can be found here: surefire-test-report.xsd.
  2. For an ant-generated XML there is a 3rd party schema available here (but it might be slightly outdated).

Hope it will help somebody.

ORA-01843 not a valid month- Comparing Dates

If the source date contains minutes and seconds part, your date comparison will fail. you need to convert source date to the required format using to_char and the target date also.

How to change screen resolution of Raspberry Pi

Just run the following simple command on Raspberry Pi 3 running Raspbian Jessie.

run terminal and type

sudo raspi-config

Go to: >Advanced Option > Resolution > just set your resolution compatible fit with your screen.

then

reboot

If you didn't found the menu on configuration, please update your raspberry pi software configuration tool (raspi-config).

That's all TQ.

inline if statement java, why is not working

This should be (condition)? True statement : False statement

Leave out the "if"

What is the Windows equivalent of the diff command?

Winmerge has a command line utility that might be worth checking out.

Also, you can use the graphical part of it too depending on what you need.

A url resource that is a dot (%2E)

It's actually not really clearly stated in the standard (RFC 3986) whether a percent-encoded version of . or .. is supposed to have the same this-folder/up-a-folder meaning as the unescaped version. Section 3.3 only talks about “The path segments . and ..”, without clarifying whether they match . and .. before or after pct-encoding.

Personally I find Firefox's interpretation that %2E does not mean . most practical, but unfortunately all the other browsers disagree. This would mean that you can't have a path component containing only . or ...

I think the only possible suggestion is “don't do that”! There are other path components that are troublesome too, typically due to server limitations: %2F, %00 and %5C sequences in paths may also be blocked by some web servers, and the empty path segment can also cause problems. So in general it's not possible to fit all possible byte sequences into a path component.

Example JavaScript code to parse CSV data

I have an implementation as part of a spreadsheet project.

This code is not yet tested thoroughly, but anyone is welcome to use it.

As some of the answers noted though, your implementation can be much simpler if you actually have DSV or TSV file, as they disallow the use of the record and field separators in the values. CSV, on the other hand, can actually have commas and newlines inside a field, which breaks most regular expression and split-based approaches.

var CSV = {
    parse: function(csv, reviver) {
        reviver = reviver || function(r, c, v) { return v; };
        var chars = csv.split(''), c = 0, cc = chars.length, start, end, table = [], row;
        while (c < cc) {
            table.push(row = []);
            while (c < cc && '\r' !== chars[c] && '\n' !== chars[c]) {
                start = end = c;
                if ('"' === chars[c]){
                    start = end = ++c;
                    while (c < cc) {
                        if ('"' === chars[c]) {
                            if ('"' !== chars[c+1]) {
                                break;
                            }
                            else {
                                chars[++c] = ''; // unescape ""
                            }
                        }
                        end = ++c;
                    }
                    if ('"' === chars[c]) {
                        ++c;
                    }
                    while (c < cc && '\r' !== chars[c] && '\n' !== chars[c] && ',' !== chars[c]) {
                        ++c;
                    }
                } else {
                    while (c < cc && '\r' !== chars[c] && '\n' !== chars[c] && ',' !== chars[c]) {
                        end = ++c;
                    }
                }
                row.push(reviver(table.length-1, row.length, chars.slice(start, end).join('')));
                if (',' === chars[c]) {
                    ++c;
                }
            }
            if ('\r' === chars[c]) {
                ++c;
            }
            if ('\n' === chars[c]) {
                ++c;
            }
        }
        return table;
    },

    stringify: function(table, replacer) {
        replacer = replacer || function(r, c, v) { return v; };
        var csv = '', c, cc, r, rr = table.length, cell;
        for (r = 0; r < rr; ++r) {
            if (r) {
                csv += '\r\n';
            }
            for (c = 0, cc = table[r].length; c < cc; ++c) {
                if (c) {
                    csv += ',';
                }
                cell = replacer(r, c, table[r][c]);
                if (/[,\r\n"]/.test(cell)) {
                    cell = '"' + cell.replace(/"/g, '""') + '"';
                }
                csv += (cell || 0 === cell) ? cell : '';
            }
        }
        return csv;
    }
};

How to increment a pointer address and pointer's value?

With regards to "How to increment a pointer address and pointer's value?" I think that ++(*p++); is actually well defined and does what you're asking for, e.g.:

#include <stdio.h>

int main() {
  int a = 100;
  int *p = &a;
  printf("%p\n",(void*)p);
  ++(*p++);
  printf("%p\n",(void*)p);
  printf("%d\n",a);
  return 0;
}

It's not modifying the same thing twice before a sequence point. I don't think it's good style though for most uses - it's a little too cryptic for my liking.

Event handler not working on dynamic content

You have to add the selector parameter, otherwise the event is directly bound instead of delegated, which only works if the element already exists (so it doesn't work for dynamically loaded content).

See http://api.jquery.com/on/#direct-and-delegated-events

Change your code to

$(document.body).on('click', '.update' ,function(){

The jQuery set receives the event then delegates it to elements matching the selector given as argument. This means that contrary to when using live, the jQuery set elements must exist when you execute the code.

As this answers receives a lot of attention, here are two supplementary advises :

1) When it's possible, try to bind the event listener to the most precise element, to avoid useless event handling.

That is, if you're adding an element of class b to an existing element of id a, then don't use

$(document.body).on('click', '#a .b', function(){

but use

$('#a').on('click', '.b', function(){

2) Be careful, when you add an element with an id, to ensure you're not adding it twice. Not only is it "illegal" in HTML to have two elements with the same id but it breaks a lot of things. For example a selector "#c" would retrieve only one element with this id.

R: invalid multibyte string

This happened to me because I had the 'copyright' symbol in one of my strings! Once it was removed, problem solved.

A good rule of thumb, make sure that characters not appearing on your keyboard are removed if you are seeing this error.

How to sort findAll Doctrine's method?

Modify the default findAll function in EntityRepository like this:

public function findAll( array $orderBy = null )
{
    return $this->findBy([], $orderBy);
}

That way you can use the ''findAll'' on any query for any data table with an option to sort the query

How do I lowercase a string in C?

It's in the standard library, and that's the most straight forward way I can see to implement such a function. So yes, just loop through the string and convert each character to lowercase.

Something trivial like this:

#include <ctype.h>

for(int i = 0; str[i]; i++){
  str[i] = tolower(str[i]);
}

or if you prefer one liners, then you can use this one by J.F. Sebastian:

for ( ; *p; ++p) *p = tolower(*p);

How to add Tomcat Server in eclipse

The Java EE version of Eclipse is not installed, insted a standard SDK version is installed.

You can go to Help > Install New Software then select the Eclipse site from the dropdown (Helios, Kepler depending upon your revision). Then select the option that shows Java EE. Restart Eclipse and you should see the Server list, such as Apache, Oracle, IBM etc.

How can I loop over entries in JSON?

Actually, to query the team_name, just add it in brackets to the last line. Apart from that, it seems to work on Python 2.7.3 on command line.

from urllib2 import urlopen
import json

url = 'http://openligadb-json.heroku.com/api/teams_by_league_saison?league_saison=2012&league_shortcut=bl1'
response = urlopen(url)
json_obj = json.load(response)

for i in json_obj['team']:
    print i['team_name']

How can I run NUnit tests in Visual Studio 2017?

  • You have to choose the processor architecture of unit tests in Visual Studio: menu Test ? Test Settings ? Default processor architecture

  • Test Adapter has to be open to see the tests: (Visual Studio e.g.: menu Test ? Windows ? Test Explorer


Additional information what's going on, you can consider at the Visual Studio 'Output-Window' and choose the dropdown 'Show output from' and set 'Tests'.

array_push() with key value pair

$data['cat'] = 'wagon';

That's all you need to add the key and value to the array.

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

For me, what solved the problem was to do a git clone of my project and run (as usual):

npm install

UnicodeDecodeError: 'utf8' codec can't decode bytes in position 3-6: invalid data

Paste this on your command line:

export LC_CTYPE="en_US.UTF-8" 

jQuery - adding elements into an array

var ids = [];

    $(document).ready(function($) {    
    $(".color_cell").bind('click', function() {
        alert('Test');

        ids.push(this.id);       
    });
});

How to calculate Date difference in Hive

I would try this first

select * from employee where month(current_date)-3 = month(joining_date)

How to export the Html Tables data into PDF using Jspdf

Unfortunately it is not possible to do it.

jsPDF does not support exporting images and tables in fromHTML method. in jsPDF v0.9.0 rc2

How do I drop a foreign key constraint only if it exists in sql server?

Ok, I know I'm late to the party, but here is the syntax I think is best. Add a schema name if needed to the OBJECT_ID clause.

IF OBJECTPROPERTY(OBJECT_ID(N'My_FK_name'),'IsConstraint') =1
ALTER TABLE dbo.TableName DROP CONSTRAINT My_FK_name

How to import a new font into a project - Angular 5

the answer is already exist above, but I would like to add some thing.. you can specify the following in your @font-face

@font-face {
  font-family: 'Name You Font';
  src: url('assets/font/xxyourfontxxx.eot');
  src: local('Cera Pro Medium'), local('CeraPro-Medium'),
  url('assets/font/xxyourfontxxx.eot?#iefix') format('embedded-opentype'),
  url('assets/font/xxyourfontxxx.woff') format('woff'),
  url('assets/font/xxyourfontxxx.ttf') format('truetype');
  font-weight: 500;
  font-style: normal;
}

So you can just indicate your fontfamily name that you already choosed

NOTE: the font-weight and font-style depend on your .woff .ttf ... files

How to create a timer using tkinter?

Tkinter root windows have a method called after which can be used to schedule a function to be called after a given period of time. If that function itself calls after you've set up an automatically recurring event.

Here is a working example:

# for python 3.x use 'tkinter' rather than 'Tkinter'
import Tkinter as tk
import time

class App():
    def __init__(self):
        self.root = tk.Tk()
        self.label = tk.Label(text="")
        self.label.pack()
        self.update_clock()
        self.root.mainloop()

    def update_clock(self):
        now = time.strftime("%H:%M:%S")
        self.label.configure(text=now)
        self.root.after(1000, self.update_clock)

app=App()

Bear in mind that after doesn't guarantee the function will run exactly on time. It only schedules the job to be run after a given amount of time. It the app is busy there may be a delay before it is called since Tkinter is single-threaded. The delay is typically measured in microseconds.

fatal: The current branch master has no upstream branch

I made the simple error of forgetting to commit:

git commit -m "first commit"

then git push origin master worked.

Module is not available, misspelled or forgot to load (but I didn't)

I have the same problem, but I resolved adding jquery.min.js before angular.min.js.

How to make a view with rounded corners?

Or you can use a android.support.v7.widget.CardView like so:

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    card_view:cardBackgroundColor="@color/white"
    card_view:cardCornerRadius="4dp">

    <!--YOUR CONTENT-->
</android.support.v7.widget.CardView>

How to link home brew python version and set it as default

After installing python3 with brew install python3 I was getting the error:

Error: An unexpected error occurred during the `brew link` step
The formula built, but is not symlinked into /usr/local
Permission denied @ dir_s_mkdir - /usr/local/Frameworks
Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks

After typing brew link python3 the error was:

Linking /usr/local/Cellar/python/3.6.4_3... Error: Permission denied @ dir_s_mkdir - /usr/local/Frameworks

To solve the problem:

sudo mkdir -p /usr/local/Frameworks
sudo chown -R $(whoami) /usr/local/*
brew link python3

After this, I could open python3 by typing python3

(From https://github.com/Homebrew/homebrew-core/issues/20985)

Regex to match only uppercase "words" with some exceptions

Maybe you can run this regex first to see if the line is all caps:

^[A-Z \d\W]+$

That will match only if it's a line like THING P1 MUST CONNECT TO X2.

Otherwise, you should be able to pull out the individual uppercase phrases with this:

[A-Z][A-Z\d]+

That should match "P1" and "J236" in The thing P1 must connect to the J236 thing in the Foo position.

How to use MySQLdb with Python and Django in OSX 10.6?

For me the problem got solved by simply reinstalling mysql-python

pip uninstall mysql-python
pip install mysql-python

Iterating over every two elements in a list

With unpacking:

l = [1,2,3,4,5,6]
while l:
    i, k, *l = l
    print(f'{i}+{k}={i+k}') 

Note: this will consume l, leaving it empty afterward.

Where does Git store files?

If you are looking for where the project folder was created. I noticed when I typed in the git bash.

$ git init projectName

it will tell me, where the project folder is for that project.

SQL Query to search schema of all tables

You do not need to type SQL Query for this in SQL Server 2008.

In SSMS Object Explorer choose Databases or Tables of the required database (if you need to search in one database), open menu View--> Object Explorer Details (alternatively press F7), type %CreatedDate% in Search textbox, ENTER, enjoy

Unique constraint on multiple columns

USE [TSQL2012]
GO

/****** Object:  Table [dbo].[Table_1]    Script Date: 11/22/2015 12:45:47 PM ******/
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Table_1](
    [seq] [bigint] IDENTITY(1,1) NOT NULL,
    [ID] [int] NOT NULL,
    [name] [nvarchar](50) NULL,
    [cat] [nvarchar](50) NULL,
 CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED 
(
    [ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
 CONSTRAINT [IX_Table_1] UNIQUE NONCLUSTERED 
(
    [name] ASC,
    [cat] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Working with huge files in VIM

For huge one-liners (prints characters from 1 to 99):

cut -c 1-99 filename

Why is my power operator (^) not working?

There is no way to use the ^ (Bitwise XOR) operator to calculate the power of a number. Therefore, in order to calculate the power of a number we have two options, either we use a while loop or the pow() function.

1. Using a while loop.

#include <stdio.h>

int main() {

    int base, expo;
    long long result = 1;

    printf("Enter a base no.: ");
    scanf("%d", &base);

    printf("Enter an exponent: ");
    scanf("%d", &expo);

    while (expo != 0) {
        result *= base;
        --expo;
    }

    printf("Answer = %lld", result);
    return 0;
}    
             

2. Using the pow() function

#include <math.h>
#include <stdio.h>

int main() {

    double base, exp, result;

    printf("Enter a base number: ");
    scanf("%lf", &base);

    printf("Enter an exponent: ");
    scanf("%lf", &exp);

    // calculate the power of our input numbers
    result = pow(base, exp);

    printf("%.1lf^%.1lf = %.2lf", base, exp, result);

    return 0;
}
     

Change url query string value using jQuery

purls $.params() used without a parameter will give you a key-value object of the parameters.

jQuerys $.param() will build a querystring from the supplied object/array.

var params = parsedUrl.param();
delete params["page"];

var newUrl = "?page=" + $(this).val() + "&" + $.param(params);

Update
I've no idea why I used delete here...

var params = parsedUrl.param();
params["page"] = $(this).val();

var newUrl = "?" + $.param(params);

Android Respond To URL in Intent

I did it! Using <intent-filter>. Put the following into your manifest file:

<intent-filter>
  <action android:name="android.intent.action.VIEW" />
  <category android:name="android.intent.category.DEFAULT" />
  <category android:name="android.intent.category.BROWSABLE" />
  <data android:host="www.youtube.com" android:scheme="http" />
</intent-filter>

This works perfectly!

Interop type cannot be embedded

.NET 4.0 allows primary interop assemblies (or rather, the bits of it that you need) to be embedded into your assembly so that you don't need to deploy them alongside your application.

For whatever reason, this assembly can't be embedded - but it sounds like that's not a problem for you. Just open the Properties tab for the assembly in Visual Studio 2010 and set "Embed Interop Types" to "False".

EDIT: See also Michael Gustus's answer, removing the Class suffix from the types you're using.

Font size relative to the user's screen resolution?

Not using media queries is nice because it allows scaling the font size gradually.

Using vw units will adjust the font size relative to the view port size.

Directly converting vw units to font size will make it difficult to hit to the sweet spot for both mobile resolutions and desktop.

I recommend trying something like:

body {
    font-size: calc(0.5em + 1vw);
}

Credit: CSS In Depth

How to get the previous page URL using JavaScript?

<script type="text/javascript">
    document.write(document.referrer);
</script>

document.referrer serves your purpose, but it doesn't work for Internet Explorer versions earlier than IE9.

It will work for other popular browsers, like Chrome, Mozilla, Opera, Safari etc.

What is difference between XML Schema and DTD?

As many people have mentioned before, XML Schema utilize an XML-based syntax and DTDs have a unique syntax. DTD doesn't support datatypes, which does matter.

Lets see a very simple example in which university has multiple students and each student has two elements "name" and "year". Please note that I have uses "// --> " in my code just for comments.

enter image description here

Now I will write this example both in DTD and in XSD.

DTD

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE university[              // --> university as root element 
<!ELEMENT university (student*)>   // --> university has  * = Multiple students
<!ELEMENT student (name,year)>     // --> Student has elements name and year
<!ELEMENT name (#PCDATA)>          // --> name as Parsed character data
<!ELEMENT year (#PCDATA)>          // --> year as Parsed character data
]>

<university>
    <student>
        <name>
            John Niel             //---> I can also use an Integer,not good
        </name>
        <year>
            2000                 //---> I can also use a string,not good
        </year>
    </student>
</university>

XML Schema Definition (XSD)

<?xml version="1.0" encoding="UTF-8"?>
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<xsd:complexType name ="uniType">                    //--> complex datatype uniType
 <xsd:sequence>
  <xsd:element ref="student" maxOccurs="unbounded"/> //--> has unbounded no.of students
 </xsd:sequence>
</xsd:complexType>

<xsd:complexType name="stuType">                     //--> complex datatype stuType
 <xsd:sequence>
  <xsd:element ref="name"/>                          //--> has element name
  <xsd:element ref="year"/>                          //--> has element year
 </xsd:sequence>
</xsd:complexType>

<xsd:element name="university" type="uniType"/>       //--> university of type UniType 
<xsd:element name="student" type="stuType"/>          //--> student of type stuType
<xsd:element name="name" type="xsd:string"/>          //--> name of datatype string
<xsd:element name="year" type="xsd:integer"/>         //--> year of datatype integer
</xsd:schema>



<?xml version="1.0" encoding="UTF-8"?>
<university>
    <student>
        <name>
            John Niel          
        </name>
        <year>
            2000                      //--> only an Integer value is allowed
        </year>
    </student>
</university>

How to check whether the user uploaded a file in PHP?

<!DOCTYPE html>
<html>
<body>

<form action="#" method="post" enctype="multipart/form-data">
    Select image to upload:
    <input name="my_files[]" type="file" multiple="multiple" />
    <input type="submit" value="Upload Image" name="submit">
</form>


<?php

 if (isset($_FILES['my_files']))
  {
    $myFile = $_FILES['my_files'];
    $fileCount = count($myFile["name"]);


        for ($i = 0; $i <$fileCount; $i++)
         {
           $error = $myFile["error"][$i]; 

            if ($error == '4')  // error 4 is for "no file selected"
             {
               echo "no file selected";
             }
            else
             {

               $name =  $myFile["name"][$i];
               echo $name; 
               echo "<br>"; 
               $temporary_file = $myFile["tmp_name"][$i];
               echo $temporary_file;
               echo "<br>";
               $type = $myFile["type"][$i];
               echo $type;
               echo "<br>";
               $size = $myFile["size"][$i];
               echo $size;
               echo "<br>";



               $target_path = "uploads/$name";   //first make a folder named "uploads" where you will upload files


                 if(move_uploaded_file($temporary_file,$target_path))
                  {
                   echo " uploaded";
                   echo "<br>";
                   echo "<br>";
                  }
                   else
                  {
                   echo "no upload ";
                  }




              }
        }  
}
        ?>


</body>
</html>

But be alert. User can upload any type of file and also can hack your server or system by uploading a malicious or php file. In this script there should be some validations. Thank you.

Update Jenkins from a war file

Though I wouldn't consider this as a valid answer to OP's question, I'd still emphasize that the best way to deploy Jenkins (and likely most if not all libraries/packages/software) on Ubuntu is to leverage aptitude (or apt-get) management system.

It is documented here: https://wiki.jenkins-ci.org/display/JENKINS/Installing+Jenkins+on+Ubuntu (notice that if you want to use the LTS build, hit on this repo http://pkg.jenkins-ci.org/debian-stable/)

So if by any chance you actually did use this approach, you'd simply do a apt-get upgrade jenkins

SQL Insert into table only if record doesn't exist

Although the answer I originally marked as chosen is correct and achieves what I asked there is a better way of doing this (which others acknowledged but didn't go into). A composite unique index should be created on the table consisting of fund_id and date.

ALTER TABLE funds ADD UNIQUE KEY `fund_date` (`fund_id`, `date`);

Then when inserting a record add the condition when a conflict is encountered:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = `price`; --this keeps the price what it was (no change to the table) or:

INSERT INTO funds (`fund_id`, `date`, `price`)
    VALUES (23, DATE('2013-02-12'), 22.5)
        ON DUPLICATE KEY UPDATE `price` = 22.5; --this updates the price to the new value

This will provide much better performance to a sub-query and the structure of the table is superior. It comes with the caveat that you can't have NULL values in your unique key columns as they are still treated as values by MySQL.

Multiple GitHub Accounts & SSH Config

Use the IdentityFile parameter in your ~/.ssh/config:

Host github.com
    HostName github.com
    IdentityFile ~/.ssh/github.rsa
    User petdance