Programs & Examples On #Fulfillment

Angular get object from array by Id

// Used In TypeScript For Angular 4+        
const viewArray = [
          {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
          {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
          {id: 3, question: "Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
          {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
          {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
          {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
          {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
          {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
          {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
          {id: 10, question: "Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
          {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
          {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
          {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
          {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
          {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
    ];

         const arrayObj = any;
         const objectData = any;

          for (let index = 0; index < this.viewArray.length; index++) {
              this.arrayObj = this.viewArray[index];
              this.arrayObj.filter((x) => {
                if (x.id === id) {
                  this.objectData = x;
                }
              });
              console.log('Json Object Data by ID ==> ', this.objectData);
            }
          };

Angular get object from array by Id

CASE - 1

Using array.filter() We can get an array of objects which will match with our condition.
see the working example.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function filter(){
  console.clear();
  var filter_id = document.getElementById("filter").value;
  var filter_array = questions.filter(x => x.id == filter_id);
  console.log(filter_array);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
}
_x000D_
<div>
  <label for="filter"></label>
  <input id="filter" type="number" name="filter" placeholder="Enter id which you want to filter">
  <button onclick="filter()">Filter</button>
</div>
_x000D_
_x000D_
_x000D_

CASE - 2

Using array.find() we can get first matched item and break the iteration.

_x000D_
_x000D_
var questions = [
      {id: 1, question: "Do you feel a connection to a higher source and have a sense of comfort knowing that you are part of something greater than yourself?", category: "Spiritual", subs: []},
      {id: 2, question: "Do you feel you are free of unhealthy behavior that impacts your overall well-being?", category: "Habits", subs: []},
      {id: 3, question: "1 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "2 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 3, question: "3 Do you feel you have healthy and fulfilling relationships?", category: "Relationships", subs: []},
      {id: 4, question: "Do you feel you have a sense of purpose and that you have a positive outlook about yourself and life?", category: "Emotional Well-being", subs: []},
      {id: 5, question: "Do you feel you have a healthy diet and that you are fueling your body for optimal health? ", category: "Eating Habits ", subs: []},
      {id: 6, question: "Do you feel that you get enough rest and that your stress level is healthy?", category: "Relaxation ", subs: []},
      {id: 7, question: "Do you feel you get enough physical activity for optimal health?", category: "Exercise ", subs: []},
      {id: 8, question: "Do you feel you practice self-care and go to the doctor regularly?", category: "Medical Maintenance", subs: []},
      {id: 9, question: "Do you feel satisfied with your income and economic stability?", category: "Financial", subs: []},
      {id: 10, question: "1 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 10, question: "2 Do you feel you do fun things and laugh enough in your life?", category: "Play", subs: []},
      {id: 11, question: "Do you feel you have a healthy sense of balance in this area of your life?", category: "Work-life Balance", subs: []},
      {id: 12, question: "Do you feel a sense of peace and contentment  in your home? ", category: "Home Environment", subs: []},
      {id: 13, question: "Do you feel that you are challenged and growing as a person?", category: "Intellectual Wellbeing", subs: []},
      {id: 14, question: "Do you feel content with what you see when you look in the mirror?", category: "Self-image", subs: []},
      {id: 15, question: "Do you feel engaged at work and a sense of fulfillment with your job?", category: "Work Satisfaction", subs: []}
];

function find(){
  console.clear();
  var find_id = document.getElementById("find").value;
  var find_object = questions.find(x => x.id == find_id);
  console.log(find_object);
}
_x000D_
button {
  background: #0095ff;
  color: white;
  border: none;
  border-radius: 3px;
  padding: 8px;
  cursor: pointer;
}

input {
  padding: 8px;
  width: 200px;
}
_x000D_
<div>
  <label for="find"></label>
  <input id="find" type="number" name="find" placeholder="Enter id which you want to find">
  <button onclick="find()">Find</button>
</div>
_x000D_
_x000D_
_x000D_

How to loop through array in jQuery?

You can use a for() loop:

var things = currnt_image_list.split(','); 
for(var i = 0; i < things.length; i++) {
    //Do things with things[i]
}

Array to Collection: Optimized code

What do you mean by better way:

more readable:

List<String> list = new ArrayList<String>(Arrays.asList(array));

less memory consumption, and maybe faster (but definitely not thread safe):

public static List<String> toList(String[] array) {
    if (array==null) {
       return new ArrayList(0);
    } else {
       int size = array.length;
       List<String> list = new ArrayList(size);
       for(int i = 0; i < size; i++) {
          list.add(array[i]);
       }
       return list;
    }
}

Btw: here is a bug in your first example:

array.length will raise a null pointer exception if array is null, so the check if (array!=null) must be done first.

How to take off line numbers in Vi?

set number set nonumber

DO work inside .vimrc and make sure you DO NOT precede commands in .vimrc with :

How can I remount my Android/system as read-write in a bash script using adb?

In addition to all the other answers you received, I want to explain the unknown option -- o error: Your command was

$ adb shell 'su -c  mount -o rw,remount /system'

which calls su through adb. You properly quoted the whole su command in order to pass it as one argument to adb shell. However, su -c <cmd> also needs you to quote the command with arguments it shall pass to the shell's -c option. (YMMV depending on su variants.) Therefore, you might want to try

$ adb shell 'su -c "mount -o rw,remount /system"'

(and potentially add the actual device listed in the output of mount | grep system before the /system arg – see the other answers.)

Plot a legend outside of the plotting area in base graphics?

Maybe what you need is par(xpd=TRUE) to enable things to be drawn outside the plot region. So if you do the main plot with bty='L' you'll have some space on the right for a legend. Normally this would get clipped to the plot region, but do par(xpd=TRUE) and with a bit of adjustment you can get a legend as far right as it can go:

 set.seed(1) # just to get the same random numbers
 par(xpd=FALSE) # this is usually the default

 plot(1:3, rnorm(3), pch = 1, lty = 1, type = "o", ylim=c(-2,2), bty='L')
 # this legend gets clipped:
 legend(2.8,0,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

 # so turn off clipping:
 par(xpd=TRUE)
 legend(2.8,-1,c("group A", "group B"), pch = c(1,2), lty = c(1,2))

How can I run a directive after the dom has finished rendering?

Probably the author won't need my answer anymore. Still, for sake of completeness i feel other users might find it useful. The best and most simple solution is to use $(window).load() inside the body of the returned function. (alternatively you can use document.ready. It really depends if you need all the images or not).

Using $timeout in my humble opinion is a very weak option and may fail in some cases.

Here is the complete code i'd use:

.directive('directiveExample', function(){
   return {
       restrict: 'A',
       link: function($scope, $elem, attrs){

           $(window).load(function() {
               //...JS here...
           });
       }
   }
});

How to create Android Facebook Key Hash?

this will help newbees also.

just adding more details to @coder_For_Life22's answer.

if this answer helps you don't forget to upvote. it motivates us.

for this you must already know the path of the app's keystore file and password

for this example consider the key is stored at "c:\keystorekey\new.jks"

1. open this page https://code.google.com/archive/p/openssl-for-windows/downloads

2. download 32 or 64 bit zip file as per your windows OS.

3. extract the downloaded file where ever you want and remember the path.

4. for this example we consider that you have extracted the folder in download folder.

so the file address will be "C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe";

5. now on keyboard press windows+r button.

6. this will open run box.

7. type cmd and press Ctrl+Shift+Enter.

8. this will open command prompt as administrator.

9. here navigate to java's bin folder:

if you use jre provided by Android Studio you will find the path as follows:
a. open android studio.
b. file->project structure
c. in the left pane, click 'SDK location'
d. in the right pane, below 'JDK location' is your jre path.
e. add "\bin" at the end of this path as the file "keytool.exe", we need, is inside this folder.
for this example i consider, you have installed java separately and following is the path
"C:\Program Files\Java\jre-10.0.2\bin"
if you have installed 32bit java it will be in
"C:\Program Files (x86)\Java\jre-10.0.2\bin"
10. now with above paths execute command as following:

keytool -exportcert -alias androiddebugkey -keystore "c:\keystorekey\new.jks" | "C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe" sha1 -binary |"C:\Users\0\Downloads\openssl-0.9.8e_X64\bin\openssl.exe" base64
  1. You will be asked for password, give the password you have given when creating keystore key.

    !!!!!! this will give you the key

errors: if you get:
---
'keytool' is not recognized as an internal or external command
---
this means that java is installed somewhere else.

What exactly does Perl's "bless" do?

bless associates a reference with a package.

It doesn't matter what the reference is to, it can be to a hash (most common case), to an array (not so common), to a scalar (usually this indicates an inside-out object), to a regular expression, subroutine or TYPEGLOB (see the book Object Oriented Perl: A Comprehensive Guide to Concepts and Programming Techniques by Damian Conway for useful examples) or even a reference to a file or directory handle (least common case).

The effect bless-ing has is that it allows you to apply special syntax to the blessed reference.

For example, if a blessed reference is stored in $obj (associated by bless with package "Class"), then $obj->foo(@args) will call a subroutine foo and pass as first argument the reference $obj followed by the rest of the arguments (@args). The subroutine should be defined in package "Class". If there is no subroutine foo in package "Class", a list of other packages (taken form the array @ISA in the package "Class") will be searched and the first subroutine foo found will be called.

Can you find all classes in a package using reflection?

You could use this method1 that uses the ClassLoader.

/**
 * Scans all classes accessible from the context class loader which belong to the given package and subpackages.
 *
 * @param packageName The base package
 * @return The classes
 * @throws ClassNotFoundException
 * @throws IOException
 */
private static Class[] getClasses(String packageName)
        throws ClassNotFoundException, IOException {
    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    assert classLoader != null;
    String path = packageName.replace('.', '/');
    Enumeration<URL> resources = classLoader.getResources(path);
    List<File> dirs = new ArrayList<File>();
    while (resources.hasMoreElements()) {
        URL resource = resources.nextElement();
        dirs.add(new File(resource.getFile()));
    }
    ArrayList<Class> classes = new ArrayList<Class>();
    for (File directory : dirs) {
        classes.addAll(findClasses(directory, packageName));
    }
    return classes.toArray(new Class[classes.size()]);
}

/**
 * Recursive method used to find all classes in a given directory and subdirs.
 *
 * @param directory   The base directory
 * @param packageName The package name for classes found inside the base directory
 * @return The classes
 * @throws ClassNotFoundException
 */
private static List<Class> findClasses(File directory, String packageName) throws ClassNotFoundException {
    List<Class> classes = new ArrayList<Class>();
    if (!directory.exists()) {
        return classes;
    }
    File[] files = directory.listFiles();
    for (File file : files) {
        if (file.isDirectory()) {
            assert !file.getName().contains(".");
            classes.addAll(findClasses(file, packageName + "." + file.getName()));
        } else if (file.getName().endsWith(".class")) {
            classes.add(Class.forName(packageName + '.' + file.getName().substring(0, file.getName().length() - 6)));
        }
    }
    return classes;
}

__________
1 This method was taken originally from http://snippets.dzone.com/posts/show/4831, which was archived by the Internet Archive, as linked to now. The snippet is also available at https://dzone.com/articles/get-all-classes-within-package.

Maven Installation OSX Error Unsupported major.minor version 51.0

The problem is because you haven't set JAVA_HOME in Mac properly. In order to do that, you should do set it like this:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk1.8.0_40.jdk/Contents/Home

In my case my JDK installation is jdk1.8.0_40, make sure you type yours.

Then you can use maven commands.

Regards!

How to create a function in a cshtml template?

why not just declare that function inside the cshtml file?

@functions{
    public string GetSomeString(){
        return string.Empty;
    }
}

<h2>index</h2>
@GetSomeString()

Creating Roles in Asp.net Identity MVC 5

Here we go:

var roleManager = new RoleManager<Microsoft.AspNet.Identity.EntityFramework.IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));


   if(!roleManager.RoleExists("ROLE NAME"))
   {
      var role = new Microsoft.AspNet.Identity.EntityFramework.IdentityRole();
      role.Name = "ROLE NAME";
      roleManager.Create(role);

    }

How do I set browser width and height in Selenium WebDriver?

For me, the only thing that worked in Java 7 on OS X 10.9 was this:

// driver = new RemoteWebDriver(new URL(grid), capability);
driver.manage().window().setPosition(new Point(0,0));
driver.manage().window().setSize(new Dimension(1024,768));

Where 1024 is the width, and 768 is the height.

psql: FATAL: Ident authentication failed for user "postgres"

If you've done all this and it still doesn't work, check the expiry for that user:

Postgres password authentication fails

Java file path in Linux

The Official Documentation is clear about Path.

Linux Syntax: /home/joe/foo

Windows Syntax: C:\home\joe\foo


Note: joe is your username for these examples.

How to retrieve Jenkins build parameters using the Groovy API?

The following snippet worked for me to get a parameter value in a parameterized project:
String myParameter = this.getProperty('binding').getVariable('MY_PARAMETER')

The goal was to dynamically lock a resource based on the selected project parameter.

In "[?] This build requires lockable resources" I have the following "[?] Groovy Expression":

if (resourceName == 'resource_lock_name') {
    Binding binding = this.getProperty('binding')
    String profile = binding.getVariable('BUILD_PROFILE')

    return profile == '-Poradb' // acquire lock if "oradb" profile is selected
}

return false

In "[?] This project is parameterized" section I have a "Choice Parameter" named e.g. BUILD_PROFILE Example of Choices are:

-Poradb
-Ph2db
-DskipTests -T4

The lock on "resource_lock_name" will be acquired only if "-Poradb" is selected when building project with parameters

[-] Use Groovy Sandbox shall be unchecked for this syntax to work

Linux error while loading shared libraries: cannot open shared object file: No such file or directory

The error occurs as the system cannot refer to the library file mentioned. Take the following steps:

  1. Running locate libpthread_rt.so.1 will list the path of all the files with that name. Let's suppose a path is /home/user/loc.
  2. Copy the path and run cd home/USERNAME. Replace USERNAME with the name of the current active user with which you want to run the file.
  3. Run vi .bash_profile and at the end of the LD_LIBRARY_PATH parameter, just before ., add the line /lib://home/usr/loc:.. Save the file.
  4. Close terminal and restart the application. It should run.

jquery change class name

I better use the .prop to change the className and it worked perfectly:

$(#td_id).prop('className','newClass');

for this line of code you just have to change the name of newClass, and of course the id of the element, in the next exemple : idelementinyourpage

$(#idelementinyourpage).prop('className','newClass');

By the way, when you want to search which style is applied to any element, you just click F12 on your browser when your page is shown, and then select in the tab of DOM Explorer, the element you want to see. In Styles you now can see what styles are applied to your element and from which class its reading.

OpenSSL: unable to verify the first certificate for Experian URL

If you are using MacOS use:

sudo cp /usr/local/etc/openssl/cert.pem /etc/ssl/certs

after this Trust anchor not found error disappears

Getting data-* attribute for onclick event for an html element

Check if the data attribute is present, then do the stuff...

$('body').on('click', '.CLICK_BUTTON_CLASS', function (e) {
                        if(e.target.getAttribute('data-title')) {
                            var careerTitle = $(this).attr('data-title');
                            if (careerTitle.length > 0) $('.careerFormTitle').text(careerTitle);
                        }
                });

Exporting results of a Mysql query to excel?

In my case, I need to dump the sql result into a file on the client side. This is the most typical use case to off load data from the database. In many situations, you don't have access to the server or don't want to write your result to the server.

mysql -h hostname -u username -ppwd -e "mysql simple sql statement that last for less than a line" DATABASE_NAME > outputfile_on_the.client

The problem comes when you have a complicated query that last for several lines; you cannot use the command line to dump the result to a file easily. In such cases, you can put your complicated query into a file, such as longquery_file.sql, then execute the command.

mysql -h hn -u un -ppwd < longquery_file.sql DBNAME > output.txt

This worked for me. The only difficulty with me is the tab character; sometimes I use for group_cancat(foo SEPARATOR 0x09) will be written as '\t' in the output file. The 0x09 character is ASCII TAB. But this problem is not particular to the way we dump sql results to file. It may be related to my pager. Let me know when you find an answer to this problem. I will update this post.

Should switch statements always contain a default clause?

You should have a default to catch un-expected values coming in.

However, I disagree with the Adrian Smith that your error message for default should be something totally meaningless. There may be an un-handled case you didn't forsee (which is kind of the point) that your user will end up seeing and a message like "unreachable" is entirely pointless and doesn't help anyone in that situation.

Case in point, how many times have you had an utterly meaningless BSOD? Or a fatal exception @ 0x352FBB3C32342?

How to add a class to a given element?

You can use the API querySelector to select your element and then create a function with the element and the new classname as parameters. Using classlist for modern browsers, else for IE8. Then you can call the function after an event.

 //select the dom element
 var addClassVar = document.querySelector('.someclass');

 //define the addclass function
 var addClass = function(el,className){
   if (el.classList){
     el.classList.add(className);
   }
   else {
     el.className += ' ' + className;
  }
};

//call the function
addClass(addClassVar, 'newClass');

Update statement using with clause

You can always do something like this:

update  mytable t
set     SomeColumn = c.ComputedValue
from    (select *, 42 as ComputedValue from mytable where id = 1) c
where t.id = c.id 

You can now also use with statement inside update

update  mytable t
set     SomeColumn = c.ComputedValue
from    (with abc as (select *, 43 as ComputedValue_new from mytable where id = 1
         select *, 42 as ComputedValue, abc.ComputedValue_new  from mytable n1
           inner join abc on n1.id=abc.id) c
where t.id = c.id 

CSS to line break before/after a particular `inline-block` item

I accomplished this by creating a ::before selector for the first inline element in the row, and making that selector a block with a top or bottom margin to separate rows a little bit.

.1st_item::before
{
  content:"";
  display:block;
  margin-top: 5px;
}

.1st_item
{
  color:orange;
  font-weight: bold;
  margin-right: 1em;
}

.2nd_item
{
  color: blue;
}

Differences between socket.io and websockets

Even if modern browsers support WebSockets now, I think there is no need to throw SocketIO away and it still has its place in any nowadays project. It's easy to understand, and personally, I learned how WebSockets work thanks to SocketIO.

As said in this topic, there's a plenty of integration libraries for Angular, React, etc. and definition types for TypeScript and other programming languages.

The other point I would add to the differences between Socket.io and WebSockets is that clustering with Socket.io is not a big deal. Socket.io offers Adapters that can be used to link it with Redis to enhance scalability. You have ioredis and socket.io-redis for example.

Yes I know, SocketCluster exists, but that's off-topic.

Destroy or remove a view in Backbone.js

I had to be absolutely sure the view was not just removed from DOM but also completely unbound from events.

destroy_view: function() {

    // COMPLETELY UNBIND THE VIEW
    this.undelegateEvents();

    this.$el.removeData().unbind(); 

    // Remove view from DOM
    this.remove();  
    Backbone.View.prototype.remove.call(this);

}

Seemed like overkill to me, but other approaches did not completely do the trick.

How to resize datagridview control when form resizes

If anyone else is stuck with this, here's what helped me. Changing the Anchor settings did not work for me. I am using datagridviews within groupboxes in a form which is inside a parent form.

Handling the form resize event was the only thing that worked for me.

private void Form1_Resize(object sender, EventArgs e)
{
     groupBoxSampleQueue.MinimumSize = new Size((this as OperatingForm).Width - 22, 167);
     groupBoxMachineStatus.MinimumSize = new Size((this as OperatingForm).Width - 22, 167);
}

I added some raw numbers as buffers.

SQLAlchemy: What's the difference between flush() and commit()?

commit () records these changes in the database. flush () is always called as part of the commit () (1) call. When you use a Session object to query a database, the query returns results from both the database and the reddened parts of the unrecorded transaction it is performing.

How to get Android application id?

Else you can get id of process your application runs in:

final static int android.os.Process.myPid()
Returns the identifier of this process, which can be used with killProcess(int) and sendSignal(int, int).

Daemon Threads Explanation

Quoting Chris: "... when your program quits, any daemon threads are killed automatically.". I think that sums it up. You should be careful when you use them as they abruptly terminate when main program executes to completion.

Method Call Chaining; returning a pointer vs a reference?

Very interesting question.

I don't see any difference w.r.t safety or versatility, since you can do the same thing with pointer or reference. I also don't think there is any visible difference in performance since references are implemented by pointers.

But I think using reference is better because it is consistent with the standard library. For example, chaining in iostream is done by reference rather than pointer.

How to generate and validate a software license key?

Caveat: you can't prevent users from pirating, but only make it easier for honest users to do the right thing.

Assuming you don't want to do a special build for each user, then:

  • Generate yourself a secret key for the product
  • Take the user's name
  • Concatentate the users name and the secret key and hash with (for example) SHA1
  • Unpack the SHA1 hash as an alphanumeric string. This is the individual user's "Product Key"
  • Within the program, do the same hash, and compare with the product key. If equal, OK.

But, I repeat: this won't prevent piracy


I have recently read that this approach is not cryptographically very sound. But this solution is already weak (as the software itself has to include the secret key somewhere), so I don't think this discovery invalidates the solution as far as it goes.

Just thought I really ought to mention this, though; if you're planning to derive something else from this, beware.

Defining an abstract class without any abstract methods

Yes, you can declare a class you cannot instantiate by itself with only methods that already have implementations. This would be useful if you wanted to add abstract methods in the future, or if you did not want the class to be directly instantiated even though it has no abstract properties.

Simulate a specific CURL in PostMan

sometimes whenever you copy cURL, it contains --compressed. Remove it while import->Paste Raw Text-->click on import. It will also solve the problem if you are getting the syntax error in postman while importing any cURL.

Generally, when people copy cURL from any proxy tools like Charles, it happens.

What's the difference between a null pointer and a void pointer?

Null pointer is a special reserved value of a pointer. A pointer of any type has such a reserved value. Formally, each specific pointer type (int *, char * etc.) has its own dedicated null-pointer value. Conceptually, when a pointer has that null value it is not pointing anywhere.

Void pointer is a specific pointer type - void * - a pointer that points to some data location in storage, which doesn't have any specific type.

So, once again, null pointer is a value, while void pointer is a type. These concepts are totally different and non-comparable. That essentially means that your question, as stated, is not exactly valid. It is like asking, for example, "What is the difference between a triangle and a car?".

./xx.py: line 1: import: command not found

If you run a script directly e.g., ./xx.py and your script has no shebang such as #!/usr/bin/env python at the very top then your shell may execute it as a shell script. POSIX says:

If the execl() function fails due to an error equivalent to the [ENOEXEC] error defined in the System Interfaces volume of POSIX.1-2008, the shell shall execute a command equivalent to having a shell invoked with the pathname resulting from the search as its first operand, with any remaining arguments passed to the new shell, except that the value of "$0" in the new shell may be set to the command name. If the executable file is not a text file, the shell may bypass this command execution. In this case, it shall write an error message, and shall return an exit status of 126.

Note: you may get ENOEXEC if your text file has no shebang.

Without the shebang, you shell tries to run your Python script as a shell script that leads to the error: import: command not found.

Also, if you run your script as python xx.py then you do not need the shebang. You don't even need it to be executable (+x). Your script is interpreted by python in this case.

On Windows, shebang is not used unless pylauncher is installed. It is included in Python 3.3+.

How can I get the average (mean) of selected columns

Here are some examples:

> z$mean <- rowMeans(subset(z, select = c(x, y)), na.rm = TRUE)
> z
  w x  y mean
1 5 1  1    1
2 6 2  2    2
3 7 3  3    3
4 8 4 NA    4

weighted mean

> z$y <- rev(z$y)
> z
  w x  y mean
1 5 1 NA    1
2 6 2  3    2
3 7 3  2    3
4 8 4  1    4
> 
> weight <- c(1, 2) # x * 1/3 + y * 2/3
> z$wmean <- apply(subset(z, select = c(x, y)), 1, function(d) weighted.mean(d, weight, na.rm = TRUE))
> z
  w x  y mean    wmean
1 5 1 NA    1 1.000000
2 6 2  3    2 2.666667
3 7 3  2    3 2.333333
4 8 4  1    4 2.000000

Cannot access mongodb through browser - It looks like you are trying to access MongoDB over HTTP on the native driver port

Before Mongo 3.6:

You may start mongodb with

mongod --httpinterface

And access it on

http://localhost:28017

Since version 2.6: MongoDB disables the HTTP interface by default.

Update

HTTP Interface and REST API

MongoDB 3.6 removes the deprecated HTTP interface and REST API to MongoDB.

See Mongo http interface and rest api

Optional Parameters in Go?

I am a little late, but if you like fluent interface you might design your setters for chained calls like this:

type myType struct {
  s string
  a, b int
}

func New(s string, err *error) *myType {
  if s == "" {
    *err = errors.New(
      "Mandatory argument `s` must not be empty!")
  }
  return &myType{s: s}
}

func (this *myType) setA (a int, err *error) *myType {
  if *err == nil {
    if a == 42 {
      *err = errors.New("42 is not the answer!")
    } else {
      this.a = a
    }
  }
  return this
}

func (this *myType) setB (b int, _ *error) *myType {
  this.b = b
  return this
}

And then call it like this:

func main() {
  var err error = nil
  instance :=
    New("hello", &err).
    setA(1, &err).
    setB(2, &err)

  if err != nil {
    fmt.Println("Failed: ", err)
  } else {
    fmt.Println(instance)
  }
}

This is similar to the Functional options idiom presented on @Ripounet answer and enjoys the same benefits but has some drawbacks:

  1. If an error occurs it will not abort immediately, thus, it would be slightly less efficient if you expect your constructor to report errors often.
  2. You'll have to spend a line declaring an err variable and zeroing it.

There is, however, a possible small advantage, this type of function calls should be easier for the compiler to inline but I am really not a specialist.

How to execute an .SQL script file using c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
using System.IO;
using System.Data.SqlClient;

public partial class ExcuteScript : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string sqlConnectionString = @"Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=ccwebgrity;Data Source=SURAJIT\SQLEXPRESS";

        string script = File.ReadAllText(@"E:\Project Docs\MX462-PD\MX756_ModMappings1.sql");

        SqlConnection conn = new SqlConnection(sqlConnectionString);

        Server server = new Server(new ServerConnection(conn));

        server.ConnectionContext.ExecuteNonQuery(script);
    }
}

checking memory_limit in PHP

If you are interested in CLI memory limit:

cat /etc/php/[7.0]/cli/php.ini | grep "memory_limit"

FPM / "Normal"

cat /etc/php/[7.0]/fpm/php.ini | grep "memory_limit"

Python error: TypeError: 'module' object is not callable for HeadFirst Python code

As @Agam said,

You need this statement in your driver file: from AthleteList import AtheleteList

How do I encode and decode a base64 string?

    using System;
    using System.Text;

    public static class Base64Conversions
    {
        public static string EncodeBase64(this string text, Encoding encoding = null)
        { 
            if (text == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = encoding.GetBytes(text);
            return Convert.ToBase64String(bytes);
        }

        public static string DecodeBase64(this string encodedText, Encoding encoding = null)
        {
            if (encodedText == null) return null;

            encoding = encoding ?? Encoding.UTF8;
            var bytes = Convert.FromBase64String(encodedText);
            return encoding.GetString(bytes);
        }
    }

Usage

    var text = "Sample Text";
    var base64 = text.EncodeBase64();
    base64 = text.EncodeBase64(Encoding.UTF8); //or with Encoding

How to clear APC cache entries?

apc.ini

apc.stat = "1" will force APC to stat (check) the script on each request to determine if it has been modified. If it has been modified it will recompile and cache the new version.

If this setting is off, APC will not check, which usually means that to force APC to recheck files, the web server will have to be restarted or the cache will have to be manually cleared. Note that FastCGI web server configurations may not clear the cache on restart. On a production server where the script files rarely change, a significant performance boost can be achieved by disabled stats.

How to get VM arguments from inside of Java application?

At startup pass this -Dname=value

and then in your code you should use

value=System.getProperty("name");

to get that value

How to add RSA key to authorized_keys file?

I know I am replying too late but for anyone else who needs this, run following command from your local machine

cat ~/.ssh/id_rsa.pub | ssh [email protected] "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys"

this has worked perfectly fine. All you need to do is just to replace

[email protected]

with your own user for that particular host

PHP preg replace only allow numbers

You could also use T-Regx library:

pattern('\D')->remove($c)

T-Regx also:

  • Throws exceptions on fail (not false, null or warnings)
  • Has automatic delimiters (delimiters are not required!)
  • Has a lot cleaner api

Intellij JAVA_HOME variable

Bit counter-intuitive, but you must first setup a SDK for Java projects. On the bottom right of the IntelliJ welcome screen, select 'Configure > Project Defaults > Project Structure'.

The Project tab on the left will show that you have no SDK selected:

Therefore, you must click the 'New...' button on the right hand side of the dropdown and point it to your JDK. After that, you can go back to the import screen and it should be populated with your JAVA_HOME variable, providing you have this set.

How to correctly dismiss a DialogFragment?

I think a better way to close a DialogFragment is this:

Fragment prev = getSupportFragmentManager().findFragmentByTag("fragment_dialog");
if (prev != null) {
    DialogFragment df = (DialogFragment) prev;
    df.dismiss();
}

This way you dont have to hold a reference to the DialogFragment and can close it from everywhere.

How to break out or exit a method in Java?

To add to the other answers, you can also exit a method by throwing an exception manually:

throw new Exception();

enter image description here

Python: convert string to byte array

An alternative to get a byte array is to encode the string in ascii: b=s.encode('ascii').

Get and Set a Single Cookie with Node.js HTTP Server

As an enhancement to @Corey Hart's answer, I've rewritten the parseCookies() using:

Here's the working example:

let http = require('http');

function parseCookies(str) {
  let rx = /([^;=\s]*)=([^;]*)/g;
  let obj = { };
  for ( let m ; m = rx.exec(str) ; )
    obj[ m[1] ] = decodeURIComponent( m[2] );
  return obj;
}

function stringifyCookies(cookies) {
  return Object.entries( cookies )
    .map( ([k,v]) => k + '=' + encodeURIComponent(v) )
    .join( '; ');
}

http.createServer(function ( request, response ) {
  let cookies = parseCookies( request.headers.cookie );
  console.log( 'Input cookies: ', cookies );
  cookies.search = 'google';
  if ( cookies.counter )
    cookies.counter++;
  else
    cookies.counter = 1;
  console.log( 'Output cookies: ', cookies );
  response.writeHead( 200, {
    'Set-Cookie': stringifyCookies(cookies),
    'Content-Type': 'text/plain'
  } );
  response.end('Hello World\n');
} ).listen(1234);

I also note that the OP uses the http module. If the OP was using restify, he can make use of restify-cookies:

var CookieParser = require('restify-cookies');
var Restify = require('restify');
var server = Restify.createServer();
server.use(CookieParser.parse);
server.get('/', function(req, res, next){
  var cookies = req.cookies; // Gets read-only cookies from the request
  res.setCookie('my-new-cookie', 'Hi There'); // Adds a new cookie to the response
  res.send(JSON.stringify(cookies));
});
server.listen(8080);

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

Your project supports .Net Framework 4.0 and .Net Framework 4.5. If you have upgrade issues

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

instead of can use;

ServicePointManager.SecurityProtocol = (SecurityProtocolType)3072;

No WebApplicationContext found: no ContextLoaderListener registered?

You'll have to have a ContextLoaderListener in your web.xml - It loads your configuration files.

<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

You need to understand the difference between Web application context and root application context .

In the web MVC framework, each DispatcherServlet has its own WebApplicationContext, which inherits all the beans already defined in the root WebApplicationContext. These inherited beans defined can be overridden in the servlet-specific scope, and new scope-specific beans can be defined local to a given servlet instance.

The dispatcher servlet's application context is a web application context which is only applicable for the Web classes . You cannot use these for your middle tier layers . These need a global app context using ContextLoaderListener .

Read the spring reference here for spring mvc .

PHP error: "The zip extension and unzip command are both missing, skipping."

The shortest command to fix it on Debian and Ubuntu (dependencies will be installed automatically):

sudo apt install php-zip

Reading int values from SqlDataReader

you can use

reader.GetInt32(3);

to read an 32 bit int from the data reader.

If you know the type of your data I think its better to read using the Get* methods which are strongly typed rather than just reading an object and casting.

Have you considered using

reader.GetInt32(reader.GetOrdinal(columnName)) 

rather than accessing by position. This makes your code less brittle and will not break if you change the query to add new columns before the existing ones. If you are going to do this in a loop, cache the ordinal first.

How long is the SHA256 hash?

A sha256 is 256 bits long -- as its name indicates.

Since sha256 returns a hexadecimal representation, 4 bits are enough to encode each character (instead of 8, like for ASCII), so 256 bits would represent 64 hex characters, therefore you need a varchar(64), or even a char(64), as the length is always the same, not varying at all.

And the demo :

$hash = hash('sha256', 'hello, world!');
var_dump($hash);

Will give you :

$ php temp.php
string(64) "68e656b251e67e8358bef8483ab0d51c6619f3e7a1a9f0e75838d41ff368f728"

i.e. a string with 64 characters.

Process with an ID #### is not running in visual studio professional 2013 update 3

Running as administrator didn't seem to make a difference when I got this.

  • Make sure all iisexpress.exe processes had been closed
  • Edit <path_to_your_solution>\Solution\.vs\config\applicationhost.config
  • Change the site name.

    <site name="MySite" id="1" serverAutoStart="true">

    to :

    <site name="MySite2" id="1" serverAutoStart="true">

  • That fixed it for me

How to change the text on the action bar

try do this...

public void onCreate(Bundle savedInstanceState) 
{
super.onCreate(savedInstanceState);
    this.setTitle(String.format(your_format_string, your_personal_text_to_display));
    setContentView(R.layout.your_layout);
       ...
       ...
}

it works for me

dropdownlist set selected value in MVC3 Razor

I prefer the lambda form of the DropDownList helper - see MVC 3 Layout Page, Razor Template, and DropdownList

If you want to use the SelectList, then I think this bug report might assist - http://aspnet.codeplex.com/workitem/4932

Write and read a list from file

If you don't need it to be human-readable/editable, the easiest solution is to just use pickle.

To write:

with open(the_filename, 'wb') as f:
    pickle.dump(my_list, f)

To read:

with open(the_filename, 'rb') as f:
    my_list = pickle.load(f)

If you do need them to be human-readable, we need more information.

If my_list is guaranteed to be a list of strings with no embedded newlines, just write them one per line:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write(s + '\n')

with open(the_filename, 'r') as f:
    my_list = [line.rstrip('\n') for line in f]

If they're Unicode strings rather than byte strings, you'll want to encode them. (Or, worse, if they're byte strings, but not necessarily in the same encoding as your system default.)

If they might have newlines, or non-printable characters, etc., you can use escaping or quoting. Python has a variety of different kinds of escaping built into the stdlib.

Let's use unicode-escape here to solve both of the above problems at once:

with open(the_filename, 'w') as f:
    for s in my_list:
        f.write((s + u'\n').encode('unicode-escape'))

with open(the_filename, 'r') as f:
    my_list = [line.decode('unicode-escape').rstrip(u'\n') for line in f]

You can also use the 3.x-style solution in 2.x, with either the codecs module or the io module:*

import io

with io.open(the_filename, 'w', encoding='unicode-escape') as f:
    f.writelines(line + u'\n' for line in my_list)

with open(the_filename, 'r') as f:
    my_list = [line.rstrip(u'\n') for line in f]

* TOOWTDI, so which is the one obvious way? It depends… For the short version: if you need to work with Python versions before 2.6, use codecs; if not, use io.

FULL OUTER JOIN vs. FULL JOIN

Microsoft® SQL Server™ 2000 uses these SQL-92 keywords for outer joins specified in a FROM clause:

  • LEFT OUTER JOIN or LEFT JOIN

  • RIGHT OUTER JOIN or RIGHT JOIN

  • FULL OUTER JOIN or FULL JOIN

From MSDN

The full outer join or full join returns all rows from both tables, matching up the rows wherever a match can be made and placing NULLs in the places where no matching row exists.

object==null or null==object?

This is probably a habit learned from C, to avoid this sort of typo (single = instead of a double ==):

if (object = null) {

The convention of putting the constant on the left side of == isn't really useful in Java since Java requires that the expression in an if evaluate to a boolean value, so unless the constant is a boolean, you'd get a compilation error either way you put the arguments. (and if it is a boolean, you shouldn't be using == anyway...)

jQuery dialog popup

You can use the following script. It worked for me

The modal itself consists of a main modal container, a header, a body, and a footer. The footer contains the actions, which in this case is the OK button, the header holds the title and the close button, and the body contains the modal content.

 $(function () {
        modalPosition();
        $(window).resize(function () {
            modalPosition();
        });
        $('.openModal').click(function (e) {
            $('.modal, .modal-backdrop').fadeIn('fast');
            e.preventDefault();
        });
        $('.close-modal').click(function (e) {
            $('.modal, .modal-backdrop').fadeOut('fast');
        });
    });
    function modalPosition() {
        var width = $('.modal').width();
        var pageWidth = $(window).width();
        var x = (pageWidth / 2) - (width / 2);
        $('.modal').css({ left: x + "px" });
    }

Refer:- Modal popup using jquery in asp.net

How to identify which columns are not "NA" per row in a matrix?

Try:

which( !is.na(p), arr.ind=TRUE)

Which I think is just as informative and probably more useful than the output you specified, But if you really wanted the list version, then this could be used:

> apply(p, 1, function(x) which(!is.na(x)) )
[[1]]
[1] 2 3

[[2]]
[1] 4 7

[[3]]
integer(0)

[[4]]
[1] 5

[[5]]
integer(0)

Or even with smushing together with paste:

lapply(apply(p, 1, function(x) which(!is.na(x)) ) , paste, collapse=", ")

The output from which function the suggested method delivers the row and column of non-zero (TRUE) locations of logical tests:

> which( !is.na(p), arr.ind=TRUE)
     row col
[1,]   1   2
[2,]   1   3
[3,]   2   4
[4,]   4   5
[5,]   2   7

Without the arr.ind parameter set to non-default TRUE, you only get the "vector location" determined using the column major ordering the R has as its convention. R-matrices are just "folded vectors".

> which( !is.na(p) )
[1]  6 11 17 24 32

How to change the color of an svg element?

You can't change the color of an image that way. If you load SVG as an image, you can't change how it is displayed using CSS or Javascript in the browser.

If you want to change your SVG image, you have to load it using <object>, <iframe> or using <svg> inline.

If you want to use the techniques in the page, you need the Modernizr library, where you can check for SVG support and conditionally display or not a fallback image. You can then inline your SVG and apply the styles you need.

See :

_x000D_
_x000D_
#time-3-icon {_x000D_
   fill: green;_x000D_
}_x000D_
_x000D_
.my-svg-alternate {_x000D_
  display: none;_x000D_
}_x000D_
.no-svg .my-svg-alternate {_x000D_
  display: block;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-image: url(image.png);_x000D_
}
_x000D_
<svg width="96px" height="96px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">_x000D_
<path id="time-3-icon" d="M256,50C142.229,50,50,142.229,50,256c0,113.77,92.229,206,206,206c113.77,0,206-92.23,206-206_x000D_
 C462,142.229,369.77,50,256,50z M256,417c-88.977,0-161-72.008-161-161c0-88.979,72.008-161,161-161c88.977,0,161,72.007,161,161_x000D_
 C417,344.977,344.992,417,256,417z M382.816,265.785c1.711,0.297,2.961,1.781,2.961,3.518v0.093c0,1.72-1.223,3.188-2.914,3.505_x000D_
 c-37.093,6.938-124.97,21.35-134.613,21.35c-13.808,0-25-11.192-25-25c0-9.832,14.79-104.675,21.618-143.081_x000D_
 c0.274-1.542,1.615-2.669,3.181-2.669h0.008c1.709,0,3.164,1.243,3.431,2.932l18.933,119.904L382.816,265.785z"/>_x000D_
</svg>_x000D_
_x000D_
<image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" />
_x000D_
_x000D_
_x000D_

You can inline your SVG, tag your fallback image with a class name (my-svg-alternate):

<svg width="96px" height="96px" viewBox="0 0 512 512" enable-background="new 0 0 512 512" xml:space="preserve">
<path id="time-3-icon" .../>
</svg>

<image class="my-svg-alternate" width="96" height="96" src="ppngfallback.png" />

And in CSS use the no-svg class from Modernizr (CDN: http://ajax.aspnetcdn.com/ajax/modernizr/modernizr-2.7.2.js ) to check for SVG support. If there is no SVG support the SVG block will be ignored and the image will be displayed, otherwise the image will be removed from the DOM tree (display: none):

.my-svg-alternate {
  display: none;
}
.no-svg .my-svg-alternate {
  display: block;
  width: 100px;
  height: 100px;
  background-image: url(image.png);
}

Then you can change the color of your inlined element:

#time-3-icon {
   fill: green;
}

Node.js Web Application examples/tutorials

I would suggest you check out the various tutorials that are coming out lately. My current fav is:

http://nodetuts.com/

Hope this helps.

How to change JAVA.HOME for Eclipse/ANT

Set environment variables

This is the part that I always forget. Because you’re installing Ant by hand, you also need to deal with setting environment variables by hand.

For Windows XP: To set environment variables on Windows XP, right click on My Computer and select Properties. Then go to the Advanced tab and click the Environment Variables button at the bottom.

For Windows 7: To set environment variables on Windows 7, right click on Computer and select Properties. Click on Advanced System Settings and click the Environment Variables button at the bottom.

The dialog for both Windows XP and Windows 7 is the same. Make sure you’re only working on system variables and not user variables.

The only environment variable that you absolutely need is JAVA_HOME, which tells Ant the location of your JRE. If you’ve installed the JDK, this is likely c:\Program Files\Java\jdk1.x.x\jre on Windows XP and c:\Program Files(x86)\Java\jdk1.x.x\jre on Windows 7. You’ll note that both have spaces in their paths, which causes a problem. You need to use the mangled name[3] instead of the complete name. So for Windows XP, use C:\Progra~1\Java\jdk1.x.x\jre and for Windows 7, use C:\Progra~2\Java\jdk1.6.0_26\jre if it’s installed in the Program Files(x86) folder (otherwise use the same as Windows XP).

That alone is enough to get Ant to work, but for convenience, it’s a good idea to add the Ant binary path to the PATH variable. This variable is a semicolon-delimited list of directories to search for executables. To be able to run ant in any directory, Windows needs to know both the location for the ant binary and for the java binary. You’ll need to add both of these to the end of the PATH variable. For Windows XP, you’ll likely add something like this:

;c:\java\ant\bin;C:\Progra~1\Java\jdk1.x.x\jre\bin

For Windows 7, it will look something like this:

;c:\java\ant\bin;C:\Progra~2\Java\jdk1.x.x\jre\bin

Done

Once you’ve done that and applied the changes, you’ll need to open a new command prompt to see if the variables are set properly. You should be able to simply run ant and see something like this:

Buildfile: build.xml does not exist!
Build failed

How to replace ${} placeholders in a text file?

I found this thread while wondering the same thing. It inspired me to this (careful with the backticks)

$ echo $MYTEST
pass!
$ cat FILE
hello $MYTEST world
$ eval echo `cat FILE`
hello pass! world

Bootstrap 3 Horizontal Divider (not in a dropdown)

As I found the default Bootstrap <hr/> size unsightly, here's some simple HTML and CSS to balance out the element visually:

HTML:

<hr class="half-rule"/>

CSS:

.half-rule { 
    margin-left: 0;
    text-align: left;
    width: 50%;
 }

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

Add below line to file where error is being thrown.This should fix the issue

declare var Promise: any;

P.S: This is definitely not the optimal solution

Remove the legend on a matplotlib figure

If you want to plot a Pandas dataframe and want to remove the legend, add legend=None as parameter to the plot command.

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

df2 = pd.DataFrame(np.random.randn(10, 5))
df2.plot(legend=None)
plt.show()

Datatables - Search Box outside datatable

I had the same problem.

I tried all alternatives posted, but no work, I used a way that is not right but it worked perfectly.

Example search input

<input id="searchInput" type="text"> 

the jquery code

$('#listingData').dataTable({
  responsive: true,
  "bFilter": true // show search input
});
$("#listingData_filter").addClass("hidden"); // hidden search input

$("#searchInput").on("input", function (e) {
   e.preventDefault();
   $('#listingData').DataTable().search($(this).val()).draw();
});

Firefox Add-on RESTclient - How to input POST parameters?

I tried the methods mentioned in some other answers, but they look like workarounds to me. Using Firefox Add-on RESTclient to send HTTP POST requests with parameters is not straightforward in my opinion, at least for the version I'm currently using, 2.0.1.

Instead, try using other free open source tools, such as Apache JMeter. It is simple and straightforward (see the screenshot as below)

enter image description here

Using Django time/date widgets in custom form

What about just assigning a class to your widget and then binding that class to the JQuery datepicker?

Django forms.py:

class MyForm(forms.ModelForm):

  class Meta:
    model = MyModel

  def __init__(self, *args, **kwargs):
    super(MyForm, self).__init__(*args, **kwargs)
    self.fields['my_date_field'].widget.attrs['class'] = 'datepicker'

And some JavaScript for the template:

  $(".datepicker").datepicker();

How to use android emulator for testing bluetooth application?

Download Androidx86 from this This is an iso file, so you'd
need something like VMWare or VirtualBox to run it When creating the virtual machine, you need to set the type of guest OS as Linux instead of Other.

After creating the virtual machine set the network adapter to 'Bridged'. · Start the VM and select 'Live CD VESA' at boot.

Now you need to find out the IP of this VM. Go to terminal in VM (use Alt+F1 & Alt+F7 to toggle) and use the netcfg command to find this.

Now you need open a command prompt and go to your android install folder (on host). This is usually C:\Program Files\Android\android-sdk\platform-tools>.

Type adb connect IP_ADDRESS. There done! Now you need to add Bluetooth. Plug in your USB Bluetooth dongle/Bluetooth device.

In VirtualBox screen, go to Devices>USB devices. Select your dongle.

Done! now your Android VM has Bluetooth. Try powering on Bluetooth and discovering/paring with other devices.

Now all that remains is to go to Eclipse and run your program. The Android AVD manager should show the VM as a device on the list.

Alternatively, Under settings of the virtual machine, Goto serialports -> Port 1 check Enable serial port select a port number then select port mode as disconnected click ok. now, start virtual machine. Under Devices -> USB Devices -> you can find your laptop bluetooth listed. You can simply check the option and start testing the android bluetooth application .

Source

compare two files in UNIX

Well, you can just sort the files first, and diff the sorted files.

sort file1 > file1.sorted
sort file2 > file2.sorted
diff file1.sorted file2.sorted

You can also filter the output to report lines in file2 which are absent from file1:

diff -u file1.sorted file2.sorted | grep "^+" 

As indicated in comments, you in fact do not need to sort the files. Instead, you can use a process substitution and say:

diff <(sort file1) <(sort file2)

OpenSSL and error in reading openssl.conf file

I know this is old -- but thought others that happen on this (and use Visual Studio) might benefit. I read this on another post that I can't seem to find.

Open your config in notepad++ and make sure it's Encoding is UTF-8 (i.e., not UTF-8-BOM*).

This would have save me a lot of searching/trial'n'errors...

VBA array sort function?

Heapsort implementation. An O(n log(n)) (both average and worst case), in place, unstable sorting algorithm.

Use with: Call HeapSort(A), where A is a one dimensional array of variants, with Option Base 1.

Sub SiftUp(A() As Variant, I As Long)
    Dim K As Long, P As Long, S As Variant
    K = I
    While K > 1
        P = K \ 2
        If A(K) > A(P) Then
            S = A(P): A(P) = A(K): A(K) = S
            K = P
        Else
            Exit Sub
        End If
    Wend
End Sub

Sub SiftDown(A() As Variant, I As Long)
    Dim K As Long, L As Long, S As Variant
    K = 1
    Do
        L = K + K
        If L > I Then Exit Sub
        If L + 1 <= I Then
            If A(L + 1) > A(L) Then L = L + 1
        End If
        If A(K) < A(L) Then
            S = A(K): A(K) = A(L): A(L) = S
            K = L
        Else
            Exit Sub
        End If
    Loop
End Sub

Sub HeapSort(A() As Variant)
    Dim N As Long, I As Long, S As Variant
    N = UBound(A)
    For I = 2 To N
        Call SiftUp(A, I)
    Next I
    For I = N To 2 Step -1
        S = A(I): A(I) = A(1): A(1) = S
        Call SiftDown(A, I - 1)
    Next
End Sub

Confirm deletion in modal / dialog using Twitter Bootstrap?

  // ---------------------------------------------------------- Generic Confirm  

  function confirm(heading, question, cancelButtonTxt, okButtonTxt, callback) {

    var confirmModal = 
      $('<div class="modal hide fade">' +    
          '<div class="modal-header">' +
            '<a class="close" data-dismiss="modal" >&times;</a>' +
            '<h3>' + heading +'</h3>' +
          '</div>' +

          '<div class="modal-body">' +
            '<p>' + question + '</p>' +
          '</div>' +

          '<div class="modal-footer">' +
            '<a href="#" class="btn" data-dismiss="modal">' + 
              cancelButtonTxt + 
            '</a>' +
            '<a href="#" id="okButton" class="btn btn-primary">' + 
              okButtonTxt + 
            '</a>' +
          '</div>' +
        '</div>');

    confirmModal.find('#okButton').click(function(event) {
      callback();
      confirmModal.modal('hide');
    });

    confirmModal.modal('show');     
  };

  // ---------------------------------------------------------- Confirm Put To Use

  $("i#deleteTransaction").live("click", function(event) {
    // get txn id from current table row
    var id = $(this).data('id');

    var heading = 'Confirm Transaction Delete';
    var question = 'Please confirm that you wish to delete transaction ' + id + '.';
    var cancelButtonTxt = 'Cancel';
    var okButtonTxt = 'Confirm';

    var callback = function() {
      alert('delete confirmed ' + id);
    };

    confirm(heading, question, cancelButtonTxt, okButtonTxt, callback);

  });

Nginx: Permission denied for nginx on Ubuntu

For me, I just changed the selinux from enforcing to permissive and then I was able to start nginx without any error.

Android Studio Error: Error:CreateProcess error=216, This version of %1 is not compatible with the version of Windows you're running

I had the same issue, but I have resolved it the next:

1) Install jdk1.8...

2) In AndroidStudio File->Project Structure->SDK Location, select your directory where the JDK is located, by default Studio uses embedded JDK but for some reason it produces error=216.

3) Click Ok.

How can I make a multipart/form-data POST request using Java?

Use this code to upload images or any other files to the server using post in multipart.

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;

public class SimplePostRequestTest {

    public static void main(String[] args) throws UnsupportedEncodingException, IOException {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://192.168.0.102/uploadtest/upload_photo");

        try {
            FileBody bin = new FileBody(new File("/home/ubuntu/cd.png"));
            StringBody id = new StringBody("3");
            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("upload_image", bin);
            reqEntity.addPart("id", id);
            reqEntity.addPart("image_title", new StringBody("CoolPic"));

            httppost.setEntity(reqEntity);
            System.out.println("Requesting : " + httppost.getRequestLine());
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String responseBody = httpclient.execute(httppost, responseHandler);
            System.out.println("responseBody : " + responseBody);

        } catch (ClientProtocolException e) {

        } finally {
            httpclient.getConnectionManager().shutdown();
        }
    }

}

it requires below files to upload.

libraries are httpclient-4.1.2.jar, httpcore-4.1.2.jar, httpmime-4.1.2.jar, httpclient-cache-4.1.2.jar, commons-codec.jar and commons-logging-1.1.1.jar to be in classpath.

How to fix date format in ASP .NET BoundField (DataFormatString)?

https://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.boundfield.dataformatstring(v=vs.110).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1 


In The above link you will find the answer

**C or c**

    Displays numeric values in currency format. You can specify the number of decimal places.
    Example:

Format: {0:C}
123.456 -> $123.46

**D or d**

    Displays integer values in decimal format. You can specify the number of digits. (Although the type is referred to as "decimal", the numbers are formatted as integers.)
    Example:
        Format: {0:D}
    1234 -> 1234
    Format: {0:D6}
    1234 -> 001234

    **E or e**
    Displays numeric values in scientific (exponential) format. You can specify the number of decimal places.
    Example:
    Format: {0:E}
    1052.0329112756 -> 1.052033E+003
    Format: {0:E2}
    -1052.0329112756 -> -1.05e+003

**F or f**
Displays numeric values in fixed format. You can specify the number of decimal places.
Example:
Format: {0:F}
1234.567 -> 1234.57
Format: {0:F3}
1234.567 -> 1234.567

**G or g**
Displays numeric values in general format (the most compact of either fixed-point or scientific notation). You can specify the number of significant digits.
Example:
Format: {0:G}
-123.456 -> -123.456
Format: {0:G2}
-123.456 -> -120

F or f
Displays numeric values in fixed format. You can specify the number of decimal places.
Format: {0:F}
1234.567 -> 1234.57
Format: {0:F3}
1234.567 -> 1234.567

G or g
Displays numeric values in general format (the most compact of either fixed-point or scientific notation). You can specify the number of significant digits.
Format: {0:G}
-123.456 -> -123.456
Format: {0:G2}
-123.456 -> -120

N or n
Displays numeric values in number format (including group separators and optional negative sign). You can specify the number of decimal places.
Format: {0:N}
1234.567 -> 1,234.57
Format: {0:N4}
1234.567 -> 1,234.5670

P or p
Displays numeric values in percent format. You can specify the number of decimal places.
Format: {0:P}
1 -> 100.00%
Format: {0:P1}
.5 -> 50.0%

R or r
Displays Single, Double, or BigInteger values in round-trip format.
Format: {0:R}
123456789.12345678 -> 123456789.12345678

X or x
Displays integer values in hexadecimal format. You can specify the number of digits.
Format: {0:X}
255 -> FF
Format: {0:x4}
255 -> 00ff

Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+)

There are two ways to do it.

  1. In the method that opens the dialog, pass in the following configuration option disableClose as the second parameter in MatDialog#open() and set it to true:

    export class AppComponent {
      constructor(private dialog: MatDialog){}
      openDialog() {
        this.dialog.open(DialogComponent, { disableClose: true });
      }
    }
    
  2. Alternatively, do it in the dialog component itself.

    export class DialogComponent {
      constructor(private dialogRef: MatDialogRef<DialogComponent>){
        dialogRef.disableClose = true;
      }
    }
    

Here's what you're looking for:

<code>disableClose</code> property in material.angular.io

And here's a Stackblitz demo


Other use cases

Here's some other use cases and code snippets of how to implement them.

Allow esc to close the dialog but disallow clicking on the backdrop to close the dialog

As what @MarcBrazeau said in the comment below my answer, you can allow the esc key to close the modal but still disallow clicking outside the modal. Use this code on your dialog component:

import { Component, OnInit, HostListener } from '@angular/core';
import { MatDialogRef } from '@angular/material';
@Component({
  selector: 'app-third-dialog',
  templateUrl: './third-dialog.component.html'
})
export class ThirdDialogComponent {
  constructor(private dialogRef: MatDialogRef<ThirdDialogComponent>) {      
}
  @HostListener('window:keyup.esc') onKeyUp() {
    this.dialogRef.close();
  }

}

Prevent esc from closing the dialog but allow clicking on the backdrop to close

P.S. This is an answer which originated from this answer, where the demo was based on this answer.

To prevent the esc key from closing the dialog but allow clicking on the backdrop to close, I've adapted Marc's answer, as well as using MatDialogRef#backdropClick to listen for click events to the backdrop.

Initially, the dialog will have the configuration option disableClose set as true. This ensures that the esc keypress, as well as clicking on the backdrop will not cause the dialog to close.

Afterwards, subscribe to the MatDialogRef#backdropClick method (which emits when the backdrop gets clicked and returns as a MouseEvent).

Anyways, enough technical talk. Here's the code:

openDialog() {
  let dialogRef = this.dialog.open(DialogComponent, { disableClose: true });
  /*
     Subscribe to events emitted when the backdrop is clicked
     NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
     See https://stackoverflow.com/a/41086381 for more info
  */
  dialogRef.backdropClick().subscribe(() => {
    // Close the dialog
    dialogRef.close();
  })

  // ...
}

Alternatively, this can be done in the dialog component:

export class DialogComponent {
  constructor(private dialogRef: MatDialogRef<DialogComponent>) {
    dialogRef.disableClose = true;
    /*
      Subscribe to events emitted when the backdrop is clicked
      NOTE: Since we won't actually be using the `MouseEvent` event, we'll just use an underscore here
      See https://stackoverflow.com/a/41086381 for more info
    */
    dialogRef.backdropClick().subscribe(() => {
      // Close the dialog
      dialogRef.close();
    })
  }
}

Attach a body onload event with JS

Why not using jQuery?

$(document).ready(function(){}))

As far as I know, this is the perfect solution.

Pass props in Link react-router

To work off the answer above (https://stackoverflow.com/a/44860918/2011818), you can also send the objects inline the "To" inside the Link object.

<Route path="/foo/:fooId" component={foo} / >

<Link to={{pathname:/foo/newb, sampleParam: "Hello", sampleParam2: "World!" }}> CLICK HERE </Link>

this.props.match.params.fooId //newb
this.props.location.sampleParam //"Hello"
this.props.location.sampleParam2 //"World!"

Using setTimeout to delay timing of jQuery actions

You can also use jQuery's delay() method instead of setTimeout(). It'll give you much more readable code. Here's an example from the docs:

$( "#foo" ).slideUp( 300 ).delay( 800 ).fadeIn( 400 );

The only limitation (that I'm aware of) is that it doesn't give you a way to clear the timeout. If you need to do that then you're better off sticking with all the nested callbacks that setTimeout thrusts upon you.

Substring in VBA

Shorter:

   Split(stringval,":")(0)

How to identify unused CSS definitions from multiple CSS files in a project

I have just found this site – http://unused-css.com/

Looks good but I would need to thoroughly check its outputted 'clean' css before uploading it to any of my sites.

Also as with all these tools I would need to check it didn't strip id's and classes with no style but are used as JavaScript selectors.

The below content is taken from http://unused-css.com/ so credit to them for recommending other solutions:

Latish Sehgal has written a windows application to find and remove unused CSS classes. I haven't tested it but from the description, you have to provide the path of your html files and one CSS file. The program will then list the unused CSS selectors. From the screenshot, it looks like there is no way to export this list or download a new clean CSS file. It also looks like the service is limited to one CSS file. If you have multiple files you want to clean, you have to clean them one by one.

Dust-Me Selectors is a Firefox extension (for v1.5 or later) that finds unused CSS selectors. It extracts all the selectors from all the stylesheets on the page you're viewing, then analyzes that page to see which of those selectors are not used. The data is then stored so that when testing subsequent pages, selectors can be crossed off the list as they're encountered. This tool is supposed to be able to spider a whole website but I unfortunately could make it work. Also, I don't believe you can configure and download the CSS file with the styles removed.

Topstyle is a windows application including a bunch of tools to edit CSS. I haven't tested it much but it looks like it has the ability to removed unused CSS selectors. This software costs 80 USD.

Liquidcity CSS cleaner is a php script that uses regular expressions to check the styles of one page. It will tell you the classes that aren't available in the HTML code. I haven't tested this solution.

Deadweight is a CSS coverage tool. Given a set of stylesheets and a set of URLs, it determines which selectors are actually used and lists which can be "safely" deleted. This tool is a ruby module and will only work with rails website. The unused selectors have to be manually removed from the CSS file.

Helium CSS is a javascript tool for discovering unused CSS across many pages on a web site. You first have to install the javascript file to the page you want to test. Then, you have to call a helium function to start the cleaning.

UnusedCSS.com is web application with an easy to use interface. Type the url of a site and you will get a list of CSS selectors. For each selector, a number indicates how many times a selector is used. This service has a few limitations. The @import statement is not supported. You can't configure and download the new clean CSS file.

CSSESS is a bookmarklet that helps you find unused CSS selectors on any site. This tool is pretty easy to use but it won't let you configure and download clean CSS files. It will only list unused CSS files.

changing iframe source with jquery

Should work.

Here's a working example:

http://jsfiddle.net/rhpNc/

Excerpt:

function loadIframe(iframeName, url) {
    var $iframe = $('#' + iframeName);
    if ($iframe.length) {
        $iframe.attr('src',url);
        return false;
    }
    return true;
}

No module named 'pymysql'

I tried installing pymysql on command prompt by typing

pip install pymysql

But it still dont work on my case, so I decided to try using the terminal IDE and it works.

Performing Inserts and Updates with Dapper

Performing CRUD operations using Dapper is an easy task. I have mentioned the below examples that should help you in CRUD operations.

Code for CRUD:

Method #1: This method is used when you are inserting values from different entities.

using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
    string insertQuery = @"INSERT INTO [dbo].[Customer]([FirstName], [LastName], [State], [City], [IsActive], [CreatedOn]) VALUES (@FirstName, @LastName, @State, @City, @IsActive, @CreatedOn)";

    var result = db.Execute(insertQuery, new
    {
        customerModel.FirstName,
        customerModel.LastName,
        StateModel.State,
        CityModel.City,
        isActive,
        CreatedOn = DateTime.Now
    });
}

Method #2: This method is used when your entity properties have the same names as the SQL columns. So, Dapper being an ORM maps entity properties with the matching SQL columns.

using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
    string insertQuery = @"INSERT INTO [dbo].[Customer]([FirstName], [LastName], [State], [City], [IsActive], [CreatedOn]) VALUES (@FirstName, @LastName, @State, @City, @IsActive, @CreatedOn)";

    var result = db.Execute(insertQuery, customerViewModel);
}

Code for CRUD:

using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
    string selectQuery = @"SELECT * FROM [dbo].[Customer] WHERE FirstName = @FirstName";

    var result = db.Query(selectQuery, new
    {
        customerModel.FirstName
    });
}

Code for CRUD:

using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
    string updateQuery = @"UPDATE [dbo].[Customer] SET IsActive = @IsActive WHERE FirstName = @FirstName AND LastName = @LastName";

    var result = db.Execute(updateQuery, new
    {
        isActive,
        customerModel.FirstName,
        customerModel.LastName
    });
}

Code for CRUD:

using (IDbConnection db = new SqlConnection(ConfigurationManager.ConnectionStrings["myDbConnection"].ConnectionString))
{
    string deleteQuery = @"DELETE FROM [dbo].[Customer] WHERE FirstName = @FirstName AND LastName = @LastName";

    var result = db.Execute(deleteQuery, new
    {
        customerModel.FirstName,
        customerModel.LastName
    });
}

Could not connect to React Native development server on Android

I met this question too in native and react-native pro, my solution was:

  1. open npm server with npm start
  2. run native project with Android Studio
  3. transmission network request with adb reverse tcp:8081 tcp:8081
  4. when you need to reload the page, just input: adb shell input keyevent 82

just keep it in order.

P.S. if you ran a fail project, just run adb kill-server

How to read an http input stream

a complete code for reading from a webservice in two ways

public void buttonclick(View view) {
    // the name of your webservice where reactance is your method
    new GetMethodDemo().execute("http://wervicename.nl/service.asmx/reactance");
}

public class GetMethodDemo extends AsyncTask<String, Void, String> {
    //see also: 
    // https://developer.android.com/reference/java/net/HttpURLConnection.html
    //writing to see:    https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html
    String server_response;
    @Override
    protected String doInBackground(String... strings) {
        URL url;
        HttpURLConnection urlConnection = null;
        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            int responseCode = urlConnection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                server_response = readStream(urlConnection.getInputStream());
                Log.v("CatalogClient", server_response);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            url = new URL(strings[0]);
            urlConnection = (HttpURLConnection) url.openConnection();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    urlConnection.getInputStream()));
            String inputLine;
            while ((inputLine = in.readLine()) != null)
                System.out.println(inputLine);
            in.close();
            Log.v("bufferv ", server_response);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onPostExecute(String s) {
        super.onPostExecute(s);
        Log.e("Response", "" + server_response);
   //assume there is a field with id editText
        EditText editText = (EditText) findViewById(R.id.editText);
        editText.setText(server_response);
    }
}

Converting an object to a string

None of the solutions here worked for me. JSON.stringify seems to be what a lot of people say, but it cuts out functions and seems pretty broken for some objects and arrays I tried when testing it.

I made my own solution which works in Chrome at least. Posting it here so anyone that looks this up on Google can find it.

//Make an object a string that evaluates to an equivalent object
//  Note that eval() seems tricky and sometimes you have to do
//  something like eval("a = " + yourString), then use the value
//  of a.
//
//  Also this leaves extra commas after everything, but JavaScript
//  ignores them.
function convertToText(obj) {
    //create an array that will later be joined into a string.
    var string = [];

    //is object
    //    Both arrays and objects seem to return "object"
    //    when typeof(obj) is applied to them. So instead
    //    I am checking to see if they have the property
    //    join, which normal objects don't have but
    //    arrays do.
    if (typeof(obj) == "object" && (obj.join == undefined)) {
        string.push("{");
        for (prop in obj) {
            string.push(prop, ": ", convertToText(obj[prop]), ",");
        };
        string.push("}");

    //is array
    } else if (typeof(obj) == "object" && !(obj.join == undefined)) {
        string.push("[")
        for(prop in obj) {
            string.push(convertToText(obj[prop]), ",");
        }
        string.push("]")

    //is function
    } else if (typeof(obj) == "function") {
        string.push(obj.toString())

    //all other values can be done with JSON.stringify
    } else {
        string.push(JSON.stringify(obj))
    }

    return string.join("")
}

EDIT: I know this code can be improved but just never got around to doing it. User andrey suggested an improvement here with the comment:

Here is a little bit changed code, which can handle 'null' and 'undefined', and also do not add excessive commas.

Use that at your own risk as I haven't verified it at all. Feel free to suggest any additional improvements as a comment.

ALTER TABLE on dependent column

you can drop the Constraint which is restricting you. If the column has access to other table. suppose a view is accessing the column which you are altering then it wont let you alter the column unless you drop the view. and after making changes you can recreate the view.

enter image description here

How to set specific Java version to Maven

On Macs, (assuming you have the right version installed)

JAVA_HOME=`/usr/libexec/java_home -v 1.8` mvn clean install -DskipTests

TypeError: Converting circular structure to JSON in nodejs

It's because you don't an async response For example:

app.get(`${api}/users`, async (req, res) => {
    const users = await User.find()
    res.send(users);
   })

Instantiating a generic type

You basically have two choices:

1.Require an instance:

public Navigation(T t) {     this("", "", t); } 

2.Require a class instance:

public Navigation(Class<T> c) {     this("", "", c.newInstance()); } 

You could use a factory pattern, but ultimately you'll face this same issue, but just push it elsewhere in the code.

What is stdClass in PHP?

Its also worth noting that by using Casting you do not actually need to create an object as in the answer given by @Bandula. Instead you can simply cast your array to an object and the stdClass is returned. For example:

$array = array(
    'Property1'=>'hello',
    'Property2'=>'world',
    'Property3'=>'again',
);

$obj = (object) $array;
echo $obj->Property3;

Output: again

How can I shrink the drawable on a button?

It is because you did not setLevel. after you setLevel(1), it will be display as u want

Can't load IA 32-bit .dll on a AMD 64-bit platform

Go to

Project properties >> Run >> VM options

and put this address:

-Djava.library.path="C:\opencv\build\java\x64"

symfony2 twig path with parameter url creation

Make sure your routing.yml file has 'id' specified in it. In other words, it should look like:

_category:
    path: /category/{id}

SQL User Defined Function Within Select

Yes, you can do almost that:

SELECT dbo.GetBusinessDays(a.opendate,a.closedate) as BusinessDays
FROM account a
WHERE...

How to check for registry value using VbScript

Set objShell = WScript.CreateObject("WScript.Shell") 
skey = "HKLM\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\{9A25302D-30C0-39D9-BD6F-21E6EC160475}\"
with CreateObject("WScript.Shell")
    on error resume next            ' turn off error trapping
    sValue = .regread(sKey)       ' read attempt
    bFound = (err.number = 0)     ' test for success
end with
if bFound then
    msgbox "exists"
else
  msgbox "not exists" 
End If

Change navbar color in Twitter Bootstrap

In this navbar CSS, set to own color:

_x000D_
_x000D_
/* Navbar */_x000D_
.navbar-default {_x000D_
    background-color: #F8F8F8;_x000D_
    border-color: #E7E7E7;_x000D_
}_x000D_
/* Title */_x000D_
.navbar-default .navbar-brand {_x000D_
    color: #777;_x000D_
}_x000D_
.navbar-default .navbar-brand:hover,_x000D_
.navbar-default .navbar-brand:focus {_x000D_
    color: #5E5E5E;_x000D_
}_x000D_
/* Link */_x000D_
.navbar-default .navbar-nav > li > a {_x000D_
    color: #777;_x000D_
}_x000D_
.navbar-default .navbar-nav > li > a:hover,_x000D_
.navbar-default .navbar-nav > li > a:focus {_x000D_
    color: #333;_x000D_
}_x000D_
.navbar-default .navbar-nav > .active > a, _x000D_
.navbar-default .navbar-nav > .active > a:hover, _x000D_
.navbar-default .navbar-nav > .active > a:focus {_x000D_
    color: #555;_x000D_
    background-color: #E7E7E7;_x000D_
}_x000D_
.navbar-default .navbar-nav > .open > a, _x000D_
.navbar-default .navbar-nav > .open > a:hover, _x000D_
.navbar-default .navbar-nav > .open > a:focus {_x000D_
    color: #555;_x000D_
    background-color: #D5D5D5;_x000D_
}_x000D_
/* Caret */_x000D_
.navbar-default .navbar-nav > .dropdown > a .caret {_x000D_
    border-top-color: #777;_x000D_
    border-bottom-color: #777;_x000D_
}_x000D_
.navbar-default .navbar-nav > .dropdown > a:hover .caret,_x000D_
.navbar-default .navbar-nav > .dropdown > a:focus .caret {_x000D_
    border-top-color: #333;_x000D_
    border-bottom-color: #333;_x000D_
}_x000D_
.navbar-default .navbar-nav > .open > a .caret, _x000D_
.navbar-default .navbar-nav > .open > a:hover .caret, _x000D_
.navbar-default .navbar-nav > .open > a:focus .caret {_x000D_
    border-top-color: #555;_x000D_
    border-bottom-color: #555;_x000D_
}
_x000D_
_x000D_
_x000D_

Primitive type 'short' - casting in Java

EDIT: Okay, now we know it's Java...

Section 4.2.2 of the Java Language Specification states:

The Java programming language provides a number of operators that act on integral values:

[...]

  • The numerical operators, which result in a value of type int or long:
  • [...]
  • The additive operators + and - (§15.18)

  • In other words, it's like C# - the addition operator (when applied to integral types) only ever results in int or long, which is why you need to cast to assign to a short variable.

    Original answer (C#)

    In C# (you haven't specified the language, so I'm guessing), the only addition operators on primitive types are:

    int operator +(int x, int y);
    uint operator +(uint x, uint y);
    long operator +(long x, long y);
    ulong operator +(ulong x, ulong y);
    float operator +(float x, float y);
    double operator +(double x, double y);
    

    These are in the C# 3.0 spec, section 7.7.4. In addition, decimal addition is defined:

    decimal operator +(decimal x, decimal y);
    

    (Enumeration addition, string concatenation and delegate combination are also defined there.)

    As you can see, there's no short operator +(short x, short y) operator - so both operands are implicitly converted to int, and the int form is used. That means the result is an expression of type "int", hence the need to cast.

    Skip the headers when editing a csv file using Python

    Your reader variable is an iterable, by looping over it you retrieve the rows.

    To make it skip one item before your loop, simply call next(reader, None) and ignore the return value.

    You can also simplify your code a little; use the opened files as context managers to have them closed automatically:

    with open("tmob_notcleaned.csv", "rb") as infile, open("tmob_cleaned.csv", "wb") as outfile:
       reader = csv.reader(infile)
       next(reader, None)  # skip the headers
       writer = csv.writer(outfile)
       for row in reader:
           # process each row
           writer.writerow(row)
    
    # no need to close, the files are closed automatically when you get to this point.
    

    If you wanted to write the header to the output file unprocessed, that's easy too, pass the output of next() to writer.writerow():

    headers = next(reader, None)  # returns the headers or `None` if the input is empty
    if headers:
        writer.writerow(headers)
    

    Python os.path.join() on a list

    This can be also thought of as a simple map reduce operation if you would like to think of it from a functional programming perspective.

    import os
    folders = [("home",".vim"),("home","zathura")]
    [reduce(lambda x,y: os.path.join(x,y), each, "") for each in folders]
    

    reduce is builtin in Python 2.x. In Python 3.x it has been moved to itertools However the accepted the answer is better.

    This has been answered below but answering if you have a list of items that needs to be joined.

    Most efficient conversion of ResultSet to JSON?

    The JIT Compiler is probably going to make this pretty fast since it's just branches and basic tests. You could probably make it more elegant with a HashMap lookup to a callback but I doubt it would be any faster. As to memory, this is pretty slim as is.

    Somehow I doubt this code is actually a critical bottle neck for memory or performance. Do you have any real reason to try to optimize it?

    Finding blocking/locking queries in MS SQL (mssql)

    I found this query which helped me find my locked table and query causing the issue.

    SELECT  L.request_session_id AS SPID, 
            DB_NAME(L.resource_database_id) AS DatabaseName,
            O.Name AS LockedObjectName, 
            P.object_id AS LockedObjectId, 
            L.resource_type AS LockedResource, 
            L.request_mode AS LockType,
            ST.text AS SqlStatementText,        
            ES.login_name AS LoginName,
            ES.host_name AS HostName,
            TST.is_user_transaction as IsUserTransaction,
            AT.name as TransactionName,
            CN.auth_scheme as AuthenticationMethod
    FROM    sys.dm_tran_locks L
            JOIN sys.partitions P ON P.hobt_id = L.resource_associated_entity_id
            JOIN sys.objects O ON O.object_id = P.object_id
            JOIN sys.dm_exec_sessions ES ON ES.session_id = L.request_session_id
            JOIN sys.dm_tran_session_transactions TST ON ES.session_id = TST.session_id
            JOIN sys.dm_tran_active_transactions AT ON TST.transaction_id = AT.transaction_id
            JOIN sys.dm_exec_connections CN ON CN.session_id = ES.session_id
            CROSS APPLY sys.dm_exec_sql_text(CN.most_recent_sql_handle) AS ST
    WHERE   resource_database_id = db_id()
    ORDER BY L.request_session_id
    

    how to get selected row value in the KendoUI

    One way is to use the Grid's select() and dataItem() methods.

    In single selection case, select() will return a single row which can be passed to dataItem()

    var entityGrid = $("#EntitesGrid").data("kendoGrid");
    var selectedItem = entityGrid.dataItem(entityGrid.select());
    // selectedItem has EntityVersionId and the rest of your model
    

    For multiple row selection select() will return an array of rows. You can then iterate through the array and the individual rows can be passed into the grid's dataItem().

    var entityGrid = $("#EntitesGrid").data("kendoGrid");
    var rows = entityGrid.select();
    rows.each(function(index, row) {
      var selectedItem = entityGrid.dataItem(row);
      // selectedItem has EntityVersionId and the rest of your model
    });
    

    How to get child element by ID in JavaScript?

    (Dwell in atom)
    
    <div id="note">
    
       <textarea id="textid" class="textclass">Text</textarea>
    
    </div>
    
    <script type="text/javascript">
    
       var note = document.getElementById('textid').value;
    
       alert(note);
    
    </script>
    

    How do I write data to csv file in columns and rows from a list in python?

    >>> import csv
    >>> with open('test.csv', 'wb') as f:
    ...     wtr = csv.writer(f, delimiter= ' ')
    ...     wtr.writerows( [[1, 2], [2, 3], [4, 5]])
    ...
    >>> with open('test.csv', 'r') as f:
    ...     for line in f:
    ...         print line,
    ...
    1 2 <<=== Exactly what you said that you wanted.
    2 3
    4 5
    >>>
    

    To get it so that it can be loaded sensibly by Excel, you need to use a comma (the csv default) as the delimiter, unless you are in a locale (e.g. Europe) where you need a semicolon.

    Play/pause HTML 5 video using JQuery

    Just as a note, make sure you check if the browser supports the video function, before you try to invoke it:

    if($('#movie1')[0].play)
        $('#movie1')[0].play();
    

    That will prevent JavaScript errors on browsers that don't support the video tag.

    String.Format like functionality in T-SQL?

    I think there is small correction while calculating end position.

    Here is correct function

    **>>**IF OBJECT_ID( N'[dbo].[FormatString]', 'FN' ) IS NOT NULL
    DROP FUNCTION [dbo].[FormatString]
    GO
    /***************************************************
    Object Name : FormatString
    Purpose : Returns the formatted string.
    Original Author : Karthik D V http://stringformat-in-sql.blogspot.com/
    Sample Call:
    SELECT dbo.FormatString ( N'Format {0} {1} {2} {0}', N'1,2,3' )
    *******************************************/
    CREATE FUNCTION [dbo].[FormatString](
        @Format NVARCHAR(4000) ,
        @Parameters NVARCHAR(4000)
    )
    RETURNS NVARCHAR(4000)
    AS
    BEGIN
        --DECLARE @Format NVARCHAR(4000), @Parameters NVARCHAR(4000) select @format='{0}{1}', @Parameters='hello,world'
        DECLARE @Message NVARCHAR(400), @Delimiter CHAR(1)
        DECLARE @ParamTable TABLE ( ID INT IDENTITY(0,1), Parameter VARCHAR(1000) )
        Declare @startPos int, @endPos int
        SELECT @Message = @Format, @Delimiter = ','**>>**
    
        --handle first parameter
         set @endPos=CHARINDEX(@Delimiter,@Parameters)
        if (@endPos=0 and @Parameters is not null) --there is only one parameter
            insert into @ParamTable (Parameter) values(@Parameters)
        else begin
            insert into @ParamTable (Parameter) select substring(@Parameters,0,@endPos)
        end
    
        while @endPos>0
        Begin
            --insert a row for each parameter in the 
            set @startPos = @endPos + LEN(@Delimiter)
            set @endPos = CHARINDEX(@Delimiter,@Parameters, @startPos)
            if (@endPos>0)
                insert into @ParamTable (Parameter) 
                    select substring(@Parameters,@startPos,@endPos - @startPos)
                else
                    insert into @ParamTable (Parameter) 
                    select substring(@Parameters,@startPos,4000)            
        End
    
        UPDATE @ParamTable SET @Message = 
            REPLACE ( @Message, '{'+CONVERT(VARCHAR,ID) + '}', Parameter )
        RETURN @Message
    END
    Go
    grant execute,references on dbo.formatString to public 
    

    java.lang.NoClassDefFoundError: org/apache/http/client/HttpClient

    If its a maven project, add the below dependency in your pom file

        <dependency>
            <groupId>org.apache.httpcomponents</groupId>
            <artifactId>httpclient</artifactId>
            <version>4.3.4</version>
        </dependency>
    

    What certificates are trusted in truststore?

    Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

    keytool -list -v -keystore truststore.jks
    

    background: fixed no repeat not working on mobile

    This is what i do and it works everythere :)

    .container {
      background: url(${myImage})
      background-attachment: fixed;
      background-size: cover;
     transform: scale(1.1, 1.1);
    

    }

    then...

    @media only screen and (max-width: 768px){
       background-size: 100% 100vh;
    }
    

    Importing CSV data using PHP/MySQL

    i think the main things to remember about parsing csv is that it follows some simple rules:

    a)it's a text file so easily opened b) each row is determined by a line end \n so split the string into lines first c) each row/line has columns determined by a comma so split each line by that to get an array of columns

    have a read of this post to see what i am talking about

    it's actually very easy to do once you have the hang of it and becomes very useful.

    Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory

    If you are running laravel inside docker then access its filesystem

    $ docker exec -it name-of-laravel-container /bin/bash
    

    Next navigate to your laravel projects root directory. Make sure that you have inside storage/framework folder:

    1. cache
    2. sessions
    3. testing
    4. views

    And they should be both readable and writable.

    How to remove class from all elements jquery

    You need to select the li tags contained within the .edgetoedge class. .edgetoedge only matches the one ul tag:

    $(".edgetoedge li").removeClass("highlight");
    

    Change Select List Option background colour on hover in html

    Currently there is no way to apply a css to get your desired result . Why not use libraries like choosen or select2 . These allow you to style the way you want.

    If you don want to use third party libraries then you can make a simple un-ordered list and play with some css.Here is thread you could follow

    How to convert <select> dropdown into an unordered list using jquery?

    Mongoose delete array element in document and save

    You can also do the update directly in MongoDB without having to load the document and modify it using code. Use the $pull or $pullAll operators to remove the item from the array :

    Favorite.updateOne( {cn: req.params.name}, { $pullAll: {uid: [req.params.deleteUid] } } )
    

    (you can also use updateMany for multiple documents)

    http://docs.mongodb.org/manual/reference/operator/update/pullAll/

    How can I listen to the form submit event in javascript?

    Based on your requirements you can also do the following without libraries like jQuery:

    Add this to your head:

    window.onload = function () {
        document.getElementById("frmSubmit").onsubmit = function onSubmit(form) {
            var isValid = true;
            //validate your elems here
            isValid = false;
    
            if (!isValid) {
                alert("Please check your fields!");
                return false;
            }
            else {
                //you are good to go
                return true;
            }
        }
    }
    

    And your form may still look something like:

        <form id="frmSubmit" action="/Submit">
            <input type="submit" value="Submit" />
        </form>
    

    How to conclude your merge of a file?

    I had the same error and i did followed article found on google solves my issue. You have not concluded your merge

    Getting "java.nio.file.AccessDeniedException" when trying to write to a folder

    Delete .android folder cache files, Also delete the build folder manually from a directory and open android studio and run again.

    enter image description here

    Allow scroll but hide scrollbar

    I know this is an oldie but here is a quick way to hide the scroll bar with pure CSS.

    Just add

    ::-webkit-scrollbar {display:none;}
    

    To your id or class of the div you're using the scroll bar with.

    Here is a helpful link Custom Scroll Bar in Webkit

    Java: Static vs inner class

    An inner class, by definition, cannot be static, so I am going to recast your question as "What is the difference between static and non-static nested classes?"

    A non-static nested class has full access to the members of the class within which it is nested. A static nested class does not have a reference to a nesting instance, so a static nested class cannot invoke non-static methods or access non-static fields of an instance of the class within which it is nested.

    How to set an button align-right with Bootstrap?

    Try this:

    <div class="row">
    <div class="alert alert-info" style="min-height:100px;">
        <div class="col-xs-9">
            <a href="#" class="alert-link">Summary:Its some
               description.......testtesttest</a>  
        </div>
        <div class="col-xs-3">
            <button type="button" class="btn btn-primary btn-lg">Large      button</button>
        </div>
     </div>
    </div>
    

    Demo:

    http://jsfiddle.net/Hx6Sx/1/

    How to remove specific session in asp.net?

    you can use Session.Remove() method; Session.Remove

    Session.Remove("yourSessionName");
    

    How to start new activity on button click

    Easy.

    Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
    myIntent.putExtra("key", value); //Optional parameters
    CurrentActivity.this.startActivity(myIntent);
    

    Extras are retrieved on the other side via:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        Intent intent = getIntent();
        String value = intent.getStringExtra("key"); //if it's a string you stored.
    }
    

    Don't forget to add your new activity in the AndroidManifest.xml:

    <activity android:label="@string/app_name" android:name="NextActivity"/>
    

    How to extract Month from date in R

    ?month states:

    Date-time must be a POSIXct, POSIXlt, Date, Period, chron, yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.

    Your object is a factor, not even a character vector (presumably because of stringsAsFactors = TRUE). You have to convert your vector to some datetime class, for instance to POSIXlt:

    library(lubridate)
    some_date <- c("01/02/1979", "03/04/1980")
    month(as.POSIXlt(some_date, format="%d/%m/%Y"))
    [1] 2 4
    

    There's also a convenience function dmy, that can do the same (tip proposed by @Henrik):

    month(dmy(some_date))
    [1] 2 4
    

    Going even further, @IShouldBuyABoat gives another hint that dd/mm/yyyy character formats are accepted without any explicit casting:

    month(some_date)
    [1] 2 4
    

    For a list of formats, see ?strptime. You'll find that "standard unambiguous format" stands for

    The default formats follow the rules of the ISO 8601 international standard which expresses a day as "2001-02-28" and a time as "14:01:02" using leading zeroes as here.

    Bootstrap 3 Styled Select dropdown looks ugly in Firefox on OS X

    I am using Chosen. Look at: http://harvesthq.github.io/chosen/

    It works on Firefox, Chrome, IE and Safari with the same style. But not on Mobile Devices.

    Run CSS3 animation only once (at page loading)

    It can be done with a little bit of extra overhead.

    Simply wrap your link in a div, and separate the animation.

    the html ..

    <div class="animateOnce">
        <a class="animateOnHover">me!</a>
    </div>
    

    .. and the css ..

    .animateOnce {
        animation: splash 1s normal forwards ease-in-out;
    }
    
    .animateOnHover:hover {
        animation: hover 1s infinite alternate ease-in-out;
    }
    

    Parse RSS with jQuery

    zRSSfeed is built on jQuery and the simple theme is awesome.
    Give it a try.

    Returning boolean if set is empty

    def myfunc(a,b):
        c = a.intersection(b)
        return bool(c)
    

    bool() will do something similar to not not, but more ideomatic and clear.

    socket.error: [Errno 48] Address already in use

    This commonly happened use case for any developer.

    It is better to have it as function in your local system. (So better to keep this script in one of the shell profile like ksh/zsh or bash profile based on the user preference)

    function killport {
       kill -9 `lsof -i tcp:"$1" | grep LISTEN | awk '{print $2}'`
    }
    

    Usage:

    killport port_number
    

    Example:

    killport 8080
    

    Play audio from a stream using C#

    I haven't tried it from a WebRequest, but both the Windows Media Player ActiveX and the MediaElement (from WPF) components are capable of playing and buffering MP3 streams.

    I use it to play data coming from a SHOUTcast stream and it worked great. However, I'm not sure if it will work in the scenario you propose.

    How to have the formatter wrap code with IntelliJ?

    In the latest Intellij ver 2020, we have an option called soft-wrap these files. Settings > Editor > General > soft-wrap these files. Check this option and add the type of files u need wrap.

    soft wrap intellij option

    How do I use the lines of a file as arguments of a command?

    I suggest using:

    command $(echo $(tr '\n' ' ' < parameters.cfg))
    

    Simply trim the end-line characters and replace them with spaces, and then push the resulting string as possible separate arguments with echo.

    Can I use library that used android support with Androidx projects.

    I used these two lines of code in application tag in manifest.xml and it worked.

     tools:replace="android:appComponentFactory"    
     android:appComponentFactory="whateverString"
    

    Source: https://github.com/android/android-ktx/issues/576#issuecomment-437145192

    How to Correctly handle Weak Self in Swift Blocks with Arguments

    If you are crashing than you probably need [weak self]

    My guess is that the block you are creating is somehow still wired up.

    Create a prepareForReuse and try clearing the onTextViewEditClosure block inside that.

    func prepareForResuse() {
       onTextViewEditClosure = nil
       textView.delegate = nil
    }
    

    See if that prevents the crash. (It's just a guess).

    Correct way to read a text file into a buffer in C?

    Why don't you just use the array of chars you have? This ought to do it:

       source[i] = getc(fp); 
       i++;
    

    How to make div fixed after you scroll to that div?

    it worked for me

    $(document).scroll(function() {
        var y = $(document).scrollTop(), //get page y value 
            header = $("#myarea"); // your div id
        if(y >= 400)  {
            header.css({position: "fixed", "top" : "0", "left" : "0"});
        } else {
            header.css("position", "static");
        }
    });
    

    GIT commit as different user without email / or only email

    Format

    A U Thor <[email protected]>
    

    simply mean that you should specify

    FirstName MiddleName LastName <[email protected]>
    

    Looks like middle and last names are optional (maybe the part before email doesn't have a strict format at all). Try, for example, this:

    git commit --author="John <[email protected]>" -m "some fix"
    

    As the docs say:

      --author=<author>
           Override the commit author. Specify an explicit author using the standard 
           A U Thor <[email protected]> format. Otherwise <author> is assumed to 
           be a pattern and is used to search for an existing commit by that author 
           (i.e. rev-list --all -i --author=<author>); the commit author is then copied 
           from the first such commit found.
    

    if you don't use this format, git treats provided string as a pattern and tries to find matching name among the authors of other commits.

    How to fix IndexError: invalid index to scalar variable

    In the for, you have an iteration, then for each element of that loop which probably is a scalar, has no index. When each element is an empty array, single variable, or scalar and not a list or array you cannot use indices.

    How to convert hex string to Java string?

    byte[] bytes = javax.xml.bind.DatatypeConverter.parseHexBinary(hexString);
    String result= new String(bytes, encoding);
    

    Reordering Chart Data Series

    Right-click any series on the chart. In the "Format Data Series" dialog, there is a "Series Order" tab, in which you can move series up and down. I find this much easier than fiddling with the last argument of the series formula.

    This is in Excel 2003 in Windows. There is a similar dialog in Excel 2011 for Mac:

    enter image description here

    How do I ignore an error on 'git pull' about my local changes would be overwritten by merge?

    This worked for me to discard changes on the live remote server and pull from the source control GitHub:

    git reset --hard
    git pull origin master
    

    A warning - comparison between signed and unsigned integer expressions

    It is usually a good idea to declare variables as unsigned or size_t if they will be compared to sizes, to avoid this issue. Whenever possible, use the exact type you will be comparing against (for example, use std::string::size_type when comparing with a std::string's length).

    Compilers give warnings about comparing signed and unsigned types because the ranges of signed and unsigned ints are different, and when they are compared to one another, the results can be surprising. If you have to make such a comparison, you should explicitly convert one of the values to a type compatible with the other, perhaps after checking to ensure that the conversion is valid. For example:

    unsigned u = GetSomeUnsignedValue();
    int i = GetSomeSignedValue();
    
    if (i >= 0)
    {
        // i is nonnegative, so it is safe to cast to unsigned value
        if ((unsigned)i >= u)
            iIsGreaterThanOrEqualToU();
        else
            iIsLessThanU();
    }
    else
    {
        iIsNegative();
    }
    

    How to handle screen orientation change when progress dialog and background thread active?

    I discovered a solution to this that I haven't yet seen elsewhere. You can use a custom application object that knows if you have background tasks going, instead of trying to do this in the activity that gets destroyed and recreated on orientation change. I blogged about this in here.

    Using Cygwin to Compile a C program; Execution error

    when you start in cygwin, you are in your $HOME, like in unix generally, which maps to c:/cygwin/home/$YOURNAME by default. So you could put everything there.

    You can also access the c: drive from cygwin through /cygdrive/c/ (e.g. /cygdrive/c/Documents anb Settings/yourname/Desktop).

    How do I free my port 80 on localhost Windows?

    I also had the same problem. net stop http didn't help and World wide web services option under IIS in Windows Control Panel was unchecked. So in XAMPP control panel I just checked the Svc checkbox near Apache start button (Install Apache as service) and rebooted Windows. And now each time Windows starts Apache is started automatically and occupies port 80 before any other service does. Worked for me!

    angular 2 sort and filter

    This is my sort. It will do number sort , string sort and date sort .

    import { Pipe , PipeTransform  } from "@angular/core";
    
    @Pipe({
      name: 'sortPipe'
     })
    
    export class SortPipe implements PipeTransform {
    
        transform(array: Array<string>, key: string): Array<string> {
    
            console.log("Entered in pipe*******  "+ key);
    
    
            if(key === undefined || key == '' ){
                return array;
            }
    
            var arr = key.split("-");
            var keyString = arr[0];   // string or column name to sort(name or age or date)
            var sortOrder = arr[1];   // asc or desc order
            var byVal = 1;
    
    
            array.sort((a: any, b: any) => {
    
                if(keyString === 'date' ){
    
                    let left    = Number(new Date(a[keyString]));
                    let right   = Number(new Date(b[keyString]));
    
                    return (sortOrder === "asc") ? right - left : left - right;
                }
                else if(keyString === 'name'){
    
                    if(a[keyString] < b[keyString]) {
                        return (sortOrder === "asc" ) ? -1*byVal : 1*byVal;
                    } else if (a[keyString] > b[keyString]) {
                        return (sortOrder === "asc" ) ? 1*byVal : -1*byVal;
                    } else {
                        return 0;
                    }  
                }
                else if(keyString === 'age'){
                    return (sortOrder === "asc") ? a[keyString] - b[keyString] : b[keyString] - a[keyString];
                }
    
            });
    
            return array;
    
      }
    
    }
    

    Keep CMD open after BAT file executes

    When the .bat file is started not from within the command line (e.g. double-clicking).

    echo The echoed text
    @pause
    

    at_pause

    echo The echoed text
    pause
    

    pause

    echo The echoed text
    cmd /k
    

    cmd k

    echo The echoed text & pause
    

    and_pause

    Does Enter key trigger a click event?

    <form (keydown)="someMethod($event)">
         <input type="text">
    </form>
    
    someMethod(event:any){
       if(event.keyCode == 13){
          alert('Entered Click Event!');
       }else{
       }
    }
    

    How to asynchronously call a method in Java

    Java 8 introduced CompletableFuture available in package java.util.concurrent.CompletableFuture, can be used to make a asynch call :

    CompletableFuture.runAsync(() -> {
        // method call or code to be asynch.
    });
    

    Is this very likely to create a memory leak in Tomcat?

    This problem appears when we are using any third party solution, without using the handlers for the cleanup activitiy. For me this was happening for EhCache. We were using EhCache in our project for caching. And often we used to see following error in the logs

     SEVERE: The web application [/products] appears to have started a thread named [products_default_cache_configuration] but has failed to stop it. This is very likely to create a memory leak.
    Aug 07, 2017 11:08:36 AM org.apache.catalina.loader.WebappClassLoader clearReferencesThreads
    SEVERE: The web application [/products] appears to have started a thread named [Statistics Thread-products_default_cache_configuration-1] but has failed to stop it. This is very likely to create a memory leak.
    

    And we often noticed tomcat failing for OutOfMemory error during development where we used to do backend changes and deploy the application multiple times for reflecting our changes.

    This is the fix we did

    <listener>
      <listener-class>
         net.sf.ehcache.constructs.web.ShutdownListener
      </listener-class>
    </listener>
    

    So point I am trying to make is check the documentation of the third party libraries which you are using. They should be providing some mechanisms to clean up the threads during shutdown. Which you need to use in your application. No need to re-invent the wheel unless its not provided by them. The worst case is to provide your own implementation.

    Reference for EHCache Shutdown http://www.ehcache.org/documentation/2.8/operations/shutdown.html

    Saving and Reading Bitmaps/Images from Internal memory in Android

    Make sure to use WEBP as your media format to save more space with same quality:

    fun saveImage(context: Context, bitmap: Bitmap, name: String): String {
            context.openFileOutput(name, Context.MODE_PRIVATE).use { fos ->
                bitmap.compress(Bitmap.CompressFormat.WEBP, 25, fos)
            }
        return context.filesDir.absolutePath
     }
    

    What's the best way to check if a file exists in C?

    Use stat like this:

    #include <sys/stat.h>   // stat
    #include <stdbool.h>    // bool type
    
    bool file_exists (char *filename) {
      struct stat   buffer;   
      return (stat (filename, &buffer) == 0);
    }
    

    and call it like this:

    #include <stdio.h>      // printf
    
    int main(int ac, char **av) {
        if (ac != 2)
            return 1;
    
        if (file_exists(av[1]))
            printf("%s exists\n", av[1]);
        else
            printf("%s does not exist\n", av[1]);
    
        return 0;
    }
    

    How to view the list of compile errors in IntelliJ?

    On my system (IntelliJ Idea 2017.2.5), it was not sufficient to enable "Make Project Automatically". I also had to use the menu item "View, Tool Windows, Problems" to see the problems tool window at the bottom of the screen.

    Opening the problems tool window

    Create controller for partial view in ASP.NET MVC

    Why not use Html.RenderAction()?

    Then you could put the following into any controller (even creating a new controller for it):

    [ChildActionOnly]
    public ActionResult MyActionThatGeneratesAPartial(string parameter1)
    {
        var model = repository.GetThingByParameter(parameter1);
        var partialViewModel = new PartialViewModel(model);
        return PartialView(partialViewModel); 
    }
    

    Then you could create a new partial view and have your PartialViewModel be what it inherits from.

    For Razor, the code block in the view would look like this:

    @{ Html.RenderAction("Index", "Home"); }
    

    For the WebFormsViewEngine, it would look like this:

    <% Html.RenderAction("Index", "Home"); %>
    

    How to play a local video with Swift?

    PlayerView for swift 4.2

    import AVFoundation
    import UIKit
    
    class PlayerView: UIView {
    
        var player: AVPlayer? {
            get {
                return playerLayer.player
            }
            set {
                playerLayer.player = newValue
            }
        }
    
        var playerLayer: AVPlayerLayer {
            return layer as! AVPlayerLayer
        }
    
        // Override UIView property
        override static var layerClass: AnyClass {
            return AVPlayerLayer.self
        }
    }
    

    How can I represent an infinite number in Python?

    Since Python 3.5 you can use math.inf:

    >>> import math
    >>> math.inf
    inf
    

    How to open port in Linux

    The following configs works on Cent OS 6 or earlier

    As stated above first have to disable selinux.

    Step 1 nano /etc/sysconfig/selinux

    Make sure the file has this configurations

    SELINUX=disabled
    
    SELINUXTYPE=targeted
    

    Then restart the system

    Step 2

    iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT
    

    Step 3

    sudo service iptables save
    

    For Cent OS 7

    step 1

    firewall-cmd --zone=public --permanent --add-port=8080/tcp
    

    Step 2

    firewall-cmd --reload
    

    How do I check/uncheck all checkboxes with a button using jQuery?

    add this in your code block, or even click of your button

    $('input:checkbox').attr('checked',false);
    

    Typescript import/as vs import/require?

    import * as express from "express";
    

    This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

    In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

    How to convert hex to rgb using Java?

    If you don't want to use the AWT Color.decode, then just copy the contents of the method:

    int i = Integer.decode("#FFFFFF");
    int[] rgb = new int[]{(i >> 16) & 0xFF, (i >> 8) & 0xFF, i & 0xFF};
    

    Integer.decode handles the # or 0x, depending on how your string is formatted

    Replace X-axis with own values

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

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

    which then gives you the graph:

    enter image description here

    What are the differences between "=" and "<-" assignment operators in R?

    The difference in assignment operators is clearer when you use them to set an argument value in a function call. For example:

    median(x = 1:10)
    x   
    ## Error: object 'x' not found
    

    In this case, x is declared within the scope of the function, so it does not exist in the user workspace.

    median(x <- 1:10)
    x    
    ## [1]  1  2  3  4  5  6  7  8  9 10
    

    In this case, x is declared in the user workspace, so you can use it after the function call has been completed.


    There is a general preference among the R community for using <- for assignment (other than in function signatures) for compatibility with (very) old versions of S-Plus. Note that the spaces help to clarify situations like

    x<-3
    # Does this mean assignment?
    x <- 3
    # Or less than?
    x < -3
    

    Most R IDEs have keyboard shortcuts to make <- easier to type. Ctrl + = in Architect, Alt + - in RStudio (Option + - under macOS), Shift + - (underscore) in emacs+ESS.


    If you prefer writing = to <- but want to use the more common assignment symbol for publicly released code (on CRAN, for example), then you can use one of the tidy_* functions in the formatR package to automatically replace = with <-.

    library(formatR)
    tidy_source(text = "x=1:5", arrow = TRUE)
    ## x <- 1:5
    

    The answer to the question "Why does x <- y = 5 throw an error but not x <- y <- 5?" is "It's down to the magic contained in the parser". R's syntax contains many ambiguous cases that have to be resolved one way or another. The parser chooses to resolve the bits of the expression in different orders depending on whether = or <- was used.

    To understand what is happening, you need to know that assignment silently returns the value that was assigned. You can see that more clearly by explicitly printing, for example print(x <- 2 + 3).

    Secondly, it's clearer if we use prefix notation for assignment. So

    x <- 5
    `<-`(x, 5)  #same thing
    
    y = 5
    `=`(y, 5)   #also the same thing
    

    The parser interprets x <- y <- 5 as

    `<-`(x, `<-`(y, 5))
    

    We might expect that x <- y = 5 would then be

    `<-`(x, `=`(y, 5))
    

    but actually it gets interpreted as

    `=`(`<-`(x, y), 5)
    

    This is because = is lower precedence than <-, as shown on the ?Syntax help page.

    100% Min Height CSS layout

    Try this:

    body{ height: 100%; }
    #content { 
        min-height: 500px;
        height: 100%;
    }
    #footer {
        height: 100px;
        clear: both !important;
    }
    

    The div element below the content div must have clear:both.

    How do I add a newline to a windows-forms TextBox?

    Have you tried something like:

    textbox.text = "text" & system.environment.newline & "some more text"

    c++ bool question

    false == 0 and true = !false

    i.e. anything that is not zero and can be converted to a boolean is not false, thus it must be true.

    Some examples to clarify:

    if(0)          // false
    if(1)          // true
    if(2)          // true
    if(0 == false) // true
    if(0 == true)  // false
    if(1 == false) // false
    if(1 == true)  // true
    if(2 == false) // false
    if(2 == true)  // false
    cout << false  // 0
    cout << true   // 1
    

    true evaluates to 1, but any int that is not false (i.e. 0) evaluates to true but is not equal to true since it isn't equal to 1.

    Is there any use for unique_ptr with array?

    • You need your structure to contain just a pointer for binary-compatibility reasons.
    • You need to interface with an API that returns memory allocated with new[]
    • Your firm or project has a general rule against using std::vector, for example, to prevent careless programmers from accidentally introducing copies
    • You want to prevent careless programmers from accidentally introducing copies in this instance.

    There is a general rule that C++ containers are to be preferred over rolling-your-own with pointers. It is a general rule; it has exceptions. There's more; these are just examples.

    Checking if any elements in one list are in another

    There is a built in function to compare lists:

    Following is the syntax for cmp() method -

    cmp(list1, list2)
    
    #!/usr/bin/python
    
    list1, list2 = [123, 'xyz'], [123, 'xyz']
    
    print cmp(list1,list2)
    

    When we run above program, it produces following result -

    0
    

    If the result is a tie, meaning that 0 is returned

    How to execute only one test spec with angular-cli

    You can test only specific file with the Angular CLI (the ng command) like this:

    ng test --main ./path/to/test.ts
    

    Further docs are at https://angular.io/cli/test

    Note that while this works for standalone library files, it will not work for angular components/services/etc. This is because angular files have dependencies on other files (namely src/test.ts in Angular 7). Sadly the --main flag doesn't take multiple arguments.

    WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser

    I ran into the same issue running Chrome via Behat/Mink and Selenium in a Docker container. After some fiddling, I arrived at the following behat.yml which supplies the switches mentioned above. Note that all of them were required for me to get it running successfully.

    default:
        extensions:
            Behat\MinkExtension:
                base_url: https://my.app/
                default_session: selenium2
                selenium2:
                    browser: chrome
                    capabilities:
                        extra_capabilities:
                            chromeOptions:
                                args:
                                    - "headless"
                                    - "no-sandbox"
                                    - "disable-dev-shm-usage"
    

    Difference between margin and padding?

    Padding is space inside the border, whereas Margin is space outside the border.

    How to convert decimal to hexadecimal in JavaScript

    For completeness, if you want the two's-complement hexadecimal representation of a negative number, you can use the zero-fill-right shift >>> operator. For instance:

    > (-1).toString(16)
    "-1"
    
    > ((-2)>>>0).toString(16)
    "fffffffe"
    

    There is however one limitation: JavaScript bitwise operators treat their operands as a sequence of 32 bits, that is, you get the 32-bits two's complement.

    Searching multiple files for multiple words

    If you are using Notepad++ editor Goto ctrl + F choose tab 3 find in files and enter:

    1. Find What = text1*.*text2
    2. Filters : .
    3. Search mode = Regular Expression
    4. Directory = enter the path of the directory you want to search in. You can check Follow current doc. to have the path of the current file to be filled.

    How can I split a delimited string into an array in PHP?

    explode has some very big problems in real life usage:

    count(explode(',', null)); // 1 !! 
    explode(',', null); // [""] not an empty array, but an array with one empty string!
    explode(',', ""); // [""]
    explode(',', "1,"); // ["1",""] ending commas are also unsupported, kinda like IE8
    

    this is why i prefer preg_split

    preg_split('@,@', $string, NULL, PREG_SPLIT_NO_EMPTY)
    

    the entire boilerplate:

    /** @brief wrapper for explode
     * @param string|int|array $val string will explode. '' return []. int return string in array (1 returns ['1']). array return itself. for other types - see $as_is
     * @param bool $as_is false (default): bool/null return []. true: bool/null return itself.
     * @param string $delimiter default ','
     * @return array|mixed
     */
    public static function explode($val, $as_is = false, $delimiter = ',')
    {
        // using preg_split (instead of explode) because it is the best way to handle ending comma and avoid empty string converted to ['']
        return (is_string($val) || is_int($val)) ?
            preg_split('@' . preg_quote($delimiter, '@') . '@', $val, NULL, PREG_SPLIT_NO_EMPTY)
            :
            ($as_is ? $val : (is_array($val) ? $val : []));
    }
    

    How to filter for multiple criteria in Excel?

    The regular filter options in Excel don't allow for more than 2 criteria settings. To do 2+ criteria settings, you need to use the Advanced Filter option. Below are the steps I did to try this out.

    http://www.bettersolutions.com/excel/EDZ483/QT419412321.htm

    Set up the criteria. I put this above the values I want to filter. You could do that or put on a different worksheet. Note that putting the criteria in rows will make it an 'OR' filter and putting them in columns will make it an 'AND' filter.

    1. E1 : Letters
    2. E2 : =m
    3. E3 : =h
    4. E4 : =j

    I put the data starting on row 5:

    1. A5 : Letters
    2. A6 :
    3. A7 :
    4. ...

    Select the first data row (A6) and click the Advanced Filter option. The List Range should be pre-populated. Select the Criteria range as E1:E4 and click OK.

    That should be it. Note that I use the '=' operator. You will want to use something a bit different to test for file extensions.

    Hex-encoded String to Byte Array

    I know it's late but hope it will help someone else...

    This is my code: It takes two by two hex representations contained in String and add those into byte array. It works perfectly for me.

    public byte[] stringToByteArray (String s) {
        byte[] byteArray = new byte[s.length()/2];
        String[] strBytes = new String[s.length()/2];
        int k = 0;
        for (int i = 0; i < s.length(); i=i+2) {
            int j = i+2;
            strBytes[k] = s.substring(i,j);
            byteArray[k] = (byte)Integer.parseInt(strBytes[k], 16);
            k++;
        }
        return byteArray;
    }
    

    Set Memory Limit in htaccess

    In your .htaccess you can add:

    PHP 5.x

    <IfModule mod_php5.c>
        php_value memory_limit 64M
    </IfModule>
    

    PHP 7.x

    <IfModule mod_php7.c>
        php_value memory_limit 64M
    </IfModule>
    

    If page breaks again, then you are using PHP as mod_php in apache, but error is due to something else.

    If page does not break, then you are using PHP as CGI module and therefore cannot use php values - in the link I've provided might be solution but I'm not sure you will be able to apply it.

    Read more on http://support.tigertech.net/php-value

    AngularJS - get element attributes values

    Use Jquery functions

    <Button id="myPselector" data-id="1234">HI</Button> 
    console.log($("#myPselector").attr('data-id'));
    

    Change Bootstrap input focus blue glow

    In Bootstrap 4, if you compile SASS by yourself, you can change the following variables to control the styling of the focus shadow:

    $input-btn-focus-width:       .2rem !default;
    $input-btn-focus-color:       rgba($component-active-bg, .25) !default;
    $input-btn-focus-box-shadow:  0 0 0 $input-btn-focus-width $input-btn-focus-color !default;
    

    Note: as of Bootstrap 4.1, the $input-btn-focus-color and $input-btn-focus-box-shadow variables are used only for input elements, but not for buttons. The focus shadow for buttons is hardcoded as box-shadow: 0 0 0 $btn-focus-width rgba($border, .5);, so you can only control the shadow width via the $input-btn-focus-width variable.

    How to declare and display a variable in Oracle

    If you are using pl/sql then the following code should work :

    set server output on -- to retrieve and display a buffer

    DECLARE
    
        v_text VARCHAR2(10); -- declare
    BEGIN
    
        v_text := 'Hello';  --assign
        dbms_output.Put_line(v_text); --display
    END; 
    
    /
    

    -- this must be use to execute pl/sql script

    MySQL my.cnf file - Found option without preceding group

    Missing config header

    Just add [mysqld] as first line in the /etc/mysql/my.cnf file.

    Example

    [mysqld]
    default-time-zone = "+08:00"
    

    Afterwards, remember to restart your MySQL Service.

    sudo mysqld stop
    sudo mysqld start
    

    <button> background image

    You need to call CLASS in button

    <button class="tim" id="rock" onClick="choose(1)">Rock</button>
    
    
    
    <style>
    .tim{
    font-size: 18px;
    border: 2px solid #AD235E;
    border-radius: 100px;
    width: 150px;
    height: 150px; background-image: url(images/Sun.jpg);
    }
    </style>
    

    Table column sizing

    Disclaimer: This answer may be a bit old. Since the bootstrap 4 beta. Bootstrap has changed since then.

    The table column size class has been changed from this

    <th class="col-sm-3">3 columns wide</th>
    

    to

    <th class="col-3">3 columns wide</th>
    

    How do we update URL or query strings using javascript/jQuery without reloading the page?

    Yes - document.location = "http://my.new.url.com"

    You can also retrieve it the same way eg.

    var myURL = document.location;
    document.location = myURL + "?a=parameter";
    

    The location object has a number of useful properties too:

    hash            Returns the anchor portion of a URL
    host            Returns the hostname and port of a URL
    hostname        Returns the hostname of a URL
    href            Returns the entire URL
    pathname        Returns the path name of a URL
    port            Returns the port number the server uses for a URL
    protocol        Returns the protocol of a URL
    search          Returns the query portion of a URL
    

    EDIT: Setting the hash of the document.location shouldn't reload the page, just alter where on the page the focus is. So updating to #myId will scroll to the element with id="myId". If the id doesn't exist I believe nothing will happen? (Need to confirm on various browsers though)

    EDIT2: To make it clear, not just in a comment: You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, crafted to look like gmail, and instantly change the URL to www.gmail.com and steal people's login details.
    You can change the part after the domain on some browsers to cope with AJAX style things, but that's already been linked to by Osiris. What's more, you probably shouldn't do this, even if you could. The URL tells the user where he/she is on your site. If you change it without changing the page contents, it's becomes a little confusing.

    CSS – why doesn’t percentage height work?

    You need to give it a container with a height. width uses the viewport as the default width