Programs & Examples On #Freetext

FREETEXT is an SQL text-search predicate that uses stemming (e.g. -ing, -ly) and a thesaurus to search for the given string.

how to create and call scalar function in sql server 2008

Your Call works if it were a Table Valued Function. Since its a scalar function, you need to call it like:

SELECT dbo.fn_HomePageSlider(9, 3025) AS MyResult

Cannot use a CONTAINS or FREETEXT predicate on table or indexed view because it is not full-text indexed

There is one more solution to set column Full text to true.

These solution for example didn't work for me

ALTER TABLE news ADD FULLTEXT(headline, story);

My solution.

  1. Right click on table
  2. Design
  3. Right Click on column which you want to edit
  4. Full text index
  5. Add
  6. Close
  7. Refresh


  1. Right click on table
  2. Design
  3. Click on column which you want to edit
  4. On bottom of mssql you there will be tab "Column properties"
  5. Full-text Specification -> (Is Full-text Indexed) set to true.


Version of mssql 2014

Less aggressive compilation with CSS3 calc

There's a tidier way to include variables inside the escaped calc, as explained in this post: CSS3 calc() function doesn't work with Less #974

@variable: 2em;

body{ width: calc(~"100% - @{variable} * 2");}

By using the curly brackets you don't need to close and reopen the escaping quotes.

How do you debug React Native?

It really depends on what I am doing. If I am making UI changes or debugging UI, I typically turn on live and hot reloading and make changes then get instant feedback on it. If it's something more technical, I turn on JS debugging to look at the state of the app. However because reloading is so quick in react native, if the state is too messy, I just console log.

How do I request a file but not save it with Wget?

Use q flag for quiet mode, and tell wget to output to stdout with O- (uppercase o) and redirect to /dev/null to discard the output:

wget -qO- $url &> /dev/null

> redirects application output (to a file). if > is preceded by ampersand, shell redirects all outputs (error and normal) to the file right of >. If you don't specify ampersand, then only normal output is redirected.

./app &>  file # redirect error and standard output to file
./app >   file # redirect standard output to file
./app 2>  file # redirect error output to file

if file is /dev/null then all is discarded.

This works as well, and simpler:

wget -O/dev/null -q $url

Docker is in volume in use, but there aren't any Docker containers

Currently you can use what docker offers now for a general and more complete cleaning:

docker system prune

To additionally remove any stopped containers and all unused images (not just dangling images), add the -a flag to the command:

docker system prune -a

Saving and loading objects and using pickle

It seems you want to save your class instances across sessions, and using pickle is a decent way to do this. However, there's a package called klepto that abstracts the saving of objects to a dictionary interface, so you can choose to pickle objects and save them to a file (as shown below), or pickle the objects and save them to a database, or instead of use pickle use json, or many other options. The nice thing about klepto is that by abstracting to a common interface, it makes it easy so you don't have to remember the low-level details of how to save via pickling to a file, or otherwise.

Note that It works for dynamically added class attributes, which pickle cannot do...

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive 
>>> db = file_archive('fruits.txt')
>>> class Fruits: pass
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>> db['banana'] = banana 
>>> db.dump()

Then we restart…

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from klepto.archives import file_archive
>>> db = file_archive('fruits.txt')
>>> db.load()
>>> db['banana'].color

Klepto works on python2 and python3.

Get the code here:

MS-access reports - The search key was not found in any record - on save

Another potential cause for this error is Sandbox Mode, which prevents MS Access from running certain statements that are considered unsafe. This can be disabled by setting the following registry key...

HKLM\Software\Microsoft\Office\12.0\Access Connectivity Engine\Engines
    SandboxMode (DWORD Value) either 0 or 2:

   0    Sandbox mode is disabled at all times.
   1    Sandbox mode is used for Access, but not for non-Access programs.
   2    Sandbox mode is used for non-Access programs, but not for Access.
   3    Sandbox mode is used at all times. This is the default value.

How to enable scrolling of content inside a modal?

Actually for Bootstrap 3 you also need to override the .modal-open class on body.

    .navbar-fixed-bottom {
     margin-right: 15px; /*<-- to margin-right: 0px;*/

Cannot drop database because it is currently in use

just renaming the DB (to be delete) did the trick for me. it got off the hold of whatever process was accessing the database, and so I was able to drop the database.

Input type=password, don't let browser remember the password

Try using autocomplete="off". Not sure if every browser supports it, though. MSDN docs here.

EDIT: Note: most browsers have dropped support for this attribute. See Is autocomplete="off" compatible with all modern browsers?

This is arguably something that should be left up to the user rather than the web site designer.

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;

 gid | datepose | pvc | modifiedpvc 
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

What are FTL files

FTL stands for FreeMarker Template.

It is very useful when you want to follow the MVC (Model View Controller) pattern.

The idea behind using the MVC pattern for dynamic Web pages is that you separate the designers (HTML authors) from the programmers.

ASP.NET MVC 3 - redirect to another action

You will need to return the result of RedirectToAction.

Oracle query to identify columns having special characters

I figured out the answer to above problem. Below query will return rows which have even a signle occurrence of characters besides alphabets, numbers, square brackets, curly brackets,s pace and dot. Please note that position of closing bracket ']' in matching pattern is important.

Right ']' has the special meaning of ending a character set definition. It wouldn't make any sense to end the set before you specified any members, so the way to indicate a literal right ']' inside square brackets is to put it immediately after the left '[' that starts the set definition

SELECT * FROM test WHERE REGEXP_LIKE(sampletext,  '[^]^A-Z^a-z^0-9^[^.^{^}^ ]' );

How to query values from xml nodes?

Try this:

SELECT RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationReportReferenceIdentifier/node())[1]','varchar(50)') AS ReportIdentifierNumber,
       RawXML.value('(/GrobXmlFile//Grob//ReportHeader//OrganizationNumber/node())[1]','int') AS OrginazationNumber
FROM Batches

How to convert between bytes and strings in Python 3?

This is a Python 101 type question,

It's a simple question but one where the answer is not so simple.

In python3, a "bytes" object represents a sequence of bytes, a "string" object represents a sequence of unicode code points.

To convert between from "bytes" to "string" and from "string" back to "bytes" you use the bytes.decode and string.encode functions. These functions take two parameters, an encoding and an error handling policy.

Sadly there are an awful lot of cases where sequences of bytes are used to represent text, but it is not necessarily well-defined what encoding is being used. Take for example filenames on unix-like systems, as far as the kernel is concerned they are a sequence of bytes with a handful of special values, on most modern distros most filenames will be UTF-8 but there is no gaurantee that all filenames will be.

If you want to write robust software then you need to think carefully about those parameters. You need to think carefully about what encoding the bytes are supposed to be in and how you will handle the case where they turn out not to be a valid sequence of bytes for the encoding you thought they should be in. Python defaults to UTF-8 and erroring out on any byte sequence that is not valid UTF-8.


Python uses "repr" as a fallback conversion to string. repr attempts to produce python code that will recreate the object. In the case of a bytes object this means among other things escaping bytes outside the printable ascii range.

Sending POST data in Android

You can POST an HttpRequest using WebServer class and track the response in its listener interface.

WebServer server=new WebServer(getApplicationContext());

server.setOnServerStatusListner(new WebServer.OnServerStatusListner() {
    public void onServerResponded(String responce) {


    public void onServerRevoked() {


Now create a DataRack to bind your data

List<DataRack> racks=new ArrayList<DataRack>();
racks.add(new DataRack("name","Simon"));
racks.add(new DataRack("age","40"));
racks.add(new DataRack("location","Canada"));

Now simply send the POST request with that rack


You need to include my library for this. Documentations here

Pandas dataframe get first row of each group

>>> df.groupby('id').first()
1    first
2    first
3    first
4   second
5    first
6    first
7   fourth

If you need id as column:

>>> df.groupby('id').first().reset_index()
   id   value
0   1   first
1   2   first
2   3   first
3   4  second
4   5   first
5   6   first
6   7  fourth

To get n first records, you can use head():

>>> df.groupby('id').head(2).reset_index(drop=True)
    id   value
0    1   first
1    1  second
2    2   first
3    2  second
4    3   first
5    3   third
6    4  second
7    4   fifth
8    5   first
9    6   first
10   6  second
11   7  fourth
12   7   fifth

Simple UDP example to send and receive data from same socket

here is my soln to define the remote and local port and then write out to a file the received data, put this all in a class of your choice with the correct imports

    static UdpClient sendClient = new UdpClient();
    static int localPort = 49999;
    static int remotePort = 49000;
    static IPEndPoint localEP = new IPEndPoint(IPAddress.Any, localPort);
    static IPEndPoint remoteEP = new IPEndPoint(IPAddress.Parse(""), remotePort);
    static string logPath = System.AppDomain.CurrentDomain.BaseDirectory + "/recvd.txt";
    static System.IO.StreamWriter fw = new System.IO.StreamWriter(logPath, true);

    private static void initStuff()
        fw.AutoFlush = true;
        sendClient.ExclusiveAddressUse = false;
        sendClient.Client.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReuseAddress, true);
        sendClient.BeginReceive(DataReceived, sendClient);

    private static void DataReceived(IAsyncResult ar)
        UdpClient c = (UdpClient)ar.AsyncState;
        IPEndPoint receivedIpEndPoint = new IPEndPoint(IPAddress.Any, 0);
        Byte[] receivedBytes = c.EndReceive(ar, ref receivedIpEndPoint);
        fw.WriteLine(DateTime.Now.ToString("HH:mm:ss.ff tt") +  " (" + receivedBytes.Length + " bytes)");

        c.BeginReceive(DataReceived, ar.AsyncState);

    static void Main(string[] args)
        byte[] emptyByte = {};
        sendClient.Send(emptyByte, emptyByte.Length, remoteEP);

A cycle was detected in the build path of project xxx - Build Path Problem

Maven will fail the build if it detects a cycle, as the dependencies must be a tree.

You may find that you have additional declarations in the over those defined in the pom.xml. any extra declaration could introduce a cycle that wouldn't be apparent to Maven.

Why do I get a "permission denied" error while installing a gem?

Seems like a permissions issue. This is what worked for me

sudo chown -R $(whoami) /Library/Ruby/Gems/*

or in your case

sudo chown -R $(whoami) /usr/local/lib/ruby/gems/2.0.0/gems/

What does this do:

This is telling the system to change the files to change the ownership to the current user. Something must have gotten messed up when something got installed. Usually this is because there are multiple accounts or users are using sudo to install when they should not always have to.

Is this a good way to clone an object in ES6?

You can do it like this as well,

let copiedData = JSON.parse(JSON.stringify(data));

How to avoid HTTP error 429 (Too Many Requests) python

In many cases, continuing to scrape data from a website even when the server is requesting you not to is unethical. However, in the cases where it isn't, you can utilize a list of public proxies in order to scrape a website with many different IP addresses.

What causes java.lang.IncompatibleClassChangeError?

An additional cause of this issue, is if you have Instant Run enabled for Android Studio.

The fix

If you find you start getting this error, turn off Instant Run.

  1. Android Studio main settings
  2. Build, Execution, Deployment
  3. Instant Run
  4. Untick "Enable instant run..."


Instant Run modifies a large number of things during development, to make it quicker to provide updates to your running App. Hence instant run. When it works, it is really useful. However, when an issue such as this strikes, the best thing to do is to turn off Instant Run until the next version of Android Studio releases.

Key Shortcut for Eclipse Imports

For static import select the field and press Ctrl+Shift+M

How do I clone a specific Git branch?

git clone --single-branch --branch <branchname> <remote-repo>

The --single-branch option is valid from version 1.7.10 and later.

Please see also the other answer which many people prefer.

You may also want to make sure you understand the difference. And the difference is: by invoking git clone --branch <branchname> url you're fetching all the branches and checking out one. That may, for instance, mean that your repository has a 5kB documentation or wiki branch and 5GB data branch. And whenever you want to edit your frontpage, you may end up cloning 5GB of data.

Again, that is not to say git clone --branch is not the way to accomplish that, it's just that it's not always what you want to accomplish, when you're asking about cloning a specific branch.

Passing a string with spaces as a function argument in bash

You could have an extension of this problem in case of your initial text was set into a string type variable, for example:

function status(){    
  if [ $1 != "stopped" ]; then
     status_message="The current track is $track at $album by $artist";
     echo $status_message;
     read_status $1 "$status_message";

function read_status(){
  if [ $1 != "playing" ]; then
    echo $2

In this case if you don't pass the status_message variable forward as string (surrounded by "") it will be split in a mount of different arguments.

"$variable": The current track is CDE at DEF by ABC

$variable: The

Can an Android NFC phone act as an NFC tag?

If you mean getting a powered NFC device to pretend to be a passive one (eg a tag).. not sure how well it works but the android app NFCClassic purports to record tag contents and then allow the tag to be activated and appear to be the copied tag to NFC readers. Creates a library of recorded tags.

Parsing huge logfiles in Node.js - read in line-by-line

The Node.js Documentation offers a very elegant example using the Readline module.

Example: Read File Stream Line-by-Line

const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
    input: fs.createReadStream('sample.txt'),
    crlfDelay: Infinity

rl.on('line', (line) => {
    console.log(`Line from file: ${line}`);

Note: we use the crlfDelay option to recognize all instances of CR LF ('\r\n') as a single line break.

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

Instead of:

input:not(disabled)not:[type="submit"]:focus {}


input:not([disabled]):not([type="submit"]):focus {}

disabled is an attribute so it needs the brackets, and you seem to have mixed up/missing colons and parentheses on the :not() selector.


One thing to note: I may be wrong, but I don't think disabled inputs can normally receive focus, so that part may be redundant.

Alternatively, use :enabled

input:enabled:not([type="submit"]):focus { /* styles here */ }

Again, I can't think of a case where disabled input can receive focus, so it seems unnecessary.

Bootstrap 3 offset on right not left

Since Google seems to like this answer...

If you're looking to match Bootstrap 4's naming convention, i.e. offset-*-#, here's that modification:

.offset-right-12 {
  margin-right: 100%;
.offset-right-11 {
  margin-right: 91.66666667%;
.offset-right-10 {
  margin-right: 83.33333333%;
.offset-right-9 {
  margin-right: 75%;
.offset-right-8 {
  margin-right: 66.66666667%;
.offset-right-7 {
  margin-right: 58.33333333%;
.offset-right-6 {
  margin-right: 50%;
.offset-right-5 {
  margin-right: 41.66666667%;
.offset-right-4 {
  margin-right: 33.33333333%;
.offset-right-3 {
  margin-right: 25%;
.offset-right-2 {
  margin-right: 16.66666667%;
.offset-right-1 {
  margin-right: 8.33333333%;
.offset-right-0 {
  margin-right: 0;
@media (min-width: 576px) {
  .offset-sm-right-12 {
    margin-right: 100%;
  .offset-sm-right-11 {
    margin-right: 91.66666667%;
  .offset-sm-right-10 {
    margin-right: 83.33333333%;
  .offset-sm-right-9 {
    margin-right: 75%;
  .offset-sm-right-8 {
    margin-right: 66.66666667%;
  .offset-sm-right-7 {
    margin-right: 58.33333333%;
  .offset-sm-right-6 {
    margin-right: 50%;
  .offset-sm-right-5 {
    margin-right: 41.66666667%;
  .offset-sm-right-4 {
    margin-right: 33.33333333%;
  .offset-sm-right-3 {
    margin-right: 25%;
  .offset-sm-right-2 {
    margin-right: 16.66666667%;
  .offset-sm-right-1 {
    margin-right: 8.33333333%;
  .offset-sm-right-0 {
    margin-right: 0;
@media (min-width: 768px) {
  .offset-md-right-12 {
    margin-right: 100%;
  .offset-md-right-11 {
    margin-right: 91.66666667%;
  .offset-md-right-10 {
    margin-right: 83.33333333%;
  .offset-md-right-9 {
    margin-right: 75%;
  .offset-md-right-8 {
    margin-right: 66.66666667%;
  .offset-md-right-7 {
    margin-right: 58.33333333%;
  .offset-md-right-6 {
    margin-right: 50%;
  .offset-md-right-5 {
    margin-right: 41.66666667%;
  .offset-md-right-4 {
    margin-right: 33.33333333%;
  .offset-md-right-3 {
    margin-right: 25%;
  .offset-md-right-2 {
    margin-right: 16.66666667%;
  .offset-md-right-1 {
    margin-right: 8.33333333%;
  .offset-md-right-0 {
    margin-right: 0;
@media (min-width: 992px) {
  .offset-lg-right-12 {
    margin-right: 100%;
  .offset-lg-right-11 {
    margin-right: 91.66666667%;
  .offset-lg-right-10 {
    margin-right: 83.33333333%;
  .offset-lg-right-9 {
    margin-right: 75%;
  .offset-lg-right-8 {
    margin-right: 66.66666667%;
  .offset-lg-right-7 {
    margin-right: 58.33333333%;
  .offset-lg-right-6 {
    margin-right: 50%;
  .offset-lg-right-5 {
    margin-right: 41.66666667%;
  .offset-lg-right-4 {
    margin-right: 33.33333333%;
  .offset-lg-right-3 {
    margin-right: 25%;
  .offset-lg-right-2 {
    margin-right: 16.66666667%;
  .offset-lg-right-1 {
    margin-right: 8.33333333%;
  .offset-lg-right-0 {
    margin-right: 0;
@media (min-width: 1200px) {
  .offset-xl-right-12 {
    margin-right: 100%;
  .offset-xl-right-11 {
    margin-right: 91.66666667%;
  .offset-xl-right-10 {
    margin-right: 83.33333333%;
  .offset-xl-right-9 {
    margin-right: 75%;
  .offset-xl-right-8 {
    margin-right: 66.66666667%;
  .offset-xl-right-7 {
    margin-right: 58.33333333%;
  .offset-xl-right-6 {
    margin-right: 50%;
  .offset-xl-right-5 {
    margin-right: 41.66666667%;
  .offset-xl-right-4 {
    margin-right: 33.33333333%;
  .offset-xl-right-3 {
    margin-right: 25%;
  .offset-xl-right-2 {
    margin-right: 16.66666667%;
  .offset-xl-right-1 {
    margin-right: 8.33333333%;
  .offset-xl-right-0 {
    margin-right: 0;

Copy / Put text on the clipboard with FireFox, Safari and Chrome

Online Spreadsheets hook Ctrl+C, Ctrl+V events and transfer focus to a hidden TextArea control and either set its contents to desired new clipboard contents for copy or read its contents after the event had finished for paste.

see also Is it possible to read the clipboard in Firefox, Safari and Chrome using Javascript?

How to prevent ENTER keypress to submit a web form?

All the answers I found on this subject, here or in other posts has one drawback and that is it prevents the actual change trigger on the form element as well. So if you run these solutions onchange event is not triggered as well. To overcome this problem I modified these codes and developed the following code for myself. I hope this becomes useful for others. I gave a class to my form "prevent_auto_submit" and added the following JavaScript:

    $('form.prevent_auto_submit input,form.prevent_auto_submit select').keypress(function(event) 
        if (event.keyCode == 13)

Iteration over std::vector: unsigned vs signed index variable

Obscure but important detail: if you say "for(auto it)" as follows, you get a copy of the object, not the actual element:

struct Xs{int i} x;
x.i = 0;
vector <Xs> v;
for(auto it : v)
    it.i = 1;         // doesn't change the element v[0]

To modify the elements of the vector, you need to define the iterator as a reference:

for(auto &it : v)

Make one div visible and another invisible

You can use the display property of style. Intialy set the result section style as

style = "display:none"

Then the div will not be visible and there won't be any white space.

Once the search results are being populated change the display property using the java script like

document.getElementById("someObj").style.display = "block"

Using java script you can make the div invisible

document.getElementById("someObj").style.display = "none"

How to uninstall/upgrade Angular CLI?

I always use the following commands before upgrading to latest . If it is for Ubuntu prefix : 'sudo'

npm uninstall -g angular-cli
npm cache clean
npm install -g angular-cli@latest

ExecutorService that interrupts tasks after a timeout

After ton of time to survey,
Finally, I use invokeAll method of ExecutorService to solve this problem.
That will strictly interrupt the task while task running.
Here is example

ExecutorService executorService = Executors.newCachedThreadPool();

try {
    List<Callable<Object>> callables = new ArrayList<>();
    // Add your long time task (callable)
    callables.add(new VaryLongTimeTask());
    // Assign tasks for specific execution timeout (e.g. 2 sec)
    List<Future<Object>> futures = executorService.invokeAll(callables, 2000, TimeUnit.MILLISECONDS);
    for (Future<Object> future : futures) {
        // Getting result
} catch (InterruptedException e) {


The pro is you can also submit ListenableFuture at the same ExecutorService.
Just slightly change the first line of code.

ListeningExecutorService executorService = MoreExecutors.listeningDecorator(Executors.newCachedThreadPool());

ListeningExecutorService is the Listening feature of ExecutorService at google guava project ( )

How to check if a table exists in MS Access for vb macros

Exists = IsObject(CurrentDb.TableDefs(tablename))

How to find day of week in php in a specific timezone

Thanks a lot guys for your quick comments.

This is what i will be using now. Posting the function here so that somebody may use it.

public function getDayOfWeek($pTimezone)

    $userDateTimeZone = new DateTimeZone($pTimezone);
    $UserDateTime = new DateTime("now", $userDateTimeZone);

    $offsetSeconds = $UserDateTime->getOffset(); 
    //echo $offsetSeconds;

    return gmdate("l", time() + $offsetSeconds);


Report if you find any corrections.

How to get number of rows inserted by a transaction

@@ROWCOUNT will give the number of rows affected by the last SQL statement, it is best to capture it into a local variable following the command in question, as its value will change the next time you look at it:

DECLARE @Rows int
DECLARE @TestTable table (col1 int, col2 int)
INSERT INTO @TestTable (col1, col2) select 1,2 union select 3,4


(2 row(s) affected)
Rows        ROWCOUNT
----------- -----------
2           1

(1 row(s) affected)

you get Rows value of 2, the number of inserted rows, but ROWCOUNT is 1 because the SELECT @Rows=@@ROWCOUNT command affected 1 row

if you have multiple INSERTs or UPDATEs, etc. in your transaction, you need to determine how you would like to "count" what is going on. You could have a separate total for each table, a single grand total value, or something completely different. You'll need to DECLARE a variable for each total you want to track and add to it following each operation that applies to it:

--note there is no error handling here, as this is a simple example
DECLARE @AppleTotal  int
DECLARE @PeachTotal  int

SELECT @AppleTotal=0,@PeachTotal=0


INSERT INTO Apple (col1, col2) Select col1,col2 from xyz where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT

INSERT INTO Apple (col1, col2) Select col1,col2 from abc where ...
SET @AppleTotal=@AppleTotal+@@ROWCOUNT

INSERT INTO Peach (col1, col2) Select col1,col2 from xyz where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT

INSERT INTO Peach (col1, col2) Select col1,col2 from abc where ...
SET @PeachTotal=@PeachTotal+@@ROWCOUNT


SELECT @AppleTotal AS AppleTotal, @PeachTotal AS PeachTotal

PhpMyAdmin not working on localhost

STOP ALL SERVICES OF XAMPP Edit Apache(httpd.conf) file 1)"Listen 80" if its already 80 and not working then replace it by 81 2) "ServerName localhost:80" if its already 80 and not working then replace it by 81 SAVE EXIT RESTART [WINDOWS USER run as administrator]

How to convert a Java object (bean) to key-value pairs (and vice versa)?

Use juffrou-reflect's BeanWrapper. It is very performant.

Here is how you can transform a bean into a map:

public static Map<String, Object> getBeanMap(Object bean) {
    Map<String, Object> beanMap = new HashMap<String, Object>();
    BeanWrapper beanWrapper = new BeanWrapper(BeanWrapperContext.create(bean.getClass()));
    for(String propertyName : beanWrapper.getPropertyNames())
        beanMap.put(propertyName, beanWrapper.getValue(propertyName));
    return beanMap;

I developed Juffrou myself. It's open source, so you are free to use it and modify. And if you have any questions regarding it, I'll be more than happy to respond.



Using margin / padding to space <span> from the rest of the <p>

Overall just add display:block; to your span. You can leave your html unchanged.


You can do it with the following css:

p {
    font-weight: 300; 
    -webkit-font-smoothing: subpixel-antialiased; 

p span {
    font-style: italic; 

Can I assume (bool)true == (int)1 for any C++ compiler?

I've found different compilers return different results on true. I've also found that one is almost always better off comparing a bool to a bool instead of an int. Those ints tend to change value over time as your program evolves and if you assume true as 1, you can get bitten by an unrelated change elsewhere in your code.

php: Get html source code with cURL

$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec($curl);


"find: paths must precede expression:" How do I specify a recursive search that also finds files in the current directory?

What's happening is that the shell is expanding "*test.c" into a list of files. Try escaping the asterisk as:

find . -name \*test.c

Firing events on CSS class changes in jQuery

change() does not fire when a CSS class is added or removed or the definition changes. It fires in circumstances like when a select box value is selected or unselected.

I'm not sure if you mean if the CSS class definition is changed (which can be done programmatically but is tedious and not generally recommended) or if a class is added or removed to an element. There is no way to reliably capture this happening in either case.

You could of course create your own event for this but this can only be described as advisory. It won't capture code that isn't yours doing it.

Alternatively you could override/replace the addClass() (etc) methods in jQuery but this won't capture when it's done via vanilla Javascript (although I guess you could replace those methods too).

How can I make directory writable?

Execute at Admin privilege using sudo in order to avoid permission denied (Unable to change file mode) error.

sudo chmod 777 <directory location>

Using find command in bash script

You can use this:

list=$(find /home/user/Desktop -name '*.pdf' -o -name '*.txt' -o -name '*.bmp')

Besides, you might want to use -iname instead of -name to catch files with ".PDF" (upper-case) extension as well.

C# delete a folder and all files and folders within that folder

Try This:

foreach (string files in Directory.GetFiles(SourcePath))
   FileInfo fileInfo = new FileInfo(files);
   fileInfo.Delete(); //delete the files first. 
Directory.Delete(SourcePath);// delete the directory as it is empty now.

Iterating through a Collection, avoiding ConcurrentModificationException when removing objects in a loop

you can also use Recursion

Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is called recursive method.

batch to copy files with xcopy

Based on xcopy help, I tried and found that following works perfectly for me (tried on Win 7)

xcopy C:\folder1 C:\folder2\folder1 /E /C /I /Q /G /H /R /K /Y /Z /J

Difference between Pragma and Cache-Control headers?

There is no difference, except that Pragma is only defined as applicable to the requests by the client, whereas Cache-Control may be used by both the requests of the clients and the replies of the servers.

So, as far as standards go, they can only be compared from the perspective of the client making a requests and the server receiving a request from the client. The defines the scenario as follows:

HTTP/1.1 caches SHOULD treat "Pragma: no-cache" as if the client had sent "Cache-Control: no-cache". No new Pragma directives will be defined in HTTP.

  Note: because the meaning of "Pragma: no-cache as a response
  header field is not actually specified, it does not provide a
  reliable replacement for "Cache-Control: no-cache" in a response

The way I would read the above:

  • if you're writing a client and need no-cache:

    • just use Pragma: no-cache in your requests, since you may not know if Cache-Control is supported by the server;
    • but in replies, to decide on whether to cache, check for Cache-Control
  • if you're writing a server:

    • in parsing requests from the clients, check for Cache-Control; if not found, check for Pragma: no-cache, and execute the Cache-Control: no-cache logic;
    • in replies, provide Cache-Control.

Of course, reality might be different from what's written or implied in the RFC!

How to create a custom string representation for a class object?

Just adding to all the fine answers, my version with decoration:

from __future__ import print_function
import six

def classrep(rep):
    def decorate(cls):
        class RepMetaclass(type):
            def __repr__(self):
                return rep

        class Decorated(six.with_metaclass(RepMetaclass, cls)):

        return Decorated
    return decorate

class C(object):




The down sides:

  1. You can't declare C without a super class (no class C:)
  2. C instances will be instances of some strange derivation, so it's probably a good idea to add a __repr__ for the instances as well.

Chrome & Safari Error::Not allowed to load local resource: file:///D:/CSS/Style.css

You wont be able to access a local resource from your aspx page (web server). Have you tried a relative path from your aspx page to your css file like so...

<link rel="stylesheet" media="all" href="/CSS/Style.css" type="text/css" />

The above assumes that you have a folder called CSS in the root of your website like this:

Getting distance between two points based on latitude/longitude

import numpy as np

def Haversine(lat1,lon1,lat2,lon2, **kwarg):
    This uses the ‘haversine’ formula to calculate the great-circle distance between two points – that is, 
    the shortest distance over the earth’s surface – giving an ‘as-the-crow-flies’ distance between the points 
    (ignoring any hills they fly over, of course!).
    formula:    a = sin²(?f/2) + cos f1 · cos f2 · sin²(??/2)
    c = 2 · atan2( va, v(1-a) )
    d = R · c
    where   f is latitude, ? is longitude, R is earth’s radius (mean radius = 6,371km);
    note that angles need to be in radians to pass to trig functions!
    R = 6371.0088
    lat1,lon1,lat2,lon2 = map(np.radians, [lat1,lon1,lat2,lon2])

    dlat = lat2 - lat1
    dlon = lon2 - lon1
    a = np.sin(dlat/2)**2 + np.cos(lat1) * np.cos(lat2) * np.sin(dlon/2) **2
    c = 2 * np.arctan2(a**0.5, (1-a)**0.5)
    d = R * c
    return round(d,4)

2D Euclidean vector rotations

you should remove the vars from the function:

x = x * cs - y * sn; // now x is something different than original vector x
y = x * sn + y * cs;

create new coordinates becomes, to avoid calculation of x before it reaches the second line:

px = x * cs - y * sn; 
py = x * sn + y * cs;

Missing Push Notification Entitlement

This happened to me suddenly because my app's distribution profile had expired. Xcode began using the wildcard profile instead, which did not have the push notification entitlement enabled. I didn't receive any warning. The fix was easy; I just had to generate another distribution profile for my app in the Apple Developer Member Center, download it, and double-click to install in Xcode.

Error in Chrome only: XMLHttpRequest cannot load file URL No 'Access-Control-Allow-Origin' header is present on the requested resource

add this at the top of file,

header('content-type: application/json; charset=utf-8');
header("access-control-allow-origin: *");

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

You can use VLOOKUP, but this requires a wrapper function to return True or False. Not to mention it is (relatively) slow. Use COUNTIF or MATCH instead.

Fill down this formula in column K next to the existing values in column I (from I1 to I2691):

=COUNTIF(<entire column E range>,<single column I value>)>0

You can also use MATCH:

=NOT(ISNA(MATCH(<single column I value>,<entire column E range>)))

How to TryParse for Enum value?

There's currently no out of the box Enum.TryParse. This has been requested on Connect (Still no Enum.TryParse) and got a response indicating possible inclusion in the next framework after .NET 3.5. You'll have to implement the suggested workarounds for now.

XAMPP: Couldn't start Apache (Windows 10)

After playing around, really all you have to do is change two lines in the httpd.conf file:

Change "Listen 80" to "Listen 122" (or anything else you want)


"ServerName Localhost:80" to "Localhost:122" (or the port you changed above)

Then it all should fire right up :P

Android Studio Gradle project "Unable to start the daemon process /initialization of VM"

  • Start Android Studio.
  • Close any open project.Go to File > Close Project.(Welcome window will open)
  • Go to Configure > Settings.
  • On Settings dialog,select Compiler (Gradle-based Android Projects) from left and set VM Options to -Xmx512m(i.e. write -Xmx512m under VM Options:) and press OK.

It mostly works for that initilize vm problem.

Using Gradle to build a jar with dependencies

Excluding unwanted Manifest entries fixed the MainClass file not found error in a Gradle build jar file.

    exclude 'META-INF/*.SF', 'META-INF/*.DSA', 'META-INF/*.RSA', 'META-INF/*.MF'
    from {

matplotlib colorbar for scatter

If you're looking to scatter by two variables and color by the third, Altair can be a great choice.

Creating the dataset

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

df = pd.DataFrame(40*np.random.randn(10, 3), columns=['A', 'B','C'])

Altair plot

from altair import *
Chart(df).mark_circle().encode(x='A',y='B', color='C').configure_cell(width=200, height=150)


enter image description here

#ifdef in C#

C# does have a preprocessor. It works just slightly differently than that of C++ and C.

Here is a MSDN links - the section on all preprocessor directives.

Absolute Positioning & Text Alignment

Maybe specifying a width would work. When you position:absolute an element, it's width will shrink to the contents I believe.

Eliminate space before \begin{itemize}

The cleanest way for you to accomplish this is to use the enumitem package ( For example,

enter image description here

\noindent Here is some text and I want to make sure
there is no spacing the different items. 
  \item Item 1
  \item Item 2
  \item Item 3
\noindent Here is some text and I want to make sure
there is no spacing between this line and the item
list below it.
  \item Item 1
  \item Item 2
  \item Item 3

Furthermore, if you want to use this setting globally across lists, you can use

\setlist[itemize]{noitemsep, topsep=0pt}

However, note that this package does not work well with the beamer package which is used to make presentations in Latex.

Pass table as parameter into sql server UDF

The following will enable you to quickly remove the duplicate,null values and return only the valid one as list.

CREATE TABLE DuplicateTable (Col1 INT)
INSERT INTO DuplicateTable
SELECT 1--duplicate
SELECT 2 --duplicate

WITH CTE (COl1,DuplicateCount)
FROM DuplicateTable
WHERE DuplicateCount =1

CTE are valid in SQL 2005 , you could then store the values in a temp table and use it with your function.

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path

These steps can really help you:

  1. If you didn't install any server you have to do these steps:

    Menu Window ? Preferences ? Expend Server ? Runtime environment ? Add ? choose a name and then choose the Apache server path that you already installed on your PC (you can press download and install too) ? Finish ? OK

Ref# for more information, click here

  1. Add the Tomcat server:

    Project Properties ? Java Build Path ? Add Library ? Select "Server Runtime" from the list* ? Next ? Select "Apache Tomcat" ? Finish

Ref# This answer

Forking vs. Branching in GitHub

Here are the high-level differences:



  • Keeps branches separated by user
  • Reduces clutter in the primary repository
  • Your team process reflects the external contributor process


  • Makes it more difficult to see all of the branches that are active (or inactive, for that matter)
  • Collaborating on a branch is trickier (the fork owner needs to add the person as a collaborator)
  • You need to understand the concept of multiple remotes in Git
    • Requires additional mental bookkeeping
    • This will make the workflow more difficult for people who aren't super comfortable with Git



  • Keeps all of the work being done around a project in one place
  • All collaborators can push to the same branch to collaborate on it
  • There's only one Git remote to deal with


  • Branches that get abandoned can pile up more easily
  • Your team contribution process doesn't match the external contributor process
  • You need to add team members as contributors before they can branch

How to access the value of a promise?

There are some good answer above and here is the ES6 Arrow function version

var something = async() => {
   let result = await functionThatReturnsPromiseA();
   return result + 1;

Converting a byte array to PNG/JPG

There are two problems with this question:

Assuming you have a gray scale bitmap, you have two factors to consider:

  1. For JPGS... what loss of quality is tolerable?
  2. For pngs... what level of compression is tolerable? (Although for most things I've seen, you don't have that much of a choice, so this choice might be negligible.) For anybody thinking this question doesn't make sense: yes, you can change the amount of compression/number of passes attempted to compress; check out either Ifranview or some of it's plugins.

Answer those questions, and then you might be able to find your original answer.

Maximize a window programmatically and prevent the user from changing the windows state

Change the property WindowState to System.Windows.Forms.FormWindowState.Maximized, in some cases if the older answers doesn't works.

So the window will be maximized, and the other parts are in the other answers.

What is a lambda (function)?

The name "lambda" is just a historical artifact. All we're talking about is an expression whose value is a function.

A simple example (using Scala for the next line) is:

args.foreach(arg => println(arg))

where the argument to the foreach method is an expression for an anonymous function. The above line is more or less the same as writing something like this (not quite real code, but you'll get the idea):

void printThat(Object that) {

except that you don't need to bother with:

  1. Declaring the function somewhere else (and having to look for it when you revisit the code later).
  2. Naming something that you're only using once.

Once you're used to function values, having to do without them seems as silly as being required to name every expression, such as:

int tempVar = 2 * a + b

instead of just writing the expression where you need it:

println(2 * a + b)

The exact notation varies from language to language; Greek isn't always required! ;-)

Tensorflow import error: No module named 'tensorflow'

for python 3.8 version go for anaconda navigator then go for environments --> then go for base(root)----> not installed from drop box--->then search for tensorflow then install it then run the program.......hope it may helpful

How to lose margin/padding in UITextView?

For SwiftUI

If you are making your own TextView using UIViewRepresentable and want to control the padding, in your makeUIView function, simply do:

uiTextView.textContainerInset = UIEdgeInsets(top: 10, left: 18, bottom: 0, right: 18)

or whatever you want. ValueError: could not convert string to float

You may not pass str to fit this kind of classifier.

For example, if you have a feature column named 'grade' which has 3 different grades:

A,B and C.

you have to transfer those str "A","B","C" to matrix by encoder like the following:

A = [1,0,0]

B = [0,1,0]

C = [0,0,1]

because the str does not have numerical meaning for the classifier.

In scikit-learn, OneHotEncoder and LabelEncoder are available in inpreprocessing module. However OneHotEncoder does not support to fit_transform() of string. "ValueError: could not convert string to float" may happen during transform.

You may use LabelEncoder to transfer from str to continuous numerical values. Then you are able to transfer by OneHotEncoder as you wish.

In the Pandas dataframe, I have to encode all the data which are categorized to dtype:object. The following code works for me and I hope this will help you.

 from sklearn import preprocessing
    le = preprocessing.LabelEncoder()
    for column_name in train_data.columns:
        if train_data[column_name].dtype == object:
            train_data[column_name] = le.fit_transform(train_data[column_name])

How to clear exisiting dropdownlist items when its content changes?

You should clear out your listbbox prior to binding:

  ' now set datasource and bind

What is the best way to test for an empty string with jquery-out-of-the-box?

The link you gave seems to be attempting something different to the test you are trying to avoid repeating.

if (a == null || a=='')

tests if the string is an empty string or null. The article you linked to tests if the string consists entirely of whitespace (or is empty).

The test you described can be replaced by:

if (!a)

Because in javascript, an empty string, and null, both evaluate to false in a boolean context.

Difference between "enqueue" and "dequeue"

Enqueue and Dequeue tend to be operations on a queue, a data structure that does exactly what it sounds like it does.

You enqueue items at one end and dequeue at the other, just like a line of people queuing up for tickets to the latest Taylor Swift concert (I was originally going to say Billy Joel but that would date me severely).

There are variations of queues such as double-ended ones where you can enqueue and dequeue at either end but the vast majority would be the simpler form:

enqueue -> | 3 | 2 | 1 | -> dequeue

That diagram shows a queue where you've enqueued the numbers 1, 2 and 3 in that order, without yet dequeuing any.

By way of example, here's some Python code that shows a simplistic queue in action, with enqueue and dequeue functions. Were it more serious code, it would be implemented as a class but it should be enough to illustrate the workings:

import random

def enqueue(lst, itm):
    lst.append(itm)        # Just add item to end of list.
    return lst             # And return list (for consistency with dequeue).

def dequeue(lst):
    itm = lst[0]           # Grab the first item in list.
    lst = lst[1:]          # Change list to remove first item.
    return (itm, lst)      # Then return item and new list.

# Test harness. Start with empty queue.

myList = []

# Enqueue or dequeue a bit, with latter having probability of 10%.

for _ in range(15):
    if random.randint(0, 9) == 0 and len(myList) > 0:
        (itm, myList) = dequeue(myList)
        print(f"Dequeued {itm} to give {myList}")
        itm = 10 * random.randint(1, 9)
        myList = enqueue(myList, itm)
        print(f"Enqueued {itm} to give {myList}")

# Now dequeue remainder of list.

while len(myList) > 0:
    (itm, myList) = dequeue(myList)
    print(f"Dequeued {itm} to give {myList}")

A sample run of that shows it in operation:

Enqueued 70 to give [70]
Enqueued 20 to give [70, 20]
Enqueued 40 to give [70, 20, 40]
Enqueued 50 to give [70, 20, 40, 50]
Dequeued 70 to give [20, 40, 50]
Enqueued 20 to give [20, 40, 50, 20]
Enqueued 30 to give [20, 40, 50, 20, 30]
Enqueued 20 to give [20, 40, 50, 20, 30, 20]
Enqueued 70 to give [20, 40, 50, 20, 30, 20, 70]
Enqueued 20 to give [20, 40, 50, 20, 30, 20, 70, 20]
Enqueued 20 to give [20, 40, 50, 20, 30, 20, 70, 20, 20]
Dequeued 20 to give [40, 50, 20, 30, 20, 70, 20, 20]
Enqueued 80 to give [40, 50, 20, 30, 20, 70, 20, 20, 80]
Dequeued 40 to give [50, 20, 30, 20, 70, 20, 20, 80]
Enqueued 90 to give [50, 20, 30, 20, 70, 20, 20, 80, 90]
Dequeued 50 to give [20, 30, 20, 70, 20, 20, 80, 90]
Dequeued 20 to give [30, 20, 70, 20, 20, 80, 90]
Dequeued 30 to give [20, 70, 20, 20, 80, 90]
Dequeued 20 to give [70, 20, 20, 80, 90]
Dequeued 70 to give [20, 20, 80, 90]
Dequeued 20 to give [20, 80, 90]
Dequeued 20 to give [80, 90]
Dequeued 80 to give [90]
Dequeued 90 to give []

how to hide keyboard after typing in EditText in android?

I did not see anyone using this method:

editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    public void onFocusChange(View view, boolean focused) {
        InputMethodManager keyboard = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
        if (focused)
            keyboard.showSoftInput(editText, 0);
            keyboard.hideSoftInputFromWindow(editText.getWindowToken(), 0);

And then just request focus to the editText:


Decorators with parameters?

Edit : for an in-depth understanding of the mental model of decorators, take a look at this awesome Pycon Talk. well worth the 30 minutes.

One way of thinking about decorators with arguments is

def foo(*args, **kwargs):

translates to

foo = decorator(foo)

So if the decorator had arguments,

def foo(*args, **kwargs):

translates to

foo = decorator_with_args(arg)(foo)

decorator_with_args is a function which accepts a custom argument and which returns the actual decorator (that will be applied to the decorated function).

I use a simple trick with partials to make my decorators easy

from functools import partial

def _pseudo_decor(fun, argument):
    def ret_fun(*args, **kwargs):
        #do stuff here, for eg.
        print ("decorator arg is %s" % str(argument))
        return fun(*args, **kwargs)
    return ret_fun

real_decorator = partial(_pseudo_decor, argument=arg)

def foo(*args, **kwargs):


Above, foo becomes real_decorator(foo)

One effect of decorating a function is that the name foo is overridden upon decorator declaration. foo is "overridden" by whatever is returned by real_decorator. In this case, a new function object.

All of foo's metadata is overridden, notably docstring and function name.

>>> print(foo)
<function _pseudo_decor.<locals>.ret_fun at 0x10666a2f0>

functools.wraps gives us a convenient method to "lift" the docstring and name to the returned function.

from functools import partial, wraps

def _pseudo_decor(fun, argument):
    # magic sauce to lift the name and doc of the function
    def ret_fun(*args, **kwargs):
        # pre function execution stuff here, for eg.
        print("decorator argument is %s" % str(argument))
        returned_value =  fun(*args, **kwargs)
        # post execution stuff here, for eg.
        print("returned value is %s" % returned_value)
        return returned_value

    return ret_fun

real_decorator1 = partial(_pseudo_decor, argument="some_arg")
real_decorator2 = partial(_pseudo_decor, argument="some_other_arg")

def bar(*args, **kwargs):

>>> print(bar)
<function*args, **kwargs)>

>>> bar(1,2,3, k="v", x="z")
decorator argument is some_arg
returned value is None

C++ int float casting

Integer division occurs, then the result, which is an integer, is assigned as a float. If the result is less than 1 then it ends up as 0.

You'll want to cast the expressions to floats first before dividing, e.g.

float m = (float)(a.y - b.y) / (float)(a.x - b.x);

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

What is the "right" JSON date format?

There is no right format; The JSON specification does not specify a format for exchanging dates which is why there are so many different ways to do it.

The best format is arguably a date represented in ISO 8601 format (see Wikipedia); it is a well known and widely used format and can be handled across many different languages, making it very well suited for interoperability. If you have control over the generated json, for example, you provide data to other systems in json format, choosing 8601 as the date interchange format is a good choice.

If you do not have control over the generated json, for example, you are the consumer of json from several different existing systems, the best way of handling this is to have a date parsing utility function to handle the different formats expected.

jQuery - Click event on <tr> elements with in a table and getting <td> element values

Unless otherwise definied (<tfoot>, <thead>), browsers put <tr> implicitly in a <tbody>.

You need to put a > tbody in between > table and > tr:

$("div.custList > table > tbody > tr")

Alternatively, you can also be less strict in selecting the rows (the > denotes the immediate child):

$("div.custList table tr")

That said, you can get the immediate <td> children there by $(this).children('td').

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Paths specified with a . are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js but not if you run node folder/app.js. The only exception to this is require('./file') and that is only possible because require exists per-module and thus knows what module it is being called from.

To make a path relative to the script, you must use the __dirname variable.

var path = require('path');

path.join(__dirname, 'path/to/file')

or potentially

path.join(__dirname, 'path', 'to', 'file')

How to make a radio button look like a toggle button

Inspired by Michal B. answer. If you use bootstrap..

label.btn {_x000D_
  padding: 0;_x000D_
label.btn input {_x000D_
  opacity: 0;_x000D_
  position: absolute;_x000D_
label.btn span {_x000D_
  text-align: center;_x000D_
  padding: 6px 12px;_x000D_
  display: block;_x000D_
label.btn input:checked+span {_x000D_
  background-color: rgb(80, 110, 228);_x000D_
  color: #fff;_x000D_
<link href="" rel="stylesheet" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>One</span></label>_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Two</span></label>_x000D_
  <label class="btn btn-outline-primary"><input type="radio" name="toggle"><span>Three</span></label>_x000D_

How do I pass along variables with XMLHTTPRequest

Manually formatting the query string is fine for simple situations. But it can become tedious when there are many parameters.

You could write a simple utility function that handles building the query formatting for you.

function formatParams( params ){
  return "?" + Object
          return key+"="+encodeURIComponent(params[key])

And you would use it this way to build a request.

var endpoint = ""
var params = {
  a: 1, 
  b: 2,
  c: 3

var url = endpoint + formatParams(params)
//=> ""

There are many utility functions available for manipulating URL's. If you have JQuery in your project you could give a try.

It is similar to the above example function, but handles recursively serializing nested objects and arrays.

How should I choose an authentication library for CodeIgniter?

Tank Auth looks good but the documentation is just a one-page explanation of how to install, plus a quick run-down of each PHP file. At least that's all I found after lots of Googling. Maybe what people mean above when they say that Tank Auth is well-documented is that the code is well-commented. That's a good thing, but different than documentation. It would have been nice to have some documentation about how to integrate Tank Auth's features with your existing code.

onMeasure custom view explanation

onMeasure() is your opportunity to tell Android how big you want your custom view to be dependent the layout constraints provided by the parent; it is also your custom view's opportunity to learn what those layout constraints are (in case you want to behave differently in a match_parent situation than a wrap_content situation). These constraints are packaged up into the MeasureSpec values that are passed into the method. Here is a rough correlation of the mode values:

  • EXACTLY means the layout_width or layout_height value was set to a specific value. You should probably make your view this size. This can also get triggered when match_parent is used, to set the size exactly to the parent view (this is layout dependent in the framework).
  • AT_MOST typically means the layout_width or layout_height value was set to match_parent or wrap_content where a maximum size is needed (this is layout dependent in the framework), and the size of the parent dimension is the value. You should not be any larger than this size.
  • UNSPECIFIED typically means the layout_width or layout_height value was set to wrap_content with no restrictions. You can be whatever size you would like. Some layouts also use this callback to figure out your desired size before determine what specs to actually pass you again in a second measure request.

The contract that exists with onMeasure() is that setMeasuredDimension() MUST be called at the end with the size you would like the view to be. This method is called by all the framework implementations, including the default implementation found in View, which is why it is safe to call super instead if that fits your use case.

Granted, because the framework does apply a default implementation, it may not be necessary for you to override this method, but you may see clipping in cases where the view space is smaller than your content if you do not, and if you lay out your custom view with wrap_content in both directions, your view may not show up at all because the framework doesn't know how large it is!

Generally, if you are overriding View and not another existing widget, it is probably a good idea to provide an implementation, even if it is as simple as something like this:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {

    int desiredWidth = 100;
    int desiredHeight = 100;

    int widthMode = MeasureSpec.getMode(widthMeasureSpec);
    int widthSize = MeasureSpec.getSize(widthMeasureSpec);
    int heightMode = MeasureSpec.getMode(heightMeasureSpec);
    int heightSize = MeasureSpec.getSize(heightMeasureSpec);

    int width;
    int height;

    //Measure Width
    if (widthMode == MeasureSpec.EXACTLY) {
        //Must be this size
        width = widthSize;
    } else if (widthMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        width = Math.min(desiredWidth, widthSize);
    } else {
        //Be whatever you want
        width = desiredWidth;

    //Measure Height
    if (heightMode == MeasureSpec.EXACTLY) {
        //Must be this size
        height = heightSize;
    } else if (heightMode == MeasureSpec.AT_MOST) {
        //Can't be bigger than...
        height = Math.min(desiredHeight, heightSize);
    } else {
        //Be whatever you want
        height = desiredHeight;

    setMeasuredDimension(width, height);

Hope that Helps.

iPhone and WireShark

The easiest way of doing this will be to use wifi of course. You will need to determine if your wifi base acts as a hub or a switch. If it acts as a hub then just connect your windows pc to it and wireshark should be able to see all the traffic from the iPhone. If it is a switch then your easiest bet will be to buy a cheap hub and connect the wan side of your wifi base to the hub and then connect your windows pc running wireshark to the hub as well. At that point wireshark will be able to see all the traffic as it passes over the hub.

How do I add an integer value with javascript (jquery) to a value that's returning a string?

In regards to the octal misinterpretation of .js - I just used this...


and after testing with leading zeros, came back everytime with the correct representation.

hope this helps.

Convert into a useable string using Arduino?

Credit for this goes to magma. Great answer, but here it is using c++ style strings instead of c style strings. Some users may find that easier.

String string = "";
char ch; // Where to store the character read

void setup() {
    Serial.write("Power On");
boolean Comp(String par) {
    while (Serial.available() > 0) // Don't read unless
                                       // there you know there is data
        ch =; // Read a character
        string += ch; // Add it
    if (par == string) {
       string = "";
    else {
       //dont reset string
void loop()
    if (Comp("m1 on")) {
        Serial.write("Motor 1 -> Online\n");
    if (Comp("m1 off")) {
        Serial.write("Motor 1 -> Offline\n");

Java abstract interface

It's not necessary, as interfaces are by default abstract as all the methods in an interface are abstract.

What to do with "Unexpected indent" in python?

Python uses spacing at the start of the line to determine when code blocks start and end. Errors you can get are:

Unexpected indent. This line of code has more spaces at the start than the one before, but the one before is not the start of a subblock (e.g. if/while/for statement). All lines of code in a block must start with exactly the same string of whitespace. For instance:

>>> def a():
...   print "foo"
...     print "bar"
IndentationError: unexpected indent

This one is especially common when running python interactively: make sure you don't put any extra spaces before your commands. (Very annoying when copy-and-pasting example code!)

>>>   print "hello"
IndentationError: unexpected indent

Unindent does not match any outer indentation level. This line of code has fewer spaces at the start than the one before, but equally it does not match any other block it could be part of. Python cannot decide where it goes. For instance, in the following, is the final print supposed to be part of the if clause, or not?

>>> if user == "Joey":
...     print "Super secret powers enabled!"
...   print "Revealing super secrets"
IndendationError: unindent does not match any outer indentation level

Expected an indented block. This line of code has the same number of spaces at the start as the one before, but the last line was expected to start a block (e.g. if/while/for statement, function definition).

>>> def foo():
... print "Bar"
IndentationError: expected an indented block

If you want a function that doesn't do anything, use the "no-op" command pass:

>>> def foo():
...     pass

Mixing tabs and spaces is allowed (at least on my version of Python), but Python assumes tabs are 8 characters long, which may not match your editor. Just say "no" to tabs. Most editors allow them to be automatically replaced by spaces.

The best way to avoid these issues is to always use a consistent number of spaces when you indent a subblock, and ideally use a good IDE that solves the problem for you. This will also make your code more readable.

CustomErrors mode="Off"

If you're using the MVC preview 4, you could be experiencing this because you're using the HandleErrorAttribute. The behavior changed in 5 so that it doesn't handle exceptions if you turn off custom errors.

How to check if all of the following items are in a list?

Not OP's case, but - for anyone who wants to assert intersection in dicts and ended up here due to poor googling (e.g. me) - you need to work with dict.items:

>>> a = {'key': 'value'}
>>> b = {'key': 'value', 'extra_key': 'extra_value'}
>>> all(item in a.items() for item in b.items())
>>> all(item in b.items() for item in a.items())

That's because dict.items returns tuples of key/value pairs, and much like any object in Python, they're interchangeably comparable

How to find out the MySQL root password

I solved this a different way, this may be easier for some.

I did it this way because I tried starting in safe mode but cannot connect with the error: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)

What I did was to connect normally as root:

$ sudo mysql -u root

Then I created a new super user:

mysql> grant all privileges on *.* to 'myuser'@'%' identified by 'mypassword' with grant option;
mysql> quit

Then log in as myuser

$ mysql -u myuser -p -h localhost

Trying to change the password gave me no errors but did nothing for me so I dropped and re-created the root user

mysql> drop user 'root'@'localhost;
mysql> mysql> grant all privileges on *.* to 'root'@'localhost' identified by 'mypassword' with grant option;

The root user is now working with the new password

What is REST? Slightly confused

REST is not a specific web service but a design concept (architecture) for managing state information. The seminal paper on this was Roy Thomas Fielding's dissertation (2000), "Architectural Styles and the Design of Network-based Software Architectures" (available online from the University of California, Irvine).

First read Ryan Tomayko's post How I explained REST to my wife; it's a great starting point. Then read Fielding's actual dissertation. It's not that advanced, nor is it long (six chapters, 180 pages)! (I know you kids in school like it short).

EDIT: I feel it's pointless to try to explain REST. It has so many concepts like scalability, visibility (stateless) etc. that the reader needs to grasp, and the best source for understanding those are the actual dissertation. It's much more than POST/GET etc.

jQuery: Can I call delay() between addClass() and such?

Try this:

function removeClassDelayed(jqObj, c, to) {    
    setTimeout(function() { jqObj.removeClass(c); }, to);
removeClassDelayed($("#div"), "error", 1000);

How to append elements at the end of ArrayList in Java?

import java.util.*;

public class matrixcecil {
    public static void main(String args[]){
        List<Integer> k1=new ArrayList<Integer>(10);
        int i=0;



I think this example will help you for better solution.

What is the best way to search the Long datatype within an Oracle database?

Don't use LONGs, use CLOB instead. You can index and search CLOBs like VARCHAR2.

Additionally, querying with a leading wildcard(%) will ALWAYS result in a full-table-scan. Look into Oracle Text indexes instead.

Click through div to underlying elements

  1. Hide overlaying the element
  2. Determine cursor coordinates
  3. Get element on those coordinates
  4. Trigger click on element
  5. Show overlaying element again
$('#elementontop').click(e => {
    $(document.elementFromPoint(e.clientX, e.clientY)).trigger("click");

How can I convert a PFX certificate file for use with Apache on a linux server?

SSLSHopper has some pretty thorough articles about moving between different servers.

Just pick the relevant link at bottom of this page.

Note: they have an online converter which gives them access to your private key. They can probably be trusted but it would be better to use the OPENSSL command (also shown on this site) to keep the private key private on your own machine.

How to sort with a lambda?

Got it.

sort(mMyClassVector.begin(), mMyClassVector.end(), 
    [](const MyClass & a, const MyClass & b) -> bool
    return a.mProperty > b.mProperty; 

I assumed it'd figure out that the > operator returned a bool (per documentation). But apparently it is not so.

Invalidating JSON Web Tokens

Haven't tried this yet, and it is uses a lot of information based on some of the other answers. The complexity here is to avoid a server side data store call per request for user information. Most of the other solutions require a db lookup per request to a user session store. That is fine in certain scenarios but this was created in an attempt to avoid such calls and make whatever required server side state to be very small. You will end up recreating a server side session, however small to provide all the force invalidation features. But if you want to do it here is the gist:


  • Mitigate use of a data store (state-less).
  • Ability to force log out all users.
  • Ability to force log out any individual at any time.
  • Ability to require password re-entry after a certain amount of time.
  • Ability to work with multiple clients.
  • Ability to force a re-log in when a user clicks logout from a particular client. (To prevent someone "un-deleting" a client token after user walks away - see comments for additional information)

The Solution:

  • Use short lived (<5m) access tokens paired with a longer lived (few hours) client stored refresh-token.
  • Every request checks either the auth or refresh token expiration date for validity.
  • When the access token expires, the client uses the refresh token to refresh the access token.
  • During the refresh token check, the server checks a small blacklist of user ids - if found reject the refresh request.
  • When a client doesn't have a valid(not expired) refresh or auth token the user must log back in, as all other requests will be rejected.
  • On login request, check user data store for ban.
  • On logout - add that user to the session blacklist so they have to log back in. You would have to store additional information to not log them out of all devices in a multi device environment but it could be done by adding a device field to the user blacklist.
  • To force re-entry after x amount of time - maintain last login date in the auth token, and check it per request.
  • To force log out all users - reset token hash key.

This requires you to maintain a blacklist(state) on the server, assuming the user table contains banned user information. The invalid sessions blacklist - is a list of user ids. This blacklist is only checked during a refresh token request. Entries are required to live on it as long as the refresh token TTL. Once the refresh token expires the user would be required to log back in.


  • Still required to do a data store lookup on the refresh token request.
  • Invalid tokens may continue to operate for access token's TTL.


  • Provides desired functionality.
  • Refresh token action is hidden from the user under normal operation.
  • Only required to do a data store lookup on refresh requests instead of every request. ie 1 every 15 min instead of 1 per second.
  • Minimizes server side state to a very small blacklist.

With this solution an in memory data store like reddis isn't needed, at least not for user information as you are as the server is only making a db call every 15 or so minutes. If using reddis, storing a valid/invalid session list in there would be a very fast and simpler solution. No need for a refresh token. Each auth token would have a session id and device id, they could be stored in a reddis table on creation and invalidated when appropriate. Then they would be checked on every request and rejected when invalid.

How to access form methods and controls from a class in C#?


Class1 excell = new Class1 (); //you must declare this in form as you want to control

excel.get_data_from_excel(this); // And create instance for class and sen this form to another class


class Class1
    public void get_data_from_excel (Form1 form) //you getting the form here and you can control as you want
        form.ComboBox1.text = "try it"; //you can chance Form1 UI elements inside the class now

IMPORTANT : But you must not forgat you have declare modifier form properties as PUBLIC and you can access other wise you can not see the control in form from class

Difference between @Mock and @InjectMocks

@InjectMocks annotation can be used to inject mock fields into a test object automatically.

In below example @InjectMocks has used to inject the mock dataMap into the dataLibrary .

Map<String, String> dataMap ;

DataLibrary dataLibrary = new DataLibrary();

    public void whenUseInjectMocksAnnotation_() {
        Mockito.when(dataMap .get("aData")).thenReturn("aMeaning");

        assertEquals("aMeaning", dataLibrary .getMeaning("aData"));

How to get a path to the desktop for current user in C#?

// Environment.GetFolderPath
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData); // Current User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); // All User's Application Data
Environment.GetFolderPath(Environment.SpecialFolder.CommonProgramFiles); // Program Files
Environment.GetFolderPath(Environment.SpecialFolder.Cookies); // Internet Cookie
Environment.GetFolderPath(Environment.SpecialFolder.Desktop); // Logical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); // Physical Desktop
Environment.GetFolderPath(Environment.SpecialFolder.Favorites); // Favorites
Environment.GetFolderPath(Environment.SpecialFolder.History); // Internet History
Environment.GetFolderPath(Environment.SpecialFolder.InternetCache); // Internet Cache
Environment.GetFolderPath(Environment.SpecialFolder.MyComputer); // "My Computer" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // "My Documents" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyMusic); // "My Music" Folder
Environment.GetFolderPath(Environment.SpecialFolder.MyPictures); // "My Pictures" Folder
Environment.GetFolderPath(Environment.SpecialFolder.Personal); // "My Document" Folder
Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles); // Program files Folder
Environment.GetFolderPath(Environment.SpecialFolder.Programs); // Programs Folder
Environment.GetFolderPath(Environment.SpecialFolder.Recent); // Recent Folder
Environment.GetFolderPath(Environment.SpecialFolder.SendTo); // "Sent to" Folder
Environment.GetFolderPath(Environment.SpecialFolder.StartMenu); // Start Menu
Environment.GetFolderPath(Environment.SpecialFolder.Startup); // Startup
Environment.GetFolderPath(Environment.SpecialFolder.System); // System Folder
Environment.GetFolderPath(Environment.SpecialFolder.Templates); // Document Templates

jquery how to empty input field

While submitting form use reset method on form. The reset() method resets the values of all elements in a form.




$("#submit-button").on("click", function(){_x000D_
       //code here_x000D_
<script src=""></script>_x000D_
<form id="form-id">_x000D_
  First name:<br>_x000D_
  <input type="text" name="firstname">_x000D_
  Last name:<br>_x000D_
  <input type="text" name="lastname">_x000D_
  <input id="submit-button" type="submit" value="Submit">_x000D_
</form> _x000D_

Allowed memory size of 536870912 bytes exhausted in Laravel

for xampp it there is in xampp\php\php.ini now mine new option in it looks as :

;Maximum amount of memory a script may consume

What is in your .vimrc?

My heavily commented vimrc, with readline-esque (emacs) keybindings:

if version >= 700

"------ Meta ------"

" clear all autocommands! (this comment must be on its own line)

set nocompatible                " break away from old vi compatibility
set fileformats=unix,dos,mac    " support all three newline formats
set viminfo=                    " don't use or save viminfo files

"------ Console UI & Text display ------"

set cmdheight=1                 " explicitly set the height of the command line
set showcmd                     " Show (partial) command in status line.
set number                      " yay line numbers
set ruler                       " show current position at bottom
set noerrorbells                " don't whine
set visualbell t_vb=            " and don't make faces
set lazyredraw                  " don't redraw while in macros
set scrolloff=5                 " keep at least 5 lines around the cursor
set wrap                        " soft wrap long lines
set list                        " show invisible characters
set listchars=tab:>·,trail:·    " but only show tabs and trailing whitespace
set report=0                    " report back on all changes
set shortmess=atI               " shorten messages and don't show intro
set wildmenu                    " turn on wild menu :e <Tab>
set wildmode=list:longest       " set wildmenu to list choice
if has('syntax')
    syntax on
    " Remember that rxvt-unicode has 88 colors by default; enable this only if
    " you are using the 256-color patch
    if &term == 'rxvt-unicode'
        set t_Co=256

    if &t_Co == 256
        colorscheme xoria256
        colorscheme peachpuff

"------ Text editing and searching behavior ------"

set nohlsearch                  " turn off highlighting for searched expressions
set incsearch                   " highlight as we search however
set matchtime=5                 " blink matching chars for .x seconds
set mouse=a                     " try to use a mouse in the console (wimp!)
set ignorecase                  " set case insensitivity
set smartcase                   " unless there's a capital letter
set completeopt=menu,longest,preview " more autocomplete <Ctrl>-P options
set nostartofline               " leave my cursor position alone!
set backspace=2                 " equiv to :set backspace=indent,eol,start
set textwidth=80                " we like 80 columns
set showmatch                   " show matching brackets
set formatoptions=tcrql         " t - autowrap to textwidth
                                " c - autowrap comments to textwidth
                                " r - autoinsert comment leader with <Enter>
                                " q - allow formatting of comments with :gq
                                " l - don't format already long lines

"------ Indents and tabs ------"

set autoindent                  " set the cursor at same indent as line above
set smartindent                 " try to be smart about indenting (C-style)
set expandtab                   " expand <Tab>s with spaces; death to tabs!
set shiftwidth=4                " spaces for each step of (auto)indent
set softtabstop=4               " set virtual tab stop (compat for 8-wide tabs)
set tabstop=8                   " for proper display of files with tabs
set shiftround                  " always round indents to multiple of shiftwidth
set copyindent                  " use existing indents for new indents
set preserveindent              " save as much indent structure as possible
filetype plugin indent on       " load filetype plugins and indent settings

"------ Key bindings ------"

" Remap broken meta-keys that send ^[
for n in range(97,122) " ASCII a-z
    let c = nr2char(n)
    exec "set <M-". c .">=\e". c
    exec "map  \e". c ." <M-". c .">"
    exec "map! \e". c ." <M-". c .">"

""" Emacs keybindings
" first move the window command because we'll be taking it over
noremap <C-x> <C-w>
" Movement left/right
noremap! <C-b> <Left>
noremap! <C-f> <Right>
" word left/right
noremap  <M-b> b
noremap! <M-b> <C-o>b
noremap  <M-f> w
noremap! <M-f> <C-o>w
" line start/end
noremap  <C-a> ^
noremap! <C-a> <Esc>I
noremap  <C-e> $
noremap! <C-e> <Esc>A
" Rubout word / line and enter insert mode
noremap  <C-w> i<C-w>
noremap  <C-u> i<C-u>
" Forward delete char / word / line and enter insert mode
noremap! <C-d> <C-o>x
noremap  <M-d> dw
noremap! <M-d> <C-o>dw
noremap  <C-k> Da
noremap! <C-k> <C-o>D
" Undo / Redo and enter normal mode
noremap  <C-_> u
noremap! <C-_> <C-o>u<Esc><Right>
noremap! <C-r> <C-o><C-r><Esc>

" Remap <C-space> to word completion
noremap! <Nul> <C-n>

" OS X paste (pretty poor implementation)
if has('mac')
    noremap  v :r!pbpaste<CR>
    noremap! v <Esc>v

""" screen.vim REPL:
" send paragraph to parallel process
vmap <C-c><C-c> :ScreenSend<CR>
nmap <C-c><C-c> mCvip<C-c><C-c>`C
imap <C-c><C-c> <Esc><C-c><C-c><Right>
" set shell region height
let g:ScreenShellHeight = 12

"------ Filetypes ------"

" Vimscript
autocmd FileType vim setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4

" Shell
autocmd FileType sh setlocal expandtab shiftwidth=4 tabstop=8 softtabstop=4

" Lisp
autocmd Filetype lisp,scheme setlocal equalprg=~/.vim/bin/lispindent.lisp expandtab shiftwidth=2 tabstop=8 softtabstop=2

" Ruby
autocmd FileType ruby setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2

autocmd FileType php setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4

autocmd FileType html,xhtml,xml setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2

autocmd FileType css setlocal expandtab shiftwidth=4 tabstop=4 softtabstop=4

" JavaScript
" autocmd BufRead,BufNewFile *.json setfiletype javascript
autocmd FileType javascript setlocal expandtab shiftwidth=2 tabstop=2 softtabstop=2
let javascript_enable_domhtmlcss=1

"------ END VIM-500 ------"

endif " version >= 500

HTML5 input type range show range value

Try This :

 <input min="0" max="100" id="when_change_range" type="range">
 <input type="text" id="text_for_show_range">

and in jQuery section :


Android Location Providers - GPS or Network Provider?

There are 3 location providers in Android.

They are:

gps –> (GPS, AGPS): Name of the GPS location provider. This provider determines location using satellites. Depending on conditions, this provider may take a while to return a location fix. Requires the permission android.permission.ACCESS_FINE_LOCATION.

network –> (AGPS, CellID, WiFi MACID): Name of the network location provider. This provider determines location based on availability of cell tower and WiFi access points. Results are retrieved by means of a network lookup. Requires either of the permissions android.permission.ACCESS_COARSE_LOCATION or android.permission.ACCESS_FINE_LOCATION.

passive –> (CellID, WiFi MACID): A special location provider for receiving locations without actually initiating a location fix. This provider can be used to passively receive location updates when other applications or services request them without actually requesting the locations yourself. This provider will return locations generated by other providers. Requires the permission android.permission.ACCESS_FINE_LOCATION, although if the GPS is not enabled this provider might only return coarse fixes. This is what Android calls these location providers, however, the underlying technologies to make this stuff work is mapped to the specific set of hardware and telco provided capabilities (network service).

The best way is to use the “network” or “passive” provider first, and then fallback on “gps”, and depending on the task, switch between providers. This covers all cases, and provides a lowest common denominator service (in the worst case) and great service (in the best case).

enter image description here

Article Reference : Android Location Providers - gps, network, passive By Nazmul Idris

Code Reference :


Now Android have Fused location provider

The Fused Location Provider intelligently manages the underlying location technology and gives you the best location according to your needs. It simplifies ways for apps to get the user’s current location with improved accuracy and lower power usage

Fused location provider provide three ways to fetch location

  1. Last Location: Use when you want to know current location once.
  2. Request Location using Listener: Use when application is on screen / frontend and require continues location.
  3. Request Location using Pending Intent: Use when application in background and require continues location.

References :

Official site :

Fused location provider example: GIT :


phpMyAdmin + CentOS 6.0 - Forbidden

None of the configuration above worked for me on my CentOS 7 server. After hours of searching, that's what worked for me:

Edit file phpMyAdmin.conf

sudo nano /etc/httpd/conf.d/phpMyAdmin.conf

And replace this at the top:

<Directory /usr/share/phpMyAdmin/>
   AddDefaultCharset UTF-8

   <IfModule mod_authz_core.c>
     # Apache 2.4
       #Require ip
       #Require ip ::1
       Require all granted
   <IfModule !mod_authz_core.c>
     # Apache 2.2
     Order Deny,Allow
     Deny from All
     Allow from
     Allow from ::1

How do I assign ls to an array in Linux Bash?

Whenever possible, you should avoid parsing the output of ls (see Greg's wiki on the subject). Basically, the output of ls will be ambiguous if there are funny characters in any of the filenames. It's also usually a waste of time. In this case, when you execute ls -d */, what happens is that the shell expands */ to a list of subdirectories (which is already exactly what you want), passes that list as arguments to ls -d, which looks at each one, says "yep, that's a directory all right" and prints it (in an inconsistent and sometimes ambiguous format). The ls command isn't doing anything useful!

Well, ok, it is doing one thing that's useful: if there are no subdirectories, */ will get left as is, ls will look for a subdirectory named "*", not find it, print an error message that it doesn't exist (to stderr), and not print the "*/" (to stdout).

The cleaner way to make an array of subdirectory names is to use the glob (*/) without passing it to ls. But in order to avoid putting "*/" in the array if there are no actual subdirectories, you should set nullglob first (again, see Greg's wiki):

shopt -s nullglob
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}"  # Note double-quotes to avoid extra parsing of funny characters in filenames

If you want to print an error message if there are no subdirectories, you're better off doing it yourself:

if (( ${#array[@]} == 0 )); then
    echo "No subdirectories found" >&2

Apply CSS rules to a nested class inside a div

If you need to target multiple classes use:

#main_text .title, #main_text .title2 {
  /* Properties */

Why are arrays of references illegal?

Answering to your question about standard I can cite the C++ Standard §8.3.2/4:

There shall be no references to references, no arrays of references, and no pointers to references.

Convert NSArray to NSString in Objective-C

The way I know is easy.

var NSArray_variable = NSArray_Object[n]
var stringVarible = NSArray_variable as String

n is the inner position in the array This in SWIFT Language. It might work in Objective C

How to hide a mobile browser's address bar?

create host file = manifest.json

html tag head

<link rel="manifest" href="/manifest.json">



"name": "news",
"short_name": "news",
"description": "des news application day",
"categories": [
"theme_color": "#ffffff",
"background_color": "#ffffff",
"display": "standalone",
"orientation": "natural",
"lang": "fa",
"dir": "rtl",
"start_url": "/?application=true",
"gcm_sender_id": "482941778795",
"DO_NOT_CHANGE_GCM_SENDER_ID": "Do not change the GCM Sender ID",
"icons": [
"src": "",
"sizes": "192x192",
"type": "image/png"
"src": "",
"sizes": "512x512",
"type": "image/png"
"related_applications": [
"platform": "play",
"url": ""
"prefer_related_applications": true

Difference between number and integer datatype in oracle dictionary views

This is what I got from oracle documentation, but it is for oracle 10g release 2:

When you define a NUMBER variable, you can specify its precision (p) and scale (s) so that it is sufficiently, but not unnecessarily, large. Precision is the number of significant digits. Scale can be positive or negative. Positive scale identifies the number of digits to the right of the decimal point; negative scale identifies the number of digits to the left of the decimal point that can be rounded up or down.

The NUMBER data type is supported by Oracle Database standard libraries and operates the same way as it does in SQL. It is used for dimensions and surrogates when a text or INTEGER data type is not appropriate. It is typically assigned to variables that are not used for calculations (like forecasts and aggregations), and it is used for variables that must match the rounding behavior of the database or require a high degree of precision. When deciding whether to assign the NUMBER data type to a variable, keep the following facts in mind in order to maximize performance:

  • Analytic workspace calculations on NUMBER variables is slower than other numerical data types because NUMBER values are calculated in software (for accuracy) rather than in hardware (for speed).
  • When data is fetched from an analytic workspace to a relational column that has the NUMBER data type, performance is best when the data already has the NUMBER data type in the analytic workspace because a conversion step is not required.

CSS body background image fixed to full screen even when zooming in/out

Use Directly like this

     background: url(../img/beach.jpg) no-repeat fixed 100% 100%;

or call CSS separately like

    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;

How to find all the dependencies of a table in sql server

SELECT referencing_schema_name, referencing_entity_name,
case when is_caller_dependent=0 then 'NO' ELSE 'Yes'
END AS is_caller_dependent FROM sys.dm_sql_referencing_entities ('Tablename', 'OBJECT');

Background service with location listener in android

First you need to create a Service. In that Service, create a class extending LocationListener. For this, use the following code snippet of Service:

public class LocationService extends Service {
public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;

Intent intent;
int counter = 0;

public void onCreate() {
    intent = new Intent(BROADCAST_ACTION);

public void onStart(Intent intent, int startId) {
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    listener = new MyLocationListener();
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 4000, 0, (LocationListener) listener);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 4000, 0, listener);

public IBinder onBind(Intent intent)
    return null;

protected boolean isBetterLocation(Location location, Location currentBestLocation) {
    if (currentBestLocation == null) {
        // A new location is always better than no location
        return true;

    // Check whether the new location fix is newer or older
    long timeDelta = location.getTime() - currentBestLocation.getTime();
    boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
    boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
    boolean isNewer = timeDelta > 0;

    // If it's been more than two minutes since the current location, use the new location
    // because the user has likely moved
    if (isSignificantlyNewer) {
        return true;
        // If the new location is more than two minutes older, it must be worse
    } else if (isSignificantlyOlder) {
        return false;

    // Check whether the new location fix is more or less accurate
    int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
    boolean isLessAccurate = accuracyDelta > 0;
    boolean isMoreAccurate = accuracyDelta < 0;
    boolean isSignificantlyLessAccurate = accuracyDelta > 200;

    // Check if the old and new location are from the same provider
    boolean isFromSameProvider = isSameProvider(location.getProvider(),

    // Determine location quality using a combination of timeliness and accuracy
    if (isMoreAccurate) {
        return true;
    } else if (isNewer && !isLessAccurate) {
        return true;
    } else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
        return true;
    return false;

/** Checks whether two providers are the same */
private boolean isSameProvider(String provider1, String provider2) {
    if (provider1 == null) {
        return provider2 == null;
    return provider1.equals(provider2);

public void onDestroy() {
    // handler.removeCallbacks(sendUpdatesToUI);     
    Log.v("STOP_SERVICE", "DONE");

public static Thread performOnBackgroundThread(final Runnable runnable) {
    final Thread t = new Thread() {
        public void run() {
            try {
            } finally {

    return t;
public class MyLocationListener implements LocationListener

    public void onLocationChanged(final Location loc)
        Log.i("*****", "Location changed");
        if(isBetterLocation(loc, previousBestLocation)) {
            intent.putExtra("Latitude", loc.getLatitude());
            intent.putExtra("Longitude", loc.getLongitude());
            intent.putExtra("Provider", loc.getProvider());


    public void onStatusChanged(String provider, int status, Bundle extras) {


    public void onProviderDisabled(String provider)
        Toast.makeText( getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show();

    public void onProviderEnabled(String provider)
        Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show();

Add this Service any where in your project, the way you want! :)

Removing Data From ElasticSearch

You can delete the index by Kibana Console:

Console Icon

To get all index:

GET /_cat/indices?v

To delete a specific index:


How can I make a thumbnail <img> show a full size image when clicked?

<img src='thumb.gif' onclick='this.src="full_size.gif"' />

Of course you can change the onclick event to load the image wherever you want.

Can't connect to local MySQL server through socket homebrew

I manually started mysql in the system preferences pane by initialising the database and then starting it. This solved my problem.

Regular expression to match a dot

"In the default mode, Dot (.) matches any character except a newline. If the DOTALL flag has been specified, this matches any character including a newline." (python Doc)

So, if you want to evaluate dot literaly, I think you should put it in square brackets:

>>> p = re.compile(r'\b(\w+[.]\w+)')
>>> resp ="blah blah blah [email protected] blah blah")

Border around specific rows in a table?

I was just playing around with doing this too, and this seemed to be the best option for me:

    tr { 
        display: table;            /* this makes borders/margins work */
        border: 1px solid black;
        margin: 5px;

Note that this will prevent the use of fluid/automatic column widths, as cells will no longer align with those in other rows, but border/colour formatting still works OK. The solution is to give the TR and TDs a specified width (either px or %).

Of course you could make the selector tr.myClass if you wanted to apply it only to certain rows. Apparently display: table doesn't work for IE 6/7, however, but there's probably other hacks (hasLayout?) that might work for those. :-(

Does Python support short-circuiting?

Yes, Python does support Short-circuit evaluation, minimal evaluation, or McCarthy evaluation for Boolean operators. It is used to reduce the number of evaluations for computing the output of boolean expression. Example -

Base Functions

def a(x):
    return x

def b(x):
    return x 


if(a(True) and b(True)):

if(a(False) and b(True)):





if(a(True) or b(False)):

if(a(False) or b(True)):




Node.js for() loop returning the same values at each loop

  for(var i = 0; i < BoardMessages.length;i++){
            console.log("Loading message %d".green, j);
            htmlMessageboardString += MessageToHTMLString(BoardMessages[j]);

That should work; however, you should never create a function in a loop. Therefore,

  for(var i = 0; i < BoardMessages.length;i++){

  function composeMessage(message){
      console.log("Loading message %d".green, message);
      htmlMessageboardString += MessageToHTMLString(message);

The POST method is not supported for this route. Supported methods: GET, HEAD. Laravel

In my case just run the command and worked like charm.

php artisan route:clear

How to force deletion of a python object?

In general, to make sure something happens no matter what, you use

from exceptions import NameError

    f = open(x)
except ErrorType as e:
    pass # handle the error
    except NameError: pass

finally blocks will be run whether or not there is an error in the try block, and whether or not there is an error in any error handling that takes place in except blocks. If you don't handle an exception that is raised, it will still be raised after the finally block is excecuted.

The general way to make sure a file is closed is to use a "context manager".

with open(x) as f:
    # do stuff

This will automatically close f.

For your question #2, bar gets closed on immediately when it's reference count reaches zero, so on del foo if there are no other references.

Objects are NOT created by __init__, they're created by __new__.

When you do foo = Foo() two things are actually happening, first a new object is being created, __new__, then it is being initialized, __init__. So there is no way you could possibly call del foo before both those steps have taken place. However, if there is an error in __init__, __del__ will still be called because the object was actually already created in __new__.

Edit: Corrected when deletion happens if a reference count decreases to zero.

Assigning default value while creating migration file

t.integer :retweets_count, :default => 0

... should work.

See the Rails guide on migrations

Datatable to html Table

From this link

using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Text;
using System.Xml;

namespace ClientUtil
public class DataTableUtil

public static string DataTableToXmlString(DataTable dtData)
if (dtData == null || dtData.Columns.Count == 0)
return (string) null;
DataColumn[] primaryKey = dtData.PrimaryKey;
StringBuilder stringBuilder = new StringBuilder();
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
if (DataTableUtil.IsPrimaryKey(dataColumn.ColumnName, primaryKey))
stringBuilder.Append(“<TH IsPK=’true’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
stringBuilder.Append(“<TH IsPK=’false’ ColType='”).Append(Convert.ToString(dataColumn.DataType == typeof (object) ? (object) typeof (string) : (object) dataColumn.DataType)).Append(“‘>”).Append(dataColumn.ColumnName.Replace(“&”, “”)).Append(“</TH>”);
int num1 = 0;
foreach (DataRow dataRow in (InternalDataCollectionBase) dtData.Rows)
int num2 = 0;
foreach (DataColumn dataColumn in (InternalDataCollectionBase) dtData.Columns)
string str = Convert.IsDBNull(dataRow[dataColumn.ColumnName]) ? (string) null : Convert.ToString(dataRow[dataColumn.ColumnName]).Replace(“<“, “&lt;”).Replace(“>”, “&gt;”).Replace(“\””, “&quot;”).Replace(“‘”, “&apos;”).Replace(“&”, “&amp;”);
if (!string.IsNullOrEmpty(str))
return ((object) stringBuilder).ToString();

protected static bool IsPrimaryKey(string ColumnName, DataColumn[] PKs)
if (PKs == null || string.IsNullOrEmpty(ColumnName))
return false;
foreach (DataColumn dataColumn in PKs)
if (dataColumn.ColumnName.ToLower().Trim() == ColumnName.ToLower().Trim())
return true;
return false;

public static DataTable XmlStringToDataTable(string XmlData)
DataTable dataTable = (DataTable) null;
IList<DataColumn> list = (IList<DataColumn>) new List<DataColumn>();
if (string.IsNullOrEmpty(XmlData))
return (DataTable) null;
XmlDocument xmlDocument1 = new XmlDocument();
xmlDocument1.PreserveWhitespace = true;
XmlDocument xmlDocument2 = xmlDocument1;
XmlNode xmlNode1 = xmlDocument2.SelectSingleNode(“/TABLE”);
if (xmlNode1 != null)
dataTable = new DataTable();
int num = 0;
foreach (XmlNode xmlNode2 in xmlNode1.SelectNodes(“TR”))
if (num == 0)
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TH”))
bool result = false;
string str = xmlNode3.Attributes[“IsPK”].Value;
if (!string.IsNullOrEmpty(str))
if (!bool.TryParse(str, out result))
result = false;
result = false;
Type type = Type.GetType(xmlNode3.Attributes[“ColType”].Value);
DataColumn column = new DataColumn(xmlNode3.InnerText, type);
if (result)
if (!dataTable.Columns.Contains(column.ColumnName))
if (list.Count > 0)
DataColumn[] dataColumnArray = new DataColumn[list.Count];
for (int index = 0; index < list.Count; ++index)
dataColumnArray[index] = list[index];
dataTable.PrimaryKey = dataColumnArray;
DataRow row = dataTable.NewRow();
int index = 0;
foreach (XmlNode xmlNode3 in xmlNode2.SelectNodes(“TD”))
Type dataType = dataTable.Columns[index].DataType;
string s = xmlNode3.InnerText;
if (!string.IsNullOrEmpty(s))
s = s.Replace(“&lt;”, “<“);
s = s.Replace(“&gt;”, “>”);
s = s.Replace(“&quot;”, “\””);
s = s.Replace(“&apos;”, “‘”);
s = s.Replace(“&amp;”, “&”);
row[index] = Convert.ChangeType((object) s, dataType);
if (dataType == typeof (DateTime))
row[index] = (object) DateTime.ParseExact(s, “yyyyMMdd”, (IFormatProvider) CultureInfo.InvariantCulture);
row[index] = Convert.DBNull;
return dataTable;

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This is surely an encoding problem. You have a different encoding in your database and in your website and this fact is the cause of the problem. Also if you ran that command you have to change the records that are already in your tables to convert those character in UTF-8.

Update: Based on your last comment, the core of the problem is that you have a database and a data source (the CSV file) which use different encoding. Hence you can convert your database in UTF-8 or, at least, when you get the data that are in the CSV, you have to convert them from UTF-8 to latin1.

You can do the convertion following this articles:

How do you run a js file using npm scripts?

{ "scripts" :
  { "build": "node build.js"}

npm run build OR npm run-script build

  "name": "build",
  "version": "1.0.0",
  "scripts": {
    "start": "node build.js"

npm start

NB: you were missing the { brackets } and the node command

folder structure is fine:

+ build
  - package.json
  - build.js

TextView bold via xml file?

use textstyle property as bold

android:textStyle = "bold";

Python pip install module is not found. How to link python to pip location?

Make sure to check the python version you are working on if it is 2 then only pip install works If it is 3. something then make sure to use pip3 install

How to specify the bottom border of a <tr>?

tr td 
    border-bottom: 2px solid silver;

or if you want the border inside the TR tag, you can do this:

tr td {
    box-shadow: inset 0px -2px 0px silver;

IntelliJ IDEA generating serialVersionUID

Install the GenerateSerialVersionUID plugin by Olivier Descout.

Go to: menu File ? Settings ? Plugins ? Browse repositories ? GenerateSerialVersionUID

Install the plugin and restart.

Now you can generate the id from menu Code ? Generate ? serialVersionUID` or the shortcut.

How do you determine the ideal buffer size when using FileInputStream?

In most cases, it really doesn't matter that much. Just pick a good size such as 4K or 16K and stick with it. If you're positive that this is the bottleneck in your application, then you should start profiling to find the optimal buffer size. If you pick a size that's too small, you'll waste time doing extra I/O operations and extra function calls. If you pick a size that's too big, you'll start seeing a lot of cache misses which will really slow you down. Don't use a buffer bigger than your L2 cache size.

Advantages of std::for_each over for loop

You're mostly correct: most of the time, std::for_each is a net loss. I'd go so far as to compare for_each to goto. goto provides the most versatile flow-control possible -- you can use it to implement virtually any other control structure you can imagine. That very versatility, however, means that seeing a goto in isolation tells you virtually nothing about what's it's intended to do in this situation. As a result, almost nobody in their right mind uses goto except as a last resort.

Among the standard algorithms, for_each is much the same way -- it can be used to implement virtually anything, which means that seeing for_each tells you virtually nothing about what it's being used for in this situation. Unfortunately, people's attitude toward for_each is about where their attitude toward goto was in (say) 1970 or so -- a few people had caught onto the fact that it should be used only as a last resort, but many still consider it the primary algorithm, and rarely if ever use any other. The vast majority of the time, even a quick glance would reveal that one of the alternatives was drastically superior.

Just for example, I'm pretty sure I've lost track of how many times I've seen people writing code to print out the contents of a collection using for_each. Based on posts I've seen, this may well be the single most common use of for_each. They end up with something like:

class XXX { 
// ...
     std::ostream &print(std::ostream &os) { return os << "my data\n"; }

And their post is asking about what combination of bind1st, mem_fun, etc. they need to make something like:

std::vector<XXX> coll;

std::for_each(coll.begin(), coll.end(), XXX::print);

work, and print out the elements of coll. If it really did work exactly as I've written it there, it would be mediocre, but it doesn't -- and by the time you've gotten it to work, it's difficult to find those few bits of code related to what's going on among the pieces that hold it together.

Fortunately, there is a much better way. Add a normal stream inserter overload for XXX:

std::ostream &operator<<(std::ostream *os, XXX const &x) { 
   return x.print(os);

and use std::copy:

std::copy(coll.begin(), coll.end(), std::ostream_iterator<XXX>(std::cout, "\n"));

That does work -- and takes virtually no work at all to figure out that it prints the contents of coll to std::cout.

Merge r brings error "'by' must specify uniquely valid columns"

This is what I tried for a right outer join [as per my requirement]:

m1 <- merge(x=companies, y=rounds2, by.x=companies$permalink, 
            by.y=rounds2$company_permalink, all.y=TRUE)
# Error in, x) : 'by' must specify uniquely valid columns
m1 <- merge(x=companies, y=rounds2, by.x=c("permalink"), 
            by.y=c("company_permalink"), all.y=TRUE)

This worked.

c# replace \" characters

Where do these characters occur? Do you see them if you examine the XML data in, say, notepad? Or do you see them when examining the XML data in the debugger. If it is the latter, they are only escape characters for the " characters, and so part of the actual XML data.

How to import/include a CSS file using PHP code and not HTML code?

  define('CSSPATH', 'template/css/'); //define css path
  $cssItem = 'style.css'; //css item to display
 <title>Including css</title>
  <link rel="stylesheet" href="<?php echo (CSSPATH . "$cssItem"); ?>" type="text/css">


Get the client IP address using PHP

In PHP 5.3 or greater, you can get it like this:

$ip = getenv('HTTP_CLIENT_IP')?:

How can I rollback an UPDATE query in SQL server 2005?

You can use implicit transactions for this


update Staff set staff_Name='jas' where staff_id=7


As you request-- You can SET this setting ( SET IMPLICIT_TRANSACTIONS ON) from a stored procedure by setting that stored procedure as the start up procedure.

But SET IMPLICIT TRANSACTION ON command is connection specific. So any connection other than the one which running the start up stored procedure will not benefit from the setting you set.

Better way to sum a property value in an array

It's working for me in TypeScript and JavaScript:

let lst = [_x000D_
     { description:'Senior', price: 10},_x000D_
     { description:'Adult', price: 20},_x000D_
     { description:'Child', price: 30}_x000D_
let sum = => o.price).reduce((a, c) => { return a + c });_x000D_

I hope is useful.

FORCE INDEX in MySQL - where do I put it?

The syntax for index hints is documented here:

FORCE INDEX goes right after the table reference:

    SELECT owner_id,
    FROM db_products FORCE INDEX (products_start_time)
    ORDER BY start_time DESC
) as resultstable
WHERE resultstable.closed = 0
      AND = 1
      AND resultstable.approved = 1
      AND resultstable.deleted = 0
      AND resultstable.creation_in_progress = 0
GROUP BY resultstable.owner_id
ORDER BY start_time DESC


If you're using ORDER BY before GROUP BY to get the latest entry per owner_id, you're using a nonstandard and undocumented behavior of MySQL to do that.

There's no guarantee that it'll continue to work in future versions of MySQL, and the query is likely to be an error in any other RDBMS.

Search the tag for many explanations of better solutions for this type of query.

What is the python "with" statement designed for?

In python generally “with” statement is used to open a file, process the data present in the file, and also to close the file without calling a close() method. “with” statement makes the exception handling simpler by providing cleanup activities.

General form of with:

with open(“file name”, “mode”) as file-var:
    processing statements

note: no need to close the file by calling close() upon file-var.close()

how to assign a block of html code to a javascript variable

 var test = "<div class='saved' >"+
 "<div >test.test</div> <div class='remove'>[Remove]</div></div>";

You can add "\n" if you require line-break.

How to run shell script file using nodejs?

You could use "child process" module of nodejs to execute any shell commands or scripts with in nodejs. Let me show you with an example, I am running a shell script( with in nodejs.

echo "Hi There!"


const { exec } = require('child_process');
var yourscript = exec('sh',
        (error, stdout, stderr) => {
            if (error !== null) {
                console.log(`exec error: ${error}`);

Here, when I run the nodejs file, it will execute the shell file and the output would be:


node node_program.js


Hi There!

You can execute any script just by mentioning the shell command or shell script in exec callback.

Hope this helps! Happy coding :)

ORA-06508: PL/SQL: could not find program unit being called

I suspect you're only reporting the last error in a stack like this:

ORA-04068: existing state of packages has been discarded
ORA-04061: existing state of package body "schema.package" has been invalidated
ORA-04065: not executed, altered or dropped package body "schema.package"
ORA-06508: PL/SQL: could not find program unit being called: "schema.package"

If so, that's because your package is stateful:

The values of the variables, constants, and cursors that a package declares (in either its specification or body) comprise its package state. If a PL/SQL package declares at least one variable, constant, or cursor, then the package is stateful; otherwise, it is stateless.

When you recompile the state is lost:

If the body of an instantiated, stateful package is recompiled (either explicitly, with the "ALTER PACKAGE Statement", or implicitly), the next invocation of a subprogram in the package causes Oracle Database to discard the existing package state and raise the exception ORA-04068.

After PL/SQL raises the exception, a reference to the package causes Oracle Database to re-instantiate the package, which re-initializes it...

You can't avoid this if your package has state. I think it's fairly rare to really need a package to be stateful though, so you should revisit anything you have declared in the package, but outside a function or procedure, to see if it's really needed at that level. Since you're on 10g though, that includes constants, not just variables and cursors.

But the last paragraph from the quoted documentation means that the next time you reference the package in the same session, you won't get the error and it will work as normal (until you recompile again).

Deleting objects from an ArrayList in Java

Maybe Iterator’s remove() method? The JDK’s default collection classes should all creator iterators that support this method.

is it possible to add colors to python output?

being overwhelmed by being VERY NEW to python i missed some very simple and useful commands given here: Print in terminal with colors using Python? -

eventually decided to use CLINT as an answer that was given there by great and smart people

Best way to do multiple constructors in PHP

For php7, I compare parameters type as well, you can have two constructors with same number of parameters but different type.

trait GenericConstructorOverloadTrait
     * @var array Constructors metadata
    private static $constructorsCache;
     * Generic constructor
     * GenericConstructorOverloadTrait constructor.
    public function __construct()
        $params = func_get_args();
        $numParams = func_num_args();

        $finish = false;

            $class = new \ReflectionClass($this);
            $constructors =  array_filter($class->getMethods(),
                function (\ReflectionMethod $method) {
                return preg_match("/\_\_construct[0-9]+/",$method->getName());
            self::$constructorsCache = $constructors;
            $constructors = self::$constructorsCache;
        foreach($constructors as $constructor){
            $reflectionParams = $constructor->getParameters();
            if(count($reflectionParams) != $numParams){
            $matched = true;
            for($i=0; $i< $numParams; $i++){
                    $type = $reflectionParams[$i]->getType()->__toString();
                        !$reflectionParams[$i]->hasType() ||
                        ($reflectionParams[$i]->hasType() &&
                            is_object($params[$i]) &&
                            $params[$i] instanceof $type) ||
                        ($reflectionParams[$i]->hasType() &&
                            $reflectionParams[$i]->getType()->__toString() ==
                ) {
                    $matched = false;


                $finish = true;


            throw new \InvalidArgumentException("Cannot match construct by params");


To use it:

class MultiConstructorClass{

    use GenericConstructorOverloadTrait;

    private $param1;

    private $param2;

    private $param3;

    public function __construct1($param1, array $param2)
        $this->param1 = $param1;
        $this->param2 = $param2;

    public function __construct2($param1, array $param2, \DateTime $param3)
        $this->__construct1($param1, $param2);
        $this->param3 = $param3;

     * @return \DateTime
    public function getParam3()
        return $this->param3;

     * @return array
    public function getParam2()
        return $this->param2;

     * @return mixed
    public function getParam1()
        return $this->param1;

What are the differences between a multidimensional array and an array of arrays in C#?

I would like to update on this, because in .NET Core multi-dimensional arrays are faster than jagged arrays. I ran the tests from John Leidegren and these are the results on .NET Core 2.0 preview 2. I increased the dimension value to make any possible influences from background apps less visible.

Debug (code optimalization disabled)
Running jagged 
187.232 200.585 219.927 227.765 225.334 222.745 224.036 222.396 219.912 222.737 

Running multi-dimensional  
130.732 151.398 131.763 129.740 129.572 159.948 145.464 131.930 133.117 129.342 

Running single-dimensional  
 91.153 145.657 111.974  96.436 100.015  97.640  94.581 139.658 108.326  92.931 

Release (code optimalization enabled)
Running jagged 
108.503 95.409 128.187 121.877 119.295 118.201 102.321 116.393 125.499 116.459 

Running multi-dimensional 
 62.292  60.627  60.611  60.883  61.167  60.923  62.083  60.932  61.444  62.974 

Running single-dimensional 
 34.974  33.901  34.088  34.659  34.064  34.735  34.919  34.694  35.006  34.796 

I looked into disassemblies and this is what I found

jagged[i][j][k] = i * j * k; needed 34 instructions to execute

multi[i, j, k] = i * j * k; needed 11 instructions to execute

single[i * dim * dim + j * dim + k] = i * j * k; needed 23 instructions to execute

I wasn't able to identify why single-dimensional arrays were still faster than multi-dimensional but my guess is that it has to do with some optimalization made on the CPU

Format date and Subtract days using Moment.js

Try this:

var duration = moment.duration({'days' : 1});

This will give you 14-04-2015 - today is 15-04-2015

Alternatively if your momentjs version is less than 2.8.0, you can use:

startdate = moment().subtract('days', 1).format('DD-MM-YYYY');

Instead of this:

startdate = moment().subtract(1, 'days').format('DD-MM-YYYY');

Sorting string array in C#

If you have problems with numbers (say 1, 2, 10, 12 which will be sorted 1, 10, 12, 2) you can use LINQ:

var arr = arr.OrderBy(x=>x).ToArray();

Iterating over each line of ls -l output

Set IFS to newline, like this:

for x in `ls -l $1`; do echo $x; done

Put a sub-shell around it if you don't want to set IFS permanently:

for x in `ls -l $1`; do echo $x; done)

Or use while | read instead:

ls -l $1 | while read x; do echo $x; done

One more option, which runs the while/read at the same shell level:

while read x; do echo $x; done << EOF
$(ls -l $1)

Using jquery to get all checked checkboxes with a certain class name

If you need to get the value of all checked checkboxes as an array:

let myArray = (function() {
    let a = [];
    $(".checkboxes:checked").each(function() {
    return a;

How to select the nth row in a SQL database table?

It seems to me that, to be efficient, you need to 1) generate a random number between 0 and one less than the number of database records, and 2) be able to select the row at that position. Unfortunately, different databases have different random number generators and different ways to select a row at a position in a result set - usually you specify how many rows to skip and how many rows you want, but it's done differently for different databases. Here is something that works for me in SQLite:

select * 
from Table 
limit abs(random()) % (select count(*) from Words), 1;

It does depend on being able to use a subquery in the limit clause (which in SQLite is LIMIT <recs to skip>,<recs to take>) Selecting the number of records in a table should be particularly efficient, being part of the database's meta data, but that depends on the database's implementation. Also, I don't know if the query will actually build the result set before retrieving the Nth record, but I would hope that it doesn't need to. Note that I'm not specifying an "order by" clause. It might be better to "order by" something like the primary key, which will have an index - getting the Nth record from an index might be faster if the database can't get the Nth record from the database itself without building the result set.

What are the differences between a superkey and a candidate key?

Super key: super key is a set of atttibutes in a relation(table).which can define every tupple in the relation(table) uniquely.

Candidate key: we can say minimal super key is candidate key. Candidate is the smallest sub set of super key. And can uniquely define each and every tupple.

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.

This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.

A transport-level error has occurred when receiving results from the server

For me the solution was totally different.

In my case I had an objectsource which required a datetimestamp parameter. Even though that ODS parameter ConvertEmptyStringToNull was true 1/1/0001 was being passed to SelectMethod. That in turn caused a sql datetime overflow exception when that datetime was passed to the sql server.

Added an additional check for datetime.year != 0001 and that solved it for me.

Weird that it would throw a transport level error and not a datetime overflow error. Anyways..

How to call function on child component on parent events

A simple decoupled way to call methods on child components is by emitting a handler from the child and then invoking it from parent.

var Child = {_x000D_
  template: '<div>{{value}}</div>',_x000D_
  data: function () {_x000D_
    return {_x000D_
      value: 0_x000D_
  methods: {_x000D_
   setValue(value) {_x000D_
     this.value = value;_x000D_
  created() {_x000D_
    this.$emit('handler', this.setValue);_x000D_
new Vue({_x000D_
  el: '#app',_x000D_
  components: {_x000D_
    'my-component': Child_x000D_
  methods: {_x000D_
   setValueHandler(fn) {_x000D_
     this.setter = fn_x000D_
    click() {_x000D_
<script src="[email protected]/dist/vue.js"></script>_x000D_
<div id="app">_x000D_
  <my-component @handler="setValueHandler"></my-component>_x000D_
  <button @click="click">Click</button>  _x000D_

The parent keeps track of the child handler functions and calls whenever necessary.

Can I install/update WordPress plugins without providing FTP access?

Just a quick change to wp-config.php


That’s it, enjoy your wordpress updates without ftp!

Alternate Method:

There are hosts out there that will prevent this method from working to ease your WordPress updating. Fortunately, there is another way to keep this pest from prompting you for your FTP user name and password.

Again, after the MYSQL login declarations in your wp-config.php file, add the following:

define("FTP_HOST", "localhost");
define("FTP_USER", "yourftpusername");
define("FTP_PASS", "yourftppassword");

How to convert a Title to a URL slug in jQuery?

Yet another one. Short and keeps special characters:

imaginação é mato => imaginacao-e-mato

function slugify (text) {
  const a = 'àáäâãèéëêìíïîòóöôùúüûñçßÿœærsn?????u?z?·/_,:;'
  const b = 'aaaaaeeeeiiiioooouuuuncsyoarsnpwgnmuxzh------'
  const p = new RegExp(a.split('').join('|'), 'g')

  return text.toString().toLowerCase()
    .replace(/\s+/g, '-')           // Replace spaces with -
    .replace(p, c =>
        b.charAt(a.indexOf(c)))     // Replace special chars
    .replace(/&/g, '-and-')         // Replace & with 'and'
    .replace(/[^\w\-]+/g, '')       // Remove all non-word chars
    .replace(/\-\-+/g, '-')         // Replace multiple - with single -
    .replace(/^-+/, '')             // Trim - from start of text
    .replace(/-+$/, '')             // Trim - from end of text

jQuery trigger file input

Correct code:

    .upload input[type='file']{
        position: absolute;
        float: left;
        opacity: 0; /* For IE8 "Keep the IE opacity settings in this order for max compatibility" */
        -ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)"; /* For IE5 - 7 */
        filter: alpha(opacity=0);
        width: 100px; height: 30px; z-index: 51
    .upload input[type='button']{
        width: 100px;
        height: 30px;
        z-index: 50;
    .upload input[type='submit']{
        display: none;
        width: 100px; height: 30px
<div class="upload">
    <input type='file' ID="flArquivo" onchange="upload();" />
    <input type="button" value="Selecionar" onchange="open();" />
    <input type='submit' ID="btnEnviarImagem"  />

<script type="text/javascript">
    function open() {
    function upload() {

A CORS POST request works from plain JavaScript, but why not with jQuery?

UPDATE: As TimK pointed out, this isn't needed with jquery 1.5.2 any more. But if you want to add custom headers or allow the use of credentials (username, password, or cookies, etc), read on.

I think I found the answer! (4 hours and a lot of cursing later)

//This does not work!!
Access-Control-Allow-Headers: *

You need to manually specify all the headers you will accept (at least that was the case for me in FF 4.0 & Chrome 10.0.648.204).

jQuery's $.ajax method sends the "x-requested-with" header for all cross domain requests (i think its only cross domain).

So the missing header needed to respond to the OPTIONS request is:

//no longer needed as of jquery 1.5.2
Access-Control-Allow-Headers: x-requested-with

If you are passing any non "simple" headers, you will need to include them in your list (i send one more):

//only need part of this for my custom header
Access-Control-Allow-Headers: x-requested-with, x-requested-by

So to put it all together, here is my PHP:

// * wont work in FF w/ Allow-Credentials
//if you dont need Allow-Credentials, * seems to work
//if you need cookies or login etc
header('Access-Control-Allow-Credentials: true');
if ($this->getRequestMethod() == 'OPTIONS')
  header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
  header('Access-Control-Max-Age: 604800');
  //if you need special headers
  header('Access-Control-Allow-Headers: x-requested-with');

Changing width property of a :before css selector using JQuery

I don't think there's a jQuery-way to directly access the pseudoclass' rules, but you could always append a new style element to the document's head like:

$('head').append('<style>.column:before{width:800px !important;}</style>');

See a live demo here

I also remember having seen a plugin that tackles this issue once but I couldn't find it on first googling unfortunately.

Moment JS - check if a date is today or in the future


moment().isSame('2010-02-01', 'day'); // Return true if we are the 2010-02-01

I have since found the isSame function, which in I believe is the correct function to use for figuring out if a date is today.

Original answer

Just in case someone else needs this, just do this:

const isToday = moment(0, "HH").diff(date, "days") == 0;

or if you want a function:

isToday = date => moment(0,"HH").diff(date, "days") == 0;

Where date is the date you want to check for.


moment(0, "HH") returns today's day at midnight.

date1.diff(date2, "days") returns the number of days between the date1 and date2.

How To Use DateTimePicker In WPF?

I don't think this DateTimePicker has been mentioned before:

A WPF DateTimePicker That Works Like the One in Winforms

That one is in VB and has some bugs. I converted it to C# and made a new version with bug fixes.


Note: I used the Calendar control in WPFToolkit so that I could use .NET 3.5 instead of .NET 4. If you are using .NET 4, just remove references to "wpftc" in the XAML.


Update the create action as below:

def create
  respond_to do |format|
      format.html do
        redirect_to '/'
      format.json { render json: @reservation.to_json }
      format.html { render 'new'} ## Specify the format in which you are rendering "new" page
      format.json { render json: @reservation.errors } ## You might want to specify a json format as well

You are using respond_to method but anot specifying the format in which a new page is rendered. Hence, the error ActionController::UnknownFormat .

Converting a factor to numeric without losing information R (as.numeric() doesn't seem to work)

First, factor consists of indices and levels. This fact is very very important when you are struggling with factor.

For example,

> z <- factor(letters[c(3, 2, 3, 4)])

# human-friendly display, but internal structure is invisible
> z
[1] c b c d
Levels: b c d

# internal structure of factor
> unclass(z)
[1] 2 1 2 3
[1] "b" "c" "d"

here, z has 4 elements.
The index is 2, 1, 2, 3 in that order.
The level is associated with each index: 1 -> b, 2 -> c, 3 -> d.

Then, as.numeric converts simply the index part of factor into numeric.
as.character handles the index and levels, and generates character vector expressed by its level.

?as.numeric says that Factors are handled by the default method.

Running CMake on Windows

The default generator for Windows seems to be set to NMAKE. Try to use:

cmake -G "MinGW Makefiles"

Or use the GUI, and select MinGW Makefiles when prompted for a generator. Don't forget to cleanup the directory where you tried to run CMake, or delete the cache in the GUI. Otherwise, it will try again with NMAKE.

What's a good hex editor/viewer for the Mac?

One recommendation I've gotten is Hex Fiend.

Expand a div to fill the remaining width

You can use W3's CSS library that contains a class called rest that does just that:

<link rel="stylesheet" href="">_x000D_
<div class="w3-row">_x000D_
  <div class="w3-col " style="width:150px">_x000D_
  <div class="w3-rest w3-green">_x000D_

Don't forget to link the CSS library in the page's header:

<link rel="stylesheet" href="">

Here's the official demo: W3 School Tryit Editor

Best practice for partial updates in a RESTful service

You basically have two options:

  1. Use PATCH (but note that you have to define your own media type that specifies what will happen exactly)

  2. Use POST to a sub resource and return 303 See Other with the Location header pointing to the main resource. The intention of the 303 is to tell the client: "I have performed your POST and the effect was that some other resource was updated. See Location header for which resource that was." POST/303 is intended for iterative additions to a resources to build up the state of some main resource and it is a perfect fit for partial updates.

Bootstrap collapse animation not smooth

Mine got smoother not by wrapping each child but wrapping whole markup with a helper div. Like this:

<div class="accordeonBigWrapper">
    <div class="panel-group accordion partnersAccordeonWrapper" id="partnersAccordeon" role="tablist" aria-multiselectable="false">
         accordeon markup inside...

How can we stop a running java process through Windows cmd?

It is rather messy but you need to do something like the following:

START "do something window" dir
FOR /F "tokens=2" %I in ('TASKLIST /NH /FI "WINDOWTITLE eq do something window"' ) DO SET PID=%I

Found this on this page.

(This kind of thing is much easier if you have a UNIX / LINUX system ... or if you run Cygwin or similar on Windows.)

AttributeError: 'datetime' module has no attribute 'strptime'

If I had to guess, you did this:

import datetime

at the top of your code. This means that you have to do this:

datetime.datetime.strptime(date, "%Y-%m-%d")

to access the strptime method. Or, you could change the import statement to this:

from datetime import datetime

and access it as you are.

The people who made the datetime module also named their class datetime:

#module  class    method
datetime.datetime.strptime(date, "%Y-%m-%d")

svn : how to create a branch from certain revision of trunk

append the revision using an "@" character:

svn copy http://src@REV http://dev

Or, use the -r [--revision] command line argument.

The required anti-forgery form field "__RequestVerificationToken" is not present Error in user Registration

In my EPiServer solution on several controllers there was a ContentOutputCache attribute on the Index action which accepted HttpGet. Each view for those actions contained a form which was posting to a HttpPost action to the same controller or to a different one. As soon as I removed that attribute from all of those Index actions problem was gone.

How may I align text to the left and text to the right in the same line?

If you don't want to use floating elements and want to make sure that both blocks do not overlap, try:

<p style="text-align: left; width:49%; display: inline-block;">LEFT</p>
<p style="text-align: right; width:50%;  display: inline-block;">RIGHT</p>

Is this the right way to clean-up Fragment back stack when leaving a deeply nested stack?

The other clean solution if you don't want to pop all stack entries...

getSupportFragmentManager().popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
getSupportFragmentManager().beginTransaction().replace(, fragmentInstance).addToBackStack(null).commit();

This will clean the stack first and then load a new fragment, so at any given point you'll have only single fragment in stack

Use String.split() with multiple delimiters

String[] token=s.split("[.-]");

How do I revert my changes to a git submodule?

do 4 steps sequential:

git submodule foreach git reset --hard HEAD
git submodule update
git submodule foreach "git checkout master; git pull"
git submodule foreach git clean -f

path.join vs path.resolve with __dirname

From the doc for path.resolve:

The resulting path is normalized and trailing slashes are removed unless the path is resolved to the root directory.

But path.join keeps trailing slashes


__dirname = '/';
path.resolve(__dirname, 'foo/'); // '/foo'
path.join(__dirname, 'foo/'); // '/foo/'

ASP.Net MVC: How to display a byte array image from model

This is an modified version of Manoj's answer that I use on a project. Just updated to take a class, html attributes and use the TagBuilder.

    public static IHtmlString Image(this HtmlHelper helper, byte[] image, string imgclass, 
                                     object htmlAttributes = null)
        var builder = new TagBuilder("img");
        builder.MergeAttribute("class", imgclass);
        builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));

        var imageString = image != null ? Convert.ToBase64String(image) : "";
        var img = string.Format("data:image/jpg;base64,{0}", imageString);
        builder.MergeAttribute("src", img);

        return MvcHtmlString.Create(builder.ToString(TagRenderMode.SelfClosing));

Which can be used then as follows:

    @Html.Image(Model.Image, "img-cls", new { width="200", height="200" })

Mvn install or Mvn package

mvn install is the option that is most often used.
mvn package is seldom used, only if you're debugging some issue with the maven build process.


Note that mvn package will only create a jar file.
mvn install will do that and install the jar (and class etc.) files in the proper places if other code depends on those jars.

I usually do a mvn clean install; this deletes the target directory and recreates all jars in that location.
The clean helps with unneeded or removed stuff that can sometimes get in the way.
Rather then debug (some of the time) just start fresh all of the time.

How to add an item to an ArrayList in Kotlin?

For people just migrating from java, In Kotlin List is by default immutable and mutable version of Lists is called MutableList.

Hence if you have something like :

val list: List<String> = ArrayList()

In this case you will not get an add() method as list is immutable. Hence you will have to declare a MutableList as shown below :

val list: MutableList<String> = ArrayList()

Now you will see an add() method and you can add elements to any list.

Loop through an array of strings in Bash?

This is similar to user2533809's answer, but each file will be executed as a separate command.


while read -r line; do
    echo line: "$line"
done <<< "$names"

Where do I find the bashrc file on Mac?

The .bash_profile for macOS is found in the $HOME directory. You can create the file if it does not exit. Sublime Text 3 can help.

  • If you follow the instruction from OS X Command Line - Sublime Text to launch ST3 with subl then you can just do this

    $ subl ~/.bash_profile
  • An easier method is to use open

    $ open ~/.bash_profile -a "Sublime Text"

Use Command + Shift + . in Finder to view hidden files in your home directory.

Retrieve Button value with jQuery

As a button value is an attribute you need to use the .attr() method in jquery. This should do it

<script type="text/javascript">
    $(document).ready(function() {
        $('.my_button').click(function() {

You can also use attr to set attributes, more info in the docs.

This only works in JQuery 1.6+. See postpostmodern's answer for older versions.

Why is printing "B" dramatically slower than printing "#"?

Yes the culprit is definitely word-wrapping. When I tested your two programs, NetBeans IDE 8.2 gave me the following result.

  1. First Matrix: O and # = 6.03 seconds
  2. Second Matrix: O and B = 50.97 seconds

Looking at your code closely you have used a line break at the end of first loop. But you didn't use any line break in second loop. So you are going to print a word with 1000 characters in the second loop. That causes a word-wrapping problem. If we use a non-word character " " after B, it takes only 5.35 seconds to compile the program. And If we use a line break in the second loop after passing 100 values or 50 values, it takes only 8.56 seconds and 7.05 seconds respectively.

Random r = new Random();
for (int i = 0; i < 1000; i++) {
    for (int j = 0; j < 1000; j++) {
        if(r.nextInt(4) == 0) {
        } else {
        if(j%100==0){               //Adding a line break in second loop      

Another advice is that to change settings of NetBeans IDE. First of all, go to NetBeans Tools and click Options. After that click Editor and go to Formatting tab. Then select Anywhere in Line Wrap Option. It will take almost 6.24% less time to compile the program.

NetBeans Editor Settings