Programs & Examples On #Limesurvey

LimeSurvey is a web based survey application built on PHP and MySQL. It is free and open-source, and provides extensive question templates and easy to use statistics.

How to export data to an excel file using PHPExcel

I currently use this function in my project after a series of googling to download excel file from sql statement

    // $sql = sql query e.g "select * from mytablename"
    // $filename = name of the file to download 
        function queryToExcel($sql, $fileName = 'name.xlsx') {
                // initialise excel column name
                // currently limited to queries with less than 27 columns
        $columnArray = array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z");
                // Execute the database query
                $result =  mysql_query($sql) or die(mysql_error());

                // Instantiate a new PHPExcel object
                $objPHPExcel = new PHPExcel();
                // Set the active Excel worksheet to sheet 0
                $objPHPExcel->setActiveSheetIndex(0);
                // Initialise the Excel row number
                $rowCount = 1;
    // fetch result set column information
                $finfo = mysqli_fetch_fields($result);
// initialise columnlenght counter                
$columnlenght = 0;
                foreach ($finfo as $val) {
// set column header values                   
  $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$columnlenght++] . $rowCount, $val->name);
                }
// make the column headers bold
                $objPHPExcel->getActiveSheet()->getStyle($columnArray[0]."1:".$columnArray[$columnlenght]."1")->getFont()->setBold(true);

                $rowCount++;
                // Iterate through each result from the SQL query in turn
                // We fetch each database result row into $row in turn

                while ($row = mysqli_fetch_array($result, MYSQL_NUM)) {
                    for ($i = 0; $i < $columnLenght; $i++) {
                        $objPHPExcel->getActiveSheet()->SetCellValue($columnArray[$i] . $rowCount, $row[$i]);
                    }
                    $rowCount++;
                }
// set header information to force download
                header('Content-type: application/vnd.ms-excel');
                header('Content-Disposition: attachment; filename="' . $fileName . '"');
                // Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file        
                // Write the Excel file to filename some_excel_file.xlsx in the current directory                
                $objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
                // Write the Excel file to filename some_excel_file.xlsx in the current directory
                $objWriter->save('php://output');
            }

How do I read the contents of a Node.js stream into a string variable?

None of the above worked for me. I needed to use the Buffer object:

  const chunks = [];

  readStream.on("data", function (chunk) {
    chunks.push(chunk);
  });

  // Send the buffer or you can put it into a var
  readStream.on("end", function () {
    res.send(Buffer.concat(chunks));
  });

How can I check the size of a collection within a Django template?

You can try with:

{% if theList.object_list.count > 0 %}
    blah, blah...
{% else %}
    blah, blah....
{% endif %} 

String to LocalDate

DateTimeFormatter has in-built formats that can directly be used to parse a character sequence. It is case Sensitive, Nov will work however nov and NOV wont work:

DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy-MMM-dd");

try {
    LocalDate datetime = LocalDate.parse(oldDate, pattern);
    System.out.println(datetime); 
} catch (DateTimeParseException e) {
    // DateTimeParseException - Text '2019-nov-12' could not be parsed at index 5
    // Exception handling message/mechanism/logging as per company standard
}

DateTimeFormatterBuilder provides custom way to create a formatter. It is Case Insensitive, Nov , nov and NOV will be treated as same.

DateTimeFormatter f = new DateTimeFormatterBuilder().parseCaseInsensitive()
        .append(DateTimeFormatter.ofPattern("yyyy-MMM-dd")).toFormatter();
try {
    LocalDate datetime = LocalDate.parse(oldDate, f);
    System.out.println(datetime); // 2019-11-12
} catch (DateTimeParseException e) {
     // Exception handling message/mechanism/logging as per company standard
}

CSS to select/style first word

There isn't a plain CSS method for this. You might have to go with JavaScript + Regex to pop in a span.

Ideally, there would be a pseudo-element for first-word, but you're out of luck as that doesn't appear to work. We do have :first-letter and :first-line.

You might be able to use a combination of :after or :before to get at it without using a span.

How do I copy a hash in Ruby?

Alternative way to Deep_Copy that worked for me.

h1 = {:a => 'foo'} 
h2 = Hash[h1.to_a]

This produced a deep_copy since h2 is formed using an array representation of h1 rather than h1's references.

How do you convert epoch time in C#?

You actually want to AddMilliseconds(milliseconds), not seconds. Adding seconds will give you an out of range exception.

How to display images from a folder using php - PHP

You have two ways to do that:

METHOD 1. The secure way.

Put the images on /www/htdocs/

<?php
    $www_root = 'http://localhost/images';
    $dir = '/var/www/images';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="', $www_root, '/', $file, '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

METHOD 2. Unsecure but more flexible.

Put the images on any directory (apache must have permission to read the file).

<?php
    $dir = '/home/user/Pictures';
    $file_display = array('jpg', 'jpeg', 'png', 'gif');

    if ( file_exists( $dir ) == false ) {
       echo 'Directory \'', $dir, '\' not found!';
    } else {
       $dir_contents = scandir( $dir );

        foreach ( $dir_contents as $file ) {
           $file_type = strtolower( end( explode('.', $file ) ) );
           if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
              echo '<img src="file_viewer.php?file=', base64_encode($dir . '/' . $file), '" alt="', $file, '"/>';
           break;
           }
        }
    }
?>

And create another script to read the image file.

<?php
    $filename = base64_decode($_GET['file']);
    // Check the folder location to avoid exploit
    if (dirname($filename) == '/home/user/Pictures')
        echo file_get_contents($filename);
?>

Fatal error: Class 'SoapClient' not found

To install SOAP in PHP-7 run following in your Ubuntu terminal:

sudo apt-get install php7.0-soap

To install SOAP in PHP-7.1 run following in your Ubuntu terminal:

sudo apt-get install php7.1-soap

To install SOAP in PHP-7.2 run following in your Ubuntu terminal:

sudo apt-get install php7.2-soap

To install SOAP in PHP-7.3 run following in your Ubuntu terminal:

sudo apt-get install php7.3-soap

Error: Segmentation fault (core dumped)

"Segmentation fault (core dumped)" is the string that Linux prints when a program exits with a SIGSEGV signal and you have core creation enabled. This means some program has crashed.

If you're actually getting this error from running Python, this means the Python interpreter has crashed. There are only a few reasons this can happen:

  1. You're using a third-party extension module written in C, and that extension module has crashed.

  2. You're (directly or indirectly) using the built-in module ctypes, and calling external code that crashes.

  3. There's something wrong with your Python installation.

  4. You've discovered a bug in Python that you should report.

The first is by far the most common. If your q is an instance of some object from some third-party extension module, you may want to look at the documentation.

Often, when C modules crash, it's because you're doing something which is invalid, or at least uncommon and untested. But whether it's your "fault" in that sense or not - that doesn't matter. The module should raise a Python exception that you can debug, instead of crashing. So, you should probably report a bug to whoever wrote the extension. But meanwhile, rather than waiting 6 months for the bug to be fixed and a new version to come out, you need to figure out what you did that triggered the crash, and whether there's some different way to do what you want. Or switch to a different library.

On the other hand, since you're reading and printing out data from somewhere else, it's possible that your Python interpreter just read the line "Segmentation fault (core dumped)" and faithfully printed what it read. In that case, some other program upstream presumably crashed. (It's even possible that nobody crashed—if you fetched this page from the web and printed it out, you'd get that same line, right?) In your case, based on your comment, it's probably the Java program that crashed.

If you're not sure which case it is (and don't want to learn how to do process management, core-file inspection, or C-level debugging today), there's an easy way to test: After print line add a line saying print "And I'm OK". If you see that after the Segmentation fault line, then Python didn't crash, someone else did. If you don't see it, then it's probably Python that's crashed.

Finding version of Microsoft C++ compiler from command-line (for makefiles)

I had the same problem today. I needed to set a flag in a nmake Makefile if the cl compiler version is 15. Here is the hack I came up with:

!IF ([cl /? 2>&1 | findstr /C:"Version 15" > nul] == 0)
FLAG = "cl version 15"
!ENDIF

Note that cl /? prints the version information to the standard error stream and the help text to the standard output. To be able to check the version with the findstr command one must first redirect stderr to stdout using 2>&1.

The above idea can be used to write a Windows batch file that checks if the cl compiler version is <= a given number. Here is the code of cl_version_LE.bat:

@echo off
FOR /L %%G IN (10,1,%1) DO cl /? 2>&1 | findstr /C:"Version %%G" > nul && goto FOUND
EXIT /B 0
:FOUND
EXIT /B 1

Now if you want to set a flag in your nmake Makefile if the cl version <= 15, you can use:

!IF [cl_version_LE.bat 15]
FLAG = "cl version <= 15"
!ENDIF

How to underline a UILabel in swift?

Same Answer in Swift 4.2

For UILable

extension UILabel {
    func underline() {
        if let textString = self.text {
            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
                                          value: NSUnderlineStyle.single.rawValue,
                                          range: NSRange(location: 0, length: textString.count))
            self.attributedText = attributedString
        }
    }
}

Call for UILabel like below

myLable.underline()

For UIButton

extension UIButton {
    func underline() {
        if let textString = self.titleLabel?.text {

            let attributedString = NSMutableAttributedString(string: textString)
            attributedString.addAttribute(NSAttributedString.Key.underlineStyle,
                                          value: NSUnderlineStyle.single.rawValue,
                                          range: NSRange(location: 0, length: textString.count))
            self.setAttributedTitle(attributedString, for: .normal)
        }

    }
}

Call for UIButton like below

myButton.underline()

I looked into above answers and some of them are force unwrapping text value. I will suggest to get value by safely unwrapping. This will avoid crash in case of nil value. Hope This helps :)

How to use Python's "easy_install" on Windows ... it's not so easy

Copy the below script "ez_setup.py" from the below URL

https://bootstrap.pypa.io/ez_setup.py

And copy it into your Python location

C:\Python27>

Run the command

C:\Python27? python ez_setup.py

This will install the easy_install under Scripts directory

C:\Python27\Scripts

Run easy install from the Scripts directory >

C:\Python27\Scripts> easy_install

How to subtract/add days from/to a date?

Just subtract a number:

> as.Date("2009-10-01")
[1] "2009-10-01"
> as.Date("2009-10-01")-5
[1] "2009-09-26"

Since the Date class only has days, you can just do basic arithmetic on it.

If you want to use POSIXlt for some reason, then you can use it's slots:

> a <- as.POSIXlt("2009-10-04")
> names(unclass(as.POSIXlt("2009-10-04")))
[1] "sec"   "min"   "hour"  "mday"  "mon"   "year"  "wday"  "yday"  "isdst"
> a$mday <- a$mday - 6
> a
[1] "2009-09-28 EDT"

@Autowired and static method

This builds upon @Pavel's answer, to solve the possibility of Spring context not being initialized when accessing from the static getBean method:

@Component
public class Spring {
  private static final Logger LOG = LoggerFactory.getLogger (Spring.class);

  private static Spring spring;

  @Autowired
  private ApplicationContext context;

  @PostConstruct
  public void registerInstance () {
    spring = this;
  }

  private Spring (ApplicationContext context) {
    this.context = context;
  }

  private static synchronized void initContext () {
    if (spring == null) {
      LOG.info ("Initializing Spring Context...");
      ApplicationContext context = new AnnotationConfigApplicationContext (io.zeniq.spring.BaseConfig.class);
      spring = new Spring (context);
    }
  }

  public static <T> T getBean(String name, Class<T> className) throws BeansException {
    initContext();
    return spring.context.getBean(name, className);
  }

  public static <T> T getBean(Class<T> className) throws BeansException {
    initContext();
    return spring.context.getBean(className);
  }

  public static AutowireCapableBeanFactory getBeanFactory() throws IllegalStateException {
    initContext();
    return spring.context.getAutowireCapableBeanFactory ();
  }
}

The important piece here is the initContext method. It ensures that the context will always get initialized. But, do note that initContext will be a point of contention in your code as it is synchronized. If your application is heavily parallelized (for eg: the backend of a high traffic site), this might not be a good solution for you.

Is there a maximum number you can set Xmx to when trying to increase jvm memory?

Have a look at this for some common errors in setting the java heap. You've probably set the heap size to a larger value than your computer's physical memory.

You should avoid solving this problem by increasing the heap size. Instead, you should profile your application to see where you spend such a large amount of memory.

Peak detection in a 2D array

Heres another approach that I used when doing something similar for a large telescope:

1) Search for the highest pixel. Once you have that, search around that for the best fit for 2x2 (maybe maximizing the 2x2 sum), or do a 2d gaussian fit inside the sub region of say 4x4 centered on the highest pixel.

Then set those 2x2 pixels you have found to zero (or maybe 3x3) around the peak center

go back to 1) and repeat till the highest peak falls below a noise threshold, or you have all the toes you need

Google Maps API v2: How to make markers clickable?

setTag(position) while adding marker to map.

Marker marker =  map.addMarker(new MarkerOptions()
                .position(new LatLng(latitude, longitude)));
marker.setTag(position);

getTag() on setOnMarkerClickListener listener

map.setOnMarkerClickListener(new GoogleMap.OnMarkerClickListener() {
                @Override
                public boolean onMarkerClick(Marker marker) {
                    int position = (int)(marker.getTag());
                   //Using position get Value from arraylist 
                    return false;
                }
            });

Permission denied for relation

To grant permissions to all of the existing tables in the schema use:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA <schema> TO <role>

To specify default permissions that will be applied to future tables use:

ALTER DEFAULT PRIVILEGES IN SCHEMA <schema> 
  GRANT <privileges> ON TABLES TO <role>;

e.g.

ALTER DEFAULT PRIVILEGES IN SCHEMA public 
  GRANT SELECT, INSERT, UPDATE, DELETE ON TABLES TO admin;

If you use SERIAL or BIGSERIAL columns then you will probably want to do the same for SEQUENCES, or else your INSERT will fail (Postgres 10's IDENTITY doesn't suffer from that problem, and is recommended over the SERIAL types), i.e.

ALTER DEFAULT PRIVILEGES IN SCHEMA <schema> GRANT ALL ON SEQUENCES TO <role>;

See also my answer to PostgreSQL Permissions for Web App for more details and a reusable script.

Ref:

GRANT

ALTER DEFAULT PRIVILEGES

document.getElementById("remember").visibility = "hidden"; not working on a checkbox

There are two problems in your code:

  • The property is called visibility and not visiblity.
  • It is not a property of the element itself but of its .style property.

It's easy to fix. Simple replace this:

document.getElementById("remember").visiblity

with this:

document.getElementById("remember").style.visibility

git visual diff between branches

If you're using github you can use the website for this:

github.com/url/to/your/repo/compare/SHA_of_tip_of_one_branch...SHA_of_tip_of_another_branch

That will show you a compare of the two.

Does a foreign key automatically create an index?

Say you have a big table called orders, and a small table called customers. There is a foreign key from an order to a customer. Now if you delete a customer, Sql Server must check that there are no orphan orders; if there are, it raises an error.

To check if there are any orders, Sql Server has to search the big orders table. Now if there is an index, the search will be fast; if there is not, the search will be slow.

So in this case, the slow delete could be explained by the absence of an index. Especially if Sql Server would have to search 15 big tables without an index.

P.S. If the foreign key has ON DELETE CASCADE, Sql Server still has to search the order table, but then to remove any orders that reference the deleted customer.

How to access to a child method from the parent in vue.js

Ref and event bus both has issues when your control render is affected by v-if. So, I decided to go with a simpler method.

The idea is using an array as a queue to send methods that needs to be called to the child component. Once the component got mounted, it will process this queue. It watches the queue to execute new methods.

(Borrowing some code from Desmond Lua's answer)

Parent component code:

import ChildComponent from './components/ChildComponent'

new Vue({
  el: '#app',
  data: {
    item: {},
    childMethodsQueue: [],
  },
  template: `
  <div>
     <ChildComponent :item="item" :methods-queue="childMethodsQueue" />
     <button type="submit" @click.prevent="submit">Post</button>
  </div>
  `,
  methods: {
    submit() {
      this.childMethodsQueue.push({name: ChildComponent.methods.save.name, params: {}})
    }
  },
  components: { ChildComponent },
})

This is code for ChildComponent

<template>
 ...
</template>

<script>
export default {
  name: 'ChildComponent',
  props: {
    methodsQueue: { type: Array },
  },
  watch: {
    methodsQueue: function () {
      this.processMethodsQueue()
    },
  },
  mounted() {
    this.processMethodsQueue()
  },
  methods: {
    save() {
        console.log("Child saved...")
    },
    processMethodsQueue() {
      if (!this.methodsQueue) return
      let len = this.methodsQueue.length
      for (let i = 0; i < len; i++) {
        let method = this.methodsQueue.shift()
        this[method.name](method.params)
      }
    },
  },
}
</script>

And there is a lot of room for improvement like moving processMethodsQueue to a mixin...

How do I find duplicates across multiple columns?

You have to self join stuff and match name and city. Then group by count.

select 
   s.id, s.name, s.city 
from stuff s join stuff p ON (
   s.name = p.city OR s.city = p.name
)
group by s.name having count(s.name) > 1

What are the First and Second Level caches in (N)Hibernate?

There's a pretty good explanation of first level caching on the Streamline Logic blog.

Basically, first level caching happens on a per session basis where as second level caching can be shared across multiple sessions.

In Java, how to append a string more efficiently?

- Each time you append or do any modification with it, it creates a new String object.

- So use append() method of StringBuilder(If thread safety is not important), else use StringBuffer(If thread safety is important.), that will be efficient way to do it.

How can I concatenate strings in VBA?

There is the concatenate function. For example

=CONCATENATE(E2,"-",F2)
But the & operator always concatenates strings. + often will work, but if there is a number in one of the cells, it won't work as expected.

Calling a JavaScript function named in a variable

I'd avoid eval.

To solve this problem, you should know these things about JavaScript.

  1. Functions are first-class objects, so they can be properties of an object (in which case they are called methods) or even elements of arrays.
  2. If you aren't choosing the object a function belongs to, it belongs to the global scope. In the browser, that means you're hanging it on the object named "window," which is where globals live.
  3. Arrays and objects are intimately related. (Rumor is they might even be the result of incest!) You can often substitute using a dot . rather than square brackets [], or vice versa.

Your problem is a result of considering the dot manner of reference rather than the square bracket manner.

So, why not something like,

window["functionName"]();

That's assuming your function lives in the global space. If you've namespaced, then:

myNameSpace["functionName"]();

Avoid eval, and avoid passing a string in to setTimeout and setInterval. I write a lot of JS, and I NEVER need eval. "Needing" eval comes from not knowing the language deeply enough. You need to learn about scoping, context, and syntax. If you're ever stuck with an eval, just ask--you'll learn quickly.

Android Spinner: Get the selected item change event

By default, you will get the first item of the spinner array through

value = spinner.getSelectedItem().toString();

whenever you selected the value in the spinner this will give you the selected value

if you want the position of the selected item then do it like that

pos = spinner.getSelectedItemPosition();

the above two answers are for without applying listener

how to prevent this error : Warning: mysql_fetch_assoc() expects parameter 1 to be resource, boolean given in ... on line 11

The proper syntax is (in example):

$query = mysql_query('SELECT * FROM beer ORDER BY quality');
while($row = mysql_fetch_assoc($query)) $results[] = $row;

How can I wait for set of asynchronous callback functions?

This is the most neat way in my opinion.

Promise.all

FetchAPI

(for some reason Array.map doesn't work inside .then functions for me. But you can use a .forEach and [].concat() or something similar)

Promise.all([
  fetch('/user/4'),
  fetch('/user/5'),
  fetch('/user/6'),
  fetch('/user/7'),
  fetch('/user/8')
]).then(responses => {
  return responses.map(response => {response.json()})
}).then((values) => {
  console.log(values);
})

Session 'app': Error Launching activity

I had same problem. I was using AVD with arm processor image and received this same message. The only way for me to make Android Studio 2.1.2 runs the app with instant run was change to an X86 processor image. The error was gone and ( until this moment) I think the emulator works faster than ARM emulated. My workstation configuration is Intel I5, 6Gb RAM. Maybe this helps until next fix.

Measuring function execution time in R

The package "tictoc" gives you a very simple way of measuring execution time. The documentation is in: https://cran.fhcrc.org/web/packages/tictoc/tictoc.pdf.

install.packages("tictoc")
require(tictoc)
tic()
rnorm(1000,0,1)
toc()

To save the elapsed time into a variable you can do:

install.packages("tictoc")
require(tictoc)
tic()
rnorm(1000,0,1)
exectime <- toc()
exectime <- exectime$toc - exectime$tic

Understanding events and event handlers in C#

My understanding of the events is;

Delegate:

A variable to hold reference to method / methods to be executed. This makes it possible to pass around methods like a variable.

Steps for creating and calling the event:

  1. The event is an instance of a delegate

  2. Since an event is an instance of a delegate, then we have to first define the delegate.

  3. Assign the method / methods to be executed when the event is fired (Calling the delegate)

  4. Fire the event (Call the delegate)

Example:

using System;

namespace test{
    class MyTestApp{
        //The Event Handler declaration
        public delegate void EventHandler();

        //The Event declaration
        public event EventHandler MyHandler;

        //The method to call
        public void Hello(){
            Console.WriteLine("Hello World of events!");
        }

        public static void Main(){
            MyTestApp TestApp = new MyTestApp();

            //Assign the method to be called when the event is fired
            TestApp.MyHandler = new EventHandler(TestApp.Hello);

            //Firing the event
            if (TestApp.MyHandler != null){
                TestApp.MyHandler();
            }
        }

    }   

}

Image is not showing in browser?

I find out the way how to set the image path just remove the "/" before the destination folder as "images/66.jpg" not "/images/66.jpg" And its working fine for me.

Excel VBA Automation Error: The object invoked has disconnected from its clients

Couple of things to try...

  1. Comment out the second "Set NewBook" line of code...

  2. You already have an object reference to the workbook.

  3. Do your SaveAs after copying the sheets.

"Unable to locate tools.jar" when running ant

Make sure you use the root folder of the JDK. Don't add "\lib" to the end of the path, where tools.jar is physically located. It took me an hour to figure that one out. Also, this post will help show you where Ant is looking for tools.jar:

Why does ANT tell me that JAVA_HOME is wrong when it is not?

Why is January month 0 in Java Calendar?

It's just part of the horrendous mess which is the Java date/time API. Listing what's wrong with it would take a very long time (and I'm sure I don't know half of the problems). Admittedly working with dates and times is tricky, but aaargh anyway.

Do yourself a favour and use Joda Time instead, or possibly JSR-310.

EDIT: As for the reasons why - as noted in other answers, it could well be due to old C APIs, or just a general feeling of starting everything from 0... except that days start with 1, of course. I doubt whether anyone outside the original implementation team could really state reasons - but again, I'd urge readers not to worry so much about why bad decisions were taken, as to look at the whole gamut of nastiness in java.util.Calendar and find something better.

One point which is in favour of using 0-based indexes is that it makes things like "arrays of names" easier:

// I "know" there are 12 months
String[] monthNames = new String[12]; // and populate...
String name = monthNames[calendar.get(Calendar.MONTH)];

Of course, this fails as soon as you get a calendar with 13 months... but at least the size specified is the number of months you expect.

This isn't a good reason, but it's a reason...

EDIT: As a comment sort of requests some ideas about what I think is wrong with Date/Calendar:

  • Surprising bases (1900 as the year base in Date, admittedly for deprecated constructors; 0 as the month base in both)
  • Mutability - using immutable types makes it much simpler to work with what are really effectively values
  • An insufficient set of types: it's nice to have Date and Calendar as different things, but the separation of "local" vs "zoned" values is missing, as is date/time vs date vs time
  • An API which leads to ugly code with magic constants, instead of clearly named methods
  • An API which is very hard to reason about - all the business about when things are recomputed etc
  • The use of parameterless constructors to default to "now", which leads to hard-to-test code
  • The Date.toString() implementation which always uses the system local time zone (that's confused many Stack Overflow users before now)

What is the best way to use a HashMap in C++?

Evidence that std::unordered_map uses a hash map in GCC stdlibc++ 6.4

This was mentioned at: https://stackoverflow.com/a/3578247/895245 but in the following answer: What data structure is inside std::map in C++? I have given further evidence of such for the GCC stdlibc++ 6.4 implementation by:

  • GDB step debugging into the class
  • performance characteristic analysis

Here is a preview of the performance characteristic graph described in that answer:

enter image description here

How to use a custom class and hash function with unordered_map

This answer nails it: C++ unordered_map using a custom class type as the key

Excerpt: equality:

struct Key
{
  std::string first;
  std::string second;
  int         third;

  bool operator==(const Key &other) const
  { return (first == other.first
            && second == other.second
            && third == other.third);
  }
};

Hash function:

namespace std {

  template <>
  struct hash<Key>
  {
    std::size_t operator()(const Key& k) const
    {
      using std::size_t;
      using std::hash;
      using std::string;

      // Compute individual hash values for first,
      // second and third and combine them using XOR
      // and bit shifting:

      return ((hash<string>()(k.first)
               ^ (hash<string>()(k.second) << 1)) >> 1)
               ^ (hash<int>()(k.third) << 1);
    }
  };

}

How can I make Flexbox children 100% height of their parent?

fun fact: height-100% works in the latest chrome; but not in safari;


so solution in tailwind would be

"flex items-stretch"

https://tailwindcss.com/docs/align-items

and be applied recursively to the child's child's child ...

Activate a virtualenv with a Python script

You should create all your virtualenvs in one folder, such as virt.

Assuming your virtualenv folder name is virt, if not change it

cd
mkdir custom

Copy the below lines...

#!/usr/bin/env bash
ENV_PATH="$HOME/virt/$1/bin/activate"
bash --rcfile $ENV_PATH -i

Create a shell script file and paste the above lines...

touch custom/vhelper
nano custom/vhelper

Grant executable permission to your file:

sudo chmod +x custom/vhelper

Now export that custom folder path so that you can find it on the command-line by clicking tab...

export PATH=$PATH:"$HOME/custom"

Now you can use it from anywhere by just typing the below command...

vhelper YOUR_VIRTUAL_ENV_FOLDER_NAME

Suppose it is abc then...

vhelper abc

Strings and character with printf

The name of an array is the address of its first element, so name is a pointer to memory containing the string "siva".

Also you don't need a pointer to display a character; you are just electing to use it directly from the array in this case. You could do this instead:

char c = *name;
printf("%c\n", c);

Could not open ServletContext resource

I think currently the application-context.xml file is into src/main/resources AND the social.properties file is into src/main/java... so when you package (mvn package) or when you run tomcat (mvn tomcat:run) your social.properties disappeared (I know you said when you checked into the .war the files are here... but your exception says the opposite).

The solution is simply to put all your configuration files (application-context.xml and social.properties) into src/main/resources to follow the maven standard structure.

How to check if a float value is a whole number

Just a side info, is_integer is doing internally:

import math
isInteger = (math.floor(x) == x)

Not exactly in python, but the cpython implementation is implemented as mentioned above.

How to remove leading zeros using C#

I just crafted this as I needed a good, simple way.

If it gets to the final digit, and if it is a zero, it will stay.

You could also use a foreach loop instead for super long strings.

I just replace each leading oldChar with the newChar.


This is great for a problem I just solved, after formatting an int into a string.

    /* Like this: */
    int counterMax = 1000;
    int counter = ...;
    string counterString = counter.ToString($"D{counterMax.ToString().Length}");
    counterString = RemoveLeadingChars('0', ' ', counterString);
    string fullCounter = $"({counterString}/{counterMax})";
    // = (   1/1000) ... ( 430/1000) ... (1000/1000)

    static string RemoveLeadingChars(char oldChar, char newChar, char[] chars)
    {
        string result = "";
        bool stop = false;
        for (int i = 0; i < chars.Length; i++)
        {
            if (i == (chars.Length - 1)) stop = true;
            if (!stop && chars[i] == oldChar) chars[i] = newChar;
            else stop = true;
            result += chars[i];
        }
        return result;
    }

    static string RemoveLeadingChars(char oldChar, char newChar, string text)
    {
        return RemoveLeadingChars(oldChar, newChar, text.ToCharArray());
    }

I always tend to make my functions suitable for my own library, so there are options.

jQuery slide left and show

This feature is included as part of jquery ui http://docs.jquery.com/UI/Effects/Slide if you want to extend it with your own names you can use this.

jQuery.fn.extend({
  slideRightShow: function() {
    return this.each(function() {
        $(this).show('slide', {direction: 'right'}, 1000);
    });
  },
  slideLeftHide: function() {
    return this.each(function() {
      $(this).hide('slide', {direction: 'left'}, 1000);
    });
  },
  slideRightHide: function() {
    return this.each(function() {
      $(this).hide('slide', {direction: 'right'}, 1000);
    });
  },
  slideLeftShow: function() {
    return this.each(function() {
      $(this).show('slide', {direction: 'left'}, 1000);
    });
  }
});

you will need the following references

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://jquery-ui.googlecode.com/svn/tags/latest/ui/jquery.effects.core.js"></script>
<script src="http://jquery-ui.googlecode.com/svn/tags/latest/ui/jquery.effects.slide.js"></script>

How do I tell if .NET 3.5 SP1 is installed?

Take a look at this article which shows the registry keys you need to look for and provides a .NET library that will do this for you.

First, you should to determine if .NET 3.5 is installed by looking at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\Install, which is a DWORD value. If that value is present and set to 1, then that version of the Framework is installed.

Look at HKLM\Software\Microsoft\NET Framework Setup\NDP\v3.5\SP, which is a DWORD value which indicates the Service Pack level (where 0 is no service pack).

To be correct about things, you really need to ensure that .NET Fx 2.0 and .NET Fx 3.0 are installed first and then check to see if .NET 3.5 is installed. If all three are true, then you can check for the service pack level.

can we use xpath with BeautifulSoup?

from lxml import etree
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('path of your localfile.html'),'html.parser')
dom = etree.HTML(str(soup))
print dom.xpath('//*[@id="BGINP01_S1"]/section/div/font/text()')

Above used the combination of Soup object with lxml and one can extract the value using xpath

Closing Excel Application using VBA

You can try out

ThisWorkbook.Save
ThisWorkbook.Saved = True
Application.Quit

Deserialize JSON with Jackson into Polymorphic Types - A Complete Example is giving me a compile error

As promised, I'm putting an example for how to use annotations to serialize/deserialize polymorphic objects, I based this example in the Animal class from the tutorial you were reading.

First of all your Animal class with the Json Annotations for the subclasses.

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.fasterxml.jackson.annotation.JsonSubTypes;
import com.fasterxml.jackson.annotation.JsonTypeInfo;

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY)
@JsonSubTypes({
    @JsonSubTypes.Type(value = Dog.class, name = "Dog"),

    @JsonSubTypes.Type(value = Cat.class, name = "Cat") }
)
public abstract class Animal {

    private String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

}

Then your subclasses, Dog and Cat.

public class Dog extends Animal {

    private String breed;

    public Dog() {

    }

    public Dog(String name, String breed) {
        setName(name);
        setBreed(breed);
    }

    public String getBreed() {
        return breed;
    }

    public void setBreed(String breed) {
        this.breed = breed;
    }
}

public class Cat extends Animal {

    public String getFavoriteToy() {
        return favoriteToy;
    }

    public Cat() {}

    public Cat(String name, String favoriteToy) {
        setName(name);
        setFavoriteToy(favoriteToy);
    }

    public void setFavoriteToy(String favoriteToy) {
        this.favoriteToy = favoriteToy;
    }

    private String favoriteToy;

}

As you can see, there is nothing special for Cat and Dog, the only one that know about them is the abstract class Animal, so when deserializing, you'll target to Animal and the ObjectMapper will return the actual instance as you can see in the following test:

public class Test {

    public static void main(String[] args) {

        ObjectMapper objectMapper = new ObjectMapper();

        Animal myDog = new Dog("ruffus","english shepherd");

        Animal myCat = new Cat("goya", "mice");

        try {
            String dogJson = objectMapper.writeValueAsString(myDog);

            System.out.println(dogJson);

            Animal deserializedDog = objectMapper.readValue(dogJson, Animal.class);

            System.out.println("Deserialized dogJson Class: " + deserializedDog.getClass().getSimpleName());

            String catJson = objectMapper.writeValueAsString(myCat);

            Animal deseriliazedCat = objectMapper.readValue(catJson, Animal.class);

            System.out.println("Deserialized catJson Class: " + deseriliazedCat.getClass().getSimpleName());



        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

Output after running the Test class:

{"@type":"Dog","name":"ruffus","breed":"english shepherd"}

Deserialized dogJson Class: Dog

{"@type":"Cat","name":"goya","favoriteToy":"mice"}

Deserialized catJson Class: Cat

Hope this helps,

Jose Luis

What is class="mb-0" in Bootstrap 4?

Bootstrap has predefined classes that we use for styling. If you are familiar with CSS, you'd know what padding, margin and spacing etc. are.

mb-0 = margin-bottom:0;

OK now moving a little further in knowledge, bootstrap has more classes for margin including:

mt- = margin-top
mb- = margin-bottom
ml- = margin-left
mr- = margin-right
my- = it sets margin-left and margin-right at the same time on y axes
mX- = it sets margin-bottom and margin-top at the same time on X axes

This and much more is explained here https://getbootstrap.com/docs/5.0/utilities/spacing/ The best way to learn is through https://getbootstrap.com site itself. It explains a lot obout its built in classes.

How to clear the cache in NetBeans

The path of the cache directory is listed in the About window (menu Help/About). Close NetBeans, then delete (or rename) the directory. NetBeans will rebuild its cache when it starts up.

Why doesn't [01-12] range work as expected?

This also works:

^([1-9]|[0-1][0-2])$

[1-9] matches single digits between 1 and 9

[0-1][0-2] matches double digits between 10 and 12

There are some good examples here

What does "./" (dot slash) refer to in terms of an HTML file path location?

You can use the following list as quick reference:

   /   = Root directory
   .   = This location
   ..  = Up a directory
   ./  = Current directory
   ../ = Parent of current directory
   ../../ = Two directories backwards

Useful article: https://css-tricks.com/quick-reminder-about-file-paths/

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

In Your RecyclerView in Kotlin

inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    fun bind(t: YourObject, listener: OnItemClickListener.YourObjectListener) = with(itemView) {
        textViewcolor.setTextColor(ContextCompat.getColor(itemView.context, R.color.colorPrimary))
        textViewcolor.text = t.name
    }
}

How to affect other elements when one element is hovered

Here is another idea that allow you to affect other elements without considering any specific selector and by only using the :hover state of the main element.

For this, I will rely on the use of custom properties (CSS variables). As we can read in the specification:

Custom properties are ordinary properties, so they can be declared on any element, are resolved with the normal inheritance and cascade rules ...

The idea is to define custom properties within the main element and use them to style child elements and since these properties are inherited we simply need to change them within the main element on hover.

Here is an example:

_x000D_
_x000D_
#container {_x000D_
  width: 200px;_x000D_
  height: 30px;_x000D_
  border: 1px solid var(--c);_x000D_
  --c:red;_x000D_
}_x000D_
#container:hover {_x000D_
  --c:blue;_x000D_
}_x000D_
#container > div {_x000D_
  width: 30px;_x000D_
  height: 100%;_x000D_
  background-color: var(--c);_x000D_
}
_x000D_
<div id="container">_x000D_
  <div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Why this can be better than using specific selector combined with hover?

I can provide at least 2 reasons that make this method a good one to consider:

  1. If we have many nested elements that share the same styles, this will avoid us complex selector to target all of them on hover. Using Custom properties, we simply change the value when hovering on the parent element.
  2. A custom property can be used to replace a value of any property and also a partial value of it. For example we can define a custom property for a color and we use it within a border, linear-gradient, background-color, box-shadow etc. This will avoid us reseting all these properties on hover.

Here is a more complex example:

_x000D_
_x000D_
.container {_x000D_
  --c:red;_x000D_
  width:400px;_x000D_
  display:flex;_x000D_
  border:1px solid var(--c);_x000D_
  justify-content:space-between;_x000D_
  padding:5px;_x000D_
  background:linear-gradient(var(--c),var(--c)) 0 50%/100% 3px no-repeat;_x000D_
}_x000D_
.box {_x000D_
  width:30%;_x000D_
  background:var(--c);_x000D_
  box-shadow:0px 0px 5px var(--c);_x000D_
  position:relative;_x000D_
}_x000D_
.box:before {_x000D_
  content:"A";_x000D_
  display:block;_x000D_
  width:15px;_x000D_
  margin:0 auto;_x000D_
  height:100%;_x000D_
  color:var(--c);_x000D_
  background:#fff;_x000D_
}_x000D_
_x000D_
/*Hover*/_x000D_
.container:hover {_x000D_
  --c:blue;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
<div class="box"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

As we can see above, we only need one CSS declaration in order to change many properties of different elements.

How can I check file size in Python?

we have two options Both include importing os module

1) import os, as os.stat() function returns an object which contains so many headers including file created time and last modified time etc.. among them st_size gives the exact size of the file.

os.stat("filename").st_size

2) import os In this, we have to provide the exact file path(absolute path), not a relative path.

os.path.getsize("path of file")

How do I get the path and name of the file that is currently executing?

if you want just the filename without ./ or .py you can try this

filename = testscript.py
file_name = __file__[2:-3]

file_name will print testscript you can generate whatever you want by changing the index inside []

Angular JS POST request not sending JSON data

$http({
    url: '/api/user',
    method: "POST",
    data: angular.toJson(yourData)
}).success(function (data, status, headers, config) {
    $scope.users = data.users;
}).error(function (data, status, headers, config) {
    $scope.status = status + ' ' + headers;
});

PSQLException: current transaction is aborted, commands ignored until end of transaction block

Check the output before the statement that caused current transaction is aborted. This typically means that database threw an exception that your code had ignored and now expecting next queries to return some data.

So you now have a state mismatch between your application, which considers things are fine, and database, that requires you to rollback and re-start your transaction from the beginning.

You should catch all exceptions and rollback transactions in such cases.

Here's a similar issue.

"This operation requires IIS integrated pipeline mode."

I resolved this problem by following steps:

  1. Right click on root folder of project.
  2. Goto properties
  3. Click web in left menu
  4. change current port http://localhost:####/
  5. click create virtual directory
  6. Save the changes (ctrl+s)
  7. Run

may be it help you to.

How can I go back/route-back on vue-router?

If you're using Vuex you can use https://github.com/vuejs/vuex-router-sync

Just initialize it in your main file with:

import VuexRouterSync from 'vuex-router-sync';
VuexRouterSync.sync(store, router);

Each route change will update route state object in Vuex. You can next create getter to use the from Object in route state or just use the state (better is to use getters, but it's other story https://vuex.vuejs.org/en/getters.html), so in short it would be (inside components methods/values):

this.$store.state.route.from.fullPath

You can also just place it in <router-link> component:

<router-link :to="{ path: $store.state.route.from.fullPath }"> 
  Back 
</router-link>

So when you use code above, link to previous path would be dynamically generated.

SQL Error: ORA-00913: too many values

this is a bit late.. but i have seen this problem occurs when you want to insert or delete one line from/to DB but u put/pull more than one line or more than one value ,

E.g:

you want to delete one line from DB with a specific value such as id of an item but you've queried a list of ids then you will encounter the same exception message.

regards.

How to remove all the null elements inside a generic list in one go?

You'll probably want the following.

List<EmailParameterClass> parameterList = new List<EmailParameterClass>{param1, param2, param3...};
parameterList.RemoveAll(item => item == null);

How to _really_ programmatically change primary and accent color in Android Lollipop?

This is what you CAN do:

write a file in drawable folder, lets name it background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="?attr/colorPrimary"/>
</shape>

then set your Layout's (or what so ever the case is) android:background="@drawable/background"

on setting your theme this color would represent the same.

Send request to curl with post data sourced from a file

I had to use a HTTP connection, because on HTTPS there is default file size limit.

https://techcommunity.microsoft.com/t5/IIS-Support-Blog/Solution-for-Request-Entity-Too-Large-error/ba-p/501134

    curl -i -X 'POST' -F 'file=@/home/testeincremental.xlsx' 'http://example.com/upload.aspx?user=example&password=example123&type=XLSX'

When should I use GET or POST method? What's the difference between them?

When the user enters information in a form and clicks Submit , there are two ways the information can be sent from the browser to the server: in the URL, or within the body of the HTTP request.

The GET method, which was used in the example earlier, appends name/value pairs to the URL. Unfortunately, the length of a URL is limited, so this method only works if there are only a few parameters. The URL could be truncated if the form uses a large number of parameters, or if the parameters contain large amounts of data. Also, parameters passed on the URL are visible in the address field of the browser not the best place for a password to be displayed.

The alternative to the GET method is the POST method. This method packages the name/value pairs inside the body of the HTTP request, which makes for a cleaner URL and imposes no size limitations on the forms output. It is also more secure.

HTML5 Audio stop function

It don't work sometimes in chrome,

sound.pause();
sound.currentTime = 0;

just change like that,

sound.currentTime = 0;
sound.pause();

Setting size for icon in CSS

The better way is using 'background-size'.

.pnx-msg-icon .pnx-icon-msg-warning{
background-image: url("../pics/edit.png");
background-repeat: no-repeat;
background-size: 10px;
width: 10px;
height: 10px;
cursor: pointer;
}

even if your icon dimensions is bigger than 10px it will be 10px.

comparing 2 strings alphabetically for sorting purposes

"a".localeCompare("b") should actually return -1 since a sorts before b

http://www.w3schools.com/jsref/jsref_localecompare.asp

Creating a singleton in Python

I'll toss mine into the ring. It's a simple decorator.

from abc import ABC

def singleton(real_cls):

    class SingletonFactory(ABC):

        instance = None

        def __new__(cls, *args, **kwargs):
            if not cls.instance:
                cls.instance = real_cls(*args, **kwargs)
            return cls.instance

    SingletonFactory.register(real_cls)
    return SingletonFactory

# Usage
@singleton
class YourClass:
    ...  # Your normal implementation, no special requirements.

Benefits I think it has over some of the other solutions:

  • It's clear and concise (to my eye ;D).
  • Its action is completely encapsulated. You don't need to change a single thing about the implementation of YourClass. This includes not needing to use a metaclass for your class (note that the metaclass above is on the factory, not the "real" class).
  • It doesn't rely on monkey-patching anything.
  • It's transparent to callers:
    • Callers still simply import YourClass, it looks like a class (because it is), and they use it normally. No need to adapt callers to a factory function.
    • What YourClass() instantiates is still a true instance of the YourClass you implemented, not a proxy of any kind, so no chance of side effects resulting from that.
    • isinstance(instance, YourClass) and similar operations still work as expected (though this bit does require abc so precludes Python <2.6).

One downside does occur to me: classmethods and staticmethods of the real class are not transparently callable via the factory class hiding it. I've used this rarely enough that I've never happen to run into that need, but it would be easily rectified by using a custom metaclass on the factory that implements __getattr__() to delegate all-ish attribute access to the real class.

A related pattern I've actually found more useful (not that I'm saying these kinds of things are required very often at all) is a "Unique" pattern where instantiating the class with the same arguments results in getting back the same instance. I.e. a "singleton per arguments". The above adapts to this well and becomes even more concise:

def unique(real_cls):

    class UniqueFactory(ABC):

        @functools.lru_cache(None)  # Handy for 3.2+, but use any memoization decorator you like
        def __new__(cls, *args, **kwargs):
            return real_cls(*args, **kwargs)

    UniqueFactory.register(real_cls)
    return UniqueFactory

All that said, I do agree with the general advice that if you think you need one of these things, you really should probably stop for a moment and ask yourself if you really do. 99% of the time, YAGNI.

Open Form2 from Form1, close Form1 from Form2

on the form2.buttonclick put

this.close();

form1 should have object of form2.

you need to subscribe Closing event of form2.

and in closing method put

this.close();

Virtualhost For Wildcard Subdomain and Static Subdomain

<VirtualHost *:80>
  DocumentRoot /var/www/app1
  ServerName app1.example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/example
  ServerName example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /var/www/wildcard
  ServerName other.example.com
  ServerAlias *.example.com
</VirtualHost>

Should work. The first entry will become the default if you don't get an explicit match. So if you had app.otherexample.com point to it, it would be caught be app1.example.com.

Getting current directory in VBScript

Use With in the code.

Try this way :

''''Way 1

currentdir=Left(WScript.ScriptFullName,InStrRev(WScript.ScriptFullName,"\"))


''''Way 2

With CreateObject("WScript.Shell")
CurrentPath=.CurrentDirectory
End With


''''Way 3

With WSH
CD=Replace(.ScriptFullName,.ScriptName,"")
End With

Is there a kind of Firebug or JavaScript console debug for Android?

If you're using Cordova 3.3 or higher and your device is running Android 4.4 or higher you can use 'Remote Debugging on Android with Chrome'. Full instructions are here:

https://developer.chrome.com/devtools/docs/remote-debugging

In summary:

  • Plug the device into your desktop computer using a USB cable
  • Enable USB debugging on your device (on my device this is under Settings > More > Developer options > USB debugging)

Or, if you're using Cordova 3.3+ and don't have a physical device with 4.4, you can use an emulator that uses Android 4.4+ to run the application through the emulator, on your desktop computer.

  • Run your Cordova application on the device or emulator
  • In Chrome on your desktop computer, enter chrome://inspect/#devices in the address bar
  • Your device/emulator will be displayed along with any other recognised devices that are connected to your computer, and under your device there will be details of the Cordova 'WebView' (basically your Cordova app), which is running on the device/emulator (the way Cordova works is that it basically creates a 'browser' window on your device/emulator, within which there is a 'WebView' which is your running HTML/JavaScript app)
  • Click the 'inspect' link under the 'WebView' section where you see your device/emulator listed. This brings up the Chrome developer tools that now allow you to debug your application.
  • Select the 'sources' tab of the Chrome developer tools to view JavaScript that your Cordova app on the device/emulator is currently running. You can add breakpoints in the JavaScript that allow you to debug your code.
  • Also, you can use the 'console' tab to view any errors (which will be shown in red), or at the bottom of the console you'll see a '>' prompt. Here you can type in any variables or objects (e.g. DOM objects) that you want to inspect the current value of, and the value will be displayed.

Where is the IIS Express configuration / metabase file found?

For VS 2015 & VS 2017: Right-click the IIS Express system tray icon (when running the application), and select "Show all applications":

Context menu for IIS Express system tray icon showing the alternative "Show all applications" highlighted

Then, select the relevant application and click the applicationhost.config file path:

Dialog showing arbritrary website with accompanying applicationhost.config file path

Git Bash won't run my python files?

Tried multiple of these, I switched to Cygwin instead which fixed python and some other problems I was having on Windows:

https://www.cygwin.com/

Python Error: "ValueError: need more than 1 value to unpack"

Probably you didn't provide an argument on the command line. In that case, sys.argv only contains one value, but it would have to have two in order to provide values for both user_name and script.

How to add composite primary key to table

The ALTER TABLE statement presented by Chris should work, but first you need to declare the columns NOT NULL. All parts of a primary key need to be NOT NULL.

git pull keeping local changes

To answer the question : if you want to exclude certain files of a checkout, you can use sparse-checkout

  1. In .git/info/sparse-checkout, define what you want to keep. Here, we want all (*) but (note the exclamation mark) config.php :

    /* !/config.php

  2. Tell git you want to take sparse-checkout into account

    git config core.sparseCheckout true

  3. If you already have got this file locally, do what git does on a sparse checkout (tell it it must exclude this file by setting the "skip-worktree" flag on it)

    git update-index --skip-worktree config.php

  4. Enjoy a repository where your config.php file is yours - whatever changes are on the repository.


Please note that configuration values SHOULDN'T be in source control :

  • It is a potential security breach
  • It causes problems like this one for deployment

This means you MUST exclude them (put them in .gitignore before first commit), and create the appropriate file on each instance where you checkout your app (by copying and adapting a "template" file)

Note that, once a file is taken in charge by git, .gitignore won't have any effect.

Given that, once the file is under source control, you only have two choices () :

  • rebase all your history to remove the file (with git filter-branch)

  • create a commit that removes the file. It is like fighting a loosing battle, but, well, sometimes you have to live with that.

Locking a file in Python

The scenario is like that: The user requests a file to do something. Then, if the user sends the same request again, it informs the user that the second request is not done until the first request finishes. That's why, I use lock-mechanism to handle this issue.

Here is my working code:

from lockfile import LockFile
lock = LockFile(lock_file_path)
status = ""
if not lock.is_locked():
    lock.acquire()
    status = lock.path + ' is locked.'
    print status
else:
    status = lock.path + " is already locked."
    print status

return status

Elasticsearch : Root mapping definition has unsupported parameters index : not_analyzed

Check your Elastic version.

I had these problem because I was looking at the incorrect version's documentation.

enter image description here

How to set dropdown arrow in spinner?

copy and paste this xml instead of your xml

<?xml version="1.0" encoding="UTF-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/back1"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="20dp" 
        android:background="@drawable/red">

        <Spinner
            android:id="@+id/spinner1"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:dropDownWidth="fill_parent" 
            android:background="@android:drawable/btn_dropdown"
         />

    </LinearLayout>

    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignLeft="@+id/linearLayout1"
        android:layout_alignRight="@+id/linearLayout1"
        android:layout_below="@+id/linearLayout1"
        android:layout_marginTop="25dp"
        android:background="@drawable/red"
        android:ems="10"
        android:hint="enter card number" >

        <requestFocus />
    </EditText>

    <LinearLayout
        android:id="@+id/linearLayout2"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignLeft="@+id/editText1"
        android:layout_alignRight="@+id/editText1"
        android:layout_below="@+id/editText1"
        android:layout_marginTop="33dp"
        android:orientation="horizontal" 
        android:background="@drawable/red">

        <Spinner
            android:id="@+id/spinner3"
            android:layout_width="72dp"
            android:layout_height="wrap_content"
            android:background="@android:drawable/btn_dropdown"
             />

        <Spinner
            android:id="@+id/spinner2"
            android:layout_width="72dp"
            android:layout_height="wrap_content" 
            android:background="@android:drawable/btn_dropdown"
            />

        <EditText
            android:id="@+id/editText2"
            android:layout_width="22dp"
            android:layout_height="match_parent"
            android:layout_weight="0.18"
            android:ems="10"
            android:hint="enter cvv" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout3"
        android:layout_width="wrap_content"
        android:layout_height="55dp"
        android:layout_alignParentLeft="true"
        android:layout_alignRight="@+id/linearLayout2"
        android:layout_below="@+id/linearLayout2"
        android:layout_marginTop="26dp"
        android:orientation="vertical"
        android:background="@drawable/red" >
    </LinearLayout>

    <Spinner
        android:id="@+id/spinner4"
        android:layout_width="15dp"
        android:layout_height="18dp"
        android:layout_alignBottom="@+id/linearLayout3"
        android:layout_alignLeft="@+id/linearLayout3"
        android:layout_alignRight="@+id/linearLayout3"
        android:layout_alignTop="@+id/linearLayout3"
        android:background="@android:drawable/btn_dropdown"
      />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/linearLayout3"
        android:layout_marginTop="18dp"
        android:text="Add Amount" 
        android:background="@drawable/buttonsty"/>
</RelativeLayout>

Quicker way to get all unique values of a column in VBA?

Loading the values in an array would be much faster:

Dim data(), dict As Object, r As Long
Set dict = CreateObject("Scripting.Dictionary")

data = ActiveSheet.UsedRange.Columns(1).Value

For r = 1 To UBound(data)
    dict(data(r, some_column_number)) = Empty
Next

data = WorksheetFunction.Transpose(dict.keys())

You should also consider early binding for the Scripting.Dictionary:

Dim dict As New Scripting.Dictionary  ' requires `Microsoft Scripting Runtime` '

Note that using a dictionary is way faster than Range.AdvancedFilter on large data sets.

As a bonus, here's a procedure similare to Range.RemoveDuplicates to remove duplicates from a 2D array:

Public Sub RemoveDuplicates(data, ParamArray columns())
    Dim ret(), indexes(), ids(), r As Long, c As Long
    Dim dict As New Scripting.Dictionary  ' requires `Microsoft Scripting Runtime` '

    If VarType(data) And vbArray Then Else Err.Raise 5, , "Argument data is not an array"

    ReDim ids(LBound(columns) To UBound(columns))

    For r = LBound(data) To UBound(data)         ' each row '
        For c = LBound(columns) To UBound(columns)   ' each column '
            ids(c) = data(r, columns(c))                ' build id for the row
        Next
        dict(Join$(ids, ChrW(-1))) = r  ' associate the row index to the id '
    Next

    indexes = dict.Items()
    ReDim ret(LBound(data) To LBound(data) + dict.Count - 1, LBound(data, 2) To UBound(data, 2))

    For c = LBound(ret, 2) To UBound(ret, 2)  ' each column '
        For r = LBound(ret) To UBound(ret)      ' each row / unique id '
            ret(r, c) = data(indexes(r - 1), c)   ' copy the value at index '
        Next
    Next

    data = ret
End Sub

Ping all addresses in network, windows

@ECHO OFF

IF "%SUBNET%"=="" SET SUBNET=10

:ARGUMENTS
ECHO SUBNET=%SUBNET%
ECHO ARGUMENT %1 
IF "%1"=="SUM" GOTO SUM
IF "%1"=="SLOW" GOTO SLOW
IF "%1"=="ARP" GOTO ARP
IF "%1"=="FAST" GOTO FAST

REM PRINT ARP TABLE BY DEFAULT
:DEFAULT
ARP -a
GOTO END

REM METHOD 1 ADDRESS AT A TIME
:SLOW
ECHO START SCAN
ECHO %0 > ipaddresses.txt
DATE /T >> ipaddresses.txt
TIME /T >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO ping -a -n 2 192.168.%SUBNET%.%%i | FIND /i "TTL="  >> ipaddresses.txt
GOTO END

REM METHOD 2 MULTITASKING ALL ADDRESS AT SAME TIME
:FAST
ECHO START FAST SCANNING 192.168.%SUBNET%.X
set /a n=0
:FASTLOOP
set /a n+=1
ECHO 192.168.%SUBNET%.%n%
START CMD.exe /c call ipaddress.bat 192.168.%SUBNET%.%n% 
IF %n% lss 254 GOTO FASTLOOP
GOTO END

:SUM
ECHO START SUM
ECHO %0 > ipaddresses.txt
DATE /T >> ipaddresses.txt
TIME /T >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO TYPE ip192.168.%SUBNET%.%%i.txt | FIND /i "TTL=" >> ipaddresses.txt
FOR /L %%i IN (1,1,254) DO DEL ip192.168.%SUBNET%.%%i.txt
type ipaddresses.txt
GOTO END

:ARP
ARP -a >> ipaddresses.txt
type ipaddresses.txt
GOTO END


:END
ECHO DONE WITH IP SCANNING
ECHO OPTION "%0 SLOW" FOR SCANNING 1 AT A TIME
ECHO OPTION "%0 SUM" FOR COMBINE ALL TO FILE
ECHO OPTION "%0 ARP" FOR ADD ARP - IP LIST
ECHO PARAMETER "SET SUBNET=X" FOR SUBNET
ECHO.

How can I easily view the contents of a datatable or dataview in the immediate window

To beautify adinas's debugger output I made some simple formattings:

    public void DebugTable(DataTable table)
    {
        Debug.WriteLine("--- DebugTable(" + table.TableName + ") ---");
        int zeilen = table.Rows.Count;
        int spalten = table.Columns.Count;

        // Header
        for (int i = 0; i < table.Columns.Count; i++)
        {
            string s = table.Columns[i].ToString();
            Debug.Write(String.Format("{0,-20} | ", s));
        }
        Debug.Write(Environment.NewLine);
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Debug.Write("---------------------|-");
        }
        Debug.Write(Environment.NewLine);

        // Data
        for (int i = 0; i < zeilen; i++)
        {
            DataRow row = table.Rows[i];
            //Debug.WriteLine("{0} {1} ", row[0], row[1]);
            for (int j = 0; j < spalten; j++)
            {
                string s = row[j].ToString();
                if (s.Length > 20) s = s.Substring(0, 17) + "...";
                Debug.Write(String.Format("{0,-20} | ", s));
            }
            Debug.Write(Environment.NewLine);
        }
        for (int i = 0; i < table.Columns.Count; i++)
        {
            Debug.Write("---------------------|-");
        }
        Debug.Write(Environment.NewLine);
    }

Best of this solution: You don't need Visual Studio! Here my example output:

SELECT PackKurz, PackName, PackGewicht FROM verpackungen

PackKurz             | PackName             | PackGewicht          | 
---------------------|----------------------|----------------------|-
BB205                | BigBag 205 kg        | 205                  | 
BB300                | BigBag 300 kg        | 300                  | 
BB365                | BigBag 365 kg        | 365                  | 
CO                   | Container, Alteru... |                      | 
EP                   | Palette              |                      | 
IBC                  | Chemikaliengefäß ... |                      | 
lose                 | nicht verpackungs... | 0                    | 
---------------------|----------------------|----------------------|-

How to get character for a given ascii value

I believe a simple cast can work

int ascii = (int) "A"

dereferencing pointer to incomplete type

I saw a question the other day where someone inadvertently used an incomplete type by specifying something like

struct a {
    int q; 
}; 
struct A *x; 
x->q = 3;

The compiler knew that struct A was a struct, despite A being totally undefined, by virtue of the struct keyword.

That was in C++, where such usage of struct is atypical (and, it turns out, can lead to foot-shooting). In C if you do

typedef struct a {
    ...
} a;

then you can use a as the typename and omit the struct later. This will lead the compiler to give you an undefined identifier error later, rather than incomplete type, if you mistype the name or forget a header.

Escape Character in SQL Server

You need to just replace ' with '' inside your string

SELECT colA, colB, colC
FROM tableD
WHERE colA = 'John''s Mobile'

You can also use REPLACE(@name, '''', '''''') if generating the SQL dynamically

If you want to escape inside a like statement then you need to use the ESCAPE syntax

It's also worth mentioning that you're leaving yourself open to SQL injection attacks if you don't consider it. More info at Google or: http://it.toolbox.com/wiki/index.php/How_do_I_escape_single_quotes_in_SQL_queries%3F

"Debug only" code that should run only when "turned on"

An instance variable would probably be the way to do what you want. You could make it static to persist the same value for the life of the program (or thread depending on your static memory model), or make it an ordinary instance var to control it over the life of an object instance. If that instance is a singleton, they'll behave the same way.

#if DEBUG
private /*static*/ bool s_bDoDebugOnlyCode = false;
#endif

void foo()
{   
  // ...
#if DEBUG
  if (s_bDoDebugOnlyCode)
  {
      // Code here gets executed only when compiled with the DEBUG constant, 
      // and when the person debugging manually sets the bool above to true.  
      // It then stays for the rest of the session until they set it to false.
  }
#endif
 // ...
}

Just to be complete, pragmas (preprocessor directives) are considered a bit of a kludge to use to control program flow. .NET has a built-in answer for half of this problem, using the "Conditional" attribute.

private /*static*/ bool doDebugOnlyCode = false; 
[Conditional("DEBUG")]
void foo()
{   
  // ...    
  if (doDebugOnlyCode)
  {
      // Code here gets executed only when compiled with the DEBUG constant, 
      // and when the person debugging manually sets the bool above to true.  
      // It then stays for the rest of the session until they set it to false.
  }    
  // ...
}

No pragmas, much cleaner. The downside is that Conditional can only be applied to methods, so you'll have to deal with a boolean variable that doesn't do anything in a release build. As the variable exists solely to be toggled from the VS execution host, and in a release build its value doesn't matter, it's pretty harmless.

How to draw a dotted line with css?

Using HTML:

<div class="horizontal_dotted_line"></div>

and in styles.css:

.horizontal_dotted_line{
  border-bottom: 1px dotted [color];
  width: [put your width here]px;
} 

Find out which remote branch a local branch is tracking

Update: Well, it's been several years since I posted this! For my specific purpose of comparing HEAD to upstream, I now use @{u}, which is a shortcut that refers to the HEAD of the upstream tracking branch. (See https://git-scm.com/docs/gitrevisions#gitrevisions-emltbranchnamegtupstreamemegemmasterupstreamememuem ).

Original answer: I've run across this problem as well. I often use multiple remotes in a single repository, and it's easy to forget which one your current branch is tracking against. And sometimes it's handy to know that, such as when you want to look at your local commits via git log remotename/branchname..HEAD.

All this stuff is stored in git config variables, but you don't have to parse the git config output. If you invoke git config followed by the name of a variable, it will just print the value of that variable, no parsing required. With that in mind, here are some commands to get info about your current branch's tracking setup:

LOCAL_BRANCH=`git name-rev --name-only HEAD`
TRACKING_BRANCH=`git config branch.$LOCAL_BRANCH.merge`
TRACKING_REMOTE=`git config branch.$LOCAL_BRANCH.remote`
REMOTE_URL=`git config remote.$TRACKING_REMOTE.url`

In my case, since I'm only interested in finding out the name of my current remote, I do this:

git config branch.`git name-rev --name-only HEAD`.remote

Conditional WHERE clause with CASE statement in Oracle

You can write the where clause as:

where (case when (:stateCode = '') then (1)
            when (:stateCode != '') and (vw.state_cd in (:stateCode)) then 1
            else 0)
       end) = 1;

Alternatively, remove the case entirely:

where (:stateCode = '') or
      ((:stateCode != '') and vw.state_cd in (:stateCode));

Or, even better:

where (:stateCode = '') or vw.state_cd in (:stateCode)

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

<?php header("Access-Control-Allow-Origin: http://example.com"); ?>

This command disables only first console warning info

console

Result: console result

Best way to create an empty map in Java

Since in many cases an empty map is used for null-safe design, you can utilize the nullToEmpty utility method:

class MapUtils {

  static <K,V> Map<K,V> nullToEmpty(Map<K,V> map) {
    if (map != null) {
      return map;
    } else {
       return Collections.<K,V>emptyMap(); // or guava ImmutableMap.of()
    }
  }

}  

Similarly for sets:

class SetUtils {

  static <T> Set<T> nullToEmpty(Set<T> set) {
    if (set != null) {
      return set;
    } else {
      return Collections.<T>emptySet();
    }
  }

}

and lists:

class ListUtils {

  static <T> List<T> nullToEmpty(List<T> list) {
    if (list != null) {
      return list;
    } else {
      return Collections.<T>emptyList();
    }
  }

}

Excel function to get first word from sentence in other cell

If you want to cater to 1-word cell, use this... based upon astander's

=IFERROR(LEFT(A1,SEARCH(" ",A1)-1),A1)

Could not load file or assembly 'Microsoft.ReportViewer.Common, Version=11.0.0.0

Add Microsot.ReportViewer 2010 or 2012 in prerequisite of setup project then it first install Report Viewer if it's not present in "C:\Windows\assembly\GAC_MSIL..." and after installing, it installs set up project

how to download file in react js

Download file


For downloading you can use multiple ways as been explained above, moreover I will also provide my strategy for this scenario.

  1. npm install --save react-download-link
  2. import DownloadLink from "react-download-link";
  3. React download link for client side cache data
    <DownloadLink 
        label="Download" 
        filename="fileName.txt"
        exportFile={() => "Client side cache data here…"}
    />
    
  4. Download link for client side cache data with Promises
    <DownloadLink
        label="Download with Promise"
        filename="fileName.txt"
        exportFile={() => Promise.resolve("cached data here …")}
    />
    
  5. Download link for data from URL with Promises Function to Fetch data from URL
     getDataFromURL = (url) => new Promise((resolve, reject) => {
        setTimeout(() => {
            fetch(url)
                .then(response => response.text())
                .then(data => {
                    resolve(data)
                });
        });
    }, 2000);
    
  6. DownloadLink component calling Fetch function
    <DownloadLink
          label=”Download”
          filename=”filename.txt”
          exportFile={() => Promise.resolve(this. getDataFromURL (url))}
    />
    

Happy coding! ;)

Get Value of a Edit Text field

Try this code

final EditText editText = findViewById(R.id.name); // your edittext id in xml
Button submit = findViewById(R.id.submit_button); // your button id in xml
submit.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) 
    {
        String string = editText.getText().toString();
        Toast.makeText(MainActivity.this, string, Toast.LENGTH_SHORT).show();
    }
});

How do I check if a cookie exists?

There are several good answers here. I however prefer [1] not using a regular expression, and [2] using logic that is simple to read, and [3] to have a short function that [4] does not return true if the name is a substring of another cookie name . Lastly [5] we can't use a for each loop since a return doesn't break it.

function cookieExists(name) {
  var cks = document.cookie.split(';');
  for(i = 0; i < cks.length; i++)
    if (cks[i].split('=')[0].trim() == name) return true;
}

Check if null Boolean is true results in exception

Use the Apache BooleanUtils.

(If peak performance is the most important priority in your project then look at one of the other answers for a native solution that doesn't require including an external library.)

Don't reinvent the wheel. Leverage what's already been built and use isTrue():

BooleanUtils.isTrue( bool );

Checks if a Boolean value is true, handling null by returning false.

If you're not limited to the libraries you're "allowed" to include, there are a bunch of great helper functions for all sorts of use-cases, including Booleans and Strings. I suggest you peruse the various Apache libraries and see what they already offer.

Why does Eclipse Java Package Explorer show question mark on some classes?

this is because your project has been linked to a git-hub repository, and the file having question mark on it, is not been added yet. if you want to remove this sign you will have to add this file to git-hub repository.

How do I do base64 encoding on iOS?

Since this seems to be the number one google hit on base64 encoding and iphone, I felt like sharing my experience with the code snippet above.

It works, but it is extremely slow. A benchmark on a random image (0.4 mb) took 37 seconds on native iphone. The main reason is probably all the OOP magic - single char NSStrings etc, which are only autoreleased after the encoding is done.

Another suggestion posted here (ab)uses the openssl library, which feels like overkill as well.

The code below takes 70 ms - that's a 500 times speedup. This only does base64 encoding (decoding will follow as soon as I encounter it)

+ (NSString *) base64StringFromData: (NSData *)data length: (int)length {
int lentext = [data length]; 
if (lentext < 1) return @"";

char *outbuf = malloc(lentext*4/3+4); // add 4 to be sure

if ( !outbuf ) return nil;

const unsigned char *raw = [data bytes];

int inp = 0;
int outp = 0;
int do_now = lentext - (lentext%3);

for ( outp = 0, inp = 0; inp < do_now; inp += 3 )
{
    outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
    outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
    outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
    outbuf[outp++] = base64EncodingTable[raw[inp+2] & 0x3F];
}

if ( do_now < lentext )
{
    char tmpbuf[2] = {0,0};
    int left = lentext%3;
    for ( int i=0; i < left; i++ )
    {
        tmpbuf[i] = raw[do_now+i];
    }
    raw = tmpbuf;
    outbuf[outp++] = base64EncodingTable[(raw[inp] & 0xFC) >> 2];
    outbuf[outp++] = base64EncodingTable[((raw[inp] & 0x03) << 4) | ((raw[inp+1] & 0xF0) >> 4)];
    if ( left == 2 ) outbuf[outp++] = base64EncodingTable[((raw[inp+1] & 0x0F) << 2) | ((raw[inp+2] & 0xC0) >> 6)];
}

NSString *ret = [[[NSString alloc] initWithBytes:outbuf length:outp encoding:NSASCIIStringEncoding] autorelease];
free(outbuf);

return ret;
}

I left out the line-cutting since I didn't need it, but it's trivial to add.

For those who are interested in optimizing: the goal is to minimize what happens in the main loop. Therefore all logic to deal with the last 3 bytes is treated outside the loop.

Also, try to work on data in-place, without additional copying to/from buffers. And reduce any arithmetic to the bare minimum.

Observe that the bits that are put together to look up an entry in the table, would not overlap when they were to be orred together without shifting. A major improvement could therefore be to use 4 separate 256 byte lookup tables and eliminate the shifts, like this:

outbuf[outp++] = base64EncodingTable1[(raw[inp] & 0xFC)];
outbuf[outp++] = base64EncodingTable2[(raw[inp] & 0x03) | (raw[inp+1] & 0xF0)];
outbuf[outp++] = base64EncodingTable3[(raw[inp+1] & 0x0F) | (raw[inp+2] & 0xC0)];
outbuf[outp++] = base64EncodingTable4[raw[inp+2] & 0x3F];

Of course you could take it a whole lot further, but that's beyond the scope here.

What's the difference between "git reset" and "git checkout"?

The two commands (reset and checkout) are completely different.

checkout X IS NOT reset --hard X

If X is a branch name, checkout X will change the current branch while reset --hard X will not.

How to make program go back to the top of the code instead of closing

write a for or while loop and put all of your code inside of it? Goto type programming is a thing of the past.

https://wiki.python.org/moin/ForLoop

How do I get video durations with YouTube API version 3?

I wrote the following class to get YouTube video duration using the YouTube API v3 (it returns thumbnails as well):

class Youtube
{
    static $api_key = '<API_KEY>';
    static $api_base = 'https://www.googleapis.com/youtube/v3/videos';
    static $thumbnail_base = 'https://i.ytimg.com/vi/';

    // $vid - video id in youtube
    // returns - video info
    public static function getVideoInfo($vid)
    {
        $params = array(
            'part' => 'contentDetails',
            'id' => $vid,
            'key' => self::$api_key,
        );

        $api_url = Youtube::$api_base . '?' . http_build_query($params);
        $result = json_decode(@file_get_contents($api_url), true);

        if(empty($result['items'][0]['contentDetails']))
            return null;
        $vinfo = $result['items'][0]['contentDetails'];

        $interval = new DateInterval($vinfo['duration']);
        $vinfo['duration_sec'] = $interval->h * 3600 + $interval->i * 60 + $interval->s;

        $vinfo['thumbnail']['default']       = self::$thumbnail_base . $vid . '/default.jpg';
        $vinfo['thumbnail']['mqDefault']     = self::$thumbnail_base . $vid . '/mqdefault.jpg';
        $vinfo['thumbnail']['hqDefault']     = self::$thumbnail_base . $vid . '/hqdefault.jpg';
        $vinfo['thumbnail']['sdDefault']     = self::$thumbnail_base . $vid . '/sddefault.jpg';
        $vinfo['thumbnail']['maxresDefault'] = self::$thumbnail_base . $vid . '/maxresdefault.jpg';

        return $vinfo;
    }
}

Please note that you'll need API_KEY to use the YouTube API:

  1. Create a new project here: https://console.developers.google.com/project
  2. Enable "YouTube Data API" under "APIs & auth" -> APIs
  3. Create a new server key under "APIs & auth" -> Credentials

Compare object instances for equality by their attributes

With Dataclasses in Python 3.7 (and above), a comparison of object instances for equality is an inbuilt feature.

A backport for Dataclasses is available for Python 3.6.

(Py37) nsc@nsc-vbox:~$ python
Python 3.7.5 (default, Nov  7 2019, 10:50:52) 
[GCC 8.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from dataclasses import dataclass
>>> @dataclass
... class MyClass():
...     foo: str
...     bar: str
... 
>>> x = MyClass(foo="foo", bar="bar")
>>> y = MyClass(foo="foo", bar="bar")
>>> x == y
True

Iterating a JavaScript object's properties using jQuery

$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

each

Change Button color onClick

1.

function setColor(e) {
  var target = e.target,
      count = +target.dataset.count;

   target.style.backgroundColor = count === 1 ? "#7FFF00" : '#FFFFFF';
   target.dataset.count = count === 1 ? 0 : 1;
   /* 

   () : ? - this is conditional (ternary) operator - equals 

   if (count === 1) {
      target.style.backgroundColor = "#7FFF00";
      target.dataset.count = 0;
   } else {
      target.style.backgroundColor = "#FFFFFF";
      target.dataset.count = 1;
   } 
   target.dataset - return all "data attributes" for current element, 
   in the form of object, 
   and you don't need use global variable in order to save the state 0 or 1
  */ 
}


<input 
  type="button" 
  id="button" 
  value="button" 
  style="color:white" 
  onclick="setColor(event)"; 
  data-count="1" 
/>

2.

function setColor(e) {
   var target = e.target,
       status = e.target.classList.contains('active');

   e.target.classList.add(status ? 'inactive' : 'active');
   e.target.classList.remove(status ? 'active' : 'inactive'); 
}

.active {
  background-color: #7FFF00;  
}

.inactive {
  background-color: #FFFFFF;
}

<input 
  type="button" 
  id="button" 
  value="button" 
  style="color:white" 
  onclick="setColor(event)" 
/>

([conditional (ternary) operator])

Example-1

Example-2

Setting a JPA timestamp column to be generated by the database?

I'm posting this for people searching for an answer when using MySQL and Java Spring Boot JPA, like @immanuelRocha says, only have too @CreationTimeStamp to the @Column in Spring, and in MySQL set the default value to "CURRENT_TIMESTAMP".

In Spring add just the line :

_x000D_
_x000D_
@Column(name = "insert_date")_x000D_
@CreationTimestamp_x000D_
private Timestamp insert_date;
_x000D_
_x000D_
_x000D_

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

This is very strange behavior for me. I'm surprised that no one thought of savepoints. In my code failing query was expected behavior:

from django.db import transaction
@transaction.commit_on_success
def update():
    skipped = 0
    for old_model in OldModel.objects.all():
        try:
            Model.objects.create(
                group_id=old_model.group_uuid,
                file_id=old_model.file_uuid,
            )
        except IntegrityError:
            skipped += 1
    return skipped

I have changed code this way to use savepoints:

from django.db import transaction
@transaction.commit_on_success
def update():
    skipped = 0
    sid = transaction.savepoint()
    for old_model in OldModel.objects.all():
        try:
            Model.objects.create(
                group_id=old_model.group_uuid,
                file_id=old_model.file_uuid,
            )
        except IntegrityError:
            skipped += 1
            transaction.savepoint_rollback(sid)
        else:
            transaction.savepoint_commit(sid)
    return skipped

AutoComplete TextBox Control

    You can add a parameter in the query like @emailadd to be added in the aspx.cs file where the Stored Procedure is called with cmd.Parameter.AddWithValue.
    The trick is that the @emailadd parameter doesn't exist in the table design of the select query, but being added and inserted in the table.

    USE [DRDOULATINSTITUTE]
    GO
    /****** Object:  StoredProcedure [dbo].[ReikiInsertRow]    Script Date: 5/18/2016 11:12:33 AM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER procedure [dbo].[ReikiInsertRow]
    @Reiki varchar(100),
    @emailadd varchar(50)
    as
    insert into dbo.ReikiPowerDisplay
    select Reiki,ReikiDescription, @emailadd from ReikiPower
    where Reiki=@Reiki;

Posted By: Aneel Goplani. CIS. 2002. USA

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

How do I use popover from Twitter Bootstrap to display an image?

Sort of similar to what mattbtay said, but a few changes. needed html:true.
Put this script on bottom of the page towards close body tag.

<script type="text/javascript">
 $(document).ready(function() {
  $("[rel=drevil]").popover({
      placement : 'bottom', //placement of the popover. also can use top, bottom, left or right
      title : '<div style="text-align:center; color:red; text-decoration:underline; font-size:14px;"> Muah ha ha</div>', //this is the top title bar of the popover. add some basic css
      html: 'true', //needed to show html of course
      content : '<div id="popOverBox"><img src="http://www.hd-report.com/wp-content/uploads/2008/08/mr-evil.jpg" width="251" height="201" /></div>' //this is the content of the html box. add the image here or anything you want really.
});
});
</script>


Then HTML is:

<a href="#" rel="drevil">mischief</a>

Process list on Linux via Python

You can use a third party library, such as PSI:

PSI is a Python package providing real-time access to processes and other miscellaneous system information such as architecture, boottime and filesystems. It has a pythonic API which is consistent accross all supported platforms but also exposes platform-specific details where desirable.

How can I select rows by range?

For mysql you have limit, you can fire query as :

SELECT * FROM table limit 100` -- get 1st 100 records
SELECT * FROM table limit 100, 200` -- get 200 records beginning with row 101

For Oracle you can use rownum

See mysql select syntax and usage for limit here.

For SQLite, you have limit, offset. I haven't used SQLite but I checked it on SQLite Documentation. Check example for SQLite here.

How do I invert BooleanToVisibilityConverter?

Here's one I wrote and use a lot. It uses a boolean converter parameter that indicates whether or not to invert the value and then uses XOR to perform the negation:

[ValueConversion(typeof(bool), typeof(System.Windows.Visibility))]
public class BooleanVisibilityConverter : IValueConverter
{
    System.Windows.Visibility _visibilityWhenFalse = System.Windows.Visibility.Collapsed;

    /// <summary>
    /// Gets or sets the <see cref="System.Windows.Visibility"/> value to use when the value is false. Defaults to collapsed.
    /// </summary>
    public System.Windows.Visibility VisibilityWhenFalse
    {
        get { return _visibilityWhenFalse; }
        set { _visibilityWhenFalse = value; }
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool negateValue;
        Boolean.TryParse(parameter as string, out negateValue);

        bool val = negateValue ^ System.Convert.ToBoolean(value); //Negate the value when negateValue is true using XOR
        return val ? System.Windows.Visibility.Visible : _visibilityWhenFalse;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool negateValue;
        Boolean.TryParse(parameter as string, out negateValue);

        if ((System.Windows.Visibility)value == System.Windows.Visibility.Visible)
            return true ^ negateValue;
        else
            return false ^ negateValue;
    }
}

Here's an XOR truth table for reference:

        XOR
        x  y  XOR
        ---------
        0  0  0
        0  1  1
        1  0  1
        1  1  0

How do I tell if a variable has a numeric value in Perl?

if ( defined $x && $x !~ m/\D/ ) {} or $x = 0 if ! $x; if ( $x !~ m/\D/) {}

This is a slight variation on Veekay's answer but let me explain my reasoning for the change.

Performing a regex on an undefined value will cause error spew and will cause the code to exit in many if not most environments. Testing if the value is defined or setting a default case like i did in the alternative example before running the expression will, at a minimum, save your error log.

Oracle: SQL select date with timestamp

Answer provided by Nicholas Krasnov

SELECT *
FROM BOOKING_SESSION
WHERE TO_CHAR(T_SESSION_DATETIME, 'DD-MM-YYYY') ='20-03-2012';

How to send multiple data fields via Ajax?

You can send data through JSON or via normal POST, here is an example for JSON.

 var value1 = 1;
 var value2 = 2;
 var value3 = 3;   
 $.ajax({
      type: "POST",
      contentType: "application/json; charset=utf-8",
      url: "yoururlhere",
      data: { data1: value1, data2: value2, data3: value3 },
      success: function (result) {
           // do something here
      }
 });

If you want to use it via normal post try this

 $.ajax({
      type: "POST",
      url: $('form').attr("action"),   
      data: $('#form0').serialize(),
      success: function (result) {
         // do something here
      }
 });

How to hide "Showing 1 of N Entries" with the dataTables.js library

Now, this seems to work:

$('#example').DataTable({
  "info": false
});

it hides that div, altogether

JQuery: Change value of hidden input field

It's simple as:

$('#action').val("1");

#action is hidden input field id.

How do I check to see if a value is an integer in MySQL?

Match it against a regular expression.

c.f. http://forums.mysql.com/read.php?60,1907,38488#msg-38488 as quoted below:

Re: IsNumeric() clause in MySQL??
Posted by: kevinclark ()
Date: August 08, 2005 01:01PM


I agree. Here is a function I created for MySQL 5:

CREATE FUNCTION IsNumeric (sIn varchar(1024)) RETURNS tinyint
RETURN sIn REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';


This allows for an optional plus/minus sign at the beginning, one optional decimal point, and the rest numeric digits.

Python Key Error=0 - Can't find Dict error in code

Try this:

class Flonetwork(Object):
    def __init__(self,adj = {},flow={}):
        self.adj = adj
        self.flow = flow

Cast to generic type in C#

I had a similar problem. I have a class;

Action<T>

which has a property of type T.

How do I get the property when I don't know T? I can't cast to Action<> unless I know T.

SOLUTION:

Implement a non-generic interface;

public interface IGetGenericTypeInstance
{
    object GenericTypeInstance();
}

Now I can cast the object to IGetGenericTypeInstance and GenericTypeInstance will return the property as type object.

How can I check if string contains characters & whitespace, not just whitespace?

I've used the following method to detect if a string contains only whitespace. It also matches empty strings.

if (/^\s*$/.test(myStr)) {
  // the string contains only whitespace
}

Output array to CSV in Ruby

I've got this down to just one line.

rows = [['a1', 'a2', 'a3'],['b1', 'b2', 'b3', 'b4'], ['c1', 'c2', 'c3'], ... ]
csv_str = rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join("")
#=> "a1,a2,a3\nb1,b2,b3\nc1,c2,c3\n" 

Do all of the above and save to a csv, in one line.

File.open("ss.csv", "w") {|f| f.write(rows.inject([]) { |csv, row|  csv << CSV.generate_line(row) }.join(""))}

NOTE:

To convert an active record database to csv would be something like this I think

CSV.open(fn, 'w') do |csv|
  csv << Model.column_names
  Model.where(query).each do |m|
    csv << m.attributes.values
  end
end

Hmm @tamouse, that gist is somewhat confusing to me without reading the csv source, but generically, assuming each hash in your array has the same number of k/v pairs & that the keys are always the same, in the same order (i.e. if your data is structured), this should do the deed:

rowid = 0
CSV.open(fn, 'w') do |csv|
  hsh_ary.each do |hsh|
    rowid += 1
    if rowid == 1
      csv << hsh.keys# adding header row (column labels)
    else
      csv << hsh.values
    end# of if/else inside hsh
  end# of hsh's (rows)
end# of csv open

If your data isn't structured this obviously won't work

Java string replace and the NUL (NULL, ASCII 0) character?

Does replacing a character in a String with a null character even work in Java? I know that '\0' will terminate a c-string.

That depends on how you define what is working. Does it replace all occurrences of the target character with '\0'? Absolutely!

String s = "food".replace('o', '\0');
System.out.println(s.indexOf('\0')); // "1"
System.out.println(s.indexOf('d')); // "3"
System.out.println(s.length()); // "4"
System.out.println(s.hashCode() == 'f'*31*31*31 + 'd'); // "true"

Everything seems to work fine to me! indexOf can find it, it counts as part of the length, and its value for hash code calculation is 0; everything is as specified by the JLS/API.

It DOESN'T work if you expect replacing a character with the null character would somehow remove that character from the string. Of course it doesn't work like that. A null character is still a character!

String s = Character.toString('\0');
System.out.println(s.length()); // "1"
assert s.charAt(0) == 0;

It also DOESN'T work if you expect the null character to terminate a string. It's evident from the snippets above, but it's also clearly specified in JLS (10.9. An Array of Characters is Not a String):

In the Java programming language, unlike C, an array of char is not a String, and neither a String nor an array of char is terminated by '\u0000' (the NUL character).


Would this be the culprit to the funky characters?

Now we're talking about an entirely different thing, i.e. how the string is rendered on screen. Truth is, even "Hello world!" will look funky if you use dingbats font. A unicode string may look funky in one locale but not the other. Even a properly rendered unicode string containing, say, Chinese characters, may still look funky to someone from, say, Greenland.

That said, the null character probably will look funky regardless; usually it's not a character that you want to display. That said, since null character is not the string terminator, Java is more than capable of handling it one way or another.


Now to address what we assume is the intended effect, i.e. remove all period from a string, the simplest solution is to use the replace(CharSequence, CharSequence) overload.

System.out.println("A.E.I.O.U".replace(".", "")); // AEIOU

The replaceAll solution is mentioned here too, but that works with regular expression, which is why you need to escape the dot meta character, and is likely to be slower.

PHP Warning: Unknown: failed to open stream

In Fedora 25, it turned out to be an SE Linux issue, and the notification gave this solution which worked for me.

setsebool -P httpd_read_user_content 1

Copy/Paste from Excel to a web page

For any future googlers ending up here like me, I used @tatu Ulmanen's concept and just turned it into an array of objects. This simple function takes a string of pasted excel (or Google sheet) data (preferably from a textarea) and turns it into an array of objects. It uses the first row for column/property names.

function excelToObjects(stringData){
    var objects = [];
    //split into rows
    var rows = stringData.split('\n');

    //Make columns
    columns = rows[0].split('\t');

    //Note how we start at rowNr = 1, because 0 is the column row
    for (var rowNr = 1; rowNr < rows.length; rowNr++) {
        var o = {};
        var data = rows[rowNr].split('\t');

        //Loop through all the data
        for (var cellNr = 0; cellNr < data.length; cellNr++) {
            o[columns[cellNr]] = data[cellNr];
        }

        objects.push(o);
    }

    return objects;
}

Hopefully it helps someone in the future.

Open two instances of a file in a single Visual Studio session

I don't have a copy of Visual Studio 2005, but this process works on Visual Studio 2008:

  1. Open xyz.cpp along with some other file.
  2. Right click on tab header and select new vertical tab group.
  3. Left click on that other file in the first tab group.
  4. Open xyz.cpp through solution explorer again.

You should now have two instances of file in separate vertical tab groups.

The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions

ORDER BY column OFFSET 0 ROWS

Surprisingly makes it work, what a strange feature.

A bigger example with a CTE as a way to temporarily "store" a long query to re-order it later:

;WITH cte AS (
    SELECT .....long select statement here....
)

SELECT * FROM 
(
    SELECT * FROM 
    ( -- necessary to nest selects for union to work with where & order clauses
        SELECT * FROM cte WHERE cte.MainCol= 1 ORDER BY cte.ColX asc OFFSET 0 ROWS 
    ) first
    UNION ALL
    SELECT * FROM 
    (  
        SELECT * FROM cte WHERE cte.MainCol = 0 ORDER BY cte.ColY desc OFFSET 0 ROWS 
    ) last
) as unionized
ORDER BY unionized.MainCol desc -- all rows ordered by this one
OFFSET @pPageSize * @pPageOffset ROWS -- params from stored procedure for pagination, not relevant to example
FETCH FIRST @pPageSize ROWS ONLY -- params from stored procedure for pagination, not relevant to example

So we get all results ordered by MainCol

But the results with MainCol = 1 get ordered by ColX

And the results with MainCol = 0 get ordered by ColY

nullable object must have a value

You should change the line this.MyDateTime = myNewDT.MyDateTime.Value; to just this.MyDateTime = myNewDT.MyDateTime;

The exception you were receiving was thrown in the .Value property of the Nullable DateTime, as it is required to return a DateTime (since that's what the contract for .Value states), but it can't do so because there's no DateTime to return, so it throws an exception.

In general, it is a bad idea to blindly call .Value on a nullable type, unless you have some prior knowledge that that variable MUST contain a value (i.e. through a .HasValue check).

EDIT

Here's the code for DateTimeExtended that does not throw an exception:

class DateTimeExtended
{
    public DateTime? MyDateTime;
    public int? otherdata;

    public DateTimeExtended() { }

    public DateTimeExtended(DateTimeExtended other)
    {
        this.MyDateTime = other.MyDateTime;
        this.otherdata = other.otherdata;
    }
}

I tested it like this:

DateTimeExtended dt1 = new DateTimeExtended();
DateTimeExtended dt2 = new DateTimeExtended(dt1);

Adding the .Value on other.MyDateTime causes an exception. Removing it gets rid of the exception. I think you're looking in the wrong place.

Selecting multiple items in ListView

I would advice to check the logic of ListActivity according to what is needed could be the best way not to lose much time

link

developer.android

How do I find out which keystore was used to sign an app?

Much easier way to view the signing certificate:

jarsigner.exe -verbose -verify -certs myapk.apk

This will only show the DN, so if you have two certs with the same DN, you might have to compare by fingerprint.

How to convert String to long in Java?

For those who switched to Kotlin just use
string.toLong()
That will call Long.parseLong(string) under the hood

Apache Cordova - uninstall globally

Super late here and I still couldn't uninstall using sudo as the other answers suggest. What did it for me was checking where cordova was installed by running

which cordova

it will output something like this

/usr/local/bin/

then removing by

rm -rf /usr/local/bin/cordova

fatal error: Python.h: No such file or directory

For Python 3.7 and Ubuntu in particular, I needed

sudo apt install libpython3.7-dev

. I think at some point names were changed from pythonm.n-dev to this.

for Python 3.6, 3.8, and 3.9 similarly:

sudo apt install libpython3.6-dev

 

sudo apt install libpython3.8-dev

 

sudo apt install libpython3.9-dev

How to perform a fade animation on Activity transition?

You could create your own .xml animation files to fade in a new Activity and fade out the current Activity:

fade_in.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
           android:interpolator="@android:anim/accelerate_interpolator"
           android:fromAlpha="0.0" android:toAlpha="1.0"
           android:duration="500" />

fade_out.xml

<?xml version="1.0" encoding="utf-8"?>
<alpha xmlns:android="http://schemas.android.com/apk/res/android"
           android:interpolator="@android:anim/accelerate_interpolator"
           android:fromAlpha="1.0" android:toAlpha="0.0"
           android:fillAfter="true"
           android:duration="500" />

Use it in code like that: (Inside your Activity)

Intent i = new Intent(this, NewlyStartedActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);

The above code will fade out the currently active Activity and fade in the newly started Activity resulting in a smooth transition.

UPDATE: @Dan J pointed out that using the built in Android animations improves performance, which I indeed found to be the case after doing some testing. If you prefer working with the built in animations, use:

overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

Notice me referencing android.R instead of R to access the resource id.

UPDATE: It is now common practice to perform transitions using the Transition class introduced in API level 19.

SQL Server® 2016, 2017 and 2019 Express full download

Scott Hanselman put together a great summary page with all of the various SQL downloads here https://www.hanselman.com/blog/DownloadSQLServerExpress.aspx.

For offline installers, see this answer https://stackoverflow.com/a/42952186/407188

How do I add PHP code/file to HTML(.html) files?

For combining HTML and PHP you can use .phtml files.

Is Secure.ANDROID_ID unique for each device?

//Fields
String myID;
int myversion = 0;


myversion = Integer.valueOf(android.os.Build.VERSION.SDK);
if (myversion < 23) {
        TelephonyManager mngr = (TelephonyManager) 
getSystemService(Context.TELEPHONY_SERVICE);
        myID= mngr.getDeviceId();
    }
    else
    {
        myID = 
Settings.Secure.getString(getApplicationContext().getContentResolver(), 
Settings.Secure.ANDROID_ID);
    }

Yes, Secure.ANDROID_ID is unique for each device.

How to update the value stored in Dictionary in C#?

Just point to the dictionary at given key and assign a new value:

myDictionary[myKey] = myNewValue;

How to add data into ManyToMany field?

In case someone else ends up here struggling to customize admin form Many2Many saving behaviour, you can't call self.instance.my_m2m.add(obj) in your ModelForm.save override, as ModelForm.save later populates your m2m from self.cleaned_data['my_m2m'] which overwrites your changes. Instead call:

my_m2ms = list(self.cleaned_data['my_m2ms'])
my_m2ms.extend(my_custom_new_m2ms)
self.cleaned_data['my_m2ms'] = my_m2ms

(It is fine to convert the incoming QuerySet to a list - the ManyToManyField does that anyway.)

Install specific version using laravel installer

Using composer you can specify the version you want easily by running

composer create-project laravel/laravel="5.1.*" myProject

Using the 5.1.* will ensure that you get all the latest patches in the 5.1 branch.

ORA-06502: PL/SQL: numeric or value error: character string buffer too small

CHAR is a fixed-length data type that uses as much space as possible. So a:= a||'one '; will require more space than is available. Your problem can be reduced to the following example:

declare
  v_foo char(50);
begin
  v_foo := 'A';
  dbms_output.put_line('length of v_foo(A) = ' || length(v_foo));
  -- next line will raise:
  -- ORA-06502: PL/SQL: numeric or value error: character string buffer too small
  v_foo := v_foo || 'B';
  dbms_output.put_line('length of v_foo(AB) = ' || length(v_foo));  
end;
/

Never use char. For rationale check the following question (read also the links):

How to set aliases in the Git Bash for Windows?

  • Go to: C:\Users\ [youruserdirectory] \bash_profile

  • In your bash_profile file type - alias desk='cd " [DIRECTORY LOCATION] "'

  • Refresh your User directory where the bash_profile file exists then reopen your CMD or Git Bash window

Type in desk to see if you get to the Desktop location or the location you want in the "DIRECTORY LOCATION" area above

Note: [ desk ] can be what ever name that you choose and should get you to the location you want to get to when typed in the CMD window.

SQL Server replace, remove all after certain character

For the times when some fields have a ";" and some do not you can also add a semi-colon to the field and use the same method described.

SET MyText = LEFT(MyText+';', CHARINDEX(';',MyText+';')-1)

How to mock location on device?

I wrote an App that runs a WebServer (REST-Like) on your Android Phone, so you can set the GPS position remotely. The website provides an Map on which you can click to set a new position, or use the "wasd" keys to move in any direction. The app was a quick solution so there is nearly no UI nor Documentation, but the implementation is straight forward and you can look everything up in the (only four) classes.

Project repository: https://github.com/juliusmh/RemoteGeoFix

Skip over a value in the range function in python

It is time inefficient to compare each number, needlessly leading to a linear complexity. Having said that, this approach avoids any inequality checks:

import itertools

m, n = 5, 10
for i in itertools.chain(range(m), range(m + 1, n)):
    print(i)  # skips m = 5

As an aside, you woudn't want to use (*range(m), *range(m + 1, n)) even though it works because it will expand the iterables into a tuple and this is memory inefficient.


Credit: comment by njzk2, answer by Locke

Class JavaLaunchHelper is implemented in two places

This happened to me when I installed Intellij IDEA 2017, go to menu Preferences -> Build, Execution, Deployment -> Debugger and disable the option: "Force Classic VM for JDK 1.3.x and earlier". This works to me.

Chrome blocks different origin requests

Direct Javascript calls between frames and/or windows are only allowed if they conform to the same-origin policy. If your window and iframe share a common parent domain you can set document.domain to "domain lower") one or both such that they can communicate. Otherwise you'll need to look into something like the postMessage() API.

Is it possible to get multiple values from a subquery?

Can't you use JOIN like this one?

SELECT
a.x , b.y, b.z 
FROM a 
LEFT OUTER JOIN b ON b.v = a.v

(I don't know Oracle Syntax. So I wrote SQL syntax)

Subprocess changing directory

To run your_command as a subprocess in a different directory, pass cwd parameter, as suggested in @wim's answer:

import subprocess

subprocess.check_call(['your_command', 'arg 1', 'arg 2'], cwd=working_dir)

A child process can't change its parent's working directory (normally). Running cd .. in a child shell process using subprocess won't change your parent Python script's working directory i.e., the code example in @glglgl's answer is wrong. cd is a shell builtin (not a separate executable), it can change the directory only in the same process.

DB2 Query to retrieve all table names for a given schema

This should work:

select * from syscat.tables

What exactly does Double mean in java?

A double is an IEEE754 double-precision floating point number, similar to a float but with a larger range and precision.

IEEE754 single precision numbers have 32 bits (1 sign, 8 exponent and 23 mantissa bits) while double precision numbers have 64 bits (1 sign, 11 exponent and 52 mantissa bits).

A Double in Java is the class version of the double basic type - you can use doubles but, if you want to do something with them that requires them to be an object (such as put them in a collection), you'll need to box them up in a Double object.

Set default value of javascript object attributes

I'm surprised nobody has mentioned ternary operator yet.

var emptyObj = {a:'123', b:'234', c:0};
var defaultValue = 'defaultValue';
var attr = 'someNonExistAttribute';
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue;//=> 'defaultValue'


attr = 'c'; // => 'c'
emptyObj.hasOwnProperty(attr) ? emptyObj[attr] : defaultValue; // => 0

In this way, even if the value of 'c' is 0, it will still get the correct value.

How to declare a global variable in a .js file

As mentioned above, there are issues with using the top-most scope in your script file. Here is another issue: The script file might be run from a context that is not the global context in some run-time environment.

It has been proposed to assign the global to window directly. But that is also run-time dependent and does not work in Node etc. It goes to show that portable global variable management needs some careful consideration and extra effort. Maybe they will fix it in future ECMS versions!

For now, I would recommend something like this to support proper global management for all run-time environments:

/**
 * Exports the given object into the global context.
 */
var exportGlobal = function(name, object) {
    if (typeof(global) !== "undefined")  {
        // Node.js
        global[name] = object;
    }
    else if (typeof(window) !== "undefined") {
        // JS with GUI (usually browser)
        window[name] = object;
    }
    else {
        throw new Error("Unkown run-time environment. Currently only browsers and Node.js are supported.");
    }
};


// export exportGlobal itself
exportGlobal("exportGlobal", exportGlobal);

// create a new global namespace
exportGlobal("someothernamespace", {});

It's a bit more typing, but it makes your global variable management future-proof.

Disclaimer: Part of this idea came to me when looking at previous versions of stacktrace.js.

I reckon, one can also use Webpack or other tools to get more reliable and less hackish detection of the run-time environment.

How should I load files into my Java application?

The short answer

Use one of these two methods:

For example:

InputStream inputStream = YourClass.class.getResourceAsStream("image.jpg");

--

The long answer

Typically, one would not want to load files using absolute paths. For example, don’t do this if you can help it:

File file = new File("C:\\Users\\Joe\\image.jpg");

This technique is not recommended for at least two reasons. First, it creates a dependency on a particular operating system, which prevents the application from easily moving to another operating system. One of Java’s main benefits is the ability to run the same bytecode on many different platforms. Using an absolute path like this makes the code much less portable.

Second, depending on the relative location of the file, this technique might create an external dependency and limit the application’s mobility. If the file exists outside the application’s current directory, this creates an external dependency and one would have to be aware of the dependency in order to move the application to another machine (error prone).

Instead, use the getResource() methods in the Class class. This makes the application much more portable. It can be moved to different platforms, machines, or directories and still function correctly.

Relationship between hashCode and equals method in Java

The contract is that if obj1.equals(obj2) then obj1.hashCode() == obj2.hashCode() , it is mainly for performance reasons, as maps are mainly using hashCode method to compare entries keys.

How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause()

  1. All new browser support video to be auto-played with being muted only so please put

<video autoplay muted="muted" loop id="myVideo"> <source src="https://w.r.glob.net/Coastline-3581.mp4" type="video/mp4"> </video>

Something like this

  1. URL of video should match the SSL status if your site is running with https then video URL should also in https and same for HTTP

pip issue installing almost any library

As posted above by blackjar, the below lines worked for me

pip --trusted-host pypi.python.org --trusted-host files.pythonhosted.org --trusted-host pypi.org install xxx

You need to give all three --trusted-host options. I was trying with only the first one after looking at the answers but it didn't work for me like that.

Android get image from gallery into ImageView

The original answer is that your path has to join prefix like Uri.parse("file://" + file.getPath);

How get sound input from microphone in python, and process it on the fly?

If you are using LINUX, you can use pyALSAAUDIO. For windows, we have PyAudio and there is also a library called SoundAnalyse.

I found an example for Linux here:

#!/usr/bin/python
## This is an example of a simple sound capture script.
##
## The script opens an ALSA pcm for sound capture. Set
## various attributes of the capture, and reads in a loop,
## Then prints the volume.
##
## To test it out, run it and shout at your microphone:

import alsaaudio, time, audioop

# Open the device in nonblocking capture mode. The last argument could
# just as well have been zero for blocking mode. Then we could have
# left out the sleep call in the bottom of the loop
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)

# Set attributes: Mono, 8000 Hz, 16 bit little endian samples
inp.setchannels(1)
inp.setrate(8000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)

# The period size controls the internal number of frames per period.
# The significance of this parameter is documented in the ALSA api.
# For our purposes, it is suficcient to know that reads from the device
# will return this many frames. Each frame being 2 bytes long.
# This means that the reads below will return either 320 bytes of data
# or 0 bytes of data. The latter is possible because we are in nonblocking
# mode.
inp.setperiodsize(160)

while True:
    # Read data from device
    l,data = inp.read()
    if l:
        # Return the maximum of the absolute value of all samples in a fragment.
        print audioop.max(data, 2)
    time.sleep(.001)

Sequence contains no elements?

Please use

.FirstOrDefault()

because if in the first row of the result there is no info this instruction goes to the default info.

Convert JSON string to dict using Python

use simplejson or cjson for speedups

import simplejson as json

json.loads(obj)

or 

cjson.decode(obj)

Adding hours to JavaScript Date object?

The below code is to add 4 hours to date(example today's date)

var today = new Date();
today.setHours(today.getHours() + 4);

It will not cause error if you try to add 4 to 23 (see the docs):

If a parameter you specify is outside of the expected range, setHours() attempts to update the date information in the Date object accordingly

How to create an XML document using XmlDocument?

Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here

and edited my code: (xmlDoc.DocumentElement.AppendChild(body))

//a dictionary:
Dictionary<string, string> Level2Data 
{
    {"level2", "text"},
    {"level2", "other text"},
    {"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR



foreach (KeyValuePair<string, string> entry in Level2Data)
{
    //write to xml: - it works version 1.
    XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
    keyNode.InnerText = entry.Value;
    body.AppendChild(keyNode); //close TAB

    //Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
    //XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
    //XmlText value = xmlDoc.CreateTextNode(entry.Value);
    //key.AppendChild(value);
    //body.AppendChild(key);
}

Both versions (1 and 2 inside foreach loop) give the output:

<?xml version="1.0" encoding="UTF-8"?>
<body>
    <level1>
        <level2>text</level2>
        <level2>ther text</level2>
         <same_level2>more text</same_level2>
    </level1>
</body>

(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.

How to center the content inside a linear layout?

android:layout_gravity is used for the layout itself

Use android:gravity="center" for children of your LinearLayout

So your code should be:

<LinearLayout
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_weight="1" >

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

I use Ctrl-b + q which makes it flash number for each pane, redrawing them on the way.

What is the unix command to see how much disk space there is and how much is remaining?

If you want to see how much space each folder ocuppes:

du -sh *

  • s – summarize
  • h – human readable
  • * – list of folders

Is there a way to get a list of column names in sqlite?

You can get a list of column names by running:

SELECT name FROM PRAGMA_TABLE_INFO('your_table');
name      
tbl_name  
rootpage  
sql

You can check if a certain column exists by running:

SELECT 1 FROM PRAGMA_TABLE_INFO('your_table') WHERE name='sql';
1

Reference:

https://www.sqlite.org/pragma.html#pragfunc

pythonw.exe or python.exe?

See here: http://docs.python.org/using/windows.html

pythonw.exe "This suppresses the terminal window on startup."

Trying to get PyCharm to work, keep getting "No Python interpreter selected"

I got the same issue when i newly installed pycharm in my windows 10 machine.

  • download python setup

  • install this solved my problem.

for more help visit goodluck

During the install of python make sure you have "Install for all users" selected. Uninstall python and do a custom install and check "Install for all users"

What is {this.props.children} and when you should use it?

props.children represents the content between the opening and the closing tags when invoking/rendering a component:

const Foo = props => (
  <div>
    <p>I'm {Foo.name}</p>
    <p>abc is: {props.abc}</p>

    <p>I have {props.children.length} children.</p>
    <p>They are: {props.children}.</p>
    <p>{Array.isArray(props.children) ? 'My kids are an array.' : ''}</p>
  </div>
);

const Baz = () => <span>{Baz.name} and</span>;
const Bar = () => <span> {Bar.name}</span>;

invoke/call/render Foo:

<Foo abc={123}>
  <Baz />
  <Bar />
</Foo>

props and props.children

Generating a random password in php

base_convert(uniqid('pass', true), 10, 36);

eg. e0m6ngefmj4

EDIT

As I've mentioned in comments, the length means that brute force attacks would work better against it then timing attacks so it's not really relevant to worry about "how secure the random generator was." Security, specifically for this use case, needs to complement usability so the above solution is actually good enough for the required problem.

However, just in case you stumbled upon this answer while searching for a secure random string generator (as I assume some people have based on the responses), for something such as generating tokens, here is how a generator of such codes would look like:

function base64urlEncode($data) {
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function secureId($length = 32) {

    if (function_exists('openssl_random_pseudo_bytes')) {
        $bytes = openssl_random_pseudo_bytes($length);
        return rtrim(strtr(base64_encode($bytes), '+/', '0a'), '=');
    }
    else { // fallback to system bytes

        error_log("Missing support for openssl_random_pseudo_bytes");

        $pr_bits = '';

        $fp = @fopen('/dev/urandom', 'rb');
        if ($fp !== false) {
            $pr_bits .= @fread($fp, $length);
            @fclose($fp);
        }

        if (strlen($pr_bits) < $length) {
            error_log('unable to read /dev/urandom');
            throw new \Exception('unable to read /dev/urandom');
        }

        return base64urlEncode($pr_bits);
    }
}

Delete multiple objects in django

You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model

Post.objects.all().delete()

and to delete any Post with a future publication date

Post.objects.filter(pub_date__gt=datetime.now()).delete()

You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.

EDIT:

Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForms and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.

Zipping a file in bash fails

Run dos2unix or similar utility on it to remove the carriage returns (^M).

This message indicates that your file has dos-style lineendings:

-bash: /backup/backup.sh: /bin/bash^M: bad interpreter: No such file or directory 

Utilities like dos2unix will fix it:

 dos2unix <backup.bash >improved-backup.sh 

Or, if no such utility is installed, you can accomplish the same thing with translate:

tr -d "\015\032" <backup.bash >improved-backup.sh 

As for how those characters got there in the first place, @MadPhysicist had some good comments.

What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?

That's called a closure. It basically seals the code inside the function so that other libraries don't interfere with it. It's similar to creating a namespace in compiled languages.

Example. Suppose I write:

(function() {

    var x = 2;

    // do stuff with x

})();

Now other libraries cannot access the variable x I created to use in my library.

Directory-tree listing in Python

If figured I'd throw this in. Simple and dirty way to do wildcard searches.

import re
import os

[a for a in os.listdir(".") if re.search("^.*\.py$",a)]

How to save and load cookies using Python + Selenium WebDriver

When you need cookies from session to session, there is another way to do it. Use the Chrome options user-data-dir in order to use folders as profiles. I run:

# You need to: from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com")

Here you can do the logins that check for human interaction. I do this and then the cookies I need now every time I start the Webdriver with that folder everything is in there. You can also manually install the Extensions and have them in every session.

The second time I run, all the cookies are there:

# You need to: from selenium.webdriver.chrome.options import Options    
chrome_options = Options()
chrome_options.add_argument("user-data-dir=selenium") 
driver = webdriver.Chrome(chrome_options=chrome_options)
driver.get("www.google.com") # Now you can see the cookies, the settings, extensions, etc., and the logins done in the previous session are present here. 

The advantage is you can use multiple folders with different settings and cookies, Extensions without the need to load, unload cookies, install and uninstall Extensions, change settings, change logins via code, and thus no way to have the logic of the program break, etc.

Also, this is faster than having to do it all by code.

How to dynamically add and remove form fields in Angular 2

addAccordian(type, data) { console.log(type, data);

let form = this.form;

if (!form.controls[type]) {
  let ownerAccordian = new FormArray([]);
  const group = new FormGroup({});
  ownerAccordian.push(
    this.applicationService.createControlWithGroup(data, group)
  );
  form.controls[type] = ownerAccordian;
} else {
  const group = new FormGroup({});
  (<FormArray>form.get(type)).push(
    this.applicationService.createControlWithGroup(data, group)
  );
}
console.log(this.form);

}

Angular 2 - Redirect to an external URL and open in a new tab

To solve this issue more globally, here is another way using a directive:

import { Directive, HostListener, ElementRef } from "@angular/core";

@Directive({
  selector: "[hrefExternalUrl]"
})
export class HrefExternalUrlDirective {
  constructor(elementRef: ElementRef) {}

  @HostListener("click", ["$event"])
  onClick(event: MouseEvent) {
    event.preventDefault();

    let url: string = (<any>event.currentTarget).getAttribute("href");

    if (url && url.indexOf("http") === -1) {
      url = `//${url}`;
    }

    window.open(url, "_blank");
  }
}

then it's as simple as using it like this:

<a [href]="url" hrefExternalUrl> Link </a>

and don't forget to declare the directive in your module.

Permissions error when connecting to EC2 via SSH on Mac OSx

I had met this problem too.And I found that happend beacuse I forgot to add the user-name before the host name: like this:

ssh -i test.pem ec2-32-122-42-91.us-west-2.compute.amazonaws.com

and I add the user name:

ssh -i test.pem [email protected]

it works!

Suppress/ print without b' prefix for bytes in Python 3

If the data is in an UTF-8 compatible format, you can convert the bytes to a string.

>>> import curses
>>> print(str(curses.version, "utf-8"))
2.2

Optionally convert to hex first, if the data is not already UTF-8 compatible. E.g. when the data are actual raw bytes.

from binascii import hexlify
from codecs import encode  # alternative
>>> print(hexlify(b"\x13\x37"))
b'1337'
>>> print(str(hexlify(b"\x13\x37"), "utf-8"))
1337
>>>> print(str(encode(b"\x13\x37", "hex"), "utf-8"))
1337

Python: BeautifulSoup - get an attribute value based on the name attribute

One can also try this solution :

To find the value, which is written in span of table

htmlContent


<table>
    <tr>
        <th>
            ID
        </th>
        <th>
            Name
        </th>
    </tr>


    <tr>
        <td>
            <span name="spanId" class="spanclass">ID123</span>
        </td>

        <td>
            <span>Bonny</span>
        </td>
    </tr>
</table>

Python code


soup = BeautifulSoup(htmlContent, "lxml")
soup.prettify()

tables = soup.find_all("table")

for table in tables:
   storeValueRows = table.find_all("tr")
   thValue = storeValueRows[0].find_all("th")[0].string

   if (thValue == "ID"): # with this condition I am verifying that this html is correct, that I wanted.
      value = storeValueRows[1].find_all("span")[0].string
      value = value.strip()

      # storeValueRows[1] will represent <tr> tag of table located at first index and find_all("span")[0] will give me <span> tag and '.string' will give me value

      # value.strip() - will remove space from start and end of the string.

     # find using attribute :

     value = storeValueRows[1].find("span", {"name":"spanId"})['class']
     print value
     # this will print spanclass

javascript if number greater than number

You can "cast" to number using the Number constructor..

var number = new Number("8"); // 8 number

You can also call parseInt builtin function:

var number = parseInt("153"); // 153 number

What is the meaning of "operator bool() const"

I'd like to give more codes to make it clear.

struct A
{
    operator bool() const { return true; }
};

struct B
{
    explicit operator bool() const { return true; }
};

int main()
{
    A a1;
    if (a1) cout << "true" << endl; // OK: A::operator bool()
    bool na1 = a1; // OK: copy-initialization selects A::operator bool()
    bool na2 = static_cast<bool>(a1); // OK: static_cast performs direct-initialization

    B b1;     
    if (b1) cout << "true" << endl; // OK: B::operator bool()
    // bool nb1 = b1; // error: copy-initialization does not consider B::operator bool()
    bool nb2 = static_cast<bool>(b1); // OK: static_cast performs direct-initialization
}

python: after installing anaconda, how to import pandas

The cool thing about anaconda is, that you can manage virtual environments for several projects. Those also have the benefit of keeping several python installations apart. This could be a problem when several installations of a module or package are interfering with each other.

Try the following:

  1. Create a new anaconda environment with user@machine:~$ conda create -n pandas_env python=2.7
  2. Activate the environment with user@machine:~$ source activate pandas_env on Linux/OSX or $ activate pandas_env on Windows. On Linux the active environment is shown in parenthesis in front of the user name in the shell. (I am not sure how windows handles this, but you can see it by typing $ conda info -e. The one with the * next to it is the active one)
  3. Type (pandas_env)user@machine:~$ conda list to show a list of all installed modules.
  4. If pandas is missing from this list, install it (while still inside the pandas_env environment) with (pandas_env)user@machine:~$ conda install pandas, as @Fiabetto suggested.
  5. Open python (pandas_env)user@machine:~$ python and try to load pandas again.

Note that now you are working in a python environment, that only knows the modules installed inside the pandas_env environment. Every time you want to use it you have to activate the environment. This might feel a little bit clunky at first, but really shines once you have to manage different versions of python (like 2.7 or 3.4) or you need a specific version of a module (like numpy 1.7).

Edit:

If this still does not work you have several options:

  1. Check if the right pandas module is found:

    `(pandas_env)user@machine:~$ python`
    Python 2.7.10 |Continuum Analytics, Inc.| (default, Sep 15 2015, 14:50:01)
    >>> import imp
    >>> imp.find_module("pandas")
    (None, '/path/to/miniconda3/envs/foo/lib/python2.7/site-packages/pandas', ('', '', 5))
    
    # See what this returns on your system.
    
  2. Reinstall pandas in your environment with $ conda install -f pandas. This might help if you files have been corrupted somehow.

  3. Install pandas from a different source (using pip). To do this, create a new environment like above (make sure to pick a different name to avoid clashes here) but replace point 4 by (pandas_env)user@machine:~$ pip install pandas.
  4. Reinstall anaconda (make sure you pick the right version 32bit / 64bit depending on your OS, this can sometimes lead to problems). It could be possible, that your 'normal' and your anaconda python are clashing. As a last resort you could try to uninstall your 'normal' python before you reinstall anaconda.

Using cURL with a username and password?

To securely pass the password in a script (i.e. prevent it from showing up with ps auxf or logs) you can do it with the -K- flag (read config from stdin) and a heredoc:

curl --url url -K- <<< "--user user:password"

Best way to get application folder path

If you know to get the root directory:

string rootPath = Path.GetPathRoot(Application.StartupPath)

How to encrypt and decrypt file in Android?

Use a CipherOutputStream or CipherInputStream with a Cipher and your FileInputStream / FileOutputStream.

I would suggest something like Cipher.getInstance("AES/CBC/PKCS5Padding") for creating the Cipher class. CBC mode is secure and does not have the vulnerabilities of ECB mode for non-random plaintexts. It should be present in any generic cryptographic library, ensuring high compatibility.

Don't forget to use a Initialization Vector (IV) generated by a secure random generator if you want to encrypt multiple files with the same key. You can prefix the plain IV at the start of the ciphertext. It is always exactly one block (16 bytes) in size.

If you want to use a password, please make sure you do use a good key derivation mechanism (look up password based encryption or password based key derivation). PBKDF2 is the most commonly used Password Based Key Derivation scheme and it is present in most Java runtimes, including Android. Note that SHA-1 is a bit outdated hash function, but it should be fine in PBKDF2, and does currently present the most compatible option.

Always specify the character encoding when encoding/decoding strings, or you'll be in trouble when the platform encoding differs from the previous one. In other words, don't use String.getBytes() but use String.getBytes(StandardCharsets.UTF_8).

To make it more secure, please add cryptographic integrity and authenticity by adding a secure checksum (MAC or HMAC) over the ciphertext and IV, preferably using a different key. Without an authentication tag the ciphertext may be changed in such a way that the change cannot be detected.

Be warned that CipherInputStream may not report BadPaddingException, this includes BadPaddingException generated for authenticated ciphers such as GCM. This would make the streams incompatible and insecure for these kind of authenticated ciphers.

JSON.Net Self referencing loop detected

Sometimes you have loops becouse your type class have references to other classes and that classes have references to your type class, thus you have to select the parameters that you need exactly in the json string, like this code.

List<ROficina> oficinas = new List<ROficina>();
oficinas = /*list content*/;
var x = JsonConvert.SerializeObject(oficinas.Select(o => new
            {
                o.IdOficina,
                o.Nombre
            }));

C string append

You can try something like this:

strncpy(new_str, str1, strlen(str1));
strcat(new_str, str2);

More info on strncpy: http://www.cplusplus.com/reference/clibrary/cstring/strncpy/

Passing additional variables from command line to make

There's another option not cited here which is included in the GNU Make book by Stallman and McGrath (see http://www.chemie.fu-berlin.de/chemnet/use/info/make/make_7.html). It provides the example:

archive.a: ...
ifneq (,$(findstring t,$(MAKEFLAGS)))
        +touch archive.a
        +ranlib -t archive.a
else
        ranlib archive.a
endif

It involves verifying if a given parameter appears in MAKEFLAGS. For example .. suppose that you're studying about threads in c++11 and you've divided your study across multiple files (class01, ... , classNM) and you want to: compile then all and run individually or compile one at a time and run it if a flag is specified (-r, for instance). So, you could come up with the following Makefile:

CXX=clang++-3.5
CXXFLAGS = -Wall -Werror -std=c++11
LDLIBS = -lpthread

SOURCES = class01 class02 class03

%: %.cxx
    $(CXX) $(CXXFLAGS) -o [email protected] $^ $(LDLIBS)
ifneq (,$(findstring r,  $(MAKEFLAGS)))
    ./[email protected]
endif

all: $(SOURCES)

.PHONY: clean

clean:
    find . -name "*.out" -delete

Having that, you'd:

  • build and run a file w/ make -r class02;
  • build all w/ make or make all;
  • build and run all w/ make -r (suppose that all of them contain some certain kind of assert stuff and you just want to test them all)

How to import a jar in Eclipse

You can add a jar in Eclipse by right-clicking on the Project ? Build Path ? Configure Build Path. Under Libraries tab, click Add Jars or Add External JARs and give the Jar. A quick demo here.

enter image description here

The above solution is obviously a "Quick" one. However, if you are working on a project where you need to commit files to the source control repository, I would recommend adding Jar files to a dedicated library folder within your source control repository and referencing few or all of them as mentioned above.

Converting list to *args when calling function

You can use the * operator before an iterable to expand it within the function call. For example:

timeseries_list = [timeseries1 timeseries2 ...]
r = scikits.timeseries.lib.reportlib.Report(*timeseries_list)

(notice the * before timeseries_list)

From the python documentation:

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from this iterable are treated as if they were additional positional arguments; if there are positional arguments x1, ..., xN, and expression evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+N positional arguments x1, ..., xN, y1, ..., yM.

This is also covered in the python tutorial, in a section titled Unpacking argument lists, where it also shows how to do a similar thing with dictionaries for keyword arguments with the ** operator.

Properties file with a list as the value for an individual key

The comma separated list option is the easiest but becomes challenging if the values could include commas.

Here is an example of the a.1, a.2, ... approach:

for (String value : getPropertyList(prop, "a"))
{
    System.out.println(value);
}

public static List<String> getPropertyList(Properties properties, String name) 
{
    List<String> result = new ArrayList<String>();
    for (Map.Entry<Object, Object> entry : properties.entrySet())
    {
        if (((String)entry.getKey()).matches("^" + Pattern.quote(name) + "\\.\\d+$"))
        {
            result.add((String) entry.getValue());
        }
    }
    return result;
}