Programs & Examples On #Iframe app

Remove IE10's "clear field" X button on certain inputs?

I found it's better to set the width and height to 0px. Otherwise, IE10 ignores the padding defined on the field -- padding-right -- which was intended to keep the text from typing over the 'X' icon that I overlayed on the input field. I'm guessing that IE10 is internally applying the padding-right of the input to the ::--ms-clear pseudo element, and hiding the pseudo element does not restore the padding-right value to the input.

This worked better for me:

.someinput::-ms-clear {
  width : 0;
  height: 0;
}

DataGridView changing cell background color

If you are still intrested in why this didn't work for you at first:

The reason you don't see changes you've made to the cell's style is because you do these changes before the form was shown, and so they are disregarded.

Changing cell styles in the events suggested here will do the job, but they are called multiple times causing your style changes to happen more times than you wish, and so aren't very efficient.

To solve this, either change the style after the point in your code in which the form is shown, or subscribe to the Shown event, and place your changes there (this is event is called significantly less than the other events suggested).

How to git ignore subfolders / subdirectories?

The question isn't asking about ignoring all subdirectories, but I couldn't find the answer anywhere, so I'll post it: */*.

Replacing values from a column using a condition in R

# reassign depth values under 10 to zero
df$depth[df$depth<10] <- 0

(For the columns that are factors, you can only assign values that are factor levels. If you wanted to assign a value that wasn't currently a factor level, you would need to create the additional level first:

levels(df$species) <- c(levels(df$species), "unknown") 
df$species[df$depth<10]  <- "unknown" 

python for increment inner loop

I read all the above answers and those are actually good.

look at this code:

for i in range(1, 4):
    print("Before change:", i)
    i = 20 # changing i variable
    print("After change:", i) # this line will always print 20

When we execute above code the output is like below,

Before Change: 1
After change: 20
Before Change: 2
After change: 20
Before Change: 3
After change: 20

in python for loop is not trying to increase i value. for loop is just assign values to i which we gave. Using range(4) what we are doing is we give the values to for loop which need assign to the i.

You can use while loop instead of for loop to do same thing what you want,

i = 0
while i < 6:
    print(i)
    j = 0
    while j < 5:
        i += 2 # to increase `i` by 2

This will give,

0
2
4

Thank you !

How to calculate the number of occurrence of a given character in each row of a column of strings?

The next expression does the job and also works for symbols, not only letters.

The expression works as follows:

1: it uses lapply on the columns of the dataframe q.data to iterate over the rows of the column 2 ("lapply(q.data[,2],"),

2: it apply to each row of the column 2 a function "function(x){sum('a' == strsplit(as.character(x), '')[[1]])}". The function takes each row value of column 2 (x), convert to character (in case it is a factor for example), and it does the split of the string on every character ("strsplit(as.character(x), '')"). As a result we have a a vector with each character of the string value for each row of the column 2.

3: Each vector value of the vector is compared with the desired character to be counted, in this case "a" (" 'a' == "). This operation will return a vector of True and False values "c(True,False,True,....)", being True when the value in the vector matches the desired character to be counted.

4: The total times the character 'a' appears in the row is calculated as the sum of all the 'True' values in the vector "sum(....)".

5: Then it is applied the "unlist" function to unpack the result of the "lapply" function and assign it to a new column in the dataframe ("q.data$number.of.a<-unlist(....")

q.data$number.of.a<-unlist(lapply(q.data[,2],function(x){sum('a' == strsplit(as.character(x), '')[[1]])}))

>q.data

#  number     string     number.of.a
#1   greatgreat         2
#2      magic           1
#3      not             0

What is the difference between Google App Engine and Google Compute Engine?

To put it simply: compute engine gives you a server which you have full control/responsibility for. You have direct access to the operating system, and you install all the software that you want, which is usually a web server, database, etc...

In app engine you don't manage the operating system of any of the underlying software. You only upload code (Java, PHP, Python, or Go) and voila - it just runs...

App engine saves tons of headache, especially for inexperienced people but it has 2 significant drawbacks: 1. more expensive (but it does have a free quota which compute engine doesn't) 2. you have less control, thus certain things are just not possible, or only possible in one specific way (for example saving and writing files).

Best Practices for mapping one object to another

I would opt for AutoMapper, an open source and free mapping library which allows to map one type into another, based on conventions (i.e. map public properties with the same names and same/derived/convertible types, along with many other smart ones). Very easy to use, will let you achieve something like this:

Model model = Mapper.Map<Model>(dto);

Not sure about your specific requirements, but AutoMapper also supports custom value resolvers, which should help you writing a single, generic implementation of your particular mapper.

Create a GUID in Java

It depends what kind of UUID you want.

  • The standard Java UUID class generates Version 4 (random) UUIDs. (UPDATE - Version 3 (name) UUIDs can also be generated.) It can also handle other variants, though it cannot generate them. (In this case, "handle" means construct UUID instances from long, byte[] or String representations, and provide some appropriate accessors.)

  • The Java UUID Generator (JUG) implementation purports to support "all 3 'official' types of UUID as defined by RFC-4122" ... though the RFC actually defines 4 types and mentions a 5th type.

For more information on UUID types and variants, there is a good summary in Wikipedia, and the gory details are in RFC 4122 and the other specifications.

php.ini: which one?

Although Pascal's answer was detailed and informative it failed to mention some key information in the assumption that everyone knows how to use phpinfo()

For those that don't:

Navigate to your webservers root folder such as /var/www/

Within this folder create a text file called info.php

Edit the file and type phpinfo()

Navigate to the file such as: http://www.example.com/info.php

Here you will see the php.ini path under Loaded Configuration File:

phpinfo

Make sure you delete info.php when you are done.

How do I create a URL shortener?

C# version:

public class UrlShortener 
{
    private static String ALPHABET = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
    private static int    BASE     = 62;

    public static String encode(int num)
    {
        StringBuilder sb = new StringBuilder();

        while ( num > 0 )
        {
            sb.Append( ALPHABET[( num % BASE )] );
            num /= BASE;
        }

        StringBuilder builder = new StringBuilder();
        for (int i = sb.Length - 1; i >= 0; i--)
        {
            builder.Append(sb[i]);
        }
        return builder.ToString(); 
    }

    public static int decode(String str)
    {
        int num = 0;

        for ( int i = 0, len = str.Length; i < len; i++ )
        {
            num = num * BASE + ALPHABET.IndexOf( str[(i)] ); 
        }

        return num;
    }   
}

How do I dump an object's fields to the console?

You might find a use for the methods method which returns an array of methods for an object. It's not the same as print_r, but still useful at times.

>> "Hello".methods.sort
=> ["%", "*", "+", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", "[]", "[]=", "__id__", "__send__", "all?", "any?", "between?", "capitalize", "capitalize!", "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "class", "clone", "collect", "concat", "count", "crypt", "delete", "delete!", "detect", "display", "downcase", "downcase!", "dump", "dup", "each", "each_byte", "each_line", "each_with_index", "empty?", "entries", "eql?", "equal?", "extend", "find", "find_all", "freeze", "frozen?", "grep", "gsub", "gsub!", "hash", "hex", "id", "include?", "index", "inject", "insert", "inspect", "instance_eval", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "intern", "is_a?", "is_binary_data?", "is_complex_yaml?", "kind_of?", "length", "ljust", "lstrip", "lstrip!", "map", "match", "max", "member?", "method", "methods", "min", "next", "next!", "nil?", "object_id", "oct", "partition", "private_methods", "protected_methods", "public_methods", "reject", "replace", "respond_to?", "reverse", "reverse!", "rindex", "rjust", "rstrip", "rstrip!", "scan", "select", "send", "singleton_methods", "size", "slice", "slice!", "sort", "sort_by", "split", "squeeze", "squeeze!", "strip", "strip!", "sub", "sub!", "succ", "succ!", "sum", "swapcase", "swapcase!", "taguri", "taguri=", "taint", "tainted?", "to_a", "to_f", "to_i", "to_s", "to_str", "to_sym", "to_yaml", "to_yaml_properties", "to_yaml_style", "tr", "tr!", "tr_s", "tr_s!", "type", "unpack", "untaint", "upcase", "upcase!", "upto", "zip"]

Truncate (not round off) decimal numbers in javascript

The one that is mark as the solution is the better solution I been found until today, but has a serious problem with 0 (for example, 0.toFixedDown(2) gives -0.01). So I suggest to use this:

Number.prototype.toFixedDown = function(digits) {
  if(this == 0) {
    return 0;
  }
  var n = this - Math.pow(10, -digits)/2;
  n += n / Math.pow(2, 53); // added 1360765523: 17.56.toFixedDown(2) === "17.56"
  return n.toFixed(digits);
}

Reading HTTP headers in a Spring REST controller

The error that you get does not seem to be related to the RequestHeader.

And you seem to be confusing Spring REST services with JAX-RS, your method signature should be something like:

@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(@RequestHeader(value="User-Agent") String userAgent, @RequestParam(value = "ID", defaultValue = "") String id) {
    // your code goes here
}

And your REST class should have annotations like:

@Controller
@RequestMapping("/rest/")


Regarding the actual question, another way to get HTTP headers is to insert the HttpServletRequest into your method and then get the desired header from there.

Example:

@RequestMapping(produces = "application/json", method = RequestMethod.GET, value = "data")
@ResponseBody
public ResponseEntity<Data> getData(HttpServletRequest request, @RequestParam(value = "ID", defaultValue = "") String id) {
    String userAgent = request.getHeader("user-agent");
}

Don't worry about the injection of the HttpServletRequest because Spring does that magic for you ;)

Transport endpoint is not connected

There is a segmentation fault problem which was introduced in 0.1.39. You may check my repository that fixed this one in meanwhile: https://github.com/vdudouyt/mhddfs-nosegfault

Accessing Redux state in an action creator?

Presenting an alternative way of solving this. This may be better or worse than Dan's solution, depending on your application.

You can get the state from the reducers into the actions by splitting the action in 2 separate functions: first ask for the data, second act on the data. You can do that by using redux-loop.

First 'kindly ask for the data'

export const SOME_ACTION = 'SOME_ACTION';
export function someAction() {
    return {
        type: SOME_ACTION,
    }
}

In the reducer, intercept the ask and provide the data to the second stage action by using redux-loop.

import { loop, Cmd } from 'redux-loop';
const initialState = { data: '' }
export default (state=initialState, action) => {
    switch(action.type) {
        case SOME_ACTION: {
            return loop(state, Cmd.action(anotherAction(state.data))
        }
    }
}

With the data in hand, do whatever you initially wanted

export const ANOTHER_ACTION = 'ANOTHER_ACTION';
export function anotherAction(data) {
    return {
        type: ANOTHER_ACTION,
        payload: data,
    }
}

Hope this helps someone.

Auto code completion on Eclipse

Use the Ctrl+Space shortcut for getting all possible autocomplete options available in a particular context in the editor.

Auto Complete will also allow you to insert custom code templates into the editor, with placeholders for various inputs. For instance, attempting to auto complete the word "test" in a Java editor, in the context of a class body, will allow you to create a unit test that uses JUnit; you'll have to code the body of the method though. Some code templates like the former, come out of the box.

Configuration options of interest

  • Auto-activation delay. If the list of auto complete options is taking too long to appear, the delay can be reduced from Windows -> Preferences -> Java -> Editor -> Content Assist -> Auto Activation delay (specify the reduced delay here).
  • Auto activation trigger for Java. Accessible in the same pane, this happens to be the . character by default. When you have just keyed in typeA. and you expect to see relevant members that can be accessed, the auto completion list will automatically popup with the appropriate members, on this trigger.
  • Proposal types. If you do not want to see proposals of a particular variety, you can disable them from Windows -> Preferences -> Java -> Editor -> Content Assist -> Advanced. I typically switch off proposals of most kinds except Java and Template proposals. Hitting Ctrl+Space multiple times will cycle you through proposals of various kinds.
  • Template Proposals. These are different from your run of the mill proposals. You could add your code templates in here; it can be accessed from Windows -> Preferences -> Java -> Editor -> Templates. Configuration of existing templates is allowed and so is addition of new ones. Reserve usage however for the tedious typing tasks that do not have a template yet.

Why do we usually use || over |? What is the difference?

There are many use cases suggesting why should you go for || rather than | . Some use cases have to use | operator to check all the conditions.

For example, if you want to check form validation and you want to show the user all the invalid fields with error texts rather than just a first invalid field.

|| operator would be,

   if(checkIfEmpty(nameField) || checkIfEmpty(phoneField) || checkIfEmpty(emailField)) {
      // invalid form with one or more empty fields
   }

   private boolean checkIfEmpty(Widget field) {
      if(field.isEmpty()) {
        field.setErrorMessage("Should not be empty!");
        return true;
      }
      return false;
   }

So with above snippet, if user submits the form with ALL empty fields, ONLY nameField would be shown with error message. But, if you change it to,

   if(checkIfEmpty(nameField) | checkIfEmpty(phoneField) | checkIfEmpty(emailField)) {
      // invalid form with one or more empty fields
   }

It will show proper error message on the each field irrespective of true conditions.

Event listener for when element becomes visible?

If you just want to run some code when an element becomes visible in the viewport:

function onVisible(element, callback) {
  new IntersectionObserver((entries, observer) => {
    entries.forEach(entry => {
      if(entry.intersectionRatio > 0) {
        callback(element);
        observer.disconnect();
      }
    });
  }).observe(element);
}

When the element has become visible the intersection observer calls callback and then destroys itself with .disconnect().

Use it like this:

onVisible(document.querySelector("#myElement"), () => console.log("it's visible"));

Counter increment in Bash loop not working

There were two conditions that caused the expression ((var++)) to fail for me:

  1. If I set bash to strict mode (set -euo pipefail) and if I start my increment at zero (0).

  2. Starting at one (1) is fine but zero causes the increment to return "1" when evaluating "++" which is a non-zero return code failure in strict mode.

I can either use ((var+=1)) or var=$((var+1)) to escape this behavior

jQuery: more than one handler for same event

You should be able to use chaining to execute the events in sequence, e.g.:

$('#target')
  .bind('click',function(event) {
    alert('Hello!');
  })
  .bind('click',function(event) {
    alert('Hello again!');
  })
  .bind('click',function(event) {
    alert('Hello yet again!');
  });

I guess the below code is doing the same

$('#target')
      .click(function(event) {
        alert('Hello!');
      })
      .click(function(event) {
        alert('Hello again!');
      })
      .click(function(event) {
        alert('Hello yet again!');
      });

Source: http://www.peachpit.com/articles/article.aspx?p=1371947&seqNum=3

TFM also says:

When an event reaches an element, all handlers bound to that event type for the element are fired. If there are multiple handlers registered, they will always execute in the order in which they were bound. After all handlers have executed, the event continues along the normal event propagation path.

python variable NameError

Initialize tSize to

tSize = ""  

before your if block to be safe. Also in your else case, put tSize in quotes so it is a string not an int. Also also you are comparing strings to ints.

LINQ Using Max() to select a single row

More one example:

Follow:

 qryAux = (from q in qryAux where
            q.OrdSeq == (from pp in Sessao.Query<NameTable>() where pp.FieldPk
            == q.FieldPk select pp.OrdSeq).Max() select q);

Equals:

 select t.*   from nametable t  where t.OrdSeq =
        (select max(t2.OrdSeq) from nametable t2 where t2.FieldPk= t.FieldPk)

How would I check a string for a certain letter in Python?

If you want a version that raises an error:

"string to search".index("needle") 

If you want a version that returns -1:

"string to search".find("needle") 

This is more efficient than the 'in' syntax

How to loop over a Class attributes in Java?

There is no linguistic support to do what you're asking for.

You can reflectively access the members of a type at run-time using reflection (e.g. with Class.getDeclaredFields() to get an array of Field), but depending on what you're trying to do, this may not be the best solution.

See also

Related questions


Example

Here's a simple example to show only some of what reflection is capable of doing.

import java.lang.reflect.*;

public class DumpFields {
    public static void main(String[] args) {
        inspect(String.class);
    }
    static <T> void inspect(Class<T> klazz) {
        Field[] fields = klazz.getDeclaredFields();
        System.out.printf("%d fields:%n", fields.length);
        for (Field field : fields) {
            System.out.printf("%s %s %s%n",
                Modifier.toString(field.getModifiers()),
                field.getType().getSimpleName(),
                field.getName()
            );
        }
    }
}

The above snippet uses reflection to inspect all the declared fields of class String; it produces the following output:

7 fields:
private final char[] value
private final int offset
private final int count
private int hash
private static final long serialVersionUID
private static final ObjectStreamField[] serialPersistentFields
public static final Comparator CASE_INSENSITIVE_ORDER

Effective Java 2nd Edition, Item 53: Prefer interfaces to reflection

These are excerpts from the book:

Given a Class object, you can obtain Constructor, Method, and Field instances representing the constructors, methods and fields of the class. [They] let you manipulate their underlying counterparts reflectively. This power, however, comes at a price:

  • You lose all the benefits of compile-time checking.
  • The code required to perform reflective access is clumsy and verbose.
  • Performance suffers.

As a rule, objects should not be accessed reflectively in normal applications at runtime.

There are a few sophisticated applications that require reflection. Examples include [...omitted on purpose...] If you have any doubts as to whether your application falls into one of these categories, it probably doesn't.

how to add lines to existing file using python

If you want to append to the file, open it with 'a'. If you want to seek through the file to find the place where you should insert the line, use 'r+'. (docs)

How can I indent multiple lines in Xcode?

Shortcut key:

ctrl + i

NOTE: Please select codes to Re-indent and press 'control' and 'i' on your mac.

How to fix this Error: #include <gl/glut.h> "Cannot open source file gl/glut.h"

Visual Studio Community 2017

Go here : C:\Program Files (x86)\Windows Kits\10

and do whatever you were supposed to go in the given directory for VS 13.

in the lib folder, you will find some versions, I copied the 32-bit glut.lib files in amd and x86 and 64-bit glut.lib in arm64 and x64 directories in um folder for every version that I could find.

That worked for me.

EDIT : I tried this in windows 10, maybe you need to go to C:\Program Files (x86)\Windows Kits\8.1 folder for windows 8/8.1.

MySQL Select all columns from one table and some from another table

I need more information really but it will be along the lines of..

SELECT table1.*, table2.col1, table2.col3 FROM table1 JOIN table2 USING(id)

How to align a div to the top of its parent but keeping its inline-block behaviour?

Or you could just add some content to the div and use inline-table

Task vs Thread differences

Usually you hear Task is a higher level concept than thread... and that's what this phrase means:

  1. You can't use Abort/ThreadAbortedException, you should support cancel event in your "business code" periodically testing token.IsCancellationRequested flag (also avoid long or timeoutless connections e.g. to db, otherwise you will never get a chance to test this flag). By the similar reason Thread.Sleep(delay) call should be replaced with Task.Delay(delay, token) call (passing token inside to have possibility to interrupt delay).

  2. There are no thread's Suspend and Resume methods functionality with tasks. Instance of task can't be reused either.

  3. But you get two new tools:

    a) continuations

    // continuation with ContinueWhenAll - execute the delegate, when ALL
    // tasks[] had been finished; other option is ContinueWhenAny
    
    Task.Factory.ContinueWhenAll( 
       tasks,
       () => {
           int answer = tasks[0].Result + tasks[1].Result;
           Console.WriteLine("The answer is {0}", answer);
       }
    );
    

    b) nested/child tasks

    //StartNew - starts task immediately, parent ends whith child
    var parent = Task.Factory.StartNew
    (() => {
              var child = Task.Factory.StartNew(() =>
             {
             //...
             });
          },  
          TaskCreationOptions.AttachedToParent
    );
    
  4. So system thread is completely hidden from task, but still task's code is executed in the concrete system thread. System threads are resources for tasks and ofcourse there is still thread pool under the hood of task's parallel execution. There can be different strategies how thread get new tasks to execute. Another shared resource TaskScheduler cares about it. Some problems that TaskScheduler solves 1) prefer to execute task and its conitnuation in the same thread minimizing switching cost - aka inline execution) 2) prefer execute tasks in an order they were started - aka PreferFairness 3) more effective distribution of tasks between inactive threads depending on "prior knowledge of tasks activity" - aka Work Stealing. Important: in general "async" is not same as "parallel". Playing with TaskScheduler options you can setup async tasks be executed in one thread synchronously. To express parallel code execution higher abstractions (than Tasks) could be used: Parallel.ForEach, PLINQ, Dataflow.

  5. Tasks are integrated with C# async/await features aka Promise Model, e.g there requestButton.Clicked += async (o, e) => ProcessResponce(await client.RequestAsync(e.ResourceName)); the execution of client.RequestAsync will not block UI thread. Important: under the hood Clicked delegate call is absolutely regular (all threading is done by compiler).

That is enough to make a choice. If you need to support Cancel functionality of calling legacy API that tends to hang (e.g. timeoutless connection) and for this case supports Thread.Abort(), or if you are creating multithread background calculations and want to optimize switching between threads using Suspend/Resume, that means to manage parallel execution manually - stay with Thread. Otherwise go to Tasks because of they will give you easy manipulate on groups of them, are integrated into the language and make developers more productive - Task Parallel Library (TPL) .

How do you convert CString and std::string std::wstring to each other?

Solve that by using std::basic_string<TCHAR> instead of std::string and it should work fine regardless of your character setting.

What is the difference between H.264 video and MPEG-4 video?

H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance application

H264 is now enshrined in MPEG4 as part 10 also known as AVC

Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf

Hope this helps.

How can we convert an integer to string in AngularJs

.toString() is available, or just add "" to the end of the int

var x = 3,
    toString = x.toString(),
    toConcat = x + "";

Angular is simply JavaScript at the core.

expected constructor, destructor, or type conversion before ‘(’ token

This is not only a 'newbie' scenario. I just ran across this compiler message (GCC 5.4) when refactoring a class to remove some constructor parameters. I forgot to update both the declaration and definition, and the compiler spit out this unintuitive error.

The bottom line seems to be this: If the compiler can't match the definition's signature to the declaration's signature it thinks the definition is not a constructor and then doesn't know how to parse the code and displays this error. Which is also what happened for the OP: std::string is not the same type as string so the declaration's signature differed from the definition's and this message was spit out.

As a side note, it would be nice if the compiler looked for almost-matching constructor signatures and upon finding one suggested that the parameters didn't match rather than giving this message.

Save array in mysql database

You can store the array using serialize/unserialize. With that solution they cannot easily be used from other programming languages, so you may consider using json_encode/json_decode instead (which gives you a widely supported format). Avoid using implode/explode for this since you'll probably end up with bugs or security flaws.

Note that this makes your table non-normalized, which may be a bad idea since you cannot easily query the data. Therefore consider this carefully before going forward. May you need to query the data for statistics or otherwise? Are there other reasons to normalize the data?

Also, don't save the raw $_POST array. Someone can easily make their own web form and post data to your site, thereby sending a really large form which takes up lots of space. Save those fields you want and make sure to validate the data before saving it (so you won't get invalid values).

How do you check if a JavaScript Object is a DOM Object?

old thread, but here's an updated possibility for ie8 and ff3.5 users:

function isHTMLElement(o) {
    return (o.constructor.toString().search(/\object HTML.+Element/) > -1);
}

How do I get the MAX row with a GROUP BY in LINQ query?

var q = from s in db.Serials
        group s by s.Serial_Number into g
        select new {Serial_Number = g.Key, MaxUid = g.Max(s => s.uid) }

How to reset sequence in postgres and fill id column with new data?

To retain order of the rows:

UPDATE thetable SET rowid=col_serial FROM 
(SELECT rowid, row_number() OVER ( ORDER BY lngid) AS col_serial FROM thetable ORDER BY lngid) AS t1 
WHERE thetable.rowid=t1.rowid;

MySQL 1062 - Duplicate entry '0' for key 'PRIMARY'

this step work perfectly for me.. you can try it

  1. Add indexing
  2. Add Autoincrement
  3. Add Primary Key

hope it work for you too. good luck

Regular expression - starting and ending with a character string

^wp.*\.php$ Should do the trick.

The .* means "any character, repeated 0 or more times". The next . is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.

How to test valid UUID/GUID?

Use the .match() method to check whether String is UUID.

public boolean isUUID(String s){
    return s.match("^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$");
}

How to delete history of last 10 commands in shell?

Short but sweet: for i in {1..10}; do history -d $(($HISTCMD-11)); done

How to set minDate to current date in jQuery UI Datepicker?

You can specify minDate as today by adding minDate: 0 to the options.

$("input.DateFrom").datepicker({
    minDate: 0,
    ...
});

Demo: http://jsfiddle.net/2CZtV/

Docs: http://jqueryui.com/datepicker/#min-max

Expected response code 220 but got code "", with message "" in Laravel

This problem can generally occur when you do not enable two step verification for the gmail account (which can be done here) you are using to send an email. So first, enable two step verification, you can find plenty of resources for enabling two step verification. After you enable it, then you have to create an app password. And use the app password in your .env file. When you are done with it, your .env file will look something like.

MAIL_DRIVER=smtp
MAIL_HOST=smtp.gmail.com
MAIL_PORT=587
MAIL_USERNAME=<<your email address>>
MAIL_PASSWORD=<<app password>>
MAIL_ENCRYPTION=tls

and your mail.php

<?php

return [
    'driver' => env('MAIL_DRIVER', 'smtp'),
    'host' => env('MAIL_HOST', 'smtp.gmail.com'),
    'port' => env('MAIL_PORT', 587),
    'from' => ['address' => '<<your email>>', 'name' => '<<any name>>'],
    'encryption' => env('MAIL_ENCRYPTION', 'tls'),
    'username' => env('MAIL_USERNAME'),
    'password' => env('MAIL_PASSWORD'),
    'sendmail' => '/usr/sbin/sendmail -bs',
    'pretend' => false,

];

After doing so, run php artisan config:cache and php artisan config:clear, then check, email should work.

Use :hover to modify the css of another class?

You can do this.
When hovering to the .item1, it will change the .item2 element.

.item1 {
  size:100%;
}

.item1:hover
{
   .item2 {
     border:none;
   }
}

.item2{
  border: solid 1px blue;
}

Using the RUN instruction in a Dockerfile with 'source' does not work

I also had issues in running source in a Dockerfile

This runs perfectly fine for building CentOS 6.6 Docker container, but gave issues in Debian containers

RUN cd ansible && source ./hacking/env-setup

This is how I tackled it, may not be an elegant way but this is what worked for me

RUN echo "source /ansible/hacking/env-setup" >> /tmp/setup
RUN /bin/bash -C "/tmp/setup"
RUN rm -f /tmp/setup

Total size of the contents of all the files in a directory

If you want the 'apparent size' (that is the number of bytes in each file), not size taken up by files on the disk, use the -b or --bytes option (if you got a Linux system with GNU coreutils):

% du -sbh <directory>

Asp.net Validation of viewstate MAC failed

On multi-server environment, this error likely occurs when session expires and another instance of an application is resorted with same session id and machine key but on a different server. At first, each server produce its own machine key which later is associated with a single instance of an application. When session expires and current server is busy, the application is redirected like, via load balancer to a more operational server. In my case I run same app from multiple servers, the error message:

Validation of viewstate MAC failed. If this application is hosted by a Web Farm or cluster, ensure that configuration specifies the same validationKey and validation algorithm

Defining the machine code under in web.config have solve the problem. But instead of using 3rd party sites for code generation which might be corrupted, please run this from your command shell: Based on microsoft solution 1a, https://support.microsoft.com/en-us/kb/2915218#AppendixA

# Generates a <machineKey> element that can be copied + pasted into a Web.config file.
function Generate-MachineKey {
  [CmdletBinding()]
  param (
    [ValidateSet("AES", "DES", "3DES")]
    [string]$decryptionAlgorithm = 'AES',
    [ValidateSet("MD5", "SHA1", "HMACSHA256", "HMACSHA384", "HMACSHA512")]
    [string]$validationAlgorithm = 'HMACSHA256'
  )
  process {
    function BinaryToHex {
        [CmdLetBinding()]
        param($bytes)
        process {
            $builder = new-object System.Text.StringBuilder
            foreach ($b in $bytes) {
              $builder = $builder.AppendFormat([System.Globalization.CultureInfo]::InvariantCulture, "{0:X2}", $b)
            }
            $builder
        }
    }
    switch ($decryptionAlgorithm) {
      "AES" { $decryptionObject = new-object System.Security.Cryptography.AesCryptoServiceProvider }
      "DES" { $decryptionObject = new-object System.Security.Cryptography.DESCryptoServiceProvider }
      "3DES" { $decryptionObject = new-object System.Security.Cryptography.TripleDESCryptoServiceProvider }
    }
    $decryptionObject.GenerateKey()
    $decryptionKey = BinaryToHex($decryptionObject.Key)
    $decryptionObject.Dispose()
    switch ($validationAlgorithm) {
      "MD5" { $validationObject = new-object System.Security.Cryptography.HMACMD5 }
      "SHA1" { $validationObject = new-object System.Security.Cryptography.HMACSHA1 }
      "HMACSHA256" { $validationObject = new-object System.Security.Cryptography.HMACSHA256 }
      "HMACSHA385" { $validationObject = new-object System.Security.Cryptography.HMACSHA384 }
      "HMACSHA512" { $validationObject = new-object System.Security.Cryptography.HMACSHA512 }
    }
    $validationKey = BinaryToHex($validationObject.Key)
    $validationObject.Dispose()
    [string]::Format([System.Globalization.CultureInfo]::InvariantCulture,
      "<machineKey decryption=`"{0}`" decryptionKey=`"{1}`" validation=`"{2}`" validationKey=`"{3}`" />",
      $decryptionAlgorithm.ToUpperInvariant(), $decryptionKey,
      $validationAlgorithm.ToUpperInvariant(), $validationKey)
  }
}

Then:

For ASP.NET 4.0

Generate-MachineKey

Your key will look like: <machineKey decryption="AES" decryptionKey="..." validation="HMACSHA256" validationKey="..." />

For ASP.NET 2.0 and 3.5

Generate-MachineKey -validation sha1

Your key will look like: <machineKey decryption="AES" decryptionKey="..." validation="SHA1" validationKey="..." />

How to redirect to the same page in PHP

A quick easy approach if you are not concerned about query params:

header("location: ./");

Mysql 1050 Error "Table already exists" when in fact, it does not

In my case the problem was that there was a view with the same name as my table, so I had to drop the view to allow the import to continue.

drop view `my-view-that-has-same-name-as-table`;

An automated solution that worked for me is to replace the normal drop table with this sed during the dump to also drop any views that might exist:

mysqldump my-db \
| sed -E 's/^DROP TABLE IF EXISTS(.+)$/\0 DROP VIEW IF EXISTS\1/g' \
| mysql my-other-db

Or if you would rather print to a file for backup

mysqldump my-db \
| sed -E 's/^DROP TABLE IF EXISTS(.+)$/\0 DROP VIEW IF EXISTS\1/g' \
> my-db.dump.sql

Or if you received the dumped file and you are importing it to your db

cat my-db.dump.sql \
| sed -E 's/^DROP TABLE IF EXISTS(.+)$/\0 DROP VIEW IF EXISTS\1/g' \
| mysql my-other-db

You get the idea

Note: it is important that you add the ^ at the beginning of the replacement regex, because there are other types of DROP TABLE IF EXISTS commands in dumps that you don't want to touch.

You go from having something like this:

--
-- Table structure for table `my_table`
--

DROP TABLE IF EXISTS `my_table`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `my_table` (
...

To having something like this:

--
-- Table structure for table `my_table`
--

DROP TABLE IF EXISTS `my_table`; DROP VIEW IF EXISTS `my_table`;
/*!40101 SET @saved_cs_client     = @@character_set_client */;
/*!40101 SET character_set_client = utf8 */;
CREATE TABLE `my_table` (
...

How to change xampp localhost to another folder ( outside xampp folder)?

It can be done in two steps for Ubuntu 14.04 with Xampp 1.8.3-5

Step 1:- Change DocumentRoot and Directory path in /opt/lampp/etc/httpd.conf from

DocumentRoot "/opt/lampp/htdocs" and Directory "/opt/lampp/htdocs"

to DocumentRoot "/home/user/Desktop/js" and Directory "/home/user/Desktop/js"

Step 2:- Change the rights of folder (in path and its parent folders to 777) eg via

sudo chmod -R 777 /home/user/Desktop/js

Most efficient way to concatenate strings?

Try this 2 pieces of code and you will find the solution.

 static void Main(string[] args)
    {
        StringBuilder s = new StringBuilder();
        for (int i = 0; i < 10000000; i++)
        {
            s.Append( i.ToString());
        }
        Console.Write("End");
        Console.Read();
    }

Vs

static void Main(string[] args)
    {
        string s = "";
        for (int i = 0; i < 10000000; i++)
        {
            s += i.ToString();
        }
        Console.Write("End");
        Console.Read();
    }

You will find that 1st code will end really quick and the memory will be in a good amount.

The second code maybe the memory will be ok, but it will take longer... much longer. So if you have an application for a lot of users and you need speed, use the 1st. If you have an app for a short term one user app, maybe you can use both or the 2nd will be more "natural" for developers.

Cheers.

How to find the highest value of a column in a data frame in R?

There is a package matrixStats that provides some functions to do column and row summaries, see in the package vignette, but you have to convert your data.frame into a matrix.

Then you run: colMaxs(as.matrix(ozone))

How to convert JSON to string?

Try to Use JSON.stringify

Regards

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

The regex you're looking for is ^[A-Za-z.\s_-]+$

  • ^ asserts that the regular expression must match at the beginning of the subject
  • [] is a character class - any character that matches inside this expression is allowed
  • A-Z allows a range of uppercase characters
  • a-z allows a range of lowercase characters
  • . matches a period rather than a range of characters
  • \s matches whitespace (spaces and tabs)
  • _ matches an underscore
  • - matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-) instead and put it anywhere in the character class, but that's less clear
  • + asserts that the preceding expression (in our case, the character class) must match one or more times
  • $ Finally, this asserts that we're now at the end of the subject

When you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.

Android Studio 3.0 Flavor Dimension Issue

If you don't really need the mechanism, just specify a random flavor dimension in your build.gradle:

android { 
    ...
    flavorDimensions "default"
    ...
}

For more information, check the migration guide

Printing Python version in output

import platform
print(platform.python_version())

This prints something like

3.7.2

How to logout and redirect to login page using Laravel 5.4?

In 5.5

adding

Route::get('logout', 'Auth\LoginController@logout');

to my routes file works fine.

How to set viewport meta for iPhone that handles rotation properly?

Was just trying to work this out myself, and the solution I came up with was:

<meta name="viewport" content="initial-scale = 1.0,maximum-scale = 1.0" />

This seems to lock the device into 1.0 scale regardless of it's orientation. As a side effect, it does however completely disable user scaling (pinch zooming, etc).

Sound alarm when code finishes

import subprocess

subprocess.call(['D:\greensoft\TTPlayer\TTPlayer.exe', "E:\stridevampaclip.mp3"])

How different is Scrum practice from Agile Practice?

Agile is a platform and scrum is a methodology to follow. Scrum recommends certain practices to be followed. Some of the basic scrum practices are following.

  • Fixed length Scrum/Releases.
  • Suggested meeting Structures (Release planning meeting, Sprint planning meeting, Sprint Review and Sprint Retrospective meetings)
  • Scrum also recommends roles. Following are the roles recommended by Scrum.

     - Scrum Master
     - Developer Team
     - Product Owner
    

The Scrum, just like other Agile methodologies follow iterative approach.

Following are some other Agile methodologies.

  • Extreme Programming.
  • Agile unified process
  • Dynamic System Development Method (DSDM)
  • Feature Driven Development (FDD)
  • Lean Software Development
  • Kanban
  • Scrum-ban

There are many scrum tool in the market. Yodiz is one of them that we use.

What's the most concise way to read query parameters in AngularJS?

To give a partial answer my own question, here is a working sample for HTML5 browsers:

<!DOCTYPE html>
<html ng-app="myApp">
<head>
  <script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
  <script>
    angular.module('myApp', [], function($locationProvider) {
      $locationProvider.html5Mode(true);
    });
    function QueryCntl($scope, $location) {
      $scope.target = $location.search()['target'];
    }
  </script>
</head>
<body ng-controller="QueryCntl">

Target: {{target}}<br/>

</body>
</html>

The key was to call $locationProvider.html5Mode(true); as done above. It now works when opening http://127.0.0.1:8080/test.html?target=bob. I'm not happy about the fact that it won't work in older browsers, but I might use this approach anyway.

An alternative that would work with older browsers would be to drop the html5mode(true) call and use the following address with hash+slash instead:

http://127.0.0.1:8080/test.html#/?target=bob

The relevant documentation is at Developer Guide: Angular Services: Using $location (strange that my google search didn't find this...).

Injection of autowired dependencies failed;

The error shows that com.bd.service.ArticleService is not a registered bean. Add the packages in which you have beans that will be autowired in your application context:

<context:component-scan base-package="com.bd.service"/>
<context:component-scan base-package="com.bd.controleur"/>

Alternatively, if you want to include all subpackages in com.bd:

<context:component-scan base-package="com.bd">
     <context:include-filter type="aspectj" expression="com.bd.*" />
</context:component-scan>

As a side note, if you're using Spring 3.1 or later, you can take advantage of the @ComponentScan annotation, so that you don't have to use any xml configuration regarding component-scan. Use it in conjunction with @Configuration.

@Controller
@RequestMapping("/Article/GererArticle")
@Configuration
@ComponentScan("com.bd.service") // No need to include component-scan in xml
public class ArticleControleur {

    @Autowired
    ArticleService articleService;
    ...
}

You might find this Spring in depth section on Autowiring useful.

How to check if a variable is null or empty string or all whitespace in JavaScript?

Old question, but I think it deservers a simpler answer.

You can simply do:

var addr = "  ";

if (addr && addr.trim()) {

    console.log("I'm not null, nor undefined, nor empty string, nor string composed of whitespace only.");

}

Entity Framework Code First - two Foreign Keys from same table

InverseProperty in EF Core makes the solution easy and clean.

InverseProperty

So the desired solution would be:

public class Team
{
    [Key]
    public int TeamId { get; set;} 
    public string Name { get; set; }

    [InverseProperty(nameof(Match.HomeTeam))]
    public ICollection<Match> HomeMatches{ get; set; }

    [InverseProperty(nameof(Match.GuestTeam))]
    public ICollection<Match> AwayMatches{ get; set; }
}


public class Match
{
    [Key]
    public int MatchId { get; set; }

    [ForeignKey(nameof(HomeTeam)), Column(Order = 0)]
    public int HomeTeamId { get; set; }
    [ForeignKey(nameof(GuestTeam)), Column(Order = 1)]
    public int GuestTeamId { get; set; }

    public float HomePoints { get; set; }
    public float GuestPoints { get; set; }
    public DateTime Date { get; set; }

    public Team HomeTeam { get; set; }
    public Team GuestTeam { get; set; }
}

Laravel 5.1 API Enable Cors

Here is my CORS middleware:

<?php namespace App\Http\Middleware;

use Closure;

class CORS {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

}

To use CORS middleware you have to register it first in your app\Http\Kernel.php file like this:

protected $routeMiddleware = [
        //other middlewares
        'cors' => 'App\Http\Middleware\CORS',
    ];

Then you can use it in your routes

Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));

gpg: no valid OpenPGP data found

I also got the same error. I've referred to the below mentioned link and ran this commands

gpg --import fails with no valid OpenPGP data found

gpg --import KEYS
sudo apt-get update

It worked.

I'm using Ubuntu version 12.04

Why can a function modify some arguments as perceived by the caller, but not others?

f doesn't actually alter the value of x (which is always the same reference to an instance of a list). Rather, it alters the contents of this list.

In both cases, a copy of a reference is passed to the function. Inside the function,

  • n gets assigned a new value. Only the reference inside the function is modified, not the one outside it.
  • x does not get assigned a new value: neither the reference inside nor outside the function are modified. Instead, x’s value is modified.

Since both the x inside the function and outside it refer to the same value, both see the modification. By contrast, the n inside the function and outside it refer to different values after n was reassigned inside the function.

Port 80 is being used by SYSTEM (PID 4), what is that?

This wouldn't explain the PID side of things, but if you run Skype, it likes to use Port 80 for some reason.

IF EXISTS, THEN SELECT ELSE INSERT AND THEN SELECT

It sounds like your table has no key. You should be able to simply try the INSERT: if it’s a duplicate then the key constraint will bite and the INSERT will fail. No worries: you just need to ensure the application doesn't see/ignores the error. When you say 'primary key' you presumably mean IDENTITY value. That's all very well but you also need a key constraint (e.g. UNIQUE) on your natural key.

Also, I wonder whether your procedure is doing too much. Consider having separate procedures for 'create' and 'read' actions respectively.

How can I rename a field for all documents in MongoDB?

You can use:

db.foo.update({}, {$rename:{"name.additional":"name.last"}}, false, true);

Or to just update the docs which contain the property:

db.foo.update({"name.additional": {$exists: true}}, {$rename:{"name.additional":"name.last"}}, false, true);

The false, true in the method above are: { upsert:false, multi:true }. You need the multi:true to update all your records.

Or you can use the former way:

remap = function (x) {
  if (x.additional){
    db.foo.update({_id:x._id}, {$set:{"name.last":x.name.additional}, $unset:{"name.additional":1}});
  }
}

db.foo.find().forEach(remap);

In MongoDB 3.2 you can also use

db.students.updateMany( {}, { $rename: { "oldname": "newname" } } )

The general syntax of this is

db.collection.updateMany(filter, update, options)

https://docs.mongodb.com/manual/reference/method/db.collection.updateMany/

Visual studio - getting error "Metadata file 'XYZ' could not be found" after edit continue

Close VS, locate and remove the 'packages' folder from outside of visual studio. Restart VS and build -> all dependencies are reinstalled

How to use Git Revert

The question is quite old but revert is still confusing people (like me)

As a beginner, after some trial and error (more errors than trials) I've got an important point:

  • git revert requires the id of the commit you want to remove keeping it into your history

  • git reset requires the commit you want to keep, and will consequentially remove anything after that from history.

That is, if you use revert with the first commit id, you'll find yourself into an empty directory and an additional commit in history, while with reset your directory will be.. reverted back to the initial commit and your history will get as if the last commit(s) never happened.

To be even more clear, with a log like this:

# git log --oneline

cb76ee4 wrong
01b56c6 test
2e407ce first commit

Using git revert cb76ee4 will by default bring your files back to 01b56c6 and will add a further commit to your history:

8d4406b Revert "wrong"
cb76ee4 wrong
01b56c6 test
2e407ce first commit

git reset 01b56c6 will instead bring your files back to 01b56c6 and will clean up any other commit after that from your history :

01b56c6 test
2e407ce first commit

I know these are "the basis" but it was quite confusing for me, by running revert on first id ('first commit') I was expecting to find my initial files, it taken a while to understand, that if you need your files back as 'first commit' you need to use the next id.

"replace" function examples

If you look at the function (by typing it's name at the console) you will see that it is just a simple functionalized version of the [<- function which is described at ?"[". [ is a rather basic function to R so you would be well-advised to look at that page for further details. Especially important is learning that the index argument (the second argument in replace can be logical, numeric or character classed values. Recycling will occur when there are differing lengths of the second and third arguments:

You should "read" the function call as" "within the first argument, use the second argument as an index for placing the values of the third argument into the first":

> replace( 1:20, 10:15, 1:2)
 [1]  1  2  3  4  5  6  7  8  9  1  2  1  2  1  2 16 17 18 19 20

Character indexing for a named vector:

> replace(c(a=1, b=2, c=3, d=4), "b", 10)
 a  b  c  d 
 1 10  3  4 

Logical indexing:

> replace(x <- c(a=1, b=2, c=3, d=4), x>2, 10)
 a  b  c  d 
 1  2 10 10 

How to get a JavaScript object's class?

Question seems already answered but the OP wants to access the class of and object, just like we do in Java and the selected answer is not enough (imho).

With the following explanation, we can get a class of an object(it's actually called prototype in javascript).

var arr = new Array('red', 'green', 'blue');
var arr2 = new Array('white', 'black', 'orange');

You can add a property like this:

Object.defineProperty(arr,'last', {
  get: function(){
    return this[this.length -1];
  }
});
console.log(arr.last) // blue

But .last property will only be available to 'arr' object which is instantiated from Array prototype. So, in order to have the .last property to be available for all objects instantiated from Array prototype, we have to define the .last property for Array prototype:

Object.defineProperty(Array.prototype,'last', {
  get: function(){
    return this[this.length -1];
  }
});
console.log(arr.last) // blue
console.log(arr2.last) // orange

The problem here is, you have to know which object type (prototype) the 'arr' and 'arr2' variables belongs to! In other words, if you don't know class type (prototype) of the 'arr' object, then you won't be able to define a property for them. In the above example, we know arr is instance of the Array object, that's why we used Array.prototype to define a property for Array. But what if we didn't know the class(prototype) of the 'arr'?

Object.defineProperty(arr.__proto__,'last2', {
  get: function(){
    return this[this.length -1];
  }
});
console.log(arr.last) // blue
console.log(arr2.last) // orange

As you can see, without knowing that 'arr' is an Array, we can add a new property just bu referring the class of the 'arr' by using 'arr.__proto__'.

We accessed the prototype of the 'arr' without knowing that it's an instance of Array and I think that's what OP asked.

How to split strings over multiple lines in Bash?

You can use bash arrays

$ str_array=("continuation"
             "lines")

then

$ echo "${str_array[*]}"
continuation lines

there is an extra space, because (after bash manual):

If the word is double-quoted, ${name[*]} expands to a single word with the value of each array member separated by the first character of the IFS variable

So set IFS='' to get rid of extra space

$ IFS=''
$ echo "${str_array[*]}"
continuationlines

How to disable Paste (Ctrl+V) with jQuery?

This now works for IE FF Chrome properly... I have not tested for other browsers though

$(document).ready(function(){
   $('#txtInput').on("cut copy paste",function(e) {
      e.preventDefault();
   });
});

Edit: As pointed out by webeno, .bind() is deprecated hence it is recommended to use .on() instead.

Finding current executable's path without /proc/self/exe

But I'd like to know if there is a convenient way to find the current application's directory in C/C++ with cross-platform interfaces.

You cannot do that (at least on Linux)

Since an executable could, during execution of a process running it, rename(2) its file path to a different directory (of the same file system). See also syscalls(2) and inode(7).

On Linux, an executable could even (in principle) remove(3) itself by calling unlink(2). The Linux kernel should then keep the file allocated till no process references it anymore. With proc(5) you could do weird things (e.g. rename(2) that /proc/self/exe file, etc...)

In other words, on Linux, the notion of a "current application's directory" does not make any sense.

Read also Advanced Linux Programming and Operating Systems: Three Easy Pieces for more.

Look also on OSDEV for several open source operating systems (including FreeBSD or GNU Hurd). Several of them provide an interface (API) close to POSIX ones.

Consider using (with permission) cross-platform C++ frameworks like Qt or POCO, perhaps contributing to them by porting them to your favorite OS.

How to Update/Drop a Hive Partition?

Alter table table_name drop partition (partition_name);

React Router Pass Param to Component

Since react-router v5.1 with hooks:

import { useParams } from 'react-router';

export default function DetailsPage() {
  const { id } = useParams();
}

See https://reacttraining.com/blog/react-router-v5-1/

Starting Docker as Daemon on Ubuntu

I had a same issue on ubuntu 14.04 Here is a solution

sudo service docker start

or you can list images

docker images

Format an Excel column (or cell) as Text in C#?

Below is some code to format columns A and C as text in SpreadsheetGear for .NET which has an API which is similar to Excel - except for the fact that SpreadsheetGear is frequently more strongly typed. It should not be too hard to figure out how to convert this to work with Excel / COM:

IWorkbook workbook = Factory.GetWorkbook();
IRange cells = workbook.Worksheets[0].Cells;
// Format column A as text.
cells["A:A"].NumberFormat = "@";
// Set A2 to text with a leading '0'.
cells["A2"].Value = "01234567890123456789";
// Format column C as text (SpreadsheetGear uses 0 based indexes - Excel uses 1 based indexes).
cells[0, 2].EntireColumn.NumberFormat = "@";
// Set C3 to text with a leading '0'.
cells[2, 2].Value = "01234567890123456789";
workbook.SaveAs(@"c:\tmp\TextFormat.xlsx", FileFormat.OpenXMLWorkbook);

Disclaimer: I own SpreadsheetGear LLC

How to change the port number for Asp.Net core app?

3 files have to changed appsettings.json (see the last section - kestrel ), launchsettings.json - applicationurl commented out, and a 2 lines change in Startup.cs

Add below code in appsettings.json file and port to any as you wish.

  },

 "Kestrel": {

   "Endpoints": {

     "Http": {

       "Url": "http://localhost:5003"

     }

   }

 }

 }

Modify Startup.cs with below lines.

using Microsoft.AspNetCore.Server.Kestrel.Core;

services.Configure<KestrelServerOptions>(Configuration.GetSection("Kestrel"));

How to fix "ImportError: No module named ..." error in Python?

In my mind I have to consider that the foo folder is a stand-alone library. I might want to consider moving it to the Lib\site-packages folder within a python installation. I might want to consider adding a foo.pth file there.

I know it's a library since the ./programs/my_python_program.py contains the following line:

from foo.tasks import my_function

So it doesn't matter that ./programs is a sibling folder to ./foo. It's the fact that my_python_program.py is run as a script like this:

python ./programs/my_python_program.py

What's the difference between a Future and a Promise?

I am aware that there's already an accepted answer but would like to add my two cents nevertheless:

TLDR: Future and Promise are the two sides of an asynchronous operation: consumer/caller vs. producer/implementor.

As a caller of an asynchronous API method, you will get a Future as a handle to the computation's result. You can e.g. call get() on it to wait for the computation to complete and retrieve the result.

Now think of how this API method is actually implemented: The implementor must return a Future immediately. They are responsible for completing that future as soon as the computation is done (which they will know because it is implementing the dispatch logic ;-)). They will use a Promise/CompletableFuture to do just that: Construct and return the CompletableFuture immediately, and call complete(T result) once the computation is done.

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

Because some database can throw an exception at dbContextTransaction.Commit() so better this:

using (var context = new BloggingContext()) 
{ 
  using (var dbContextTransaction = context.Database.BeginTransaction()) 
  { 
    try 
    { 
      context.Database.ExecuteSqlCommand( 
          @"UPDATE Blogs SET Rating = 5" + 
              " WHERE Name LIKE '%Entity Framework%'" 
          ); 

      var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
      foreach (var post in query) 
      { 
          post.Title += "[Cool Blog]"; 
      } 

      context.SaveChanges(false); 

      dbContextTransaction.Commit(); 

      context.AcceptAllChanges();
    } 
    catch (Exception) 
    { 
      dbContextTransaction.Rollback(); 
    } 
  } 
} 

How to check whether a select box is empty using JQuery/Javascript

One correct way to get selected value would be

var selected_value = $('#fruit_name').val()

And then you should do

if(selected_value) { ... }

Setting a div's height in HTML with CSS

A 2 column layout is a little bit tough to get working in CSS (at least until CSS3 is practical.)

Floating left and right will work to a point, but it won't allow you to extend the background. To make backgrounds stay solid, you'll have to implement a technique known as "faux columns," which basically means your columns themselves won't have a background image. Your 2 columns will be contained inside of a parent tag. This parent tag is given a background image that contains the 2 column colors you want. Make this background only as big as you need it to (if it is a solid color, only make it 1 pixel high) and have it repeat-y. AListApart has a great walkthrough on what is needed to make it work.

http://www.alistapart.com/articles/fauxcolumns/

What is unexpected T_VARIABLE in PHP?

There might be a semicolon or bracket missing a line before your pasted line.

It seems fine to me; every string is allowed as an array index.

How to sign an android apk file

For users of IntelliJ IDEA or Android Studio make these steps:
* From the menu Build/Generate signed APK
* You need to create a keystore path. From the dialog click Create new. You will create a jks file that includes your keys. Select folder, define a password. So your keystore ok.
* Create new key by for your application by using alias, key password, your name etc.
* Click next.
* From the dialog either select Proguard or not.

Your signed APK file is ready.

Help file: https://www.jetbrains.com/idea/webhelp/generate-signed-apk-wizard.html

There are No resources that can be added or removed from the server

The issue is it is missing Dynamic Web Module facet definition. Run the following at command line

mvn eclipse:eclipse -Dwtpversion=2.0

After build is success, refresh the project and you will be add the web project to server.

JPanel vs JFrame in Java

JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

You need a Swing tutorial:

http://docs.oracle.com/javase/tutorial/uiswing/

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

I solved this problem by deleting the empty users creating by MySQL. I only have root user and my own user. I deleted the rest.

Initialize/reset struct to zero/null

debugger screenshot

Take a surprise from gnu11!

typedef struct {
    uint8_t messType;
    uint8_t ax;  //axis
    uint32_t position;
    uint32_t velocity;
}TgotoData;

TgotoData tmpData = { 0 };

nothing is zero.

What is the difference between os.path.basename() and os.path.dirname()?

To summarize what was mentioned by Breno above

Say you have a variable with a path to a file

path = '/home/User/Desktop/myfile.py'

os.path.basename(path) returns the string 'myfile.py'

and

os.path.dirname(path) returns the string '/home/User/Desktop' (without a trailing slash '/')

These functions are used when you have to get the filename/directory name given a full path name.

In case the file path is just the file name (e.g. instead of path = '/home/User/Desktop/myfile.py' you just have myfile.py), os.path.dirname(path) returns an empty string.

What is the 'instanceof' operator used for in Java?

Can be used as a shorthand in equality check.

So this code

if(ob != null && this.getClass() == ob.getClass) {
}

can be written as

if(ob instanceOf ClassA) {
}
 

Fatal error: Call to undefined function pg_connect()

Edit. I just noticed you were mentionning MAMP. My advice is for Windows but may be useful if you know what corresponding tools to use.

Things to try:

  • Have you restarted PHP and Apache since your editing of php.ini?

  • Is the php_pgsql.dll found in your php\ext directory?

  • Are you running php as a module? If so, try copying the php_pgsql.dll file in the Apache\bin directory.

  • Are you running PHP from the command line with a flag specifying a different php.ini file?

  • You could try using a tool such as Sysinternals' Filemon to view what files are attempting to be accessed when running PHP.

  • You could try using a tool such as Dependency Walker to look at the dependencies for the postgreSQL DLL, in case you have a missing dependency. Quick search brought up ldd for Unix.

Check whether a variable is a string in Ruby

A more duck-typing approach would be to say

foo.respond_to?(:to_str)

to_str indicates that an object's class may not be an actual descendant of the String, but the object itself is very much string-like (stringy?).

How to find path of active app.config file?

One more option that I saw is missing here:

const string APP_CONFIG_FILE = "APP_CONFIG_FILE";
string defaultSysConfigFilePath = (string)AppDomain.CurrentDomain.GetData(APP_CONFIG_FILE);

How to replace special characters in a string?

You can get unicode for that junk character from charactermap tool in window pc and add \u e.g. \u00a9 for copyright symbol. Now you can use that string with that particular junk caharacter, don't remove any junk character but replace with proper unicode.

How to convert comma-separated String to List?

Here is another one for converting CSV to ArrayList:

String str="string,with,comma";
ArrayList aList= new ArrayList(Arrays.asList(str.split(",")));
for(int i=0;i<aList.size();i++)
{
    System.out.println(" -->"+aList.get(i));
}

Prints you

-->string
-->with
-->comma

How to add MVC5 to Visual Studio 2013?

With respect to other answers, it's not always there. Sometimes on setup process people forget to select the Web Developer Tools.

In order to fix that, one should:

  1. Open Programs and Features find Visual Studios related version there, click on it,
  2. Click to Change. Then the setup window will appear,
  3. Select Web Developer Tools there and continue to setup.

It will download or use the setup media if exist. After the setup windows may restart, and you are ready to have fun with your Web Developer Tools now.

Border around each cell in a range

I have a set of 15 subroutines I add to every Coded Excel Workbook I create and this is one of them. The following routine clears the area and creates a border.

Sample Call:

Call BoxIt(Range("A1:z25"))

Subroutine:

Sub BoxIt(aRng As Range)
On Error Resume Next

    With aRng

        'Clear existing
        .Borders.LineStyle = xlNone

        'Apply new borders
        .BorderAround xlContinuous, xlThick, 0
        With .Borders(xlInsideVertical)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .Weight = xlMedium
        End With
        With .Borders(xlInsideHorizontal)
            .LineStyle = xlContinuous
            .ColorIndex = 0
            .Weight = xlMedium
        End With
    End With

End Sub

Save child objects automatically using JPA Hibernate

I tried the above but I'm getting a database error complaining that the foreign key field in the Child table can not be NULL. Is there a way to tell JPA to automatically set this foreign key into the Child object so it can automatically save children objects?

Well, there are two things here.

First, you need to cascade the save operation (but my understanding is that you are doing this or you wouldn't get a FK constraint violation during inserts in the "child" table)

Second, you probably have a bidirectional association and I think that you're not setting "both sides of the link" correctly. You are supposed to do something like this:

Parent parent = new Parent();
...
Child c1 = new Child();
...
c1.setParent(parent);

List<Child> children = new ArrayList<Child>();
children.add(c1);
parent.setChildren(children);

session.save(parent);

A common pattern is to use link management methods:

@Entity
public class Parent {
    @Id private Long id;

    @OneToMany(mappedBy="parent")
    private List<Child> children = new ArrayList<Child>();

    ...

    protected void setChildren(List<Child> children) {
        this.children = children;
    }

    public void addToChildren(Child child) {
        child.setParent(this);
        this.children.add(child);
    }
}

And the code becomes:

Parent parent = new Parent();
...
Child c1 = new Child();
...

parent.addToChildren(c1);

session.save(parent);
References

JetBrains / IntelliJ keyboard shortcut to collapse all methods

go to menu option Code > Folding to access all code folding related options and their shortcuts.

Difference between _self, _top, and _parent in the anchor tag target attribute

Section 6.16 Frame target names in the HTML 4.01 spec defines the meanings, but it is partly outdated. It refers to “windows”, whereas HTML5 drafts more realistically speak about “browsing contexts”, since modern browsers often use tabs instead of windows in this context.

Briefly, _self is the default (current browsing context, i.e. current window or tab), so it is useful only to override a <base target=...> setting. The value _parent refers to the frameset that is the parent of the current frame, whereas _top “breaks out of all frames” and opens the linked document in the entire browser window.

Hosting ASP.NET in IIS7 gives Access is denied?

Tried most of the solutions here, but no luck. What worked for me was adding "Everyone" to the security permissions. Properties -> Security -> Edit -> Add -> Everyone. The given defaults were enough for me to regain access.

In the near future, I should probably figure out what credentials are being sent to the server so that I can give proper permissions. But I hope it helps someone!

How to attach a process in gdb

The first argument should be the path to the executable program. So

gdb progname 12271

Most efficient solution for reading CLOB to String, and String to CLOB in Java?

A friendly helper method using apache commons.io

Reader reader = clob.getCharacterStream();
StringWriter writer = new StringWriter();
IOUtils.copy(reader, writer);
String clobContent = writer.toString();

How to get DataGridView cell value in messagebox?

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

a bit late but hope it helps

Are complex expressions possible in ng-hide / ng-show?

I generally try to avoid expressions with ng-show and ng-hide as they were designed as booleans, not conditionals. If I need both conditional and boolean logic, I prefer to put in the conditional logic using ng-if as the first check, then add in an additional check for the boolean logic with ng-show and ng-hide

Howerver, if you want to use a conditional for ng-show or ng-hide, here is a link with some examples: Conditional Display using ng-if, ng-show, ng-hide, ng-include, ng-switch

Remove duplicate values from JS array

aLinks is a simple JavaScript array object. If any element exist before the elements on which the index shows that a duplicate record deleted. I repeat to cancel all duplicates. One passage array cancel more records.

var srt_ = 0;
var pos_ = 0;
do {
    var srt_ = 0;
    for (var i in aLinks) {
        pos_ = aLinks.indexOf(aLinks[i].valueOf(), 0);
        if (pos_ < i) {
            delete aLinks[i];
            srt_++;
        }
    }
} while (srt_ != 0);

What's the best visual merge tool for Git?

Araxis Merge http://www.araxis.com/merge I'm using it on Mac OS X but I've used it on windows... it's not free... but it has some nice features... nicer on windows though.

Can I change the headers of the HTTP request sent by the browser?

ModHeader extension for Google Chrome, is also a good option. You can just set the Headers you want and just enter the URL in the browser, it will automatically take the headers from the extension when you hit the url. Only thing is, it will send headers for each and every URL you will hit so you have to disable or delete it after use.

How to add additional libraries to Visual Studio project?

Add #pragma comment(lib, "Your library name here") to your source.

xlrd.biffh.XLRDError: Excel xlsx file; not supported

As noted in the release email, linked to from the release tweet and noted in large orange warning that appears on the front page of the documentation, and less orange, but still present, in the readme on the repository and the release on pypi:

xlrd has explicitly removed support for anything other than xls files.

In your case, the solution is to:

  • make sure you are on a recent version of Pandas, at least 1.0.1, and preferably the latest release. 1.2 will make his even clearer.
  • install openpyxl: https://openpyxl.readthedocs.io/en/stable/
  • change your Pandas code to be:
    df1 = pd.read_excel(
         os.path.join(APP_PATH, "Data", "aug_latest.xlsm"),
         engine='openpyxl',
    )
    

Can you break from a Groovy "each" closure?

You could break by RETURN. For example

  def a = [1, 2, 3, 4, 5, 6, 7]
  def ret = 0
  a.each {def n ->
    if (n > 5) {
      ret = n
      return ret
    }
  }

It works for me!

svn list of files that are modified in local copy

As said you have to use SVN Check for modification in GUI and tortoiseproc.exe /command:repostatus /path:"<path-to-version-control-file-or-directory>" in CLI to see changes related to the root of the <path-to-version-control-file-or-directory>.

Sadly, but this command won't show ALL local changes, it does show only those changes which are related to the requested directory root. The changes taken separately, like standalone checkouts or orphan external directories in the root subdirectory will be shown as Unversioned or Nested and you might miss to commit/lookup them.

To avoid such condition you have to either call to tortoiseproc.exe /command:repostatus /pathfile:"<path-to-file-with-list-of-items-to-lookup-from>" (see detailed documentation on the command line: https://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-automation.html), or use some 3dparty applications/utilities/scripts to wrap the call.

I has been wrote my own set of scripts for Windows to automate the call from the Total Commander: https://sf.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/ToolAdaptors/totalcmd/README_EN.txt (search for TortoiseSVN)

- Opens TortoiseSVN status dialog for a set of WC directories (always opens to show unversioned changes).

Command:   call_nowindow.vbs
Arguments: tortoisesvn\TortoiseProcByNestedWC.bat /command:repostatus "%P" %S

- Opens TortoiseSVN commit dialogs for a set of WC directories (opens only if has not empty versioned changes).

Command:   call_nowindow.vbs
Arguments: tortoisesvn\TortoiseProcByNestedWC.bat /command:commit "%P" %S

See the README_EN.txt for the latest details (you have to execute the configure.bat before the usage and copy rest of scripts on yourself like call_nowindow.vbs).

How do I restore a dump file from mysqldump?

If the database you want to restore doesn't already exist, you need to create it first.

On the command-line, if you're in the same directory that contains the dumped file, use these commands (with appropriate substitutions):

C:\> mysql -u root -p

mysql> create database mydb;
mysql> use mydb;
mysql> source db_backup.dump;

Jquery array.push() not working

Your HTML should include quotes for attributes : http://jsfiddle.net/dKWnb/4/

Not required when using a HTML5 doctype - thanks @bazmegakapa

You create the array each time and add a value to it ... its working as expected ?

Moving the array outside of the live() function works fine :

var myarray = []; // more efficient than new Array()
$("#test").live("click",function() {
        myarray.push($("#drop").val());
        alert(myarray);
});

http://jsfiddle.net/dKWnb/5/

Also note that in later versions of jQuery v1.7 -> the live() method is deprecated and replaced by the on() method.

How do I change UIView Size?

This can be achieved in various methods in Swift 3.0 Worked on Latest version MAY- 2019

Directly assign the Height & Width values for a view:

userView.frame.size.height = 0

userView.frame.size.width = 10

Assign the CGRect for the Frame

userView.frame =  CGRect(x:0, y: 0, width:0, height:0)

Method Details:

CGRect(x: point of X, y: point of Y, width: Width of View, height: Height of View)

Using an Extension method for CGRECT

Add following extension code in any swift file,

extension CGRect {

    init(_ x:CGFloat, _ y:CGFloat, _ w:CGFloat, _ h:CGFloat) {

        self.init(x:x, y:y, width:w, height:h)
    }
}

Use the following code anywhere in your application for the view to set the size parameters

userView.frame =  CGRect(1, 1, 20, 45)

How to set MouseOver event/trigger for border in XAML?

Yes, this is confusing...

According to this blog post, it looks like this is an omission from WPF.

To make it work you need to use a style:

    <Border Name="ClearButtonBorder" Grid.Column="1" CornerRadius="0,3,3,0">
        <Border.Style>
            <Style>
                <Setter Property="Border.Background" Value="Blue"/>
                <Style.Triggers>
                    <Trigger Property="Border.IsMouseOver" Value="True">
                        <Setter Property="Border.Background" Value="Green" />
                    </Trigger>
                </Style.Triggers>
            </Style>
        </Border.Style>
        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" Text="X" />
    </Border>

I guess this problem isn't that common as most people tend to factor out this sort of thing into a style, so it can be used on multiple controls.

python and sys.argv

In Python, you can't just embed arbitrary Python expressions into literal strings and have it substitute the value of the string. You need to either:

sys.stderr.write("Usage: " + sys.argv[0])

or

sys.stderr.write("Usage: %s" % sys.argv[0])

Also, you may want to consider using the following syntax of print (for Python earlier than 3.x):

print >>sys.stderr, "Usage:", sys.argv[0]

Using print arguably makes the code easier to read. Python automatically adds a space between arguments to the print statement, so there will be one space after the colon in the above example.

In Python 3.x, you would use the print function:

print("Usage:", sys.argv[0], file=sys.stderr)

Finally, in Python 2.6 and later you can use .format:

print >>sys.stderr, "Usage: {0}".format(sys.argv[0])

Replace characters from a column of a data frame R

If your variable data1$c is a factor, it's more efficient to change the labels of the factor levels than to create a new vector of characters:

levels(data1$c) <- sub("_", "-", levels(data1$c))


            a b   c
1  0.73945260 a A-B
2  0.75998815 b A-B
3  0.19576725 c A-B
4  0.85932140 d A-B
5  0.80717115 e A-C
6  0.09101492 f A-C
7  0.10183586 g A-C
8  0.97742424 h A-C
9  0.21364521 i A-C
10 0.02389782 j A-C

"unable to locate adb" using Android Studio

Else this will helps you

The ADB is now located in the Android SDK platform-tools.

Check your [sdk directory]/platform-tools directory and if it does not exist, then open the SDK manager in the Android Studio (a button somewhere in the top menu, android logo with a down arrow), switch to SDK tools tab and and select/install the Android SDK Platform-tools.

Alternatively, you can try the standalone SDK Manager: Open the SDK manager and you should see a "Launch Standalone SDK manager" link somewhere at the bottom of the settings window. Click and open the standalone SDK manager, then install/update the

"Tools > Android SDK platform tools". If the above does not solve the problem, try reinstalling the tools: open the "Standalone SDK manager" and uninstall the Android SDK platform-tools, delete the [your sdk directory]/platform-tools directory completely and install it again using the SDK manager.

Hope this helps!

WAMP won't turn green. And the VCRUNTIME140.dll error

You need to install some Visual C++ packages BEFORE installing WAMP (if you have installed then you must uninstall and reinstall).

You need: VC9, VC10, VC11, VC13 and VC14

In readme.txt of wampserver 3 (on SourceForge) you can find the links.

Be careful! If you use a 64-bit OS you need to install both versions of each package.

Where does Hive store files in HDFS?

Summarize few points posted earlier, in hive-site.xml, property hive.metastore.warehouse.dir specifies where the files located under hadoop HDFS

<property>
   <name>hive.metastore.warehouse.dir</name>
   <value>/user/hive/warehouse</value>
</property>

To view files, use this command:

hadoop fs -ls /user/hive/warehouse

or

http://localhost:50070
Utilities > Browse the file system
or
http://localhost:50070/explorer.html#/

tested under hadoop-2.7.3, hive-2.1.1

How to prevent Google Colab from disconnecting?

Try this:

function ClickConnect(){
  console.log("Working"); 
  document
    .querySelector("#top-toolbar > colab-connect-button")
    .shadowRoot
    .querySelector("#connect")
    .click()
}

setInterval(ClickConnect,60000)

Disable double-tap "zoom" option in browser on touch devices

Simple prevent the default behavior of click, dblclick or touchend events will disable the zoom functionality.

If you have already a callback on one of this events just call a event.preventDefault().

Hibernate HQL Query : How to set a Collection as a named parameter of a Query?

Use Query.setParameterList(), Javadoc here.

There are four variants to pick from.

How can I use Guzzle to send a POST request in JSON?

For Guzzle 5, 6 and 7 you do it like this:

use GuzzleHttp\Client;

$client = new Client();

$response = $client->post('url', [
    GuzzleHttp\RequestOptions::JSON => ['foo' => 'bar'] // or 'json' => [...]
]);

Docs

Permission denied: /var/www/abc/.htaccess pcfg_openfile: unable to check htaccess file, ensure it is readable?

Make sure that the htaccess file is readable by apache:

chmod 644 /var/www/abc/.htaccess 

And make sure the directory it's in is readable and executable:

chmod 755 /var/www/abc/

Convert multidimensional array into single array

Save this as a php file, simply import and use single_array() function

<?php
$GLOBALS['single_array']=[];
function array_conveter($array_list){
    if(is_array($array_list)){
        foreach($array_list as $array_ele){
            if(is_array($array_ele)){
                array_conveter($array_ele);
            }else{
                array_push($GLOBALS['single_array'],$array_ele);
            }
        }
    }else{
        array_push($GLOBALS['single_array'],$array_list);
    }
}
function single_array($mix){
    foreach($mix as $single){
        array_conveter($single);
    }return $GLOBALS['single_array'];
    $GLOBALS['single_array']=[];
}
/* Example convert your multi array to single  */
$mix_array=[3,4,5,[4,6,6,7],'abc'];
print_r(single_array($mix_array));

?>

How to set maximum height for table-cell?

Try something like this:-

 table {
    width: 50%;
    height: 50%;
    border-spacing: 0;
    position:absolute;
}
td {
    border: 1px solid black;
}
#content {
    position:absolute;
    width:100%;
    left:0px;
    top:20px;
    bottom:20px;
    overflow: hidden;
}

Getting value of HTML text input

Yes, you can use jQuery to make this done, the idea is

Use a hidden value in your form, and copy the value from external text box to this hidden value just before submitting the form.

<form name="input" action="handle_email.php" method="post">
  <input type="hidden" name="email" id="email" />
  <input type="submit" value="Submit" />
</form> 

<script>
   $("form").submit(function() {
     var emailFromOtherTextBox = $("#email_textbox").val();
     $("#email").val(emailFromOtherTextBox ); 
     return true;
  });
</script>

also see http://api.jquery.com/submit/

How do I get the SharedPreferences from a PreferenceActivity in Android?

If you don't have access to getDefaultSharedPreferenes(), you can use getSharedPreferences(name, mode) instead, you just have to pass in the right name.

Android creates this name (possibly based on the package name of your project?). You can get it by putting the following code in a SettingsActivity onCreate(), and seeing what preferencesName is.

String preferencesName = this.getPreferenceManager().getSharedPreferencesName();

The string should be something like com.example.projectname_preferences. Hard code that somewhere in your project, and pass it in to getSharedPreferences() and you should be good to go.

How to pass payload via JSON file for curl?

curl sends POST requests with the default content type of application/x-www-form-urlencoded. If you want to send a JSON request, you will have to specify the correct content type header:

$ curl -vX POST http://server/api/v1/places.json -d @testplace.json \
--header "Content-Type: application/json"

But that will only work if the server accepts json input. The .json at the end of the url may only indicate that the output is json, it doesn't necessarily mean that it also will handle json input. The API documentation should give you a hint on whether it does or not.

The reason you get a 401 and not some other error is probably because the server can't extract the auth_token from your request.

'git status' shows changed files, but 'git diff' doesn't

As already noted in a previous answer, this situation may arise due to line-ending problems (CR/LF vs. LF). I solved this problem (under Git version 2.22.0) with this command:

git add --renormalize .

According to the manual:

       --renormalize
           Apply the "clean" process freshly to all tracked files to
           forcibly add them again to the index. This is useful after
           changing core.autocrlf configuration or the text attribute in
           order to correct files added with wrong CRLF/LF line endings.
           This option implies -u.

iframe to Only Show a Certain Part of the Page

Assuming you are using an iframe to import content available to the public but not owned by you into your website, you can always use the page anchor to direct you iframe to load where you want it to.

First you create an iframe with the width and height needed to display the data.

<iframe src="http://www.mygreatsite.com/page2.html" width="200px" height="100px"></iframe>

Second install addon such as Show Anchors 2 for Firefox and use it to display all the page anchors on the page you would like display in your iframe. Find the anchor point you want your frame to use and copy the anchor location by right clicking on it.

(You can download and install the plugin here => https://addons.mozilla.org/en-us/firefox/addon/show-anchors-2/)

Third use the copied web address with anchor point as your iframe source. When the frame loads, it will show the page starting at the anchor point you specified.

<iframe src="http://www.mygreatsite.com/page2.html#anchorname_1" width="200px" height="100px"></iframe>

That is the condensed instruction list. Hope it helps!

Setting an image button in CSS - image:active

Check this link . You were missing . before myButton. It was a small error. :)

.myButton{
    background:url(./images/but.png) no-repeat;
    cursor:pointer;
    border:none;
    width:100px;
    height:100px;
}

.myButton:active  /* use Dot here */
{   
    background:url(./images/but2.png) no-repeat;
}

babel-loader jsx SyntaxError: Unexpected token

I ran into a similar issue when migrating from babel 5 to babel 6.

I was just running babel to compile the src to lib folder babel src --out-dir lib

I will share my setup for babel 6:

Ensure you have the following babel 6 devDependencies installed

"babel-core": "^6.7.6",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"babel-preset-stage-0": "^6.5.0"

Add your .babelrc file to the project:

{
  "presets": ["es2015", "stage-0", "react"]
}

How to print binary tree diagram?

A solution in Scala language, analogous to what I wrote in java:

case class Node(name: String, children: Node*) {

    def toTree: String = toTree("", "").mkString("\n")

    private def toTree(prefix: String, childrenPrefix: String): Seq[String] = {
        val firstLine = prefix + this.name

        val firstChildren = this.children.dropRight(1).flatMap { child =>
            child.toTree(childrenPrefix + "+-- ", childrenPrefix + "¦   ")
        }
        val lastChild = this.children.takeRight(1).flatMap { child =>
            child.toTree(childrenPrefix + "+-- ", childrenPrefix + "    ")
        }
        firstLine +: firstChildren ++: lastChild
    }

}

Output example:

vasya
+-- frosya
¦   +-- petya
¦   ¦   +-- masha
¦   +-- kolya
+-- frosya2

Python setup.py develop vs install

python setup.py install is used to install (typically third party) packages that you're not going to develop/modify/debug yourself.

For your own stuff, you want to first install your package and then be able to frequently edit the code without having to re-install the package every time — and that is exactly what python setup.py develop does: it installs the package (typically just a source folder) in a way that allows you to conveniently edit your code after it’s installed to the (virtual) environment, and have the changes take effect immediately.

Note that it is highly recommended to use pip install . (install) and pip install -e . (developer install) to install packages, as invoking setup.py directly will do the wrong things for many dependencies, such as pull prereleases and incompatible package versions, or make the package hard to uninstall with pip.

Chart creating dynamically. in .net, c#

Microsoft has a nice chart control. Download it here. Great video on this here. Example code is here. Happy coding!

Check if string contains only letters in javascript

Try this

var Regex='/^[^a-zA-Z]*$/';

 if(Regex.test(word))
 {
 //...
 }

I think it will be working for you.

How to scroll to bottom in react?

Thanks to @enlitement

we should avoid using findDOMNode, we can use refs to keep track of the components

render() {
  ...

  return (
    <div>
      <div
        className="MessageList"
        ref={(div) => {
          this.messageList = div;
        }}
      >
        { messageListContent }
      </div>
    </div>
  );
}



scrollToBottom() {
  const scrollHeight = this.messageList.scrollHeight;
  const height = this.messageList.clientHeight;
  const maxScrollTop = scrollHeight - height;
  this.messageList.scrollTop = maxScrollTop > 0 ? maxScrollTop : 0;
}

componentDidUpdate() {
  this.scrollToBottom();
}

reference:

NGINX - No input file specified. - php Fast/CGI

For localhost - I forgot to write in C:\Windows\System32\drivers\etc\hosts

127.0.0.1 localhost

Also removed proxy_pass http://127.0.0.1; from other server in ngnix.conf

How to place object files in separate subdirectory

The VPATH lines are wrong, they should be

vpath %.c  src
vpath %.h  src

i.e. not capital and without the = . As it is now, it doesn't find the .h file and thinks it is a target to be made.

Using css transform property in jQuery

$(".oSlider-rotate").slider({
     min: 10,
     max: 74,
     step: .01,
     value: 24,
     slide: function(e,ui){
                 $('.user-text').css('transform', 'scale(' + ui.value + ')')

            }                
  });

This will solve the issue

How to present UIAlertController when not in a view controller?

You can send the current view or controller as a parameter:

+ (void)myUtilityMethod:(id)controller {
    // do stuff
    // something bad happened, display an alert.
}

How to loop over grouped Pandas dataframe?

df.groupby('l_customer_id_i').agg(lambda x: ','.join(x)) does already return a dataframe, so you cannot loop over the groups anymore.

In general:

  • df.groupby(...) returns a GroupBy object (a DataFrameGroupBy or SeriesGroupBy), and with this, you can iterate through the groups (as explained in the docs here). You can do something like:

    grouped = df.groupby('A')
    
    for name, group in grouped:
        ...
    
  • When you apply a function on the groupby, in your example df.groupby(...).agg(...) (but this can also be transform, apply, mean, ...), you combine the result of applying the function to the different groups together in one dataframe (the apply and combine step of the 'split-apply-combine' paradigm of groupby). So the result of this will always be again a DataFrame (or a Series depending on the applied function).

How to connect wireless network adapter to VMWare workstation?

  1. Add a local loop network in your normal PC (search google how to)
  2. Click start -> type "ncpa.cpl" hit enter to open network connections.
  3. While pressing Ctrl key, select both your wireless and recently created local loop network. right click on it and create the bridge.
  4. Now in virtual network editor in vmware, select the network with type "Bridged" and change Bridged to option to the recently created bridge.

You will then have access to network via wifi card.

HTML.ActionLink vs Url.Action in ASP.NET Razor

@HTML.ActionLink generates a HTML anchor tag. While @Url.Action generates a URL for you. You can easily understand it by;

// 1. <a href="/ControllerName/ActionMethod">Item Definition</a>
@HTML.ActionLink("Item Definition", "ActionMethod", "ControllerName")

// 2. /ControllerName/ActionMethod
@Url.Action("ActionMethod", "ControllerName")

// 3. <a href="/ControllerName/ActionMethod">Item Definition</a>
<a href="@Url.Action("ActionMethod", "ControllerName")"> Item Definition</a>

Both of these approaches are different and it totally depends upon your need.

Regular expression to match standard 10 digit phone number

There are many variations possible for this problem. Here is a regular expression similar to an answer I previously placed on SO.

^\s*(?:\+?(\d{1,3}))?[-. (]*(\d{3})[-. )]*(\d{3})[-. ]*(\d{4})(?: *x(\d+))?\s*$

It would match the following examples and much more:

18005551234
1 800 555 1234
+1 800 555-1234
+86 800 555 1234
1-800-555-1234
1 (800) 555-1234
(800)555-1234
(800) 555-1234
(800)5551234
800-555-1234
800.555.1234
800 555 1234x5678
8005551234 x5678
1    800    555-1234
1----800----555-1234

Regardless of the way the phone number is entered, the capture groups can be used to breakdown the phone number so you can process it in your code.

  • Group1: Country Code (ex: 1 or 86)
  • Group2: Area Code (ex: 800)
  • Group3: Exchange (ex: 555)
  • Group4: Subscriber Number (ex: 1234)
  • Group5: Extension (ex: 5678)

Here is a breakdown of the expression if you're interested:

^\s*                #Line start, match any whitespaces at the beginning if any.
(?:\+?(\d{1,3}))?   #GROUP 1: The country code. Optional.
[-. (]*             #Allow certain non numeric characters that may appear between the Country Code and the Area Code.
(\d{3})             #GROUP 2: The Area Code. Required.
[-. )]*             #Allow certain non numeric characters that may appear between the Area Code and the Exchange number.
(\d{3})             #GROUP 3: The Exchange number. Required.
[-. ]*              #Allow certain non numeric characters that may appear between the Exchange number and the Subscriber number.
(\d{4})             #Group 4: The Subscriber Number. Required.
(?: *x(\d+))?       #Group 5: The Extension number. Optional.
\s*$                #Match any ending whitespaces if any and the end of string.

To make the Area Code optional, just add a question mark after the (\d{3}) for the area code.

Do C# Timers elapse on a separate thread?

It depends. The System.Timers.Timer has two modes of operation.

If SynchronizingObject is set to an ISynchronizeInvoke instance then the Elapsed event will execute on the thread hosting the synchronizing object. Usually these ISynchronizeInvoke instances are none other than plain old Control and Form instances that we are all familiar with. So in that case the Elapsed event is invoked on the UI thread and it behaves similar to the System.Windows.Forms.Timer. Otherwise, it really depends on the specific ISynchronizeInvoke instance that was used.

If SynchronizingObject is null then the Elapsed event is invoked on a ThreadPool thread and it behaves similar to the System.Threading.Timer. In fact, it actually uses a System.Threading.Timer behind the scenes and does the marshaling operation after it receives the timer callback if needed.

Authenticate Jenkins CI for Github private repository

If you need Jenkins to access more then 1 project you will need to:
1. add public key to one github user account
2. add this user as Owner (to access all projects) or as a Collaborator in every project.

Many public keys for one system user will not work because GitHub will find first matched deploy key and will send back error like "ERROR: Permission to user/repo2 denied to user/repo1"

http://help.github.com/ssh-issues/

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

I tried several of these answers to no avail for android using react-native version = 0.19.0.

For some reason, the resizeMode inside my stylesheet did not work appropriately? However, when sytlesheet had

backgroundImage: {
flex: 1,
width: null,
height: null,
}

and, within the Image tag I specified the resizeMode:

<Image source={require('path/to/image.png')} style= {styles.backgroundImage} resizeMode={Image.resizeMode.sretch}>

It worked perfectly! As mentioned above, you can use Image.resizeMode.cover or contain as well.

Hope this helps!

Compiling Java 7 code via Maven

{JAVA_1_4_HOME}/bin/javacyou can try also...

<plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
                <source>1.7</source>
                <target>1.7</target>
                <showDeprecation>true</showDeprecation>
                <showWarnings>true</showWarnings>
                <executable>{JAVA_HOME_1_7}/bin/javac</executable>
                <fork>true</fork>
        </configuration>
    </plugin>

How to list installed packages from a given repo using yum

Try

yum list installed | grep reponame

On one of my servers:

yum list installed | grep remi
ImageMagick2.x86_64                       6.6.5.10-1.el5.remi          installed
memcache.x86_64                          1.4.5-2.el5.remi             installed
mysql.x86_64                              5.1.54-1.el5.remi            installed
mysql-devel.x86_64                        5.1.54-1.el5.remi            installed
mysql-libs.x86_64                         5.1.54-1.el5.remi            installed
mysql-server.x86_64                       5.1.54-1.el5.remi            installed
mysqlclient15.x86_64                      5.0.67-1.el5.remi            installed
php.x86_64                                5.3.5-1.el5.remi             installed
php-cli.x86_64                            5.3.5-1.el5.remi             installed
php-common.x86_64                         5.3.5-1.el5.remi             installed
php-domxml-php4-php5.noarch               1.21.2-1.el5.remi            installed
php-fpm.x86_64                            5.3.5-1.el5.remi             installed
php-gd.x86_64                             5.3.5-1.el5.remi             installed
php-mbstring.x86_64                       5.3.5-1.el5.remi             installed
php-mcrypt.x86_64                         5.3.5-1.el5.remi             installed
php-mysql.x86_64                          5.3.5-1.el5.remi             installed
php-pdo.x86_64                            5.3.5-1.el5.remi             installed
php-pear.noarch                           1:1.9.1-6.el5.remi           installed
php-pecl-apc.x86_64                       3.1.6-1.el5.remi             installed
php-pecl-imagick.x86_64                   3.0.1-1.el5.remi.1           installed
php-pecl-memcache.x86_64                  3.0.5-1.el5.remi             installed
php-pecl-xdebug.x86_64                    2.1.0-1.el5.remi             installed
php-soap.x86_64                           5.3.5-1.el5.remi             installed
php-xml.x86_64                            5.3.5-1.el5.remi             installed
remi-release.noarch                       5-8.el5.remi                 installed

It works.

How to check certificate name and alias in keystore files?

In order to get all the details I had to add the -v option to romaintaz answer:

keytool -v -list -keystore <FileName>.keystore

Namespace not recognized (even though it is there)

In my case removing/adding that assembly worked.

How to run Java program in terminal with external library JAR

You can do :

1) javac -cp /path/to/jar/file Myprogram.java

2) java -cp .:/path/to/jar/file Myprogram

So, lets suppose your current working directory in terminal is src/Report/

javac -cp src/external/myfile.jar Reporter.java

java -cp .:src/external/myfile.jar Reporter

Take a look here to setup Classpath

How to convert an array to a string in PHP?

PHP's implode function can be used to convert an array into a string --- it is similar to join in other languages.

You can use it like so:

$string_product = implode(',', $array);

With an array like [1, 2, 3], this would result in a string like "1,2,3".

What do the python file extensions, .pyc .pyd .pyo stand for?

  • .py - Regular script
  • .py3 - (rarely used) Python3 script. Python3 scripts usually end with ".py" not ".py3", but I have seen that a few times
  • .pyc - compiled script (Bytecode)
  • .pyo - optimized pyc file (As of Python3.5, Python will only use pyc rather than pyo and pyc)
  • .pyw - Python script to run in Windowed mode, without a console; executed with pythonw.exe
  • .pyx - Cython src to be converted to C/C++
  • .pyd - Python script made as a Windows DLL
  • .pxd - Cython script which is equivalent to a C/C++ header
  • .pxi - MyPy stub
  • .pyi - Stub file (PEP 484)
  • .pyz - Python script archive (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .pywz - Python script archive for MS-Windows (PEP 441); this is a script containing compressed Python scripts (ZIP) in binary form after the standard Python script header
  • .py[cod] - wildcard notation in ".gitignore" that means the file may be ".pyc", ".pyo", or ".pyd".
  • .pth - a path configuration file; its contents are additional items (one per line) to be added to sys.path. See site module.

A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/

SSRS Field Expression to change the background color of the Cell

=IIF(Fields!Column.Value = "Approved", "Green", "No Color")

How to inject a Map using the @Value Spring Annotation?

Here is how we did it. Two sample classes as follow:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.kafka.annotation.EnableKafka;
@EnableKafka
@Configuration
@EnableConfigurationProperties(KafkaConsumerProperties.class)
public class KafkaContainerConfig {

    @Autowired
    protected KafkaConsumerProperties kafkaConsumerProperties;

    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        return new DefaultKafkaConsumerFactory<>(kafkaConsumerProperties.getKafkaConsumerConfig());
    }
...

@Configuration
@ConfigurationProperties
public class KafkaConsumerProperties {
    protected Map<String, Object> kafkaConsumerConfig = new HashMap<>();

    @ConfigurationProperties("kafkaConsumerConfig")
    public Map<String, Object> getKafkaConsumerConfig() {
        return (kafkaConsumerConfig);
    }
...

To provide the kafkaConsumer config from a properties file, you can use: mapname[key]=value

//application.properties
kafkaConsumerConfig[bootstrap.servers]=localhost:9092, localhost:9093, localhost:9094
kafkaConsumerConfig[group.id]=test-consumer-group-local
kafkaConsumerConfig[value.deserializer]=org.apache.kafka.common.serialization.StringDeserializer
kafkaConsumerConfig[key.deserializer=org.apache.kafka.common.serialization.StringDeserializer

To provide the kafkaConsumer config from a yaml file, you can use "[key]": value In application.yml file:

kafkaConsumerConfig:
  "[bootstrap.servers]": localhost:9092, localhost:9093, localhost:9094
  "[group.id]": test-consumer-group-local
  "[value.deserializer]": org.apache.kafka.common.serialization.StringDeserializer
  "[key.deserializer]": org.apache.kafka.common.serialization.StringDeserializer

How to update Identity Column in SQL Server?

Try using DBCC CHECKIDENT:

DBCC CHECKIDENT ('YourTable', RESEED, 1);

Can I add jars to maven 2 build classpath without installing them?

For those that didn't find a good answer here, this is what we are doing to get a jar with all the necessary dependencies in it. This answer (https://stackoverflow.com/a/7623805/1084306) mentions to use the Maven Assembly plugin but doesn't actually give an example in the answer. And if you don't read all the way to the end of the answer (it's pretty lengthy), you may miss it. Adding the below to your pom.xml will generate target/${PROJECT_NAME}-${VERSION}-jar-with-dependencies.jar

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-assembly-plugin</artifactId>
            <version>2.4.1</version>
            <configuration>
                <!-- get all project dependencies -->
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <!-- MainClass in mainfest make a executable jar -->
                <archive>
                  <manifest>
                    <mainClass>my.package.mainclass</mainClass>
                  </manifest>
                </archive>

            </configuration>
            <executions>
              <execution>
                <id>make-assembly</id>
                <!-- bind to the packaging phase -->
                <phase>package</phase> 
                <goals>
                    <goal>single</goal>
                </goals>
              </execution>
            </executions>
        </plugin>

Make an html number input always display 2 decimal places

What other folks posted here mainly worked, but using onchange doesn't work when I change the number using arrows in the same direction more than once. What did work was oninput. My code (mainly borrowing from MC9000):

HTML

<input class="form-control" oninput="setTwoNumberDecimal(this)" step="0.01" value="0.00" type="number" name="item[amount]" id="item_amount">

JS

function setTwoNumberDecimal(el) {
        el.value = parseFloat(el.value).toFixed(2);
    };

'Missing contentDescription attribute on image' in XML

Going forward, for graphical elements that are purely decorative, the best solution is to use:

android:importantForAccessibility="no"

This makes sense if your min SDK version is at least 16, since devices running lower versions will ignore this attribute.

If you're stuck supporting older versions, you should use (like others pointed out already):

android:contentDescription="@null"

Source: https://developer.android.com/guide/topics/ui/accessibility/apps#label-elements

How do you copy and paste into Git Bash

Ctrl + insert did it for me in Windows.

Making sure at least one checkbox is checked

This should work:

function valthisform()
{
    var checkboxs=document.getElementsByName("c1");
    var okay=false;
    for(var i=0,l=checkboxs.length;i<l;i++)
    {
        if(checkboxs[i].checked)
        {
            okay=true;
            break;
        }
    }
    if(okay)alert("Thank you for checking a checkbox");
    else alert("Please check a checkbox");
}

If you have a question about the code, just comment.


I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/

Rails 4 Authenticity Token

When you define you own html form then you have to include authentication token string ,that should be sent to controller for security reasons. If you use rails form helper to generate the authenticity token is added to form as follow.

<form accept-charset="UTF-8" action="/login/signin" method="post">
  <div style="display:none">
    <input name="utf8" type="hidden" value="&#x2713;" />
    <input name="authenticity_token" type="hidden" value="x37DrAAwyIIb7s+w2+AdoCR8cAJIpQhIetKRrPgG5VA=">
  </div>
    ...
</form>

So the solution to the problem is either to add authenticity_token field or use rails form helpers rather then compromising security etc.

How to find numbers from a string?

I was looking for the answer of the same question but for a while I found my own solution and I wanted to share it for other people who will need those codes in the future. Here is another solution without function.

Dim control As Boolean
Dim controlval As String
Dim resultval As String
Dim i as Integer

controlval = "A1B2C3D4"

For i = 1 To Len(controlval)
control = IsNumeric(Mid(controlval, i, 1))
If control = True Then resultval = resultval & Mid(controlval, i, 1)
Next i

resultval = 1234

How to perform case-insensitive sorting in JavaScript?

Wrap your strings in / /i. This is an easy way to use regex to ignore casing

How to read Data from Excel sheet in selenium webdriver

Don't know about what the error you are facing exactly. But log4j:WARN No appenders could be found for logger error, is due to the log4j jar file that you have included in your project.

Initializing log4j is needed but actually Log4j is not necessary for your project. So Right click on your Project → Properties → Java Build Path → Libraries.. Search for log4j jar file and remove it.

Hope it will work fine now.

Are there any HTTP/HTTPS interception tools like Fiddler for mac OS X?

WebScarab is a framework for analysing applications that communicate using the HTTP and HTTPS protocols. It is written in Java, and is thus portable to many platforms. WebScarab has several modes of operation, implemented by a number of plugins. In its most common usage, WebScarab operates as an intercepting proxy, allowing the operator to review and modify requests created by the browser before they are sent to the server, and to review and modify responses returned from the server before they are received by the browser. WebScarab is able to intercept both HTTP and HTTPS communication. The operator can also review the conversations (requests and responses) that have passed through WebScarab.

http://www.owasp.org/index.php/Category:OWASP_WebScarab_Project

How to validate an Email in PHP?

Use:

var_dump(filter_var('[email protected]', FILTER_VALIDATE_EMAIL));
$validator = new EmailValidator();
$multipleValidations = new MultipleValidationWithAnd([
    new RFCValidation(),
    new DNSCheckValidation()
]);
$validator->isValid("[email protected]", $multipleValidations); //true

Send push to Android by C# using FCM (Firebase Cloud Messaging)

Here is another approach of writing Notification Service inside ASP.Net REST API.

public async Task<bool> NotifyAsync(string to, string title, string body)
{
    try
    {
        // Get the server key from FCM console
        var serverKey = string.Format("key={0}", "Your server key - use app config");

        // Get the sender id from FCM console
        var senderId = string.Format("id={0}", "Your sender id - use app config");

        var data = new
        {
            to, // Recipient device token
            notification = new { title, body }
        };

        // Using Newtonsoft.Json
        var jsonBody = JsonConvert.SerializeObject(data);

        using (var httpRequest = new HttpRequestMessage(HttpMethod.Post, "https://fcm.googleapis.com/fcm/send"))
        {
            httpRequest.Headers.TryAddWithoutValidation("Authorization", serverKey);
            httpRequest.Headers.TryAddWithoutValidation("Sender", senderId);
            httpRequest.Content = new StringContent(jsonBody, Encoding.UTF8, "application/json");

            using (var httpClient = new HttpClient())
            {
                var result = await httpClient.SendAsync(httpRequest);

                if (result.IsSuccessStatusCode)
                {
                    return true;
                }
                else
                {
                    // Use result.StatusCode to handle failure
                    // Your custom error handler here
                    _logger.LogError($"Error sending notification. Status Code: {result.StatusCode}");
                }
            }
        }
    }
    catch (Exception ex)
    {
        _logger.LogError($"Exception thrown in Notify Service: {ex}");
    }

    return false;
}

References:

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

Missing .map resource?

jQuery recently started using source maps.

For example, let's look at the minified jQuery 2.0.3 file's first few lines.

/*! jQuery v2.0.3 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license
//@ sourceMappingURL=jquery.min.map
*/

Excerpt from Introduction to JavaScript Source Maps:

Have you ever found yourself wishing you could keep your client-side code readable and more importantly debuggable even after you've combined and minified it, without impacting performance? Well now you can through the magic of source maps.

Basically it's a way to map a combined/minified file back to an unbuilt state. When you build for production, along with minifying and combining your JavaScript files, you generate a source map which holds information about your original files. When you query a certain line and column number in your generated JavaScript you can do a lookup in the source map which returns the original location. Developer tools (currently WebKit nightly builds, Google Chrome, or Firefox 23+) can parse the source map automatically and make it appear as though you're running unminified and uncombined files.

emphasis mine

It's incredibly useful, and will only download if the user opens dev tools.

Solution

Remove the source mapping line, or do nothing. It isn't really a problem.


Side note: your server should return 404, not 500. It could point to a security problem if this happens in production.

Android getResources().getDrawable() deprecated API 22

getDrawable(int drawable) is deprecated in API level 22. For reference see this link.

Now to resolve this problem we have to pass a new constructer along with id like as :-

getDrawable(int id, Resources.Theme theme)

For Solutions Do like this:-

In Java:-

ContextCompat.getDrawable(getActivity(), R.drawable.name);   

or

 imgProfile.setImageDrawable(getResources().getDrawable(R.drawable.img_prof, getApplicationContext().getTheme()));

In Kotlin :-

rel_week.background=ContextCompat.getDrawable(this.requireContext(), R.color.colorWhite)

or

 rel_day.background=resources.getDrawable(R.drawable.ic_home, context?.theme)

Hope this will help you.Thanks.

Open Source HTML to PDF Renderer with Full CSS Support

I've always used it on the command line and not as a library, but HTMLDOC gives me excellent results, and it handles at least some CSS (I couldn't easily see how much).

Here's a sample command line

htmldoc --webpage -t pdf --size letter --fontsize 10pt index.html > index.pdf

ajax jquery simple get request

i think the problem is that there is no data in the success-function because the request breaks up with an 401 error in your case and thus has no success.

if you use

$.ajax({
        url: "https://app.asana.com/-/api/0.1/workspaces/",
        type: 'GET',
         error: function (xhr, ajaxOptions, thrownError) {
    alert(xhr.status);
    alert(thrownError);
  }
    });

there will be your 401 code i think (this link says so)

How can I use a custom font in Java?

If you want to use the font to draw with graphics2d or similar, this works:

InputStream stream = ClassLoader.getSystemClassLoader().getResourceAsStream("roboto-bold.ttf")
Font font = Font.createFont(Font.TRUETYPE_FONT, stream).deriveFont(48f)

How to get size of mysql database?

First login to MySQL using

mysql -u username -p

Command to Display the size of a single Database along with its table in MB.

SELECT table_name AS "Table",
ROUND(((data_length + index_length) / 1024 / 1024), 2) AS "Size (MB)"
FROM information_schema.TABLES
WHERE table_schema = "database_name"
ORDER BY (data_length + index_length) DESC;

Change database_name to your Database

Command to Display all the Databases with its size in MB.

SELECT table_schema AS "Database", 
ROUND(SUM(data_length + index_length) / 1024 / 1024, 2) AS "Size (MB)" 
FROM information_schema.TABLES 
GROUP BY table_schema;

How do I change the text of a span element using JavaScript?

You may also use the querySelector() method, assuming the 'myspan' id is unique as the method returns the first element with the specified selector:

document.querySelector('#myspan').textContent = 'newtext';

developer.mozilla

How do you perform address validation?

I have used the services of http://www.melissadata.com Their "address object" works very well. Its pricey, yes. But when you consider costs of writing your own solutions, the cost of dirty data in your application, returned mailers - lost sales, and the like - the costs can be justified.

Warning message: In `...` : invalid factor level, NA generated

The warning message is because your "Type" variable was made a factor and "lunch" was not a defined level. Use the stringsAsFactors = FALSE flag when making your data frame to force "Type" to be a character.

> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3))
> str(fixed)
'data.frame':   3 obs. of  2 variables:
 $ Type  : Factor w/ 1 level "": NA 1 1
 $ Amount: chr  "100" "0" "0"
> 
> fixed <- data.frame("Type" = character(3), "Amount" = numeric(3),stringsAsFactors=FALSE)
> fixed[1, ] <- c("lunch", 100)
> str(fixed)
'data.frame':   3 obs. of  2 variables:
 $ Type  : chr  "lunch" "" ""
 $ Amount: chr  "100" "0" "0"

Detect current device with UI_USER_INTERFACE_IDIOM() in Swift

Swift 2.0 & iOS 9 & Xcode 7.1

// 1. request an UITraitCollection instance
let deviceIdiom = UIScreen.mainScreen().traitCollection.userInterfaceIdiom

// 2. check the idiom
switch (deviceIdiom) {

case .Pad:
    print("iPad style UI")
case .Phone:
    print("iPhone and iPod touch style UI")
case .TV: 
    print("tvOS style UI")
default:
    print("Unspecified UI idiom")

}

Swift 3.0 and Swift 4.0

// 1. request an UITraitCollection instance
let deviceIdiom = UIScreen.main.traitCollection.userInterfaceIdiom

// 2. check the idiom
switch (deviceIdiom) {

case .pad:
    print("iPad style UI")
case .phone:
    print("iPhone and iPod touch style UI")
case .tv: 
    print("tvOS style UI")
default:
    print("Unspecified UI idiom")
}

Use UITraitCollection. The iOS trait environment is exposed though the traitCollection property of the UITraitEnvironment protocol. This protocol is adopted by the following classes:

  • UIScreen
  • UIWindow
  • UIViewController
  • UIPresentationController
  • UIView

CSS transition effect makes image blurry / moves image 1px, in Chrome?

I had a similar problem with blurry text but only the succeeding div was affected. For some reason the next div after the one that I was doing the transform in was blurry.

I tried everything that is recommended in this thread but nothing worked. For me rearranging my divs worked. I moved the div that blurres the following div to the end of parents div.

If someone know why just let me know.

#before
<header class="container">
      <div class="transformed div">
          <span class="transform wrapper">
            <span class="transformed"></span>
            <span class="transformed"></span>
          </span>
       </div>
       <div class="affected div">
       </div>
     </header>

#after
<header class="container">
   <div class="affected div">
   </div>
  <div class="transformed div">
      <span class="transform wrapper">
        <span class="transformed"></span>
        <span class="transformed"></span>
      </span>
   </div>

 </header>

Resizing a button

You should not use "width" and "height" attributes directly, use the style attribute like style="some css here" if you want to use inline styling:

<div class="button" style="width:60px;height:30px;">This is a button</div>

Note, however, that inline styling should generally be avoided since it makes maintenance and style updates a nightmare. Personally, if I had a button styling like yours but also wanted to apply different sizes, I would work with multiple css classes for sizing, like this:

_x000D_
_x000D_
   .button {_x000D_
        background-color: #000000;_x000D_
        color: #FFFFFF;_x000D_
        padding: 10px;_x000D_
        border-radius: 10px;_x000D_
        -moz-border-radius: 10px;_x000D_
        -webkit-border-radius: 10px;_x000D_
        margin:10px_x000D_
    }_x000D_
    _x000D_
    .small-btn {_x000D_
        width: 50px;_x000D_
        height: 25px;_x000D_
    }_x000D_
    _x000D_
    .medium-btn {_x000D_
        width: 70px;_x000D_
        height: 30px;_x000D_
    }_x000D_
    _x000D_
    .big-btn {_x000D_
        width: 90px;_x000D_
        height: 40px;_x000D_
    }
_x000D_
    <div class="button big-btn">This is a big button</div>_x000D_
    <div class="button medium-btn">This is a medium button</div>_x000D_
    <div class="button small-btn">This is a small button</div>_x000D_
 
_x000D_
_x000D_
_x000D_

jsFiddle example

Using this way of defining styles removes all style information from your HTML markup, which in will make it easier down the road if you want to change the size of all small buttons - you'll only have to change them once in the CSS.

How can I display a tooltip message on hover using jQuery?

You can use bootstrap tooltip. Do not forget to initialize it.

<span class="tooltip-r" data-toggle="tooltip" data-placement="left" title="Explanation">
inside span
</span>

Will be shown text Explanation on the left side.

and run it with js:

$('.tooltip-r').tooltip();

How to limit text width

<style>
     p{
         width:     70%
         word-wrap: break-word;
     }
</style>

This wasn't working in my case. It worked fine after adding following style.

<style>
     p{
        width:     70%
        word-break: break-all;
     }
</style>

Inline Form nested within Horizontal Form in Bootstrap 3

This Bootply example seems like a much better option. Only thing is that the labels are a little too high so I added padding-top:5px to center them with my inputs.

<div class="container">
<h2>Bootstrap Mixed Form <p class="lead">with horizontal and inline fields</p></h2>
<form role="form" class="form-horizontal">
    <div class="form-group">
        <label class="col-sm-1" for="inputEmail1">Email</label>
        <div class="col-sm-5"><input type="email" class="form-control" id="inputEmail1" placeholder="Email"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-1" for="inputPassword1">Password</label>
        <div class="col-sm-5"><input type="password" class="form-control" id="inputPassword1" placeholder="Password"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-12" for="TextArea">Textarea</label>
        <div class="col-sm-6"><textarea class="form-control" id="TextArea"></textarea></div>
    </div>
    <div class="form-group">
        <div class="col-sm-3"><label>First name</label><input type="text" class="form-control" placeholder="First"></div>
        <div class="col-sm-3"><label>Last name</label><input type="text" class="form-control" placeholder="Last"></div>
    </div>
    <div class="form-group">
        <label class="col-sm-12">Phone number</label>
        <div class="col-sm-1"><input type="text" class="form-control" placeholder="000"><div class="help">area</div></div>
        <div class="col-sm-1"><input type="text" class="form-control" placeholder="000"><div class="help">local</div></div>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="1111"><div class="help">number</div></div>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="123"><div class="help">ext</div></div>
    </div>
    <div class="form-group">
        <label class="col-sm-1">Options</label>
        <div class="col-sm-2"><input type="text" class="form-control" placeholder="Option 1"></div>
        <div class="col-sm-3"><input type="text" class="form-control" placeholder="Option 2"></div>
    </div>
    <div class="form-group">
        <div class="col-sm-6">
            <button type="submit" class="btn btn-info pull-right">Submit</button>
        </div>
    </div>
</form>
<hr>
</div>

WPF ListView - detect when selected item is clicked

You can handle click on list view item like this:

<ListView.ItemTemplate>
  <DataTemplate>
     <Button BorderBrush="Transparent" Background="Transparent" Focusable="False">
        <i:Interaction.Triggers>
                <i:EventTrigger EventName="Click">
                    <i:InvokeCommandAction Command="{Binding DataContext.MyCommand, ElementName=ListViewName}" CommandParameter="{Binding}"/>
                </i:EventTrigger>
        </i:Interaction.Triggers>
      <Button.Template>
      <ControlTemplate>
         <Grid VerticalAlignment="Stretch" HorizontalAlignment="Stretch">
    ...

ng-mouseover and leave to toggle item using mouse in angularjs

I would simply make the assignment happen in the ng-mouseover and ng-mouseleave; no need to bother js file :)

<ul ng-repeat="task in tasks">
    <li ng-mouseover="hoverEdit = true" ng-mouseleave="hoverEdit = false">{{task.name}}</li>
    <span ng-show="hoverEdit"><a>Edit</a></span>
</ul>