Programs & Examples On #Mockolate

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

(Edit: Forget my previous babble...)

Ok, there might be situations where you would go either to the model or to some other url... But I don't really think this belongs in the model, the view (or maybe the model) sounds more apropriate.

About the routes, as far as I know the routes is for the actions in controllers (wich usually "magically" uses a view), not directly to views. The controller should handle all requests, the view should present the results and the model should handle the data and serve it to the view or controller. I've heard a lot of people here talking about routes to models (to the point I'm allmost starting to beleave it), but as I understand it: routes goes to controllers. Of course a lot of controllers are controllers for one model and is often called <modelname>sController (e.g. "UsersController" is the controller of the model "User").

If you find yourself writing nasty amounts of logic in a view, try to move the logic somewhere more appropriate; request and internal communication logic probably belongs in the controller, data related logic may be placed in the model (but not display logic, which includes link tags etc.) and logic that is purely display related would be placed in a helper.

Passing an array of parameters to a stored procedure

this is the best source:

http://www.sommarskog.se/arrays-in-sql.html

create a split function using the link, and use it like:

DELETE YourTable
    FROM YourTable                           d
    LEFT OUTER JOIN dbo.splitFunction(@Parameter) s ON d.ID=s.Value
    WHERE s.Value IS NULL

I prefer the number table approach

This is code based on the above link that should do it for you...

Before you use my function, you need to set up a "helper" table, you only need to do this one time per database:

CREATE TABLE Numbers
(Number int  NOT NULL,
    CONSTRAINT PK_Numbers PRIMARY KEY CLUSTERED (Number ASC)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]
DECLARE @x int
SET @x=0
WHILE @x<8000
BEGIN
    SET @x=@x+1
    INSERT INTO Numbers VALUES (@x)
END

use this function to split your string, which does not loop and is very fast:

CREATE FUNCTION [dbo].[FN_ListToTable]
(
     @SplitOn              char(1)              --REQUIRED, the character to split the @List string on
    ,@List                 varchar(8000)        --REQUIRED, the list to split apart
)
RETURNS
@ParsedList table
(
    ListValue varchar(500)
)
AS
BEGIN

/**
Takes the given @List string and splits it apart based on the given @SplitOn character.
A table is returned, one row per split item, with a column name "ListValue".
This function workes for fixed or variable lenght items.
Empty and null items will not be included in the results set.


Returns a table, one row per item in the list, with a column name "ListValue"

EXAMPLE:
----------
SELECT * FROM dbo.FN_ListToTable(',','1,12,123,1234,54321,6,A,*,|||,,,,B')

    returns:
        ListValue  
        -----------
        1
        12
        123
        1234
        54321
        6
        A
        *
        |||
        B

        (10 row(s) affected)

**/



----------------
--SINGLE QUERY-- --this will not return empty rows
----------------
INSERT INTO @ParsedList
        (ListValue)
    SELECT
        ListValue
        FROM (SELECT
                  LTRIM(RTRIM(SUBSTRING(List2, number+1, CHARINDEX(@SplitOn, List2, number+1)-number - 1))) AS ListValue
                  FROM (
                           SELECT @SplitOn + @List + @SplitOn AS List2
                       ) AS dt
                      INNER JOIN Numbers n ON n.Number < LEN(dt.List2)
                  WHERE SUBSTRING(List2, number, 1) = @SplitOn
             ) dt2
        WHERE ListValue IS NOT NULL AND ListValue!=''



RETURN

END --Function FN_ListToTable

you can use this function as a table in a join:

SELECT
    Col1, COl2, Col3...
    FROM  YourTable
        INNER JOIN dbo.FN_ListToTable(',',@YourString) s ON  YourTable.ID = s.ListValue

here is your delete:

DELETE YourTable
    FROM YourTable                                d
    LEFT OUTER JOIN dbo.FN_ListToTable(',',@Parameter) s ON d.ID=s.ListValue
    WHERE s.ListValue IS NULL

Accessing MP3 metadata with Python

I used eyeD3 the other day with a lot of success. I found that it could add artwork to the ID3 tag which the other modules I looked at couldn't. You'll have to install using pip or download the tar and execute python setup.py install from the source folder.

Relevant examples from the website are below.

Reading the contents of an mp3 file containing either v1 or v2 tag info:

 import eyeD3
 tag = eyeD3.Tag()
 tag.link("/some/file.mp3")
 print tag.getArtist()
 print tag.getAlbum()
 print tag.getTitle()

Read an mp3 file (track length, bitrate, etc.) and access it's tag:

if eyeD3.isMp3File(f):
     audioFile = eyeD3.Mp3AudioFile(f)
     tag = audioFile.getTag()

Specific tag versions can be selected:

 tag.link("/some/file.mp3", eyeD3.ID3_V2)
 tag.link("/some/file.mp3", eyeD3.ID3_V1)
 tag.link("/some/file.mp3", eyeD3.ID3_ANY_VERSION)  # The default.

Or you can iterate over the raw frames:

 tag = eyeD3.Tag()
 tag.link("/some/file.mp3")
 for frame in tag.frames:
    print frame

Once a tag is linked to a file it can be modified and saved:

 tag.setArtist(u"Cro-Mags")
 tag.setAlbum(u"Age of Quarrel")
 tag.update()

If the tag linked in was v2 and you'd like to save it as v1:

 tag.update(eyeD3.ID3_V1_1)

Read in a tag and remove it from the file:

 tag.link("/some/file.mp3")
 tag.remove()
 tag.update()

Add a new tag:

 tag = eyeD3.Tag()
 tag.link('/some/file.mp3')    # no tag in this file, link returned False
 tag.header.setVersion(eyeD3.ID3_V2_3)
 tag.setArtist('Fugazi')
 tag.update()

How to create loading dialogs in Android?

Today things have changed a little.

Now we avoid use ProgressDialog to show spinning progress:

enter image description here

If you want to put in your app a spinning progress you should use an Activity indicators:

http://developer.android.com/design/building-blocks/progress.html#activity

Extract number from string with Oracle function

You'd use REGEXP_REPLACE in order to remove all non-digit characters from a string:

select regexp_replace(column_name, '[^0-9]', '')
from mytable;

or

select regexp_replace(column_name, '[^[:digit:]]', '')
from mytable;

Of course you can write a function extract_number. It seems a bit like overkill though, to write a funtion that consists of only one function call itself.

create function extract_number(in_number varchar2) return varchar2 is
begin
  return regexp_replace(in_number, '[^[:digit:]]', '');
end; 

How to get the file path from URI?

File myFile = new File(uri.toString());
myFile.getAbsolutePath()

should return u the correct path

EDIT

As @Tron suggested the working code is

File myFile = new File(uri.getPath());
myFile.getAbsolutePath()

Loop through an array php

Starting simple, with no HTML:

foreach($database as $file) {
    echo $file['filename'] . ' at ' . $file['filepath'];
}

And you can otherwise manipulate the fields in the foreach.

How to add jQuery in JS file

it is not possible to import js file inside another js file

The way to use jquery inside js is

import the js in the html or whatever view page you are using inside which you are going to include the js file

view.html

 <script src="<%=request.getContextPath()%>/js/jquery-1.11.3.js"></script>
 <script src="<%=request.getContextPath()%>/js/default.js"></script>

default.js

$('document').ready(function() {
    $('li#user').click(function() {
         $(this).addClass('selectedEmp');
    });
});

this will definitely work for you

Spring REST Service: how to configure to remove null objects in json response

@JsonSerialize(include=JsonSerialize.Inclusion.NON_EMPTY)
public class Shop {
    //...
}

for jackson 2.0 or later use @JsonInclude(Include.NON_NULL)

This will remove both empty and null Objects.

Type definition in object literal in TypeScript

You're pretty close, you just need to replace the = with a :. You can use an object type literal (see spec section 3.5.3) or an interface. Using an object type literal is close to what you have:

var obj: { property: string; } = { property: "foo" };

But you can also use an interface

interface MyObjLayout {
    property: string;
}

var obj: MyObjLayout = { property: "foo" };

Tooltip on image

You can use the following format to generate a tooltip for an image.

<div class="tooltip"><img src="joe.jpg" />
  <span class="tooltiptext">Tooltip text</span>
</div>

Submit button not working in Bootstrap form

Your problem is this

<button type="button" value=" Send" class="btn btn-success" type="submit" id="submit" />

You've set the type twice. Your browser is only accepting the first, which is "button".

<button type="submit" value=" Send" class="btn btn-success" id="submit" />

jQuery: selecting each td in a tr

You can simply do the following inside your TR loop:

$(this).find('td').each (function() {
  // do your cool stuff
});                          

How to tell if a JavaScript function is defined

One-line solution:

function something_cool(text, callback){
    callback && callback();
}

How can I exit from a javascript function?

You should use return as in:

function refreshGrid(entity) {
  var store = window.localStorage;
  var partitionKey;
  if (exit) {
    return;
  }

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

No, it is not a bad practice. It is the most easiest and efficient way.

ERROR Android emulator gets killed

It's happened to me before. It should solved now by upgrading to Android Studio 4.1.1

Please ensure you all these ticked on SDK tools

  • Google Play Intel x86 Atom System Image
  • Android Emulator
  • Android SDK Platform-Tools & Build-Tools

Restart the Android Studio. it seems work

Default parameters with C++ constructors

This discussion apply both to constructors, but also methods and functions.

Using default parameters?

The good thing is that you won't need to overload constructors/methods/functions for each case:

// Header
void doSomething(int i = 25) ;

// Source
void doSomething(int i)
{
   // Do something with i
}

The bad thing is that you must declare your default in the header, so you have an hidden dependancy: Like when you change the code of an inlined function, if you change the default value in your header, you'll need to recompile all sources using this header to be sure they will use the new default.

If you don't, the sources will still use the old default value.

using overloaded constructors/methods/functions?

The good thing is that if your functions are not inlined, you then control the default value in the source by choosing how one function will behave. For example:

// Header
void doSomething() ;
void doSomething(int i) ;

// Source

void doSomething()
{
   doSomething(25) ;
}

void doSomething(int i)
{
   // Do something with i
}

The problem is that you have to maintain multiple constructors/methods/functions, and their forwardings.

Insert image after each list item

I think your problem is that the :after psuedo-element requires the content: property set inside it. You need to tell it to insert something. You could even just have it insert the image directly:

ul li:after {
    content: url('../images/small_triangle.png');
}

How do I POST JSON data with cURL?

You can pass the extension of the format you want as the end of the url. like http://localhost:8080/xx/xxx/xxxx.json

or

http://localhost:8080/xx/xxx/xxxx.xml

Note: you need to add jackson and jaxb maven dependencies in your pom.

How do I set the default value for an optional argument in Javascript?

ES6 Update - ES6 (ES2015 specification) allows for default parameters

The following will work just fine in an ES6 (ES015) environment...

function(nodeBox, str="hai")
{
  // ...
}

How can I make grep print the lines below and above each matching line?

Use -A and -B switches (mean lines-after and lines-before):

grep -A 1 -B 1 FAILED file.txt

Instagram how to get my user id from username?

Currently there is no direct Instagram API to get user id from user name. You need to call the GET /users/search API and then iterate the results and check if the username field value is equal to your username or not, then you grab the id.

mysql query: SELECT DISTINCT column1, GROUP BY column2

Somehow your requirement sounds a bit contradictory ..

group by name (which is basically a distinct on name plus readiness to aggregate) and then a distinct on IP

What do you think should happen if two people (names) worked from the same IP within the time period specified?


Did you try this?

SELECT name, COUNT(name), time, price, ip, SUM(price) 
  FROM tablename 
 WHERE time >= $yesterday AND time <$today 
GROUP BY name,ip

How to Inspect Element using Safari Browser

in menu bar click on Edit->preference->advance at bottom click the check box true that is for Show develop menu in menu bar now a develop menu is display at menu bar where you can see all develop option and inspect.

"The remote certificate is invalid according to the validation procedure." using Gmail SMTP server

Your website folder needs network service security. Especially the web.config. It uses this account to access your registry for the certificates. This will stop the need to add a hack to your code.

Cannot execute script: Insufficient memory to continue the execution of the program

use the command-line tool SQLCMD which is much leaner on memory. It is as simple as:

SQLCMD -d <database-name> -i filename.sql

You need valid credentials to access your SQL Server instance or even to access a database

Taken from here.

How do I declare and use variables in PL/SQL like I do in T-SQL?

Revised Answer

If you're not calling this code from another program, an option is to skip PL/SQL and do it strictly in SQL using bind variables:

var myname varchar2(20);

exec :myname := 'Tom';

SELECT *
FROM   Customers
WHERE  Name = :myname;

In many tools (such as Toad and SQL Developer), omitting the var and exec statements will cause the program to prompt you for the value.


Original Answer

A big difference between T-SQL and PL/SQL is that Oracle doesn't let you implicitly return the result of a query. The result always has to be explicitly returned in some fashion. The simplest way is to use DBMS_OUTPUT (roughly equivalent to print) to output the variable:

DECLARE
   myname varchar2(20);
BEGIN
     myname := 'Tom';

     dbms_output.print_line(myname);
END;

This isn't terribly helpful if you're trying to return a result set, however. In that case, you'll either want to return a collection or a refcursor. However, using either of those solutions would require wrapping your code in a function or procedure and running the function/procedure from something that's capable of consuming the results. A function that worked in this way might look something like this:

CREATE FUNCTION my_function (myname in varchar2)
     my_refcursor out sys_refcursor
BEGIN
     open my_refcursor for
     SELECT *
     FROM   Customers
     WHERE  Name = myname;

     return my_refcursor;
END my_function;

Python Threading String Arguments

You're trying to create a tuple, but you're just parenthesizing a string :)

Add an extra ',':

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=(dRecieved,))  # <- note extra ','
processThread.start()

Or use brackets to make a list:

dRecieved = connFile.readline()
processThread = threading.Thread(target=processLine, args=[dRecieved])  # <- 1 element list
processThread.start()

If you notice, from the stack trace: self.__target(*self.__args, **self.__kwargs)

The *self.__args turns your string into a list of characters, passing them to the processLine function. If you pass it a one element list, it will pass that element as the first argument - in your case, the string.

Is there any use for unique_ptr with array?

There are tradeoffs, and you pick the solution which matches what you want. Off the top of my head:

Initial size

  • vector and unique_ptr<T[]> allow the size to be specified at run-time
  • array only allows the size to be specified at compile time

Resizing

  • array and unique_ptr<T[]> do not allow resizing
  • vector does

Storage

  • vector and unique_ptr<T[]> store the data outside the object (typically on the heap)
  • array stores the data directly in the object

Copying

  • array and vector allow copying
  • unique_ptr<T[]> does not allow copying

Swap/move

  • vector and unique_ptr<T[]> have O(1) time swap and move operations
  • array has O(n) time swap and move operations, where n is the number of elements in the array

Pointer/reference/iterator invalidation

  • array ensures pointers, references and iterators will never be invalidated while the object is live, even on swap()
  • unique_ptr<T[]> has no iterators; pointers and references are only invalidated by swap() while the object is live. (After swapping, pointers point into to the array that you swapped with, so they're still "valid" in that sense.)
  • vector may invalidate pointers, references and iterators on any reallocation (and provides some guarantees that reallocation can only happen on certain operations).

Compatibility with concepts and algorithms

  • array and vector are both Containers
  • unique_ptr<T[]> is not a Container

I do have to admit, this looks like an opportunity for some refactoring with policy-based design.

Python: URLError: <urlopen error [Errno 10060]

The error code 10060 means it cannot connect to the remote peer. It might be because of the network problem or mostly your setting issues, such as proxy setting.

You could try to connect the same host with other tools(such as ncat) and/or with another PC within your same local network to find out where the problem is occuring.

For proxy issue, there are some material here:

Using an HTTP PROXY - Python

Why can't I get Python's urlopen() method to work on Windows?

Hope it helps!

SQL How to correctly set a date variable value and use it?

If you manually write out the query with static date values (e.g. '2009-10-29 13:13:07.440') do you get any rows?

So, you are saying that the following two queries produce correct results:

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > '2009-10-29 13:13:07.440') AND (pa.AdvertiserID = 12345))

DECLARE @sp_Date DATETIME
SET @sp_Date = '2009-10-29 13:13:07.440'

SELECT DISTINCT pat.PublicationID
FROM PubAdvTransData AS pat 
    INNER JOIN PubAdvertiser AS pa 
        ON pat.AdvTransID = pa.AdvTransID
WHERE (pat.LastAdDate > @sp_Date) AND (pa.AdvertiserID = 12345))

Pretty printing JSON from Jackson 2.2's ObjectMapper

If you'd like to turn this on by default for ALL ObjectMapper instances in a process, here's a little hack that will set the default value of INDENT_OUTPUT to true:

val indentOutput = SerializationFeature.INDENT_OUTPUT
val defaultStateField = indentOutput.getClass.getDeclaredField("_defaultState")
defaultStateField.setAccessible(true)
defaultStateField.set(indentOutput, true)

How do I format date in jQuery datetimepicker?

Newer versions of datetimepicker (I'm using is use 2.3.7) use format:"Y/m/d" not dateFormat...

so

jQuery('#timePicker').datetimepicker({
    format: 'd-m-y',
    value: new Date()
});

See http://xdsoft.net/jqplugins/datetimepicker/

PHP multidimensional array search by value

Here is one liner for the same,

$pic_square = $userdb[array_search($uid,array_column($userdb, 'uid'))]['pic_square'];

Change line width of lines in matplotlib pyplot legend

@ImportanceOfBeingErnest 's answer is good if you only want to change the linewidth inside the legend box. But I think it is a bit more complex since you have to copy the handles before changing legend linewidth. Besides, it can not change the legend label fontsize. The following two methods can not only change the linewidth but also the legend label text font size in a more concise way.

Method 1

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the individual lines inside legend and set line width
for line in leg.get_lines():
    line.set_linewidth(4)
# get label texts inside legend and set font size
for text in leg.get_texts():
    text.set_fontsize('x-large')

plt.savefig('leg_example')
plt.show()

Method 2

import numpy as np
import matplotlib.pyplot as plt

# make some data
x = np.linspace(0, 2*np.pi)

y1 = np.sin(x)
y2 = np.cos(x)

# plot sin(x) and cos(x)
fig = plt.figure()
ax  = fig.add_subplot(111)
ax.plot(x, y1, c='b', label='y1')
ax.plot(x, y2, c='r', label='y2')

leg = plt.legend()
# get the lines and texts inside legend box
leg_lines = leg.get_lines()
leg_texts = leg.get_texts()
# bulk-set the properties of all lines and texts
plt.setp(leg_lines, linewidth=4)
plt.setp(leg_texts, fontsize='x-large')
plt.savefig('leg_example')
plt.show()

The above two methods produce the same output image:

output image

Python urllib2, basic HTTP authentication, and tr.im

This seems to work really well (taken from another thread)

import urllib2, base64

request = urllib2.Request("http://api.foursquare.com/v1/user")
base64string = base64.encodestring('%s:%s' % (username, password)).replace('\n', '')
request.add_header("Authorization", "Basic %s" % base64string)   
result = urllib2.urlopen(request)

What exactly is the 'react-scripts start' command?

create-react-app and react-scripts

react-scripts is a set of scripts from the create-react-app starter pack. create-react-app helps you kick off projects without configuring, so you do not have to setup your project by yourself.

react-scripts start sets up the development environment and starts a server, as well as hot module reloading. You can read here to see what everything it does for you.

with create-react-app you have following features out of the box.

  • React, JSX, ES6, and Flow syntax support.
  • Language extras beyond ES6 like the object spread operator.
  • Autoprefixed CSS, so you don’t need -webkit- or other prefixes.
  • A fast interactive unit test runner with built-in support for coverage reporting.
  • A live development server that warns about common mistakes.
  • A build script to bundle JS, CSS, and images for production, with hashes and sourcemaps.
  • An offline-first service worker and a web app manifest, meeting all the Progressive Web App criteria.
  • Hassle-free updates for the above tools with a single dependency.

npm scripts

npm start is a shortcut for npm run start.

npm run is used to run scripts that you define in the scripts object of your package.json

if there is no start key in the scripts object, it will default to node server.js

Sometimes you want to do more than the react scripts gives you, in this case you can do react-scripts eject. This will transform your project from a "managed" state into a not managed state, where you have full control over dependencies, build scripts and other configurations.

require_once :failed to open stream: no such file or directory

The error pretty much explains what the problem is: you are trying to include a file that is not there.

Try to use the full path to the file, using realpath(), and use dirname(__FILE__) to get your current directory:

require_once(realpath(dirname(__FILE__) . '/../includes/dbconn.inc'));

Sass and combined child selector

Without the combined child selector you would probably do something similar to this:

foo {
  bar {
    baz {
      color: red;
    }
  }
}

If you want to reproduce the same syntax with >, you could to this:

foo {
  > bar {
    > baz {
      color: red;
    }
  }
}

This compiles to this:

foo > bar > baz {
  color: red;
}

Or in sass:

foo
  > bar
    > baz
      color: red

GCD to perform task in main thread

No you don't need to check if you're in the main thread. Here is how you can do this in Swift:

runThisInMainThread { () -> Void in
    runThisInMainThread { () -> Void in
        // No problem
    }
}

func runThisInMainThread(block: dispatch_block_t) {
    dispatch_async(dispatch_get_main_queue(), block)
}

Its included as a standard function in my repo, check it out: https://github.com/goktugyil/EZSwiftExtensions

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

From the book VS 2015 succintly

Shared Projects allows sharing code, assets, and resources across multiple project types. More specifically, the following project types can reference and consume shared projects:

  • Console, Windows Forms, and Windows Presentation Foundation.
  • Windows Store 8.1 apps and Windows Phone 8.1 apps.
  • Windows Phone 8.0/8.1 Silverlight apps.
  • Portable Class Libraries.

Note:- Both shared projects and portable class libraries (PCL) allow sharing code, XAML resources, and assets, but of course there are some differences that might be summarized as follows.

  • A shared project does not produce a reusable assembly, so it can only be consumed from within the solution.
  • A shared project has support for platform-specific code, because it supports environment variables such as WINDOWS_PHONE_APP and WINDOWS_APP that you can use to detect which platform your code is running on.
  • Finally, shared projects cannot have dependencies on third-party libraries.
  • By comparison, a PCL produces a reusable .dll library and can have dependencies on third-party libraries, but it does not support platform environment variables

HTTP redirect: 301 (permanent) vs. 302 (temporary)

The main issue with 301 is browser will cache the redirection even if you disabled the redirection from the server level.

Its always better to use 302 if you are enabling the redirection for a short maintenance window.

How to define custom exception class in Java, the easiest way?

If you inherit from Exception, you have to provide a constructor that takes a String as a parameter (it will contain the error message).

Float a DIV on top of another DIV

Just add position, right and top to your class .close-image

.close-image {
    cursor: pointer;
    display: block;
    float: right;  
    z-index: 3;
    position: absolute; /*newly added*/
    right: 5px; /*newly added*/
    top: 5px;/*newly added*/
}

Python webbrowser.open() to open Chrome browser

Worked for me in windows

Put the path of your chrome application and do not forget to put th %s at the end. I am still trying to open the browser with html code without saving the file... I will add the code when I'll find how.

import webbrowser
chromedir= "C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s"
webbrowser.get(chromedir).open("http://pythonprogramming.altervista.org")

>>> link to: [a page from my blog where I explain this]<<<

How to use if - else structure in a batch file?

here is how I handled if else if situation

if %env%==dev ( 
    echo "dev env selected selected"
) else (
    if %env%==prod (
        echo "prod env selected"
    )
)

Note it is not the same as if-elseif block as the other programming languages like C++ or Java but it will do what you need to do

HTML Button Close Window

November 2019: onclick="self.close()" still works in Chrome while Edge gives a warning that must be confirmed before it will close.

On the other hand the solution onclick="window.open('', '_self', ''); window.close();" works in both.

Show Current Location and Update Location in MKMapView in Swift

In Swift 4, I had used the locationManager delegate function as defined above ..

func locationManager(manager: CLLocationManager!, 
    didUpdateLocations locations: [AnyObject]!) {

.. but this needed to be changed to ..

func locationManager(_ manager: CLLocationManager,
    didUpdateLocations locations: [CLLocation]) {

This came from .. https://github.com/lotfyahmed/MyLocation/blob/master/MyLocation/ViewController.swift - thanks!

git clone from another directory

Using the path itself didn't work for me.

Here's what finally worked for me on MacOS:

cd ~/projects
git clone file:///Users/me/projects/myawesomerepo myawesomerepocopy

This also worked:

git clone file://localhost/Users/me/projects/myawesomerepo myawesomerepocopy

The path itself worked if I did this:

git clone --local myawesomerepo myawesomerepocopy

Redirecting to a relative URL in JavaScript

https://developer.mozilla.org/en-US/docs/Web/API/Location/assign

  • window.location.assign("../"); // one level up
  • window.location.assign("/path"); // relative to domain

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

Instead of passing reference object passed the saved object, below is explanation which solve my issue:

//wrong
entityManager.persist(role);
user.setRole(role);
entityManager.persist(user)

//right
Role savedEntity= entityManager.persist(role);
user.setRole(savedEntity);
entityManager.persist(user)

What is Java Servlet?

Servlet is a java class to respond a HTTP request and produce a HTTP response...... when we make a page with the use of HTML then it would be a static page so to make it dynamic we use SERVLET {in simple words one can understand} To make use of servlet is overcomed by JSP it uses the code and HTML tag both in itself..

Difference between @Mock and @InjectMocks

@Mock is used to declare/mock the references of the dependent beans, while @InjectMocks is used to mock the bean for which test is being created.

For example:

public class A{

   public class B b;

   public void doSomething(){

   }

}

test for class A:

public class TestClassA{

   @Mocks
   public class B b;

   @InjectMocks
   public class A a;

   @Test
   public testDoSomething(){

   }

}

How to run a JAR file

You have to add a manifest to the jar, which tells the java runtime what the main class is. Create a file 'Manifest.mf' with the following content:

Manifest-Version: 1.0
Main-Class: your.programs.MainClass

Change 'your.programs.MainClass' to your actual main class. Now put the file into the Jar-file, in a subfolder named 'META-INF'. You can use any ZIP-utility for that.

Spark specify multiple column conditions for dataframe join

Try this:

val rccJoin=dfRccDeuda.as("dfdeuda")
.join(dfRccCliente.as("dfcliente")
,col("dfdeuda.etarcid")===col("dfcliente.etarcid") 
&& col("dfdeuda.etarcid")===col("dfcliente.etarcid"),"inner")

SQL Server : trigger how to read value for Insert, Update, Delete

Here is the syntax to create a trigger:

CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
    { { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
        [ WITH APPEND ]
        [ NOT FOR REPLICATION ]
        AS
        [ { IF UPDATE ( column )
            [ { AND | OR } UPDATE ( column ) ]
                [ ...n ]
        | IF ( COLUMNS_UPDATED ( ) { bitwise_operator } updated_bitmask )
                { comparison_operator } column_bitmask [ ...n ]
        } ]
        sql_statement [ ...n ]
    }
} 

If you want to use On Update you only can do it with the IF UPDATE ( column ) section. That's not possible to do what you are asking.

Can I make dynamic styles in React Native?

If you are using a screen with filters for example, and you want to set the background of the filter regarding if it was selected or not, you can do:

<TouchableOpacity style={this.props.venueFilters.includes('Bar')?styles.filterBtnActive:styles.filterBtn} onPress={()=>this.setFilter('Bar')}>
<Text numberOfLines={1}>
Bar
</Text>
</TouchableOpacity>

On which set filter is:

setVenueFilter(filter){
  var filters = this.props.venueFilters;
  filters.push(filter);
  console.log(filters.includes('Bar'), "Inclui Bar");
  this.setState(previousState => {
    return { updateFilter: !previousState.updateFilter };
  });
  this.props.setVenueFilter(filters);
}

PS: the function this.props.setVenueFilter(filters) is a redux action, and this.props.venueFilters is a redux state.

How do I specify different layouts for portrait and landscape orientations?

Create a layout-land directory and put the landscape version of your layout XML file in that directory.

How to start MySQL server on windows xp

The error complains about localhost rather than permissions and the current practice in MySQL is to have a bind-address specifying localhost only in a configuration file.

So I don't think it's a password problem - except that you say you 'unzipped' MySQL.

Is that enough installation? What did you download?

Was there any installation step which allowed you to define a root password?

And, as NawaMan said, is the server running?

When would you use the Builder Pattern?

Consider a restaurant. The creation of "today's meal" is a factory pattern, because you tell the kitchen "get me today's meal" and the kitchen (factory) decides what object to generate, based on hidden criteria.

The builder appears if you order a custom pizza. In this case, the waiter tells the chef (builder) "I need a pizza; add cheese, onions and bacon to it!" Thus, the builder exposes the attributes the generated object should have, but hides how to set them.

How to wait in a batch script?

You'd better ping 127.0.0.1. Windows ping pauses for one second between pings so you if you want to sleep for 10 seconds, use

ping -n 11 127.0.0.1 > nul

This way you don't need to worry about unexpected early returns (say, there's no default route and the 123.45.67.89 is instantly known to be unreachable.)

Reverse colormap in matplotlib

In matplotlib a color map isn't a list, but it contains the list of its colors as colormap.colors. And the module matplotlib.colors provides a function ListedColormap() to generate a color map from a list. So you can reverse any color map by doing

colormap_r = ListedColormap(colormap.colors[::-1])

Sending JWT token in the headers with Postman

Here is an image if it helps :)

Postman

Update:

The postman team added "Bearer token" to the "authorization tab": Updated postman

How get value from URL

You can also get a query string value as:

$uri =  $_SERVER["REQUEST_URI"]; //it will print full url
$uriArray = explode('/', $uri); //convert string into array with explode
$id = $uriArray[1]; //Print first array value

String Comparison in Java

Java lexicographically order:

  1. Numbers -before-
  2. Uppercase -before-
  3. Lowercase

Odd as this seems, it is true...
I have had to write comparator chains to be able to change the default behavior.
Play around with the following snippet with better examples of input strings to verify the order (you will need JSE 8):

import java.util.ArrayList;

public class HelloLambda {

public static void main(String[] args) {
    ArrayList<String> names = new ArrayList<>();
    names.add("Kambiz");
    names.add("kambiz");
    names.add("k1ambiz");
    names.add("1Bmbiza");
    names.add("Samantha");
    names.add("Jakey");
    names.add("Lesley");
    names.add("Hayley");
    names.add("Benjamin");
    names.add("Anthony");

    names.stream().
        filter(e -> e.contains("a")).
        sorted().
        forEach(System.out::println);
}
}

Result

1Bmbiza
Benjamin
Hayley
Jakey
Kambiz
Samantha
k1ambiz
kambiz

Please note this is answer is Locale specific.
Please note that I am filtering for a name containing the lowercase letter a.

link_to image tag. how to add class to a tag

hi you can try doing this

link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, {class: 'dock-item'}

or even

link_to image_tag("Search.png", border: 0), {action: 'search', controller: 'pages'}, class: 'dock-item'

note that the position of the curly braces is very important, because if you miss them out, rails will assume they form a single hash parameters (read more about this here)

and according to the api for link_to:

link_to(name, options = {}, html_options = nil)
  1. the first parameter is the string to be shown (or it can be an image_tag as well)
  2. the second is the parameter for the url of the link
  3. the last item is the optional parameter for declaring the html tag, e.g. class, onchange, etc.

hope it helps! =)

ssl_error_rx_record_too_long and Apache SSL

In my case, I had the wrong IP Address in the virtual host file. The listen was 443, and the stanza was <VirtualHost 192.168.0.1:443> but the server did not have the 192.168.0.1 address!

Regular expression to extract text between square brackets

Can brackets be nested?

If not: \[([^]]+)\] matches one item, including square brackets. Backreference \1 will contain the item to be match. If your regex flavor supports lookaround, use

(?<=\[)[^]]+(?=\])

This will only match the item inside brackets.

ImportError: No module named - Python

Make sure if root project directory is coming up in sys.path output. If not, please add path of root project directory to sys.path.

Better way to find index of item in ArrayList?

ArrayList has a indexOf() method. Check the API for more, but here's how it works:

private ArrayList<String> _categories; // Initialize all this stuff

private int getCategoryPos(String category) {
  return _categories.indexOf(category);
}

indexOf() will return exactly what your method returns, fast.

PHP validation/regex for URL

I don't think that using regular expressions is a smart thing to do in this case. It is impossible to match all of the possibilities and even if you did, there is still a chance that url simply doesn't exist.

Here is a very simple way to test if url actually exists and is readable :

if (preg_match("#^https?://.+#", $link) and @fopen($link,"r")) echo "OK";

(if there is no preg_match then this would also validate all filenames on your server)

how to read a long multiline string line by line in python

This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines() is the way to go. I will leave this answer nevertheless as reference.

Old (incorrect) answer:

s =  \
"""line1
line2
line3
"""

lines = s.split('\n')
print(lines)
for line in lines:
    print(line)

C++ delete vector, objects, free memory

There are two separate things here:

  1. object lifetime
  2. storage duration

For example:

{
    vector<MyObject> v;
    // do some stuff, push some objects onto v
    v.clear(); // 1
    // maybe do some more stuff
} // 2

At 1, you clear v: this destroys all the objects it was storing. Each gets its destructor called, if your wrote one, and anything owned by that MyObject is now released. However, vector v has the right to keep the raw storage around in case you want it later.

If you decide to push some more things into it between 1 and 2, this saves time as it can reuse the old memory.

At 2, the vector v goes out of scope: any objects you pushed into it since 1 will be destroyed (as if you'd explicitly called clear again), but now the underlying storage is also released (v won't be around to reuse it any more).


If I change the example so v becomes a pointer to a dynamically-allocated vector, you need to explicitly delete it, as the pointer going out of scope at 2 doesn't do that for you. It's better to use something like std::unique_ptr in that case, but if you don't and v is leaked, the storage it allocated will be leaked as well. As above, you need to make sure v is deleted, and calling clear isn't sufficient.

Number to String in a formula field

i wrote a simple function for this:

Function (stringVar param)
(
    Local stringVar oneChar := '0';
    Local numberVar strLen := Length(param);
    Local numberVar index := strLen;

    oneChar = param[strLen];

    while index > 0 and oneChar = '0' do
    (
        oneChar := param[index];
        index := index - 1;
    );

    Left(param , index + 1);
)

How to check if an element does NOT have a specific class?

Select element (or group of elements) having class "abc", not having class "xyz":

    $('.abc:not(".xyz")')

When selecting regular CSS you can use .abc:not(.xyz).

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

just unchecking Adjust Scroll View Insets didn't work for me.
Later, I tried to set tableview's header to nil, which fortunately worked.

self.tableView.tableHeaderView = nil

Failed to load resource: the server responded with a status of 404 (Not Found)

I was having this exact issue and this was because I was returning images from a server into component that is 1 step down the path. This what I mean. See file arrangement

*projectfolder/phpfiles/component.php*

Now my images folder was located here projectfolder/images/

Now I fixed it by adding ../ so that it could skip 1 step backwards

Goodluck

How does Facebook disable the browser's integrated Developer Tools?

I would go along the way of:

Object.defineProperty(window, 'console', {
  get: function() {

  },
  set: function() {

  }
});

No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization

Do not use authorization instead of authentication. I should get whole access to service all clients with header. The working code is :

public class TokenAuthenticationHandler : AuthenticationHandler<TokenAuthenticationOptions> 
{
    public IServiceProvider ServiceProvider { get; set; }

    public TokenAuthenticationHandler (IOptionsMonitor<TokenAuthenticationOptions> options, ILoggerFactory logger, UrlEncoder encoder, ISystemClock clock, IServiceProvider serviceProvider) 
        : base (options, logger, encoder, clock) 
    {
        ServiceProvider = serviceProvider;
    }

    protected override Task<AuthenticateResult> HandleAuthenticateAsync () 
    {
        var headers = Request.Headers;
        var token = "X-Auth-Token".GetHeaderOrCookieValue (Request);

        if (string.IsNullOrEmpty (token)) {
            return Task.FromResult (AuthenticateResult.Fail ("Token is null"));
        }           

        bool isValidToken = false; // check token here

        if (!isValidToken) {
            return Task.FromResult (AuthenticateResult.Fail ($"Balancer not authorize token : for token={token}"));
        }

        var claims = new [] { new Claim ("token", token) };
        var identity = new ClaimsIdentity (claims, nameof (TokenAuthenticationHandler));
        var ticket = new AuthenticationTicket (new ClaimsPrincipal (identity), this.Scheme.Name);
        return Task.FromResult (AuthenticateResult.Success (ticket));
    }
}

Startup.cs :

#region Authentication
services.AddAuthentication (o => {
    o.DefaultScheme = SchemesNamesConst.TokenAuthenticationDefaultScheme;
})
.AddScheme<TokenAuthenticationOptions, TokenAuthenticationHandler> (SchemesNamesConst.TokenAuthenticationDefaultScheme, o => { });
#endregion

And mycontroller.cs

[Authorize(AuthenticationSchemes = SchemesNamesConst.TokenAuthenticationDefaultScheme)]
public class MainController : BaseController
{ ... }

I can't find TokenAuthenticationOptions now, but it was empty. I found the same class PhoneNumberAuthenticationOptions :

public class PhoneNumberAuthenticationOptions : AuthenticationSchemeOptions
{
    public Regex PhoneMask { get; set; }// = new Regex("7\\d{10}");
}

You should define static class SchemesNamesConst. Something like:

public static class SchemesNamesConst
{
    public const string TokenAuthenticationDefaultScheme = "TokenAuthenticationScheme";
}

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

How to slice an array in Bash

There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.

version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}"    # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}"    # 7 1

Display special characters when using print statement

Use repr:

a = "Hello\tWorld\nHello World"
print(repr(a))
# 'Hello\tWorld\nHello World'

Note you do not get \s for a space. I hope that was a typo...?

But if you really do want \s for spaces, you could do this:

print(repr(a).replace(' ',r'\s'))

substring of an entire column in pandas dataframe

Use the str accessor with square brackets:

df['col'] = df['col'].str[:9]

Or str.slice:

df['col'] = df['col'].str.slice(0, 9)

jQuery AJAX form data serialize using PHP

I just had the same problem: You have to unserialize the data on the php side.

Add to the beginning of your php file (Attention this short version would replace all other post variables):

parse_str($_POST["data"], $_POST);

Oracle date format picture ends before converting entire input string

What you're trying to insert is not a date, I think, but a string. You need to use to_date() function, like this:

insert into table t1 (id, date_field) values (1, to_date('20.06.2013', 'dd.mm.yyyy'));

What does (function($) {})(jQuery); mean?

Just small addition to explanation

This structure (function() {})(); is called IIFE (Immediately Invoked Function Expression), it will be executed immediately, when the interpreter will reach this line. So when you're writing these rows:

(function($) {
  // do something
})(jQuery);

this means, that the interpreter will invoke the function immediately, and will pass jQuery as a parameter, which will be used inside the function as $.

Logical Operators, || or OR?

The difference between respectively || and OR and && and AND is operator precedence :

$bool = FALSE || TRUE;

  • interpreted as ($bool = (FALSE || TRUE))
  • value of $bool is TRUE

$bool = FALSE OR TRUE;

  • interpreted as (($bool = FALSE) OR TRUE)
  • value of $bool is FALSE

$bool = TRUE && FALSE;

  • interpreted as ($bool = (TRUE && FALSE))
  • value of $bool is FALSE

$bool = TRUE AND FALSE;

  • interpreted as (($bool = TRUE) AND FALSE)
  • value of $bool is TRUE

Twitter Bootstrap alert message close and open again

There's a very simple way to do this using JQuery

If you delete data-dismiss="alert" from the alert div, you can just hide the alert using the x button, by adding a click events and interacting with the display css attribute of the alert.

$(".close").click(function(){
   $(this).parent().css("display", "none");
});

Then, whenever you need it again, you can toggle the display attribute again.

Full Example:

<div class="alert alert-danger" role="alert" id="my_alert" style="display: none;">
   Uh Oh... Something went wrong
  <button type="button" class="close" aria-label="Close">
     <span aria-hidden="true">&times;</span>
  </button>
</div>

<script>
   $(".close").click(function(){
      $(this).parent().css("display", "none");
   });

   //Use whatever event you like
   $("#show_alert").click(function(){
      $("#my_alert).css("display", "inherit");
   });
<script>

Replace X-axis with own values

Not sure if it's what you mean, but you can do this:

plot(1:10, xaxt = "n", xlab='Some Letters')
axis(1, at=1:10, labels=letters[1:10])

which then gives you the graph:

enter image description here

angularjs: ng-src equivalent for background-image:url(...)

The above answer doesn't support observable interpolation (and cost me a lot of time trying to debug). The jsFiddle link in @BrandonTilley comment was the answer that worked for me, which I'll re-post here for preservation:

app.directive('backImg', function(){
    return function(scope, element, attrs){
        attrs.$observe('backImg', function(value) {
            element.css({
                'background-image': 'url(' + value +')',
                'background-size' : 'cover'
            });
        });
    };
});

Example using controller and template

Controller :

$scope.someID = ...;
/* 
The advantage of using directive will also work inside an ng-repeat :
someID can be inside an array of ID's 
*/

$scope.arrayOfIDs = [0,1,2,3];

Template :

Use in template like so :

<div back-img="img/service-sliders/{{someID}}/1.jpg"></div>

or like so :

<div ng-repeat="someID in arrayOfIDs" back-img="img/service-sliders/{{someID}}/1.jpg"></div>

XAMPP - Error: MySQL shutdown unexpectedly

This worked for me,

  1. quit the XAMPP
  2. cut the All files in C:\xampp\mysql\backup
  3. paste and replace files in C:\xampp\mysql\data
  4. run as administrator the XAMPP

How do I import a CSV file in R?

You would use the read.csv function; for example:

dat = read.csv("spam.csv", header = TRUE)

You can also reference this tutorial for more details.

Note: make sure the .csv file to read is in your working directory (using getwd()) or specify the right path to file. If you want, you can set the current directory using setwd.

Extract data from log file in specified range of time

well, I have spent some time on your date format.....

however, finally i worked it out..

let's take an example file (named logFile), i made it a bit short. say, you want to get last 5 mins' log in this file:

172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET 
### lines below are what you want (5 mins till the last record)
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET 

here is the solution:

# this variable you could customize, important is convert to seconds. 
# e.g 5days=$((5*24*3600))
x=$((5*60))   #here we take 5 mins as example

# this line get the timestamp in seconds of last line of your logfile
last=$(tail -n1 logFile|awk -F'[][]' '{ gsub(/\//," ",$2); sub(/:/," ",$2); "date +%s -d \""$2"\""|getline d; print d;}' )

#this awk will give you lines you needs:
awk -F'[][]' -v last=$last -v x=$x '{ gsub(/\//," ",$2); sub(/:/," ",$2); "date +%s -d \""$2"\""|getline d; if (last-d<=x)print $0 }' logFile      

output:

172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:27:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET 
172.16.0.3 - -  31 Mar 2002 19:30:41 +0200  "GET

EDIT

you may notice that in the output the [ and ] are disappeared. If you do want them back, you can change the last awk line print $0 -> print $1 "[" $2 "]" $3

How to add two strings as if they were numbers?

MDN docs for parseInt
MDN docs for parseFloat

In parseInt radix is specified as ten so that we are in base 10. In nonstrict javascript a number prepended with 0 is treated as octal. This would obviously cause problems!

parseInt(num1, 10) + parseInt(num2, 10) //base10
parseFloat(num1) + parseFloat(num2)

Also see ChaosPandion's answer for a useful shortcut using a unary operator. I have set up a fiddle to show the different behaviors.

http://jsfiddle.net/EtX6G/

var ten = '10';
var zero_ten = '010';
var one = '1';
var body = document.getElementsByTagName('body')[0];

Append(parseInt(ten) + parseInt(one));
Append(parseInt(zero_ten) + parseInt(one));
Append(+ten + +one);
Append(+zero_ten + +one);

function Append(text) {
    body.appendChild(document.createTextNode(text));
    body.appendChild(document.createElement('br'));
}

Returning JSON from a PHP Script

Whenever you are trying to return JSON response for API or else make sure you have proper headers and also make sure you return a valid JSON data.

Here is the sample script which helps you to return JSON response from PHP array or from JSON file.

PHP Script (Code):

<?php

// Set required headers
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');

/**
 * Example: First
 *
 * Get JSON data from JSON file and retun as JSON response
 */

// Get JSON data from JSON file
$json = file_get_contents('response.json');

// Output, response
echo $json;

/** =. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.=. =.  */

/**
 * Example: Second
 *
 * Build JSON data from PHP array and retun as JSON response
 */

// Or build JSON data from array (PHP)
$json_var = [
  'hashtag' => 'HealthMatters',
  'id' => '072b3d65-9168-49fd-a1c1-a4700fc017e0',
  'sentiment' => [
    'negative' => 44,
    'positive' => 56,
  ],
  'total' => '3400',
  'users' => [
    [
      'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
      'screen_name' => 'rayalrumbel',
      'text' => 'Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.',
      'timestamp' => '{{$timestamp}}',
    ],
    [
      'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
      'screen_name' => 'mikedingdong',
      'text' => 'Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.',
      'timestamp' => '{{$timestamp}}',
    ],
    [
      'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
      'screen_name' => 'ScottMili',
      'text' => 'Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.',
      'timestamp' => '{{$timestamp}}',
    ],
    [
      'profile_image_url' => 'http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg',
      'screen_name' => 'yogibawa',
      'text' => 'Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.',
      'timestamp' => '{{$timestamp}}',
    ],
  ],
];

// Output, response
echo json_encode($json_var);

JSON File (JSON DATA):

{
    "hashtag": "HealthMatters", 
    "id": "072b3d65-9168-49fd-a1c1-a4700fc017e0", 
    "sentiment": {
        "negative": 44, 
        "positive": 56
    }, 
    "total": "3400", 
    "users": [
        {
            "profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg", 
            "screen_name": "rayalrumbel", 
            "text": "Tweet (A), #HealthMatters because life is cool :) We love this life and want to spend more.", 
            "timestamp": "{{$timestamp}}"
        }, 
        {
            "profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg", 
            "screen_name": "mikedingdong", 
            "text": "Tweet (B), #HealthMatters because life is cool :) We love this life and want to spend more.", 
            "timestamp": "{{$timestamp}}"
        }, 
        {
            "profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg", 
            "screen_name": "ScottMili", 
            "text": "Tweet (C), #HealthMatters because life is cool :) We love this life and want to spend more.", 
            "timestamp": "{{$timestamp}}"
        }, 
        {
            "profile_image_url": "http://a2.twimg.com/profile_images/1285770264/PGP_normal.jpg", 
            "screen_name": "yogibawa", 
            "text": "Tweet (D), #HealthMatters because life is cool :) We love this life and want to spend more.", 
            "timestamp": "{{$timestamp}}"
        }
    ]
}

JSON Screeshot:

enter image description here

How to get the correct range to set the value to a cell?

Solution : SpreadsheetApp.getActiveSheet().getRange('F2').setValue('hello')

Explanation :

Setting value in a cell in spreadsheet to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in sheet which is open currently and to which script is attached

SpreadsheetApp.getActiveSpreadsheet().getActiveSheet().getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet name known)

SpreadsheetApp.openById(SHEET_ID).getSheetByName(SHEET_NAME).getRange(RANGE).setValue(VALUE);

Setting value in a cell in some spreadsheet to which script is NOT attached (Destination sheet position known)

SpreadsheetApp.openById(SHEET_ID).getSheets()[POSITION].getRange(RANGE).setValue(VALUE);

These are constants, you must define them yourself

SHEET_ID

SHEET_NAME

POSITION

VALUE

RANGE

By script attached to a sheet I mean that script is residing in the script editor of that sheet. Not attached means not residing in the script editor of that sheet. It can be in any other place.

Difference between DOM parentNode and parentElement

parentElement is new to Firefox 9 and to DOM4, but it has been present in all other major browsers for ages.

In most cases, it is the same as parentNode. The only difference comes when a node's parentNode is not an element. If so, parentElement is null.

As an example:

document.body.parentNode; // the <html> element
document.body.parentElement; // the <html> element

document.documentElement.parentNode; // the document node
document.documentElement.parentElement; // null

(document.documentElement.parentNode === document);  // true
(document.documentElement.parentElement === document);  // false

Since the <html> element (document.documentElement) doesn't have a parent that is an element, parentElement is null. (There are other, more unlikely, cases where parentElement could be null, but you'll probably never come across them.)

How can I insert data into a MySQL database?

This way worked for me when adding random data to MySql table using a python script.
First install the following packages using the below commands

pip install mysql-connector-python<br>
pip install random
import mysql.connector
import random

from datetime import date


start_dt = date.today().replace(day=1, month=1).toordinal()
end_dt = date.today().toordinal()

mydb = mysql.connector.connect(
    host="localhost",
    user="root",
    password="root",
    database="your_db_name"
)

mycursor = mydb.cursor()

sql_insertion = "INSERT INTO customer (name,email,address,dateJoined) VALUES (%s, %s,%s, %s)"
#insert 10 records(rows)
for x in range(1,11):
    #generate a random date
    random_day = date.fromordinal(random.randint(start_dt, end_dt))
    value = ("customer" + str(x),"customer_email" + str(x),"customer_address" + str(x),random_day)
    mycursor.execute(sql_insertion , value)

mydb.commit()

print("customer records inserted!")


Following is a sample output of the insertion

cid       |  name      |  email           |    address        |  dateJoined  |

1         | customer1  |  customer_email1 | customer_address1 |  2020-11-15  |
2         | customer2  |  customer_email2 | customer_address2 |  2020-10-11  |
3         | customer3  |  customer_email3 | customer_address3 |  2020-11-17  |
4         | customer4  |  customer_email4 | customer_address4 |  2020-09-20  |
5         | customer5  |  customer_email5 | customer_address5 |  2020-02-18  |
6         | customer6  |  customer_email6 | customer_address6 |  2020-01-11  |
7         | customer7  |  customer_email7 | customer_address7 |  2020-05-30  |
8         | customer8  |  customer_email8 | customer_address8 |  2020-04-22  |
9         | customer9  |  customer_email9 | customer_address9 |  2020-01-05  |
10        | customer10 |  customer_email10| customer_address10|  2020-11-12  |



How to change the JDK for a Jenkins job?

Here is my experience with Jenkins version 1.636: as long as I have only one "Install automatically" JDK configured in Jenkins JDK section, I don't see "JDK" dropdown in Job=>Configure section, but as soon as I added second JDK in Jenkins config, JDK dropdown appeared in Job=>Configure section with 3 options [(System), JDK1, JDK2]

Download files from server php

Here is the code that will not download courpt files

$filename = "myfile.jpg";
$file = "/uploads/images/".$filename;

header('Content-type: application/octet-stream');
header("Content-Type: ".mime_content_type($file));
header("Content-Disposition: attachment; filename=".$filename);
while (ob_get_level()) {
    ob_end_clean();
}
readfile($file);

I have included mime_content_type which will return content type of file .

To prevent from corrupt file download i have added ob_get_level() and ob_end_clean();

How to resolve : Can not find the tag library descriptor for "http://java.sun.com/jsp/jstl/core"

I tried "validating" de *.jsp and *.xml files in eclipse with the validate tool.

"right click on directory/file ->- validate" and it worked!

Using eclipse juno.

Hope it helps!

How to export and import environment variables in windows?

Combine @vincsilver and @jdigital's answers with some modifications,

  1. export .reg to current directory
  2. add date mark

code:

set TODAY=%DATE:~0,4%-%DATE:~5,2%-%DATE:~8,2%

regedit /e "%CD%\user_env_variables[%TODAY%].reg" "HKEY_CURRENT_USER\Environment"
regedit /e "%CD%\global_env_variables[%TODAY%].reg" "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"

Output would like:

global_env_variables[2017-02-14].reg
user_env_variables[2017-02-14].reg

Check if an apt-get package is installed and then install it if it's not on Linux

I had a similar requirement when running test locally instead of in docker. Basically I only wanted to install any .deb files found if they weren't already installed.

# If there are .deb files in the folder, then install them
if [ `ls -1 *.deb 2> /dev/null | wc -l` -gt 0 ]; then
  for file in *.deb; do
    # Only install if not already installed (non-zero exit code)
    dpkg -I ${file} | grep Package: | sed -r 's/ Package:\s+(.*)/\1/g' | xargs dpkg -s
    if [ $? != 0 ]; then
        dpkg -i ${file}
    fi;
  done;
else
  err "No .deb files found in '$PWD'"
fi

I guess they only problem I can see is that it doesn't check the version number of the package so if .deb file is a newer version, then this wouldn't overwrite the currently installed package.

Flask raises TemplateNotFound error even though template file exists

You need to put all you .html files in the template folder next to your python module. And if there are any images that you are using in your html files then you need put all your files in the folder named static

In the following Structure

project/
    hello.py
    static/
        image.jpg
        style.css
    templates/
        homepage.html
    virtual/
        filename.json

How to check for null/empty/whitespace values with a single test?

SELECT column_name from table_name
WHERE RTRIM(ISNULL(column_name, '')) LIKE ''

ISNULL(column_name, '') will return '' if column_name is NULL, otherwise it will return column_name.

UPDATE

In Oracle, you can use NVL to achieve the same results.

SELECT column_name from table_name
WHERE RTRIM(NVL(column_name, '')) LIKE ''

Write string to text file and ensure it always overwrites the existing content.

If your code doesn't require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn't exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

I'm assuming your using a streams here, there are other ways to write a file.

Convert integer into byte array (Java)

If you like Guava, you may use its Ints class:


For int ? byte[], use toByteArray():

byte[] byteArray = Ints.toByteArray(0xAABBCCDD);

Result is {0xAA, 0xBB, 0xCC, 0xDD}.


Its reverse is fromByteArray() or fromBytes():

int intValue = Ints.fromByteArray(new byte[]{(byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD});
int intValue = Ints.fromBytes((byte) 0xAA, (byte) 0xBB, (byte) 0xCC, (byte) 0xDD);

Result is 0xAABBCCDD.

ModalPopupExtender OK Button click event not firing?

It appears that a button that is used as the OK or CANCEL button for a ModalPopupExtender cannot have a click event. I tested this out by removing the

OkControlID="ModalOKButton"

from the ModalPopupExtender tag, and the button click fires. I'll need to figure out another way to send the data to the server.

HTML Tags in Javascript Alert() method

This is not possible.

Instead, you should create a fake window in Javascript, using something like jQuery UI Dialog.

Matplotlib-Animation "No MovieWriters Available"

I'm running Ubuntu 20 and I had a similar problem

Installed ffmpeg

pip install ffmpeg

then

sudo apt install ffmpeg

The name does not exist in the namespace error in XAML

When you are writing your wpf code and VS tell that "The name ABCDE does not exist in the namespace clr-namespace:ABC". But you can totally build your project successfully, there is only a small inconvenience because you can not see the UI designing (or just want to clean the code).

Try to do these:

  • In VS, right click on your Solution -> Properties -> Configuration Properties

  • A new dialog is opened, try to change the project configurations from Debug to Release or vice versa.

After that, re-build your solution. It can solve your problem.

How to add hyperlink in JLabel?

Update I've tidied up the SwingLink class further and added more features; an up-to-date copy of it can be found here: https://bitbucket.org/dimo414/jgrep/src/tip/src/grep/SwingLink.java


@McDowell's answer is great, but there's several things that could be improved upon. Notably text other than the hyperlink is clickable and it still looks like a button even though some of the styling has been changed/hidden. While accessibility is important, a coherent UI is as well.

So I put together a class extending JLabel based on McDowell's code. It's self-contained, handles errors properly, and feels more like a link:

public class SwingLink extends JLabel {
  private static final long serialVersionUID = 8273875024682878518L;
  private String text;
  private URI uri;

  public SwingLink(String text, URI uri){
    super();
    setup(text,uri);
  }

  public SwingLink(String text, String uri){
    super();
    setup(text,URI.create(uri));
  }

  public void setup(String t, URI u){
    text = t;
    uri = u;
    setText(text);
    setToolTipText(uri.toString());
    addMouseListener(new MouseAdapter() {
      public void mouseClicked(MouseEvent e) {
        open(uri);
      }
      public void mouseEntered(MouseEvent e) {
        setText(text,false);
      }
      public void mouseExited(MouseEvent e) {
        setText(text,true);
      }
    });
  }

  @Override
  public void setText(String text){
    setText(text,true);
  }

  public void setText(String text, boolean ul){
    String link = ul ? "<u>"+text+"</u>" : text;
    super.setText("<html><span style=\"color: #000099;\">"+
    link+"</span></html>");
    this.text = text;
  }

  public String getRawText(){
    return text;
  }

  private static void open(URI uri) {
    if (Desktop.isDesktopSupported()) {
      Desktop desktop = Desktop.getDesktop();
      try {
        desktop.browse(uri);
      } catch (IOException e) {
        JOptionPane.showMessageDialog(null,
            "Failed to launch the link, your computer is likely misconfigured.",
            "Cannot Launch Link",JOptionPane.WARNING_MESSAGE);
      }
    } else {
      JOptionPane.showMessageDialog(null,
          "Java is not able to launch links on your computer.",
          "Cannot Launch Link", JOptionPane.WARNING_MESSAGE);
    }
  }
}

You could also, for instance, change the link color to purple after being clicked, if that seemed useful. It's all self contained, you simply call:

SwingLink link = new SwingLink("Java", "http://java.sun.com");
mainPanel.add(link);

What is best tool to compare two SQL Server databases (schema and data)?

Try dbForge Data Compare for SQL Server. It can compare and sync any databases, even very large ones. Quick, easy, always delivers a correct result. Try it on your database and comment upon the product.

We can recommend you a reliable SQL comparison tool that offer 3 time’s faster comparison and synchronization of table data in your SQL Server databases. It's dbForge Data Compare for SQL Server and dbForge Schema Compare for SQL Server

Main advantages:

  • Speedier comparison and synchronization of large databases
  • Support of native SQL Server backups
  • Custom mapping of tables, columns, and schemas
  • Multiple options to tune your comparison and synchronization
  • Generating comparison and synchronization reports

Plus free 30-day trial and risk-free purchase with 30-day money back guarantee.

git undo all uncommitted or unsaved changes

Adding this answer because the previous answers permanently delete your changes

The Safe way

git stash -u

Explanation: Stash local changes including untracked changes (-u flag). The command saves your local modifications away and reverts the working directory to match the HEAD commit.

Want to recover the changes later?

git stash pop

Explanation: The command will reapply the changes to the top of the current working tree state.

Want to permanently remove the changes?

git stash drop

Explanation: The command will permanently remove the stashed entry

Link to git stash documentation

Can you disable tabs in Bootstrap?

None of the answers work for me. Remove data-toggle="tab" from the a prevents the tab from activating, but it also adds the #tabId hash to the URL. That is unacceptable to me. What is also unacceptable is using javascript.

What does work is added the disabled class to the li and removing the href attribute of its containing a.

Bootstrap 3 - jumbotron background image effect

After inspecting the sample website you provided, I found that the author might achieve the effect by using a library called Stellar.js, take a look at the library site, cheers!

When to use reinterpret_cast?

You could use reinterprete_cast to check inheritance at compile time.
Look here: Using reinterpret_cast to check inheritance at compile time

Django REST Framework: adding additional field to ModelSerializer

As Chemical Programer said in this comment, in latest DRF you can just do it like this:

class FooSerializer(serializers.ModelSerializer):
    extra_field = serializers.SerializerMethodField()

    def get_extra_field(self, foo_instance):
        return foo_instance.a + foo_instance.b

    class Meta:
        model = Foo
        fields = ('extra_field', ...)

DRF docs source

What are good message queue options for nodejs?

Take a look at node-busmq - it's a production grade, highly available and scalable message bus backed by redis.

I wrote this module for our global cloud and it's currently deployed in our production environment in several datacenters around the world. It supports named queues, peer-to-peer communication, guaranteed delivery and federation.

For more information on why we created this module you can read this blog post: All Aboard The Message Bus

How to fix error with xml2-config not found when installing PHP from sources?

All you need to do instal install package libxml2-dev for example:

sudo apt-get install libxml2-dev

On CentOS/RHEL:

sudo yum install libxml2-devel

Volatile Vs Atomic

There are two important concepts in multithreading environment:

  1. atomicity
  2. visibility

The volatile keyword eradicates visibility problems, but it does not deal with atomicity. volatile will prevent the compiler from reordering instructions which involve a write and a subsequent read of a volatile variable; e.g. k++. Here, k++ is not a single machine instruction, but three:

  1. copy the value to a register;
  2. increment the value;
  3. place it back.

So, even if you declare a variable as volatile, this will not make this operation atomic; this means another thread can see a intermediate result which is a stale or unwanted value for the other thread.

On the other hand, AtomicInteger, AtomicReference are based on the Compare and swap instruction. CAS has three operands: a memory location V on which to operate, the expected old value A, and the new value B. CAS atomically updates V to the new value B, but only if the value in V matches the expected old value A; otherwise, it does nothing. In either case, it returns the value currently in V. The compareAndSet() methods of AtomicInteger and AtomicReference take advantage of this functionality, if it is supported by the underlying processor; if it is not, then the JVM implements it via spin lock.

Retaining file permissions with Git

We can improve on the other answers by changing the format of the .permissions file to be executable chmod statements, and to make use of the -printf parameter to find. Here is the simpler .git/hooks/pre-commit file:

#!/usr/bin/env bash

echo -n "Backing-up file permissions... "

cd "$(git rev-parse --show-toplevel)"

find . -printf 'chmod %m "%p"\n' > .permissions

git add .permissions

echo done.

...and here is the simplified .git/hooks/post-checkout file:

#!/usr/bin/env bash

echo -n "Restoring file permissions... "

cd "$(git rev-parse --show-toplevel)"

. .permissions

echo "done."

Remember that other tools might have already configured these scripts, so you may need to merge them together. For example, here's a post-checkout script that also includes the git-lfs commands:

#!/usr/bin/env bash

echo -n "Restoring file permissions... "

cd "$(git rev-parse --show-toplevel)"

. .permissions

echo "done."

command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on you
r path. If you no longer wish to use Git LFS, remove this hook by deleting .git/hooks/post-checkout.\n"; exit 2; }
git lfs post-checkout "$@"

How can I make a Python script standalone executable to run without ANY dependency?

Using PyInstaller, I found a better method using shortcut to the .exe rather than making --onefile. Anyway, there are probably some data files around and if you're running a site-based app then your program depends on HTML, JavaScript, and CSS files too. There isn't any point in moving all these files somewhere... Instead what if we move the working path up?

Make a shortcut to the EXE file, move it at top and set the target and start-in paths as specified, to have relative paths going to dist\folder:

Target: %windir%\system32\cmd.exe /c start dist\web_wrapper\web_wrapper.exe
Start in: "%windir%\system32\cmd.exe /c start dist\web_wrapper\"

We can rename the shortcut to anything, so renaming to "GTFS-Manager". Now when I double-click the shortcut, it's as if I python-ran the file! I found this approach better than the --onefile one as:

  1. In onefile's case, there's a problem with a .dll missing for the Windows 7 OS which needs some prior installation, etc. Yawn. With the usual build with multiple files, no such issues.
  2. All the files that my Python script uses (it's deploying a tornado web server and needs a whole freakin' website worth of files to be there!) don't need to be moved anywhere: I simply create the shortcut at top.
  3. I can actually use this exact same folder on Ubuntu (run python3 myfile.py) and Windows (double-click the shortcut).
  4. I don't need to bother with the overly complicated hacking of .spec file to include data files, etc.

Oh, remember to delete off the build folder after building. It will save on size.

What does it mean to have an index to scalar variable error? python

IndexError: invalid index to scalar variable happens when you try to index a numpy scalar such as numpy.int64 or numpy.float64. It is very similar to TypeError: 'int' object has no attribute '__getitem__' when you try to index an int.

>>> a = np.int64(5)
>>> type(a)
<type 'numpy.int64'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: invalid index to scalar variable.
>>> a = 5
>>> type(a)
<type 'int'>
>>> a[3]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object has no attribute '__getitem__'

RESTful Authentication

Using a Public key infrastruction in which the registration of a key involves proper binding ensures that the public key is bound to the individual to which it is assigned in a way that ensures non-repudiation

See http://en.wikipedia.org/wiki/Public_key_infrastructure . If you follow the proper PKI standards, the person or agent who improperly uses the stolen key can be identified and locked out. If the agent is required to use a certificate, the binding gets pretty tight. A clever and quick-moving thief can escape, but they leave more crumbs.

Remove empty strings from a list of strings

>>> lstr = ['hello', '', ' ', 'world', ' ']
>>> lstr
['hello', '', ' ', 'world', ' ']

>>> ' '.join(lstr).split()
['hello', 'world']

>>> filter(None, lstr)
['hello', ' ', 'world', ' ']

Compare time

>>> from timeit import timeit
>>> timeit('" ".join(lstr).split()', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
4.226747989654541
>>> timeit('filter(None, lstr)', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
3.0278358459472656

Notice that filter(None, lstr) does not remove empty strings with a space ' ', it only prunes away '' while ' '.join(lstr).split() removes both.

To use filter() with white space strings removed, it takes a lot more time:

>>> timeit('filter(None, [l.replace(" ", "") for l in lstr])', "lstr=['hello', '', ' ', 'world', ' ']", number=10000000)
18.101892948150635

How to get the URL of the current page in C#

If you want to get

localhost:2806 

from

http://localhost:2806/Pages/ 

then use:

HttpContext.Current.Request.Url.Authority

OnChange event using React JS for drop down

React Hooks (16.8+):

const Dropdown = ({
  options
}) => {
  const [selectedOption, setSelectedOption] = useState(options[0].value);
  return (
      <select
        value={selectedOption}
        onChange={e => setSelectedOption(e.target.value)}>
        {options.map(o => (
          <option key={o.value} value={o.value}>{o.label}</option>
        ))}
      </select>
  );
};

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

I've had a very similar issue using spring-boot-starter-data-redis. To my implementation there was offered a @Bean for RedisTemplate as follows:

@Bean
public RedisTemplate<String, List<RoutePlantCache>> redisTemplate(RedisConnectionFactory connectionFactory) {
    final RedisTemplate<String, List<RoutePlantCache>> template = new RedisTemplate<>();
    template.setConnectionFactory(connectionFactory);
    template.setKeySerializer(new StringRedisSerializer());
    template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache.class));

    // Add some specific configuration here. Key serializers, etc.
    return template;
}

The fix was to specify an array of RoutePlantCache as following:

template.setValueSerializer(new Jackson2JsonRedisSerializer<>(RoutePlantCache[].class));

Below the exception I had:

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `[...].RoutePlantCache` out of START_ARRAY token
 at [Source: (byte[])"[{ ... },{ ... [truncated 1478 bytes]; line: 1, column: 1]
    at com.fasterxml.jackson.databind.exc.MismatchedInputException.from(MismatchedInputException.java:59) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.reportInputMismatch(DeserializationContext.java:1468) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1242) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.DeserializationContext.handleUnexpectedToken(DeserializationContext.java:1190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeFromArray(BeanDeserializer.java:604) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer._deserializeOther(BeanDeserializer.java:190) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:166) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4526) ~[jackson-databind-2.11.4.jar:2.11.4]
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:3572) ~[jackson-databind-2.11.4.jar:2.11.4]

Spring - applicationContext.xml cannot be opened because it does not exist

I solved it moving the file spring-context.xml in a src folder. ApplicationContext context = new ClassPathXmlApplicationContext("spring-context.xml");

Cannot start MongoDB as a service

Check if your mongod.cfg file has tabs in it. Removing tabs solved it for me!

EditorFor() and html properties

I don't know why it does not work for Html.EditorFor but I tried TextBoxFor and it worked for me.

@Html.TextBoxFor(m => m.Name, new { Class = "className", Size = "40"})

...and also validation works.

Getting min and max Dates from a pandas dataframe

min(df['some_property'])
max(df['some_property'])

The built-in functions work well with Pandas Dataframes.

MongoDB Data directory /data/db not found

MongoDB needs data directory to store data. Default path is /data/db

When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx permission to user.

If you want to change the path of your data directory then you should specify it while starting mongod server like,

mongod --dbpath /data/<path> --port <port no> 

This should help you start your mongod server with custom path and port.

Replace Div with another Div

This should help you

HTML

<!-- pretty much i just need to click a link within the regions table and it changes to the neccesary div. -->

<table>
<tr class="thumb"></tr>
    <td><a href="#" class="showall">All Regions</a> (shows main map) (link)</td>   

<tr class="thumb"></tr>
<td>Northern Region (link)</td>
</tr>

<tr class="thumb"></tr>
<td>Southern Region (link)</td>
</tr>

<tr class="thumb"></tr>
<td>Eastern Region (link)</td>
</tr>
</table>
<br />

<div id="mainmapplace">
    <div id="mainmap">
        All Regions image
    </div>
</div>
<div id="region">
    <div class="replace">northern image</div>
    <div class="replace">southern image</div>
    <div class="replace">Eastern image</div>
</div>

JavaScript

var originalmap;
var flag = false;

$(function (){

    $(".replace").click(function(){
            flag = true;
            originalmap = $('#mainmap');
            $('#mainmap').replaceWith($(this));
        });

    $('.showall').click(
        function(){
            if(flag == true){
                $('#region').append($('#mainmapplace .replace'));                
                $('#mainmapplace').children().remove();
                $('#mainmapplace').append($(originalmap));
                //$('#mapplace').append();
            }
        }
    )

})

CSS

#mainmapplace{
    width: 100px;
    height: 100px;
    background: red;
}

#region div{
    width: 100px;
    height: 100px;
    background: blue;
    margin: 10px 0 0 0;
}

Truncate all tables in a MySQL database in one command?

Here is a procedure that should truncate all tables in the local database.

Let me know if it doesn't work and I'll delete this answer.

Untested

CREATE PROCEDURE truncate_all_tables()
BEGIN

   -- Declare local variables
   DECLARE done BOOLEAN DEFAULT 0;
   DECLARE cmd VARCHAR(2000);

   -- Declare the cursor
   DECLARE cmds CURSOR
   FOR
   SELECT CONCAT('TRUNCATE TABLE ', TABLE_NAME) FROM INFORMATION_SCHEMA.TABLES;

   -- Declare continue handler
   DECLARE CONTINUE HANDLER FOR SQLSTATE '02000' SET done=1;

   -- Open the cursor
   OPEN cmds;

   -- Loop through all rows
   REPEAT

      -- Get order number
      FETCH cmds INTO cmd;

      -- Execute the command
      PREPARE stmt FROM cmd;
      EXECUTE stmt;
      DROP PREPARE stmt;

   -- End of loop
   UNTIL done END REPEAT;

   -- Close the cursor
   CLOSE cmds;

END;

How to print number with commas as thousands separators?

I'm using python 2.5 so I don't have access to the built-in formatting.

I looked at the Django code intcomma (intcomma_recurs in code below) and realized it's inefficient, because it's recursive and also compiling the regex on every run is not a good thing either. This is not necessary an 'issue' as django isn't really THAT focused on this kind of low-level performance. Also, I was expecting a factor of 10 difference in performance, but it's only 3 times slower.

Out of curiosity I implemented a few versions of intcomma to see what the performance advantages are when using regex. My test data concludes a slight advantage for this task, but surprisingly not much at all.

I also was pleased to see what I suspected: using the reverse xrange approach is unnecessary in the no-regex case, but it does make the code look slightly better at the cost of ~10% performance.

Also, I assume what you're passing in is a string and looks somewhat like a number. Results undetermined otherwise.

from __future__ import with_statement
from contextlib import contextmanager
import re,time

re_first_num = re.compile(r"\d")
def intcomma_noregex(value):
    end_offset, start_digit, period = len(value),re_first_num.search(value).start(),value.rfind('.')
    if period == -1:
        period=end_offset
    segments,_from_index,leftover = [],0,(period-start_digit) % 3
    for _index in xrange(start_digit+3 if not leftover else start_digit+leftover,period,3):
        segments.append(value[_from_index:_index])
        _from_index=_index
    if not segments:
        return value
    segments.append(value[_from_index:])
    return ','.join(segments)

def intcomma_noregex_reversed(value):
    end_offset, start_digit, period = len(value),re_first_num.search(value).start(),value.rfind('.')
    if period == -1:
        period=end_offset
    _from_index,segments = end_offset,[]
    for _index in xrange(period-3,start_digit,-3):
        segments.append(value[_index:_from_index])
        _from_index=_index
    if not segments:
        return value
    segments.append(value[:_from_index])
    return ','.join(reversed(segments))

re_3digits = re.compile(r'(?<=\d)\d{3}(?!\d)')
def intcomma(value):
    segments,last_endoffset=[],len(value)
    while last_endoffset > 3:
        digit_group = re_3digits.search(value,0,last_endoffset)
        if not digit_group:
            break
        segments.append(value[digit_group.start():last_endoffset])
        last_endoffset=digit_group.start()
    if not segments:
        return value
    if last_endoffset:
        segments.append(value[:last_endoffset])
    return ','.join(reversed(segments))

def intcomma_recurs(value):
    """
    Converts an integer to a string containing commas every three digits.
    For example, 3000 becomes '3,000' and 45000 becomes '45,000'.
    """
    new = re.sub("^(-?\d+)(\d{3})", '\g<1>,\g<2>', str(value))
    if value == new:
        return new
    else:
        return intcomma(new)

@contextmanager
def timed(save_time_func):
    begin=time.time()
    try:
        yield
    finally:
        save_time_func(time.time()-begin)

def testset_xsimple(func):
    func('5')

def testset_simple(func):
    func('567')

def testset_onecomma(func):
    func('567890')

def testset_complex(func):
    func('-1234567.024')

def testset_average(func):
    func('-1234567.024')
    func('567')
    func('5674')

if __name__ == '__main__':
    print 'Test results:'
    for test_data in ('5','567','1234','1234.56','-253892.045'):
        for func in (intcomma,intcomma_noregex,intcomma_noregex_reversed,intcomma_recurs):
            print func.__name__,test_data,func(test_data)
    times=[]
    def overhead(x):
        pass
    for test_run in xrange(1,4):
        for func in (intcomma,intcomma_noregex,intcomma_noregex_reversed,intcomma_recurs,overhead):
            for testset in (testset_xsimple,testset_simple,testset_onecomma,testset_complex,testset_average):
                for x in xrange(1000): # prime the test
                    testset(func)
                with timed(lambda x:times.append(((test_run,func,testset),x))):
                    for x in xrange(50000):
                        testset(func)
    for (test_run,func,testset),_delta in times:
        print test_run,func.__name__,testset.__name__,_delta

And here are the test results:

intcomma 5 5
intcomma_noregex 5 5
intcomma_noregex_reversed 5 5
intcomma_recurs 5 5
intcomma 567 567
intcomma_noregex 567 567
intcomma_noregex_reversed 567 567
intcomma_recurs 567 567
intcomma 1234 1,234
intcomma_noregex 1234 1,234
intcomma_noregex_reversed 1234 1,234
intcomma_recurs 1234 1,234
intcomma 1234.56 1,234.56
intcomma_noregex 1234.56 1,234.56
intcomma_noregex_reversed 1234.56 1,234.56
intcomma_recurs 1234.56 1,234.56
intcomma -253892.045 -253,892.045
intcomma_noregex -253892.045 -253,892.045
intcomma_noregex_reversed -253892.045 -253,892.045
intcomma_recurs -253892.045 -253,892.045
1 intcomma testset_xsimple 0.0410001277924
1 intcomma testset_simple 0.0369999408722
1 intcomma testset_onecomma 0.213000059128
1 intcomma testset_complex 0.296000003815
1 intcomma testset_average 0.503000020981
1 intcomma_noregex testset_xsimple 0.134000062943
1 intcomma_noregex testset_simple 0.134999990463
1 intcomma_noregex testset_onecomma 0.190999984741
1 intcomma_noregex testset_complex 0.209000110626
1 intcomma_noregex testset_average 0.513000011444
1 intcomma_noregex_reversed testset_xsimple 0.124000072479
1 intcomma_noregex_reversed testset_simple 0.12700009346
1 intcomma_noregex_reversed testset_onecomma 0.230000019073
1 intcomma_noregex_reversed testset_complex 0.236999988556
1 intcomma_noregex_reversed testset_average 0.56299996376
1 intcomma_recurs testset_xsimple 0.348000049591
1 intcomma_recurs testset_simple 0.34600019455
1 intcomma_recurs testset_onecomma 0.625
1 intcomma_recurs testset_complex 0.773999929428
1 intcomma_recurs testset_average 1.6890001297
1 overhead testset_xsimple 0.0179998874664
1 overhead testset_simple 0.0190000534058
1 overhead testset_onecomma 0.0190000534058
1 overhead testset_complex 0.0190000534058
1 overhead testset_average 0.0309998989105
2 intcomma testset_xsimple 0.0360000133514
2 intcomma testset_simple 0.0369999408722
2 intcomma testset_onecomma 0.207999944687
2 intcomma testset_complex 0.302000045776
2 intcomma testset_average 0.523000001907
2 intcomma_noregex testset_xsimple 0.139999866486
2 intcomma_noregex testset_simple 0.141000032425
2 intcomma_noregex testset_onecomma 0.203999996185
2 intcomma_noregex testset_complex 0.200999975204
2 intcomma_noregex testset_average 0.523000001907
2 intcomma_noregex_reversed testset_xsimple 0.130000114441
2 intcomma_noregex_reversed testset_simple 0.129999876022
2 intcomma_noregex_reversed testset_onecomma 0.236000061035
2 intcomma_noregex_reversed testset_complex 0.241999864578
2 intcomma_noregex_reversed testset_average 0.582999944687
2 intcomma_recurs testset_xsimple 0.351000070572
2 intcomma_recurs testset_simple 0.352999925613
2 intcomma_recurs testset_onecomma 0.648999929428
2 intcomma_recurs testset_complex 0.808000087738
2 intcomma_recurs testset_average 1.81900000572
2 overhead testset_xsimple 0.0189998149872
2 overhead testset_simple 0.0189998149872
2 overhead testset_onecomma 0.0190000534058
2 overhead testset_complex 0.0179998874664
2 overhead testset_average 0.0299999713898
3 intcomma testset_xsimple 0.0360000133514
3 intcomma testset_simple 0.0360000133514
3 intcomma testset_onecomma 0.210000038147
3 intcomma testset_complex 0.305999994278
3 intcomma testset_average 0.493000030518
3 intcomma_noregex testset_xsimple 0.131999969482
3 intcomma_noregex testset_simple 0.136000156403
3 intcomma_noregex testset_onecomma 0.192999839783
3 intcomma_noregex testset_complex 0.202000141144
3 intcomma_noregex testset_average 0.509999990463
3 intcomma_noregex_reversed testset_xsimple 0.125999927521
3 intcomma_noregex_reversed testset_simple 0.126999855042
3 intcomma_noregex_reversed testset_onecomma 0.235999822617
3 intcomma_noregex_reversed testset_complex 0.243000030518
3 intcomma_noregex_reversed testset_average 0.56200003624
3 intcomma_recurs testset_xsimple 0.337000131607
3 intcomma_recurs testset_simple 0.342000007629
3 intcomma_recurs testset_onecomma 0.609999895096
3 intcomma_recurs testset_complex 0.75
3 intcomma_recurs testset_average 1.68300008774
3 overhead testset_xsimple 0.0189998149872
3 overhead testset_simple 0.018000125885
3 overhead testset_onecomma 0.018000125885
3 overhead testset_complex 0.0179998874664
3 overhead testset_average 0.0299999713898

How to check whether a variable is a class or not?

The inspect.isclass is probably the best solution, and it's really easy to see how it's actually implemented

def isclass(object):
    """Return true if the object is a class.

    Class objects provide these attributes:
        __doc__         documentation string
        __module__      name of module in which this class was defined"""
    return isinstance(object, (type, types.ClassType))

How to write UTF-8 in a CSV file

For me the UnicodeWriter class from Python 2 CSV module documentation didn't really work as it breaks the csv.writer.write_row() interface.

For example:

csv_writer = csv.writer(csv_file)
row = ['The meaning', 42]
csv_writer.writerow(row)

works, while:

csv_writer = UnicodeWriter(csv_file)
row = ['The meaning', 42]
csv_writer.writerow(row)

will throw AttributeError: 'int' object has no attribute 'encode'.

As UnicodeWriter obviously expects all column values to be strings, we can convert the values ourselves and just use the default CSV module:

def to_utf8(lst):
    return [unicode(elem).encode('utf-8') for elem in lst]

...
csv_writer.writerow(to_utf8(row))

Or we can even monkey-patch csv_writer to add a write_utf8_row function - the exercise is left to the reader.

don't fail jenkins build if execute shell fails

To stop further execution when command fails:

command || exit 0

To continue execution when command fails:

command || true

Copy table from one database to another

If migrating constantly between two databases, then insert into an already existing table structure is a possibility. If so, then:

Use the following syntax:

insert into DESTINATION_DB.dbo.destination_table
select *
  from SOURCE_DB.dbo.source_table
[where x ...]

If migrating a LOT of tables (or tables with foreign keys constraints) I'd recommend:

  • Generating Scripts with the Advanced option / Types of data to script : Data only OR
  • Resort using a third party tool.

Hope it helps!

JavaScript isset() equivalent

function isset(variable) {
    try {
        return typeof eval(variable) !== 'undefined';
    } catch (err) {
        return false;
    }
}

Freeing up a TCP/IP port?

In terminal type :

netstat -anp|grep "port_number"

It will show the port details. Go to last column. It will be in this format . For example :- PID/java

then execute :

kill -9 PID. Worked on Centos5

For MAC:

lsof -n -i :'port-number' | grep LISTEN

Sample Response :

java   4744 (PID)  test  364u  IP0 asdasdasda   0t0  TCP *:port-number (LISTEN)

and then execute :

kill -9 PID 

Worked on Macbook

Create a OpenSSL certificate on Windows

To create a self signed certificate on Windows 7 with IIS 6...

  1. Open IIS

  2. Select your server (top level item or your computer's name)

  3. Under the IIS section, open "Server Certificates"

  4. Click "Create Self-Signed Certificate"

  5. Name it "localhost" (or something like that that is not specific)

  6. Click "OK"

You can then bind that certificate to your website...

  1. Right click on your website and choose "Edit bindings..."

  2. Click "Add"

    • Type: https
    • IP address: "All Unassigned"
    • Port: 443
    • SSL certificate: "localhost"
  3. Click "OK"

  4. Click "Close"

Perl: function to trim string leading and trailing whitespace

Here's one approach using a regular expression:

$string =~ s/^\s+|\s+$//g ;     # remove both leading and trailing whitespace

Perl 6 will include a trim function:

$string .= trim;

Source: Wikipedia

Reordering arrays

Try this:

playlist = playlist.concat(playlist.splice(1, 1));

Modify request parameter with servlet filter

Write a simple class that subcalsses HttpServletRequestWrapper with a getParameter() method that returns the sanitized version of the input. Then pass an instance of your HttpServletRequestWrapper to Filter.doChain() instead of the request object directly.

Your project path contains non-ASCII characters android studio

I meet this problem and find there are some Chinese characters in my path. After change these characters into English , the problem solved.

ssh "permissions are too open" error

Windows 10 ssh into Ubuntu EC2 “permissions are too open” error on AWS

I had this issue trying to ssh into an Ubuntu EC2 instance using the .pem file from AWS.

In windows this worked when I put this key in a folder created under the .ssh folder

C:\Users\USERNAME\.ssh\private_key

To change permission settings in Windows 10 :

File Settings > Security > Advanced

Disable inheritance

Convert Inherited Permissions Into Explicit Permissions

Remove all the permission entries except for Administrators

Could then connect securely.

Python os.path.join on Windows

answering to your comment : "the others '//' 'c:', 'c:\\' did not work (C:\\ created two backslashes, C:\ didn't work at all)"

On windows using os.path.join('c:', 'sourcedir') will automatically add two backslashes \\ in front of sourcedir.

To resolve the path, as python works on windows also with forward slashes -> '/', simply add .replace('\\','/') with os.path.join as below:-

os.path.join('c:\\', 'sourcedir').replace('\\','/')

e.g: os.path.join('c:\\', 'temp').replace('\\','/')

output : 'C:/temp'

In Python, how do I use urllib to see if a website is 404 or 200?

The getcode() method (Added in python2.6) returns the HTTP status code that was sent with the response, or None if the URL is no HTTP URL.

>>> a=urllib.urlopen('http://www.google.com/asdfsf')
>>> a.getcode()
404
>>> a=urllib.urlopen('http://www.google.com/')
>>> a.getcode()
200

Can I have multiple Xcode versions installed?

Whatever advice path you go down, make a copy of your project folder, and rename the external most one to reflect what XCode version it is being opened in. Your choice on whether you want it to update syntax or not, but the main reason for all this bovver is your storyboard will be altered just by looking. It may be resolved by the time a new reader coming across this in the future, or

How to get image size (height & width) using JavaScript?

Let's combine everything we learned here into one simple function (imageDimensions()). It uses promises.

_x000D_
_x000D_
// helper to get dimensions of an image
const imageDimensions = file => 
    new Promise((resolve, reject) => {
        const img = new Image()

        // the following handler will fire after the successful loading of the image
        img.onload = () => {
            const { naturalWidth: width, naturalHeight: height } = img
            resolve({ width, height })
        }

        // and this handler will fire if there was an error with the image (like if it's not really an image or a corrupted one)
        img.onerror = () => {
            reject('There was some problem with the image.')
        }
    
        img.src = URL.createObjectURL(file)
})

// here's how to use the helper
const getInfo = async ({ target: { files } }) => {
    const [file] = files
 
    try {
        const dimensions = await imageDimensions(file)
        console.info(dimensions)
    } catch(error) {
        console.error(error)
    }
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/7.0.0-beta.3/babel.min.js"></script>

Select an image:
<input
  type="file"
  onchange="getInfo(event)"
/>
<br />
<small>It works offline.</small>
_x000D_
_x000D_
_x000D_

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

There are two scenarios when this exception could occur. One is mentioned by nandeesh. Other scenario is mentioned here: http://blackriver.to/2012/08/android-annoying-exception-unable-to-add-window-is-your-activity-running/

Make sure you handle both of them

jQuery ajax success error

You did not provide your validate.php code so I'm confused. You have to pass the data in JSON Format when when mail is success. You can use json_encode(); PHP function for that.

Add json_encdoe in validate.php in last

mail($to, $subject, $message, $headers); 
echo json_encode(array('success'=>'true'));

JS Code

success: function(data){ 
     if(data.success == true){ 
       alert('success'); 
    } 

Hope it works

how can I set visible back to true in jquery

I would be careful with setting the display of the element to block. Different elements have the standard display as different things. For example setting display to block for a table row in firefox causes the width of the cells to be incorrect.

Is the name of the element actually test1. I know that .NET can add extra things onto the start or end. The best way to find out if your selector is working properly is by doing this.

alert($('#text1').length);

You might just need to remove the visibility attribute

$('#text1').removeAttr('visibility');

ggplot2 plot without axes, legends, etc

Does this do what you want?

 p <- ggplot(myData, aes(foo, bar)) + geom_whateverGeomYouWant(more = options) +
 p + scale_x_continuous(expand=c(0,0)) + 
 scale_y_continuous(expand=c(0,0)) +
 opts(legend.position = "none")

How to do a case sensitive search in WHERE clause (I'm using SQL Server)?

By using collation or casting to binary, like this:

SELECT *
FROM Users
WHERE   
    Username = @Username COLLATE SQL_Latin1_General_CP1_CS_AS
    AND Password = @Password COLLATE SQL_Latin1_General_CP1_CS_AS
    AND Username = @Username 
    AND Password = @Password 

The duplication of username/password exists to give the engine the possibility of using indexes. The collation above is a Case Sensitive collation, change to the one you need if necessary.

The second, casting to binary, could be done like this:

SELECT *
FROM Users
WHERE   
    CAST(Username as varbinary(100)) = CAST(@Username as varbinary))
    AND CAST(Password as varbinary(100)) = CAST(@Password as varbinary(100))
    AND Username = @Username 
    AND Password = @Password 

UPDATE multiple tables in MySQL using LEFT JOIN

Table A 
+--------+-----------+
| A-num  | text      | 
|    1   |           |
|    2   |           |
|    3   |           |
|    4   |           |
|    5   |           |
+--------+-----------+

Table B
+------+------+--------------+
| B-num|  date        |  A-num | 
|  22  |  01.08.2003  |     2  |
|  23  |  02.08.2003  |     2  | 
|  24  |  03.08.2003  |     1  |
|  25  |  04.08.2003  |     4  |
|  26  |  05.03.2003  |     4  |

I will update field text in table A with

UPDATE `Table A`,`Table B`
SET `Table A`.`text`=concat_ws('',`Table A`.`text`,`Table B`.`B-num`," from                                           
",`Table B`.`date`,'/')
WHERE `Table A`.`A-num` = `Table B`.`A-num`

and come to this result:

Table A 
+--------+------------------------+
| A-num  | text                   | 
|    1   |  24 from 03 08 2003 /  |
|    2   |  22 from 01 08 2003 /  |       
|    3   |                        |
|    4   |  25 from 04 08 2003 /  |
|    5   |                        |
--------+-------------------------+

where only one field from Table B is accepted, but I will come to this result:

Table A 
+--------+--------------------------------------------+
| A-num  | text                                       | 
|    1   |  24 from 03 08 2003                        |
|    2   |  22 from 01 08 2003 / 23 from 02 08 2003 / |       
|    3   |                                            |
|    4   |  25 from 04 08 2003 / 26 from 05 03 2003 / |
|    5   |                                            |
+--------+--------------------------------------------+

Simple mediaplayer play mp3 from file path?

I use this class for Audio play. If your audio location is raw folder.

Call method for play:

new AudioPlayer().play(mContext, getResources().getIdentifier(alphabetItemList.get(mPosition)
                        .getDetail().get(0).getAudio(),"raw", getPackageName()));

AudioPlayer.java class:

public class AudioPlayer {

    private MediaPlayer mMediaPlayer;

    public void stop() {
        if (mMediaPlayer != null) {
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
    // mothod for raw folder (R.raw.fileName)
    public void play(Context context, int rid){
        stop();

        mMediaPlayer = MediaPlayer.create(context, rid);
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                stop();
            }
        });

        mMediaPlayer.start();
    }

    // mothod for other folder 
    public void play(Context context, String name) {
        stop();

        //mMediaPlayer = MediaPlayer.create(c, rid);
        mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
        mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                stop();
            }
        });

        mMediaPlayer.start();
    }

}

How can I insert new line/carriage returns into an element.textContent?

I found that inserting \\n works. I.e., you escape the escaped new line character

document.createElement("script") synchronously

This is way late but for future reference to anyone who'd like to do this, you can use the following:

function require(file,callback){
    var head=document.getElementsByTagName("head")[0];
    var script=document.createElement('script');
    script.src=file;
    script.type='text/javascript';
    //real browsers
    script.onload=callback;
    //Internet explorer
    script.onreadystatechange = function() {
        if (this.readyState == 'complete') {
            callback();
        }
    }
    head.appendChild(script);
}

I did a short blog post on it some time ago http://crlog.info/2011/10/06/dynamically-requireinclude-a-javascript-file-into-a-page-and-be-notified-when-its-loaded/

Java: How can I compile an entire directory structure of code ?

The already existing answers seem to only concern oneself with the *.java files themselves and not how to easily do it with library files that might be needed for the build.

A nice one-line situation which recursively gets all *.java files as well as includes *.jar files necessary for building is:

javac -cp ".:lib/*" -d bin $(find ./src/* | grep .java)

Here the bin file is the destination of class files, lib (and potentially the current working directory) contain the library files and all the java files in the src directory and beneath are compiled.

How to access a mobile's camera from a web app?

AppMobi HTML5 SDK once promised access to native device functionality - including the camera - from an HTML5-based app, but is no longer Google-owned. Instead, try the HTML5-based answers in this post.

Generating random numbers with normal distribution in Excel

The numbers generated by

=NORMINV(RAND(),10,7)

are uniformally distributed. If you want the numbers to be normally distributed, you will have to write a function I guess.

jQuery: Setting select list 'selected' based on text, failing strangely

I usually use:

$("#my-Select option[text='" + myText +"']").attr("selected","selected") ;

Amazon S3 upload file and get URL

To make the file public before uploading you can use the #withCannedAcl method of PutObjectRequest:

myAmazonS3Client.putObject(new PutObjectRequest('some-grails-bucket',  'somePath/someKey.jpg', new    File('/Users/ben/Desktop/photo.jpg')).withCannedAcl(CannedAccessControlList.PublicRead))

Can anyone explain what JSONP is, in layman terms?

Preface:

This answer is over six years old. While the concepts and application of JSONP haven't changed (i.e. the details of the answer are still valid), you should look to use CORS where possible (i.e. your server or API supports it, and the browser support is adequate), as JSONP has inherent security risks.


JSONP (JSON with Padding) is a method commonly used to bypass the cross-domain policies in web browsers. (You are not allowed to make AJAX requests to a web page perceived to be on a different server by the browser.)

JSON and JSONP behave differently on the client and the server. JSONP requests are not dispatched using the XMLHTTPRequest and the associated browser methods. Instead a <script> tag is created, whose source is set to the target URL. This script tag is then added to the DOM (normally inside the <head> element).

JSON Request:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    // success
  };
};

xhr.open("GET", "somewhere.php", true);
xhr.send();

JSONP Request:

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';

document.getElementsByTagName("head")[0].appendChild(tag);

The difference between a JSON response and a JSONP response is that the JSONP response object is passed as an argument to a callback function.

JSON:

{ "bar": "baz" }

JSONP:

foo( { "bar": "baz" } );

This is why you see JSONP requests containing the callback parameter, so that the server knows the name of the function to wrap the response.

This function must exist in the global scope at the time the <script> tag is evaluated by the browser (once the request has completed).


Another difference to be aware of between the handling of a JSON response and a JSONP response is that any parse errors in a JSON response could be caught by wrapping the attempt to evaluate the responseText in a try/catch statement. Because of the nature of a JSONP response, parse errors in the response will cause an uncatchable JavaScript parse error.

Both formats can implement timeout errors by setting a timeout before initiating the request and clearing the timeout in the response handler.


Using jQuery

The usefulness of using jQuery to make JSONP requests, is that jQuery does all of the work for you in the background.

By default jQuery requires you to include &callback=? in the URL of your AJAX request. jQuery will take the success function you specify, assign it a unique name, and publish it in the global scope. It will then replace the question mark ? in &callback=? with the name it has assigned.


Comparable JSON/JSONP Implementations

The following assumes a response object { "bar" : "baz" }

JSON:

var xhr = new XMLHttpRequest();

xhr.onreadystatechange = function () {
  if (xhr.readyState == 4 && xhr.status == 200) {
    document.getElementById("output").innerHTML = eval('(' + this.responseText + ')').bar;
  };
};

xhr.open("GET", "somewhere.php", true);
xhr.send();

JSONP:

function foo(response) {
  document.getElementById("output").innerHTML = response.bar;
};

var tag = document.createElement("script");
tag.src = 'somewhere_else.php?callback=foo';

document.getElementsByTagName("head")[0].appendChild(tag);

Can ordered list produce result that looks like 1.1, 1.2, 1.3 (instead of just 1, 2, 3, ...) with css?

this is proper code if you want to first child li resize of other css.

<style>
    li.title { 
        font-size: 20px; 

        counter-increment: ordem; 
        color:#0080B0;
    }
    .my_ol_class { 
        counter-reset: my_ol_class; 
        padding-left: 30px !important; 
    }
    .my_ol_class li { 
          display: block;
        position: relative;

    }
    .my_ol_class li:before { 
        counter-increment: my_ol_class; 
        content: counter(ordem) "." counter(my_ol_class) " "; 
        position: absolute;
        margin-right: 100%;
        right: 10px; /* space between number and text */
    }
    li.title ol li{
         font-size: 15px;
         color:#5E5E5E;
    }
</style>

in html file.

        <ol>
            <li class="title"> <p class="page-header list_title">Acceptance of Terms. </p>
                <ol class="my_ol_class">
                    <li> 
                        <p>
                            my text 1.
                        </p>
                    </li>
                    <li>
                        <p>
                            my text 2.
                        </p>
                    </li>
                </ol>
            </li>
        </ol>

URL encoding in Android

Find Arabic chars and replace them with its UTF-8 encoding. some thing like this:

for (int i = 0; i < urlAsString.length(); i++) {
    if (urlAsString.charAt(i) > 255) {
        urlAsString = urlAsString.substring(0, i) + URLEncoder.encode(urlAsString.charAt(i)+"", "UTF-8") + urlAsString.substring(i+1);
    }
}
encodedURL = urlAsString;

Return value from a VBScript function

To return a value from a VBScript function, assign the value to the name of the function, like this:

Function getNumber
    getNumber = "423"
End Function

Check if PHP-page is accessed from an iOS device

If you just want to detect mobile devices in generel, Cake has build in support using RequestHandler->isMobile() (http://book.cakephp.org/2.0/en/core-libraries/components/request-handling.html#RequestHandlerComponent::isMobile)

MySQL INNER JOIN Alias

You'll need to join twice:

SELECT home.*, away.*, g.network, g.date_start 
FROM game AS g
INNER JOIN team AS home
  ON home.importid = g.home
INNER JOIN team AS away
  ON away.importid = g.away
ORDER BY g.date_start DESC 
LIMIT 7

How do you change the launcher logo of an app in Android Studio?

Look in the application's AndroidManifest.xml file for the <application> tag.

This application tag has an android:icon attribute, which is usually @drawable/ic_launcher. The value here is the name of the launcher icon file. If the value is @drawable/ic_launcher, then the name of the icon is ic_launcher.png.

Find this icon in your resource folders (res/mipmap-mdpi, res/mipmap-hdpi, etc.) and replace it.

A note on mipmap resources: If your launcher icon is currently in drawable folders such as res/drawable-hdpi, you should move them to the mipmap equivalents (e.g. res/mipmap-hdpi). Android will better preserve the resolution of drawables in the mipmap folder for display in launcher applications.

Android Studio note: If you are using Android Studio you can let studio place the drawables in the correct place for you. Simply right click on your application module and click New -> Image Asset.

For the icon type select either "Launcher Icons (Legacy Only)" for flat PNG files or "Launcher Icons (Adaptive and Legacy)" if you also want to generate an adaptive icon for API 26+ devices.

How to find tags with only certain attributes - BeautifulSoup

You can use lambda functions in findAll as explained in documentation. So that in your case to search for td tag with only valign = "top" use following:

td_tag_list = soup.findAll(
                lambda tag:tag.name == "td" and
                len(tag.attrs) == 1 and
                tag["valign"] == "top")

How to get the full url in Express?

You need to construct it using req.headers.host + req.url. Of course if you are hosting in a different port and such you get the idea ;-)

python request with authentication (access_token)

The requests package has a very nice API for HTTP requests, adding a custom header works like this (source: official docs):

>>> import requests
>>> response = requests.get(
... 'https://website.com/id', headers={'Authorization': 'access_token myToken'})

If you don't want to use an external dependency, the same thing using urllib2 of the standard library looks like this (source: the missing manual):

>>> import urllib2
>>> response = urllib2.urlopen(
... urllib2.Request('https://website.com/id', headers={'Authorization': 'access_token myToken'})

Are there benefits of passing by pointer over passing by reference in C++?

Passing by pointer

  • Caller has to take the address -> not transparent
  • A 0 value can be provided to mean nothing. This can be used to provide optional arguments.

Pass by reference

  • Caller just passes the object -> transparent. Has to be used for operator overloading, since overloading for pointer types is not possible (pointers are builtin types). So you can't do string s = &str1 + &str2; using pointers.
  • No 0 values possible -> Called function doesn't have to check for them
  • Reference to const also accepts temporaries: void f(const T& t); ... f(T(a, b, c));, pointers cannot be used like that since you cannot take the address of a temporary.
  • Last but not least, references are easier to use -> less chance for bugs.

What are the file limits in Git (number and size)?

I found this trying to store a massive number of files(350k+) in a repo. Yes, store. Laughs.

$ time git add . 
git add . 333.67s user 244.26s system 14% cpu 1:06:48.63 total

The following extracts from the Bitbucket documentation are quite interesting.

When you work with a DVCS repository cloning, pushing, you are working with the entire repository and all of its history. In practice, once your repository gets larger than 500MB, you might start seeing issues.

... 94% of Bitbucket customers have repositories that are under 500MB. Both the Linux Kernel and Android are under 900MB.

The recommended solution on that page is to split your project into smaller chunks.

Switch statement fall-through...should it be allowed?

I'd love a different syntax for fallbacks in switches, something like, errr..

switch(myParam)
{
  case 0 or 1 or 2:
    // Do something;
    break;
  case 3 or 4:
    // Do something else;
    break;
}

Note: This would already be possible with enums, if you declare all cases on your enum using flags, right? It doesn't sound so bad either; the cases could (should?) very well be part of your enum already.

Maybe this would be a nice case (no pun intended) for a fluent interface using extension methods? Something like, errr...

int value = 10;
value.Switch()
  .Case(() => { /* Do something; */ }, new {0, 1, 2})
  .Case(() => { /* Do something else */ } new {3, 4})
  .Default(() => { /* Do the default case; */ });

Although that's probably even less readable :P

How to update each dependency in package.json to the latest version?

I recently had to update several projects that were using npm and package.json for their gruntfile.js magic. The following bash command (multiline command) worked well for me:

npm outdated --json --depth=0 | \
jq --ascii-output --monochrome-output '. | keys | .[]' | \
xargs npm install $1 --save-dev

The idea here: To pipe the npm outdated output as json, to jq
(jq is a json command line parser/query tool)
(notice the use of --depth argument for npm outdated)
jq will strip the output down to just the top level package name only.
finally xargs puts each LIBRARYNAME one at a time into a npm install LIBRARYNAME --save-dev command

The above is what worked for me on a machine runnning: node=v0.11.10 osx=10.9.2 npm=1.3.24

this required:
xargs http://en.wikipedia.org/wiki/Xargs (native to my machine I believe)
and
jq http://stedolan.github.io/jq/ (I installed it with brew install jq)

Note: I only save the updated libraries to package.json inside of the json key devDependancies by using --save-dev, that was a requirement of my projects, quite possible not yours.

Afterward I check that everything is gravy with a simple

npm outdated --depth=0

Also, you can check the current toplevel installed library versions with

npm list --depth=0

How do I mount a remote Linux folder in Windows through SSH?

Take a look at CIFS (http://www.samba.org/cifs/). It is a virtual file system you can run on your linux machine that will allow you to mount folders on your linux machine in windows using SMB.

CIFS on linux information can be found here: http://linux-cifs.samba.org/

Reading PDF documents in .Net

Have a look at Docotic.Pdf library. It does not require you to make source code of your application open (like iTextSharp with viral AGPL 3 license, for example).

Docotic.Pdf can be used to read PDF files and extract text with or without formatting. Please have a look at the article that shows how to extract text from PDFs.

Disclaimer: I work for Bit Miracle, vendor of the library.

sqlite database default time value 'now'

It's just a syntax error, you need parenthesis: (DATETIME('now'))

If you look at the documentation, you'll note the parenthesis that is added around the 'expr' option in the syntax.

How do I include the string header?

For using the string header first we must have include string header file as #include <string> and then we can include string header in the following ways in C++:

1)

string header = "--- Demonstrates Unformatted Input ---";

2)

string header("**** Counts words****\n"), prompt("Enter a text and terminate"
" with a period and return:"), line( 60, '-'), text;

jQuery if statement, syntax

You can wrap jQuery calls inside normal JavaScript code. So, for example:

$(document).ready(function() {
    if (someCondition && someOtherCondition) {
        // Make some jQuery call.
    }
});

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

If you make this user especial for a specific database, then maybe you do not set it as db_owner in "user mapping" of properties

How to set .net Framework 4.5 version in IIS 7 application pool

Go to "Run" and execute this:

%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir

NOTE: run as administrator.

jQuery select2 get value of select tag?

Simple answer is :

$('#first').select2().val()

and you can write by this way also:

 $('#first').val()

How to check if datetime happens to be Saturday or Sunday in SQL Server 2008

This will get you the name of the day:

SELECT DATENAME(weekday, GETDATE())

Cast Int to enum in Java

I cache the values and create a simple static access method:

public static enum EnumAttributeType {
    ENUM_1,
    ENUM_2;
    private static EnumAttributeType[] values = null;
    public static EnumAttributeType fromInt(int i) {
        if(EnumAttributeType.values == null) {
            EnumAttributeType.values = EnumAttributeType.values();
        }
        return EnumAttributeType.values[i];
    }
}

How to set DOM element as the first child?

var newItem = document.createElement("LI");       // Create a <li> node
var textnode = document.createTextNode("Water");  // Create a text node
newItem.appendChild(textnode);                    // Append the text to <li>

var list = document.getElementById("myList");    // Get the <ul> element to insert a new node
list.insertBefore(newItem, list.childNodes[0]);  // Insert <li> before the first child of <ul>

https://www.w3schools.com/jsref/met_node_insertbefore.asp

WSDL vs REST Pros and Cons

The previous answers contain a lot of information, but I think there is a philosophical difference that hasn't been pointed out. SOAP was the answer to "how to we create a modern, object-oriented, platform and protocol independent successor to RPC?". REST developed from the question, "how to we take the insights that made HTTP so successful for the web, and use them for distributed computing?"

SOAP is a about giving you tools to make distributed programming look like ... programming. REST tries to impose a style to simplify distributed interfaces, so that distributed resources can refer to each other like distributed html pages can refer to each other. One way it does that is attempt to (mostly) restrict operations to "CRUD" on resources (create, read, update, delete).

REST is still young -- although it is oriented towards "human readable" services, it doesn't rule out introspection services, etc. or automatic creation of proxies. However, these have not been standardized (as I write). SOAP gives you these things, but (IMHO) gives you "only" these things, whereas the style imposed by REST is already encouraging the spread of web services because of its simplicity. I would myself encourage newbie service providers to choose REST unless there are specific SOAP-provided features they need to use.

In my opinion, then, if you are implementing a "greenfield" API, and don't know that much about possible clients, I would choose REST as the style it encourages tends to help make interfaces comprehensible, and easy to develop to. If you know a lot about client and server, and there are specific SOAP tools that will make life easy for both, then I wouldn't be religious about REST, though.

How to use Collections.sort() in Java?

The answer given by NINCOMPOOP can be made simpler using Lambda Expressions:

Collections.sort(recipes, (Recipe r1, Recipe r2) ->
r1.getID().compareTo(r2.getID()));

Also introduced after Java 8 is the comparator construction methods in the Comparator interface. Using these, one can further reduce this to 1:

recipes.sort(comparingInt(Recipe::getId));

1 Bloch, J. Effective Java (3rd Edition). 2018. Item 42, p. 194.

Format a message using MessageFormat.format() in Java

For everyone that has Android problems in the string.xml, use \'\' instead of single quote.

Removing padding gutter from grid columns in Bootstrap 4

You can use this css code to get gutterless grid in bootstrap.

.no-gutter.row,
.no-gutter.container,
.no-gutter.container-fluid{
  margin-left: 0;
  margin-right: 0;
}

.no-gutter>[class^="col-"]{
  padding-left: 0;
  padding-right: 0;
}

JavaScript onclick redirect

Doing this fixed my issue

<script type="text/javascript">
    function SubmitFrm(){
        var Searchtxt = document.getElementById("txtSearch").value;
        window.location = "http://www.mysite.com/search/?Query=" + Searchtxt;
    }
</script>

I changed .value(); to .value; taking out the ()

I did not change anything in my text field or submit button

<input name="txtSearch" type="text" id="txtSearch" class="field" />            
<input type="submit" name="btnSearch" value="" id="btnSearch" class="btn" onclick="javascript:SubmitFrm()" />

Works like a charm.

Span inside anchor or anchor inside span or doesn't matter?

that depends on what you want to markup.

  • if you want a link inside a span, put <a> inside <span>.
  • if you want to markup something in a link, put <span> into <a>