Programs & Examples On #Iadstsuserex

JavaScript Editor Plugin for Eclipse

In 2015 I would go with:

  • For small scripts: The js editor + jsHint plugin
  • For large code bases: TypeScript Eclipse plugin, or a similar transpiled language... I only know that TypeScript works well in Eclipse.

Of course you may want to keep JS for easy project setup and to avoid the transpilation process... there is no ultimate solution.

Or just wait for ECMA6, 7, ... :)

How to change the link color in a specific class for a div CSS

If you want to add CSS on a:hover to not all the tag, but the some of the tag, best way to do that is by using class. Give the class to all the tags which you want to give style - see the example below.

<style>
a.change_hover_color:hover { 
    color: white !important;
}
</style>

<a class="change_hover_color">FACEBOOK</a>
<a class="change_hover_color">GOOGLE</a>

What is this: [Ljava.lang.Object;?

If you are here because of the Liquibase error saying:

Caused By: Precondition Error
...
Can't detect type of array [Ljava.lang.Short

and you are using

not {
  indexExists()
}

precondition multiple times, then you are facing an old bug: https://liquibase.jira.com/browse/CORE-1342

We can try to execute an above check using bare sqlCheck(Postgres):

SELECT COUNT(i.relname)
FROM
    pg_class t,
    pg_class i,
    pg_index ix
WHERE
    t.oid = ix.indrelid
    and i.oid = ix.indexrelid
    and t.relkind = 'r'
    and t.relname = 'tableName'
    and i.relname = 'indexName';

where tableName - is an index table name and indexName - is an index name

Setting JDK in Eclipse

Some additional steps may be needed to set both the project and default workspace JRE correctly, as MayoMan mentioned. Here is the complete sequence in Eclipse Luna:

  • Right click your project > properties
  • Select “Java Build Path” on left, then “JRE System Library”, click Edit…
  • Select "Workspace Default JRE"
  • Click "Installed JREs"
  • If you see JRE you want in the list select it (selecting a JDK is OK too)
  • If not, click Search…, navigate to Computer > Windows C: > Program Files > Java, then click OK
  • Now you should see all installed JREs, select the one you want
  • Click OK/Finish a million times

Easy.... not.

how to add values to an array of objects dynamically in javascript?

In Year 2019, we can use Javascript's ES6 Spread syntax to do it concisely and efficiently

data = [...data, {"label": 2, "value": 13}]

Examples

_x000D_
_x000D_
var data = [_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
      {"label" : "1", "value" : 12},_x000D_
    ];_x000D_
    _x000D_
data = [...data, {"label" : "2", "value" : 14}] _x000D_
console.log(data)
_x000D_
_x000D_
_x000D_

For your case (i know it was in 2011), we can do it with map() & forEach() like below

_x000D_
_x000D_
var lab = ["1","2","3","4"];_x000D_
var val = [42,55,51,22];_x000D_
_x000D_
//Using forEach()_x000D_
var data = [];_x000D_
val.forEach((v,i) => _x000D_
   data= [...data, {"label": lab[i], "value":v}]_x000D_
)_x000D_
_x000D_
//Using map()_x000D_
var dataMap = val.map((v,i) => _x000D_
 ({"label": lab[i], "value":v})_x000D_
)_x000D_
_x000D_
console.log('data: ', data);_x000D_
console.log('dataMap : ', dataMap);
_x000D_
_x000D_
_x000D_

git push >> fatal: no configured push destination

I have faced this error, Previous I had push in root directory, and now I have push another directory, so I could be remove this error and run below commands.

git add .
git commit -m "some comments"
git push --set-upstream origin master

How to uninstall pip on OSX?

In my case I ran the following command and it worked (not that I was expecting it to):

sudo pip uninstall pip

Which resulted in:

Uninstalling pip-6.1.1:
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/DESCRIPTION.rst
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/METADATA
  /Library/Python/2.7/site-packages/pip-6.1.1.dist-info/RECORD
  <and all the other stuff>
  ...

  /usr/local/bin/pip
  /usr/local/bin/pip2
  /usr/local/bin/pip2.7
Proceed (y/n)? y
  Successfully uninstalled pip-6.1.1

How to find all the tables in MySQL with specific column names in them?

select distinct table_name 
from information_schema.columns 
where column_name in ('ColumnA') 
and table_schema='YourDatabase';
and table_name in 
(
 select distinct table_name 
 from information_schema.columns 
 where column_name in ('ColumnB')
 and table_schema='YourDatabase';
);

That ^^ will get the tables with ColumnA AND ColumnB instead of ColumnA OR ColumnB like the accepted answer

SQL - IF EXISTS UPDATE ELSE INSERT Syntax Error

You have to add THEN

IF EXISTS(SELECT * FROM component_psar WHERE tbl_id = '2' AND row_nr = '1') 
THEN
UPDATE component_psar SET col_1 = '1', col_2 = '1', col_3 = '1', col_4 = '1', col_5 = '1', col_6 = '1', unit = '1', add_info = '1', fsar_lock = '1' WHERE tbl_id = '2' AND row_nr = '1' 
ELSE 
INSERT INTO component_psar (tbl_id, row_nr, col_1, col_2, col_3, col_4, col_5, col_6, unit, add_info, fsar_lock) VALUES('2', '1', '1', '1', '1', '1', '1', '1', '1', '1', 'N')

System.Security.SecurityException when writing to Event Log

For me ony granting 'Read' permissions for 'NetworkService' to the whole 'EventLog' branch worked.

JAX-WS - Adding SOAP Headers

Not 100% sure as the question is missing some details but if you are using JAX-WS RI, then have a look at Adding SOAP headers when sending requests:

The portable way of doing this is that you create a SOAPHandler and mess with SAAJ, but the RI provides a better way of doing this.

When you create a proxy or dispatch object, they implement BindingProvider interface. When you use the JAX-WS RI, you can downcast to WSBindingProvider which defines a few more methods provided only by the JAX-WS RI.

This interface lets you set an arbitrary number of Header object, each representing a SOAP header. You can implement it on your own if you want, but most likely you'd use one of the factory methods defined on Headers class to create one.

import com.sun.xml.ws.developer.WSBindingProvider;

HelloPort port = helloService.getHelloPort();  // or something like that...
WSBindingProvider bp = (WSBindingProvider)port;

bp.setOutboundHeader(
  // simple string value as a header, like <simpleHeader>stringValue</simpleHeader>
  Headers.create(new QName("simpleHeader"),"stringValue"),
  // create a header from JAXB object
  Headers.create(jaxbContext,myJaxbObject)
);

Update your code accordingly and try again. And if you're not using JAX-WS RI, please update your question and provide more context information.

Update: It appears that the web service you want to call is secured with WS-Security/UsernameTokens. This is a bit different from your initial question. Anyway, to configure your client to send usernames and passwords, I suggest to check the great post Implementing the WS-Security UsernameToken Profile for Metro-based web services (jump to step 4). Using NetBeans for this step might ease things a lot.

The project type is not supported by this installation

I had similar issue with c#, first I found that each project may have a few different types. i.e. in .csproject file locate ProjectTypeGuids, it should be a few guids, i.e.

<ProjectTypeGuids>{F85E285D-A4E0-4152-9332-AB1D724D3325};{349c5851-65df-11da-9384-00065b846f21};{fae04ec0-301f-11d3-bf4b-00c04f79efbc}</ProjectTypeGuids>

they will point on component you are missing. In my case it was ASP.NET MVC 2. Some guys get it worked by installing MVC 2 destribution.

My case was worse, because installation didn't work, but it turned out that it was because I had Express 2008 and 2010. I fixed it by uninstalling both 2008 & 2010 and installing only 2010 versions. For c# you need both Visual C# Express and Visual Web Developer express

how to download image from any web page in java

The following code downloads an image from a direct link to the disk into the project directory. Also note that it uses try-with-resources.

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;

import org.apache.commons.io.FilenameUtils;

public class ImageDownloader
{
    public static void main(String[] arguments) throws IOException
    {
        downloadImage("https://upload.wikimedia.org/wikipedia/commons/7/73/Lion_waiting_in_Namibia.jpg",
                new File("").getAbsolutePath());
    }

    public static void downloadImage(String sourceUrl, String targetDirectory)
            throws MalformedURLException, IOException, FileNotFoundException
    {
        URL imageUrl = new URL(sourceUrl);
        try (InputStream imageReader = new BufferedInputStream(
                imageUrl.openStream());
                OutputStream imageWriter = new BufferedOutputStream(
                        new FileOutputStream(targetDirectory + File.separator
                                + FilenameUtils.getName(sourceUrl)));)
        {
            int readByte;

            while ((readByte = imageReader.read()) != -1)
            {
                imageWriter.write(readByte);
            }
        }
    }
}

NullInjectorError: No provider for AngularFirestore

Change Your Import From :

import { AngularFirestore } from '@angular/fire/firestore/firestore';

To This :

import { AngularFirestore } from '@angular/fire/firestore';

This solve my problem.

CSS for grabbing cursors (drag & drop)

CSS3 grab and grabbing are now allowed values for cursor. In order to provide several fallbacks for cross-browser compatibility3 including custom cursor files, a complete solution would look like this:

.draggable {
    cursor: move; /* fallback: no `url()` support or images disabled */
    cursor: url(images/grab.cur); /* fallback: Internet Explorer */
    cursor: -webkit-grab; /* Chrome 1-21, Safari 4+ */
    cursor:    -moz-grab; /* Firefox 1.5-26 */
    cursor:         grab; /* W3C standards syntax, should come least */
}

.draggable:active {
    cursor: url(images/grabbing.cur);
    cursor: -webkit-grabbing;
    cursor:    -moz-grabbing;
    cursor:         grabbing;
}

Update 2019-10-07:

.draggable {
    cursor: move; /* fallback: no `url()` support or images disabled */
    cursor: url(images/grab.cur); /* fallback: Chrome 1-21, Firefox 1.5-26, Safari 4+, IE, Edge 12-14, Android 2.1-4.4.4 */
    cursor: grab; /* W3C standards syntax, all modern browser */
}

.draggable:active {
    cursor: url(images/grabbing.cur);
    cursor: grabbing;
}

How many bytes is unsigned long long?

The beauty of C++, like C, is that the sized of these things are implementation-defined, so there's no correct answer without your specifying the compiler you're using. Are those two the same? Yes. "long long" is a synonym for "long long int", for any compiler that will accept both.

MySQL Foreign Key Error 1005 errno 150 primary key as foreign key

When creating a foreign key constraint, MySQL requires a usable index on both the referencing table and also on the referenced table. The index on the referencing table is created automatically if one doesn't exist, but the one on the referenced table needs to be created manually (Source). Yours appears to be missing.

Test case:

CREATE TABLE tbl_a (
    id int PRIMARY KEY,
    some_other_id int,
    value int
) ENGINE=INNODB;
Query OK, 0 rows affected (0.10 sec)

CREATE TABLE tbl_b (
    id int PRIMARY KEY,
    a_id int,
    FOREIGN KEY (a_id) REFERENCES tbl_a (some_other_id)
) ENGINE=INNODB;
ERROR 1005 (HY000): Can't create table 'e.tbl_b' (errno: 150)

But if we add an index on some_other_id:

CREATE INDEX ix_some_id ON tbl_a (some_other_id);
Query OK, 0 rows affected (0.11 sec)
Records: 0  Duplicates: 0  Warnings: 0

CREATE TABLE tbl_b (
    id int PRIMARY KEY,
    a_id int,
    FOREIGN KEY (a_id) REFERENCES tbl_a (some_other_id)
) ENGINE=INNODB;
Query OK, 0 rows affected (0.06 sec)

This is often not an issue in most situations, since the referenced field is often the primary key of the referenced table, and the primary key is indexed automatically.

html div onclick event

when click on div alert key

   $(document).delegate(".searchbtn", "click", function() {
        var key=$.trim($('#txtkey').val());
        alert(key);
        });

Converting java.sql.Date to java.util.Date

Since java.sql.Date extends java.util.Date, you should be able to do

java.util.Date newDate = result.getDate("VALUEDATE");

Linux Shell Script For Each File in a Directory Grab the filename and execute a program

find . -type f -name "*.xls" -printf "xls2csv %p %p.csv\n" | bash

bash 4 (recursive)

shopt -s globstar
for xls in /path/**/*.xls
do
  xls2csv "$xls" "${xls%.xls}.csv"
done

How to print the current Stack Trace in .NET without any exception?

There are two ways to do this. The System.Diagnostics.StackTrace() will give you a stack trace for the current thread. If you have a reference to a Thread instance, you can get the stack trace for that via the overloaded version of StackTrace().

You may also want to check out Stack Overflow question How to get non-current thread's stacktrace?.

Why javascript getTime() is not a function?

dat1 and dat2 are Strings in JavaScript. There is no getTime function on the String prototype. I believe you want the Date.parse() function: http://www.w3schools.com/jsref/jsref_parse.asp

You would use it like this:

var date = Date.parse(dat1);

Calling startActivity() from outside of an Activity context

You can achieve it with addFlags instead of setFlags

myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

According to the documentation it does:

Add additional flags to the intent (or with existing flags value).


EDIT

Be aware if you are using flags that you change the history stack as Alex Volovoy's answer says:

...avoid setting flags as it will interfere with normal flow of event and history stack.

Uncompress tar.gz file

Try this:

tar -zxvf file.tar.gz

What is use of c_str function In c++

It's used to make std::string interoperable with C code that requires a null terminated char*.

Create Excel file in Java

Fair warning about Apache POI's Excel generation... (I know this is an old post, but it's important in case someone looks this up again like I just did)

It had a memory leak issue, which supposedly was solved by 2006, but which people quite recently have still been experiencing. If you want to automate generating a large amount of excel (i.e., if you want to generate a single, large file, a large number of small files, or both), I'd recommend using a different API. Either that, or increasing the JVM stack size to preposterous proportions, and maybe looking into interning strings if you know you won't actually be working with many different strings (although, of course, interning strings means that if you have a large number of different strings, you'll have an entirely different program-crashing memory problem. So, consider that before you go that route).

How to validate inputs dynamically created using ng-repeat, ng-show (angular)

Building on pkozlowski.opensource's answer, I've added a way to have dynamic input names that also work with ngMessages. Note the ng-init part on the ng-form element and the use of furryName. furryName becomes the variable name that contains the variable value for the input's name attribute.

<ion-item ng-repeat="animal in creatures track by $index">
<ng-form name="animalsForm" ng-init="furryName = 'furry' + $index">
        <!-- animal is furry toggle buttons -->
        <input id="furryRadio{{$index}}"
               type="radio"
               name="{{furryName}}"
               ng-model="animal.isFurry"
               ng-value="radioBoolValues.boolTrue"
               required
                >
        <label for="furryRadio{{$index}}">Furry</label>

        <input id="hairlessRadio{{$index}}"
               name="{{furryName}}"
               type="radio"
               ng-model="animal.isFurry"
               ng-value="radioBoolValues.boolFalse"
               required
               >
        <label for="hairlessRadio{{$index}}">Hairless</label>

        <div ng-messages="animalsForm[furryName].$error"
             class="form-errors"
             ng-show="animalsForm[furryName].$invalid && sectionForm.$submitted">
            <div ng-messages-include="client/views/partials/form-errors.ng.html"></div>
        </div>
</ng-form>
</ion-item>

What is the facade design pattern?

Its simply creating a wrapper to call multiple methods . You have an A class with method x() and y() and B class with method k() and z(). You want to call x, y, z at once , to do that using Facade pattern you just create a Facade class and create a method lets say xyz(). Instead of calling each method (x,y and z) individually you just call the wrapper method (xyz()) of the facade class which calls those methods .

Similar pattern is repository but it s mainly for the data access layer.

XML Serialize generic list of serializable objects

I think it's best if you use methods with generic arguments, like the following :

public static void SerializeToXml<T>(T obj, string fileName)
{
    using (var fileStream = new FileStream(fileName, FileMode.Create))
    { 
        var ser = new XmlSerializer(typeof(T)); 
        ser.Serialize(fileStream, obj);
    }
}

public static T DeserializeFromXml<T>(string xml)
{
    T result;
    var ser = new XmlSerializer(typeof(T));
    using (var tr = new StringReader(xml))
    {
        result = (T)ser.Deserialize(tr);
    }
    return result;
}

Convert datetime to valid JavaScript date

This works everywhere including Safari 5 and Firefox 5 on OS X.

UPDATE: Fx Quantum (54) has no need for the replace, but Safari 11 is still not happy unless you convert as below

_x000D_
_x000D_
var date_test = new Date("2011-07-14 11:23:00".replace(/-/g,"/"));_x000D_
console.log(date_test);
_x000D_
_x000D_
_x000D_


FIDDLE

VBA array sort function?

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

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

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

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

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

passing JSON data to a Spring MVC controller

  1. Html

    $('#save').click(function(event) {        
        var jenis = $('#jenis').val();
        var model = $('#model').val();
        var harga = $('#harga').val();
        var json = { "jenis" : jenis, "model" : model, "harga": harga};
        $.ajax({
            url: 'phone/save',
            data: JSON.stringify(json),
            type: "POST",           
            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },
            success: function(data){ 
                alert(data);
            }
        });
    
        event.preventDefault();
    });
    
    1. Controller

      @Controller
      @RequestMapping(value="/phone")
      public class phoneController {
      
          phoneDao pd=new phoneDao();
      
          @RequestMapping(value="/save",method=RequestMethod.POST)
          public @ResponseBody
          int save(@RequestBody Smartphones phone)
          {
              return pd.save(phone);
          }
      
    2. Dao

      public Integer save(Smartphones i) {
          int id = 0;
          Session session=HibernateUtil.getSessionFactory().openSession();
          Transaction trans=session.beginTransaction();
          try {
              session.save(i);   
              id=i.getId();
              trans.commit();
          }
          catch(HibernateException he){}
          return id;
      }
      

What is the difference between $routeProvider and $stateProvider?

Angular's own ng-Router takes URLs into consideration while routing, UI-Router takes states in addition to URLs.

States are bound to named, nested and parallel views, allowing you to powerfully manage your application's interface.

While in ng-router, you have to be very careful about URLs when providing links via <a href=""> tag, in UI-Router you have to only keep state in mind. You provide links like <a ui-sref="">. Note that even if you use <a href=""> in UI-Router, just like you would do in ng-router, it will still work.

So, even if you decide to change your URL some day, your state will remain same and you need to change URL only at .config.

While ngRouter can be used to make simple apps, UI-Router makes development much easier for complex apps. Here its wiki.

How to center-justify the last line of text in CSS?

You can use the text-align-last property

.center-justified {
    text-align: justify;
    text-align-last: center;
}

Here is a compatibility table : https://developer.mozilla.org/en-US/docs/Web/CSS/text-align-last#Browser_compatibility.

Works in all browsers except for Safari (both Mac and iOS), including Internet Explorer.

Also in Internet Explorer, only works with text-align: justify (no other values of text-align) and start and end are not supported.

LogCat message: The Google Play services resources were not found. Check your project configuration to ensure that the resources are included

I also had the same issue. I also tried to look for solutions, but after I didn't find any of the solutions working, I tried to restart my mobile (Android device), and it resolved the issue.

Please give it a try! Restart your mobile device and Eclipse to be on safe side and check if it works.

not-null property references a null or transient value

for followers, this error message can also mean "you have it referencing a foreign object that hasn't been saved to the DB yet" (even though it's there, and is non null).

Convert DateTime in C# to yyyy-MM-dd format and Store it to MySql DateTime Field

Use DateTime.Now.ToString("yyyy-MM-dd h:mm tt");. See this.

How to get a random value from dictionary?

If you don't want to use the random module, you can also try popitem():

>> d = {'a': 1, 'b': 5, 'c': 7}
>>> d.popitem()
('a', 1)
>>> d
{'c': 7, 'b': 5}
>>> d.popitem()
('c', 7)

Since the dict doesn't preserve order, by using popitem you get items in an arbitrary (but not strictly random) order from it.

Also keep in mind that popitem removes the key-value pair from dictionary, as stated in the docs.

popitem() is useful to destructively iterate over a dictionary

frequent issues arising in android view, Error parsing XML: unbound prefix

I'll throw in a little more for the newbies and for folks, like myself, that don't understand XML.

The answers above a pretty good, but the general answer is that you need a namespace for any namespace used in the config.xml file.

Translation: Any XML tag name that has is a tag with a namespace where blah is the namespace and fubar is the XML tag. The namespace lets you use many different tools to interpret the XML with their own tag names. For example, Intel XDK uses the namespace intelxdk and android uses android. Thus you need the following namespaces or the build throws up blood (i.e. Error parsing XML: unbound prefix) which is translated to: You used a namespace, but did not define it.

  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:intelxdk="http://xdk.intel.com/ns/v1"

Count the number of occurrences of each letter in string

for (int i=0;i<word.length();i++){
         int counter=0;
         for (int j=0;j<word.length();j++){
             if(word.charAt(i)==word.charAt(j))
             counter++;
             }// inner for
             JOptionPane.showMessageDialog( null,word.charAt(i)+" found "+ counter +" times");
         }// outer for

Python readlines() usage and efficient practice for reading

The short version is: The efficient way to use readlines() is to not use it. Ever.


I read some doc notes on readlines(), where people has claimed that this readlines() reads whole file content into memory and hence generally consumes more memory compared to readline() or read().

The documentation for readlines() explicitly guarantees that it reads the whole file into memory, and parses it into lines, and builds a list full of strings out of those lines.

But the documentation for read() likewise guarantees that it reads the whole file into memory, and builds a string, so that doesn't help.


On top of using more memory, this also means you can't do any work until the whole thing is read. If you alternate reading and processing in even the most naive way, you will benefit from at least some pipelining (thanks to the OS disk cache, DMA, CPU pipeline, etc.), so you will be working on one batch while the next batch is being read. But if you force the computer to read the whole file in, then parse the whole file, then run your code, you only get one region of overlapping work for the entire file, instead of one region of overlapping work per read.


You can work around this in three ways:

  1. Write a loop around readlines(sizehint), read(size), or readline().
  2. Just use the file as a lazy iterator without calling any of these.
  3. mmap the file, which allows you to treat it as a giant string without first reading it in.

For example, this has to read all of foo at once:

with open('foo') as f:
    lines = f.readlines()
    for line in lines:
        pass

But this only reads about 8K at a time:

with open('foo') as f:
    while True:
        lines = f.readlines(8192)
        if not lines:
            break
        for line in lines:
            pass

And this only reads one line at a time—although Python is allowed to (and will) pick a nice buffer size to make things faster.

with open('foo') as f:
    while True:
        line = f.readline()
        if not line:
            break
        pass

And this will do the exact same thing as the previous:

with open('foo') as f:
    for line in f:
        pass

Meanwhile:

but should the garbage collector automatically clear that loaded content from memory at the end of my loop, hence at any instant my memory should have only the contents of my currently processed file right ?

Python doesn't make any such guarantees about garbage collection.

The CPython implementation happens to use refcounting for GC, which means that in your code, as soon as file_content gets rebound or goes away, the giant list of strings, and all of the strings within it, will be freed to the freelist, meaning the same memory can be reused again for your next pass.

However, all those allocations, copies, and deallocations aren't free—it's much faster to not do them than to do them.

On top of that, having your strings scattered across a large swath of memory instead of reusing the same small chunk of memory over and over hurts your cache behavior.

Plus, while the memory usage may be constant (or, rather, linear in the size of your largest file, rather than in the sum of your file sizes), that rush of mallocs to expand it the first time will be one of the slowest things you do (which also makes it much harder to do performance comparisons).


Putting it all together, here's how I'd write your program:

for filename in os.listdir(input_dir):
    with open(filename, 'rb') as f:
        if filename.endswith(".gz"):
            f = gzip.open(fileobj=f)
        words = (line.split(delimiter) for line in f)
        ... my logic ...  

Or, maybe:

for filename in os.listdir(input_dir):
    if filename.endswith(".gz"):
        f = gzip.open(filename, 'rb')
    else:
        f = open(filename, 'rb')
    with contextlib.closing(f):
        words = (line.split(delimiter) for line in f)
        ... my logic ...

How to connect mySQL database using C++

Finally I could successfully compile a program with C++ connector in Ubuntu 12.04 I have installed the connector using this command

'apt-get install libmysqlcppconn-dev'

Initially I faced the same problem with "undefined reference to `get_driver_instance' " to solve this I declare my driver instance variable of MySQL_Driver type. For ready reference this type is defined in mysql_driver.h file. Here is the code snippet I used in my program.

sql::mysql::MySQL_Driver *driver;
try {     
    driver = sql::mysql::get_driver_instance();
}

and I compiled the program with -l mysqlcppconn linker option

and don't forget to include this header

#include "mysql_driver.h" 

Sniff HTTP packets for GET and POST requests from an application

Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet, then expand the Hypertext Transfer Protocol field. The POST data will be right there on top.

curl usage to get header

curl --head https://www.example.net

I was pointed to this by curl itself; when I issued the command with -X HEAD, it printed:

Warning: Setting custom HTTP method to HEAD with -X/--request may not work the 
Warning: way you want. Consider using -I/--head instead.

Renaming columns in Pandas

Let's say this is your dataframe.

enter image description here

You can rename the columns using two methods.

  1. Using dataframe.columns=[#list]

    df.columns=['a','b','c','d','e']
    

    enter image description here

    The limitation of this method is that if one column has to be changed, full column list has to be passed. Also, this method is not applicable on index labels. For example, if you passed this:

    df.columns = ['a','b','c','d']
    

    This will throw an error. Length mismatch: Expected axis has 5 elements, new values have 4 elements.

  2. Another method is the Pandas rename() method which is used to rename any index, column or row

    df = df.rename(columns={'$a':'a'})
    

    enter image description here

Similarly, you can change any rows or columns.

Difference between links and depends_on in docker_compose.yml

The post needs an update after the links option is deprecated.

Basically, links is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.

For docker run, --link is also deprecated and should be replaced by a custom network.

docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image

depends_on expresses start order (and implicitly image pulling order), which was a good side effect of links.

How to get the instance id from within an ec2 instance?

For PHP:

$instance = json_decode(file_get_contents('http://169.254.169.254/latest/dynamic/instance-identity/document));
$id = $instance['instanceId'];

Edit per @John

What is Android keystore file, and what is it used for?

Android Market requires you to sign all apps you publish with a certificate, using a public/private key mechanism (the certificate is signed with your private key). This provides a layer of security that prevents, among other things, remote attackers from pushing malicious updates to your application to market (all updates must be signed with the same key).

From The App-Signing Guide of the Android Developer's site:

In general, the recommended strategy for all developers is to sign all of your applications with the same certificate, throughout the expected lifespan of your applications. There are several reasons why you should do so...

Using the same key has a few benefits - One is that it's easier to share data between applications signed with the same key. Another is that it allows multiple apps signed with the same key to run in the same process, so a developer can build more "modular" applications.

Increase heap size in Java

You can increase to 2GB on a 32 bit system. If you're on a 64 bit system you can go higher. No need to worry if you've chosen incorrectly, if you ask for 5g on a 32 bit system java will complain about an invalid value and quit.

As others have posted, use the cmd-line flags - e.g.

java -Xmx6g myprogram

You can get a full list (or a nearly full list, anyway) by typing java -X.

How to check if the string is empty?

The most elegant way would probably be to simply check if its true or falsy, e.g.:

if not my_string:

However, you may want to strip white space because:

 >>> bool("")
 False
 >>> bool("   ")
 True
 >>> bool("   ".strip())
 False

You should probably be a bit more explicit in this however, unless you know for sure that this string has passed some kind of validation and is a string that can be tested this way.

Generating a list of pages (not posts) without the index file

I can offer you a jquery solution

add this in your <head></head> tag

<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>

add this after </ul>

 <script> $('ul li:first').remove(); </script> 

Multiple "order by" in LINQ

Using non-lambda, query-syntax LINQ, you can do this:

var movies = from row in _db.Movies 
             orderby row.Category, row.Name
             select row;

[EDIT to address comment] To control the sort order, use the keywords ascending (which is the default and therefore not particularly useful) or descending, like so:

var movies = from row in _db.Movies 
             orderby row.Category descending, row.Name
             select row;

Why doesn't Java allow overriding of static methods?

overriding is reserved for instance members to support polymorphic behaviour. static class members do not belong to a particular instance. instead, static members belong to the class and as a result overriding is not supported because subclasses only inherit protected and public instance members and not static members. You may want to define an inerface and research factory and/or strategy design patterns to evaluate an alternate approach.

Add column in dataframe from list

Old question; but I always try to use fastest code!

I had a huge list with 69 millions of uint64. np.array() was fastest for me.

df['hashes'] = hashes
Time spent: 17.034842014312744

df['hashes'] = pd.Series(hashes).values
Time spent: 17.141014337539673

df['key'] = np.array(hashes)
Time spent: 10.724546194076538

Sequelize, convert entity to plain object

As CharlesA notes in his answer, .values() is technically deprecated, though this fact isn't explicitly noted in the docs. If you don't want to use { raw: true } in the query, the preferred approach is to call .get() on the results.

.get(), however, is a method of an instance, not of an array. As noted in the linked issue above, Sequelize returns native arrays of instance objects (and the maintainers don't plan on changing that), so you have to iterate through the array yourself:

db.Sensors.findAll({
    where: {
        nodeid: node.nodeid
    }
}).success((sensors) => {
    const nodeData = sensors.map((node) => node.get({ plain: true }));
});

Hide header in stack navigator React navigation

For me navigationOptions didn't work. The following worked for me.

<Stack.Screen name="Login" component={Login}
      options={{
               headerShown: false
              }}
     />

How to extract table as text from the PDF using Python?

This answer is for anyone encountering pdfs with images and needing to use OCR. I could not find a workable off-the-shelf solution; nothing that gave me the accuracy I needed.

Here are the steps I found to work.

  1. Use pdfimages from https://poppler.freedesktop.org/ to turn the pages of the pdf into images.

  2. Use Tesseract to detect rotation and ImageMagick mogrify to fix it.

  3. Use OpenCV to find and extract tables.

  4. Use OpenCV to find and extract each cell from the table.

  5. Use OpenCV to crop and clean up each cell so that there is no noise that will confuse OCR software.

  6. Use Tesseract to OCR each cell.

  7. Combine the extracted text of each cell into the format you need.

I wrote a python package with modules that can help with those steps.

Repo: https://github.com/eihli/image-table-ocr

Docs & Source: https://eihli.github.io/image-table-ocr/pdf_table_extraction_and_ocr.html

Some of the steps don't require code, they take advantage of external tools like pdfimages and tesseract. I'll provide some brief examples for a couple of the steps that do require code.

  1. Finding tables:

This link was a good reference while figuring out how to find tables. https://answers.opencv.org/question/63847/how-to-extract-tables-from-an-image/

import cv2

def find_tables(image):
    BLUR_KERNEL_SIZE = (17, 17)
    STD_DEV_X_DIRECTION = 0
    STD_DEV_Y_DIRECTION = 0
    blurred = cv2.GaussianBlur(image, BLUR_KERNEL_SIZE, STD_DEV_X_DIRECTION, STD_DEV_Y_DIRECTION)
    MAX_COLOR_VAL = 255
    BLOCK_SIZE = 15
    SUBTRACT_FROM_MEAN = -2

    img_bin = cv2.adaptiveThreshold(
        ~blurred,
        MAX_COLOR_VAL,
        cv2.ADAPTIVE_THRESH_MEAN_C,
        cv2.THRESH_BINARY,
        BLOCK_SIZE,
        SUBTRACT_FROM_MEAN,
    )
    vertical = horizontal = img_bin.copy()
    SCALE = 5
    image_width, image_height = horizontal.shape
    horizontal_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (int(image_width / SCALE), 1))
    horizontally_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, horizontal_kernel)
    vertical_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, int(image_height / SCALE)))
    vertically_opened = cv2.morphologyEx(img_bin, cv2.MORPH_OPEN, vertical_kernel)

    horizontally_dilated = cv2.dilate(horizontally_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (40, 1)))
    vertically_dilated = cv2.dilate(vertically_opened, cv2.getStructuringElement(cv2.MORPH_RECT, (1, 60)))

    mask = horizontally_dilated + vertically_dilated
    contours, hierarchy = cv2.findContours(
        mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE,
    )

    MIN_TABLE_AREA = 1e5
    contours = [c for c in contours if cv2.contourArea(c) > MIN_TABLE_AREA]
    perimeter_lengths = [cv2.arcLength(c, True) for c in contours]
    epsilons = [0.1 * p for p in perimeter_lengths]
    approx_polys = [cv2.approxPolyDP(c, e, True) for c, e in zip(contours, epsilons)]
    bounding_rects = [cv2.boundingRect(a) for a in approx_polys]

    # The link where a lot of this code was borrowed from recommends an
    # additional step to check the number of "joints" inside this bounding rectangle.
    # A table should have a lot of intersections. We might have a rectangular image
    # here though which would only have 4 intersections, 1 at each corner.
    # Leaving that step as a future TODO if it is ever necessary.
    images = [image[y:y+h, x:x+w] for x, y, w, h in bounding_rects]
    return images
  1. Extract cells from table.

This is very similar to 2, so I won't include all the code. The part I will reference will be in sorting the cells.

We want to identify the cells from left-to-right, top-to-bottom.

We’ll find the rectangle with the most top-left corner. Then we’ll find all of the rectangles that have a center that is within the top-y and bottom-y values of that top-left rectangle. Then we’ll sort those rectangles by the x value of their center. We’ll remove those rectangles from the list and repeat.

def cell_in_same_row(c1, c2):
    c1_center = c1[1] + c1[3] - c1[3] / 2
    c2_bottom = c2[1] + c2[3]
    c2_top = c2[1]
    return c2_top < c1_center < c2_bottom

orig_cells = [c for c in cells]
rows = []
while cells:
    first = cells[0]
    rest = cells[1:]
    cells_in_same_row = sorted(
        [
            c for c in rest
            if cell_in_same_row(c, first)
        ],
        key=lambda c: c[0]
    )

    row_cells = sorted([first] + cells_in_same_row, key=lambda c: c[0])
    rows.append(row_cells)
    cells = [
        c for c in rest
        if not cell_in_same_row(c, first)
    ]

# Sort rows by average height of their center.
def avg_height_of_center(row):
    centers = [y + h - h / 2 for x, y, w, h in row]
    return sum(centers) / len(centers)

rows.sort(key=avg_height_of_center)

How do I compile and run a program in Java on my Mac?

I will give you steps to writing and compiling code. Use this example:

 public class Paycheck {
    public static void main(String args[]) {
        double amountInAccount;
        amountInAccount = 128.57;
        System.out.print("You earned $");
        System.out.print(amountInAccount);
        System.out.println(" at work today.");
    }
}
  1. Save the code as Paycheck.java
  2. Go to terminal and type cd Desktop
  3. Type javac Paycheck.java
  4. Type java Paycheck
  5. Enjoy your program!

Using --add-host or extra_hosts with docker-compose

It seems like it should be made possible to say:

extra_hosts:
 - "loghost:localhost"

So if the part after the colon (normally an IP address) doesn't start with a digit, then name resolution will be performed to look up an IP for localhost, and add something like to the container's /etc/hosts:

127.0.0.1 loghost

...assuming that localhost resolves to 127.0.0.1 on the host system.

It looks like it'd be really easy to add in docker-compose's source code: compose/config/types.py's parse_extra_hosts function would likely do it.

For docker itself, this would probably be addable in opts/hosts.go's ValidateExtraHost function, though then it's not strictly validating anymore, so the function would be a little misnamed.

It might actually be a little better to add this to docker, not docker-compose - docker-compose might just get it automatically if docker gets it.

Sadly, this would probably require a container bounce to change an IP address.

VBA Subscript out of range - error 9

Option Explicit

Private Sub CommandButton1_Click()
Dim mode As String
Dim RecordId As Integer
Dim Resultid As Integer
Dim sourcewb As Workbook
Dim targetwb As Workbook
Dim SourceRowCount As Long
Dim TargetRowCount As Long
Dim SrceFile As String
Dim TrgtFile As String
Dim TitleId As Integer
Dim TestPassCount As Integer
Dim TestFailCount As Integer
Dim myWorkbook1 As Workbook
Dim myWorkbook2 As Workbook


TitleId = 4
Resultid = 0

Dim FileName1, FileName2 As String
Dim Difference As Long



'TestPassCount = 0
'TestFailCount = 0

'Retrieve number of records in the TestData SpreadSheet
Dim TestDataRowCount As Integer
TestDataRowCount = Worksheets("TestData").UsedRange.Rows.Count

If (TestDataRowCount <= 2) Then
  MsgBox "No records to validate.Please provide test data in Test Data SpreadSheet"
Else
  For RecordId = 3 To TestDataRowCount
    RefreshResultSheet

    'Source File row count
    SrceFile = Worksheets("TestData").Range("D" & RecordId).Value
    Set sourcewb = Workbooks.Open(SrceFile)
    With sourcewb.Worksheets(1)
      SourceRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      sourcewb.Close
    End With

    'Target File row count
    TrgtFile = Worksheets("TestData").Range("E" & RecordId).Value
    Set targetwb = Workbooks.Open(TrgtFile)
    With targetwb.Worksheets(1)
      TargetRowCount = .Cells(.Rows.Count, "A").End(xlUp).row
      targetwb.Close
    End With

    ' Set Row Count Result Test data value
    TitleId = TitleId + 3
    Worksheets("Result").Range("A" & TitleId).Value = Worksheets("TestData").Range("A" & RecordId).Value

    'Compare Source and Target Row count
    Resultid = TitleId + 1
    Worksheets("Result").Range("A" & Resultid).Value = "Source and Target record Count"
    If (SourceRowCount = TargetRowCount) Then
       Worksheets("Result").Range("B" & Resultid).Value = "Passed"
       Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
       TestPassCount = TestPassCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Failed"
      Worksheets("Result").Range("C" & Resultid).Value = "Source Row Count: " & SourceRowCount & " & " & " Target Row Count: " & TargetRowCount
      TestFailCount = TestFailCount + 1
    End If


    'For comparison of two files

    FileName1 = Worksheets("TestData").Range("D" & RecordId).Value
    FileName2 = Worksheets("TestData").Range("E" & RecordId).Value

    Set myWorkbook1 = Workbooks.Open(FileName1)
    Set myWorkbook2 = Workbooks.Open(FileName2)

    Difference = Compare2WorkSheets(myWorkbook1.Worksheets("Sheet1"), myWorkbook2.Worksheets("Sheet1"))
    myWorkbook1.Close
    myWorkbook2.Close


    'MsgBox Difference

    'Set Result of data validation in result sheet
    Resultid = Resultid + 1

    Worksheets("Result").Activate
    Worksheets("Result").Range("A" & Resultid).Value = "Data validation of source and target File"

    If Difference > 0 Then
        Worksheets("Result").Range("B" & Resultid).Value = "Failed"
        Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
        TestFailCount = TestFailCount + 1
    Else
      Worksheets("Result").Range("B" & Resultid).Value = "Passed"
      Worksheets("Result").Range("C" & Resultid).Value = Difference & " cells contains different data!"
      TestPassCount = TestPassCount + 1
    End If


  Next RecordId
End If

UpdateTestExecData TestPassCount, TestFailCount
End Sub

Sub RefreshResultSheet()
  Worksheets("Result").Activate
  Worksheets("Result").Range("B1:B4").Select
  Selection.ClearContents
  Worksheets("Result").Range("D1:D4").Select
  Selection.ClearContents
  Worksheets("Result").Range("B1").Value = Worksheets("Instructions").Range("D3").Value
  Worksheets("Result").Range("B2").Value = Worksheets("Instructions").Range("D4").Value
  Worksheets("Result").Range("B3").Value = Worksheets("Instructions").Range("D6").Value
  Worksheets("Result").Range("B4").Value = Worksheets("Instructions").Range("D5").Value
End Sub

Sub UpdateTestExecData(TestPassCount As Integer, TestFailCount As Integer)
  Worksheets("Result").Range("D1").Value = TestPassCount + TestFailCount
  Worksheets("Result").Range("D2").Value = TestPassCount
  Worksheets("Result").Range("D3").Value = TestFailCount
  Worksheets("Result").Range("D4").Value = ((TestPassCount / (TestPassCount + TestFailCount)))
End Sub

How do I convert NSInteger to NSString datatype?

When compiling with support for arm64, this won't generate a warning:

[NSString stringWithFormat:@"%lu", (unsigned long)myNSUInteger];

Maximum Length of Command Line String

In Windows 10, it's still 8191 characters...at least on my machine.

It just cuts off any text after 8191 characters. Well, actually, I got 8196 characters, and after 8196, then it just won't let me type any more.

Here's a script that will test how long of a statement you can use. Well, assuming you have gawk/awk installed.

echo rem this is a test of how long of a line that a .cmd script can generate >testbat.bat
gawk 'BEGIN {printf "echo -----";for (i=10;i^<=100000;i +=10) printf "%%06d----",i;print;print "pause";}' >>testbat.bat
testbat.bat

Python: Append item to list N times

For immutable data types:

l = [0] * 100
# [0, 0, 0, 0, 0, ...]

l = ['foo'] * 100
# ['foo', 'foo', 'foo', 'foo', ...]

For values that are stored by reference and you may wish to modify later (like sub-lists, or dicts):

l = [{} for x in range(100)]

(The reason why the first method is only a good idea for constant values, like ints or strings, is because only a shallow copy is does when using the <list>*<number> syntax, and thus if you did something like [{}]*100, you'd end up with 100 references to the same dictionary - so changing one of them would change them all. Since ints and strings are immutable, this isn't a problem for them.)

If you want to add to an existing list, you can use the extend() method of that list (in conjunction with the generation of a list of things to add via the above techniques):

a = [1,2,3]
b = [4,5,6]
a.extend(b)
# a is now [1,2,3,4,5,6]

What is Java String interning?

JLS

JLS 7 3.10.5 defines it and gives a practical example:

Moreover, a string literal always refers to the same instance of class String. This is because string literals - or, more generally, strings that are the values of constant expressions (§15.28) - are "interned" so as to share unique instances, using the method String.intern.

Example 3.10.5-1. String Literals

The program consisting of the compilation unit (§7.3):

package testPackage;
class Test {
    public static void main(String[] args) {
        String hello = "Hello", lo = "lo";
        System.out.print((hello == "Hello") + " ");
        System.out.print((Other.hello == hello) + " ");
        System.out.print((other.Other.hello == hello) + " ");
        System.out.print((hello == ("Hel"+"lo")) + " ");
        System.out.print((hello == ("Hel"+lo)) + " ");
        System.out.println(hello == ("Hel"+lo).intern());
    }
}
class Other { static String hello = "Hello"; }

and the compilation unit:

package other;
public class Other { public static String hello = "Hello"; }

produces the output:

true true true true false true

JVMS

JVMS 7 5.1 says says that interning is implemented magically and efficiently with a dedicated CONSTANT_String_info struct (unlike most other objects which have more generic representations):

A string literal is a reference to an instance of class String, and is derived from a CONSTANT_String_info structure (§4.4.3) in the binary representation of a class or interface. The CONSTANT_String_info structure gives the sequence of Unicode code points constituting the string literal.

The Java programming language requires that identical string literals (that is, literals that contain the same sequence of code points) must refer to the same instance of class String (JLS §3.10.5). In addition, if the method String.intern is called on any string, the result is a reference to the same class instance that would be returned if that string appeared as a literal. Thus, the following expression must have the value true:

("a" + "b" + "c").intern() == "abc"

To derive a string literal, the Java Virtual Machine examines the sequence of code points given by the CONSTANT_String_info structure.

  • If the method String.intern has previously been called on an instance of class String containing a sequence of Unicode code points identical to that given by the CONSTANT_String_info structure, then the result of string literal derivation is a reference to that same instance of class String.

  • Otherwise, a new instance of class String is created containing the sequence of Unicode code points given by the CONSTANT_String_info structure; a reference to that class instance is the result of string literal derivation. Finally, the intern method of the new String instance is invoked.

Bytecode

Let's decompile some OpenJDK 7 bytecode to see interning in action.

If we decompile:

public class StringPool {
    public static void main(String[] args) {
        String a = "abc";
        String b = "abc";
        String c = new String("abc");
        System.out.println(a);
        System.out.println(b);
        System.out.println(a == c);
    }
}

we have on the constant pool:

#2 = String             #32   // abc
[...]
#32 = Utf8               abc

and main:

 0: ldc           #2          // String abc
 2: astore_1
 3: ldc           #2          // String abc
 5: astore_2
 6: new           #3          // class java/lang/String
 9: dup
10: ldc           #2          // String abc
12: invokespecial #4          // Method java/lang/String."<init>":(Ljava/lang/String;)V
15: astore_3
16: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
19: aload_1
20: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
23: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
26: aload_2
27: invokevirtual #6          // Method java/io/PrintStream.println:(Ljava/lang/String;)V
30: getstatic     #5          // Field java/lang/System.out:Ljava/io/PrintStream;
33: aload_1
34: aload_3
35: if_acmpne     42
38: iconst_1
39: goto          43
42: iconst_0
43: invokevirtual #7          // Method java/io/PrintStream.println:(Z)V

Note how:

  • 0 and 3: the same ldc #2 constant is loaded (the literals)
  • 12: a new string instance is created (with #2 as argument)
  • 35: a and c are compared as regular objects with if_acmpne

The representation of constant strings is quite magic on the bytecode:

and the JVMS quote above seems to say that whenever the Utf8 pointed to is the same, then identical instances are loaded by ldc.

I have done similar tests for fields, and:

  • static final String s = "abc" points to the constant table through the ConstantValue Attribute
  • non-final fields don't have that attribute, but can still be initialized with ldc

Conclusion: there is direct bytecode support for the string pool, and the memory representation is efficient.

Bonus: compare that to the Integer pool, which does not have direct bytecode support (i.e. no CONSTANT_String_info analogue).

Updating a dataframe column in spark

While you cannot modify a column as such, you may operate on a column and return a new DataFrame reflecting that change. For that you'd first create a UserDefinedFunction implementing the operation to apply and then selectively apply that function to the targeted column only. In Python:

from pyspark.sql.functions import UserDefinedFunction
from pyspark.sql.types import StringType

name = 'target_column'
udf = UserDefinedFunction(lambda x: 'new_value', StringType())
new_df = old_df.select(*[udf(column).alias(name) if column == name else column for column in old_df.columns])

new_df now has the same schema as old_df (assuming that old_df.target_column was of type StringType as well) but all values in column target_column will be new_value.

Copy a table from one database to another in Postgres

To move a table from database A to database B at your local setup, use the following command:

pg_dump -h localhost -U owner-name -p 5432 -C -t table-name database1 | psql -U owner-name -h localhost -p 5432 database2

HTML Agility pack - parsing tables

The most simple what I've found to get the XPath for a particular Element is to install FireBug extension for Firefox go to the site/webpage press F12 to bring up firebug; right select and right click the element on the page that you want to query and select "Inspect Element" Firebug will select the element in its IDE then right click the Element in Firebug and choose "Copy XPath" this function will give you the exact XPath Query you need to get the element you want using HTML Agility Library.

Android studio: emulator is running but not showing up in Run App "choose a running device"

Probably the project you are running is not compatible (API version/Hardware requirements) with the emulator settings. Check in your build.gradle file if the targetSDK and minimumSdk version is lower or equal to the sdk version of your Emulator.

You should also uncheck Tools > Android > Enable ADB Integration

If your case is different then restart your Android Studio and run the emulator again.

Convert a number into a Roman Numeral in javaScript

Well, it seems as I'm not the only one that got stuck on this challenge at FreeCodeCamp. But I would like to share my code with you anyhow. It's quite performant, almost 10% faster than the top-voted solution here (I haven't tested all the others and I guess mine is not the fastest). But I think it's clean and easy to understand:

function convertToRoman(num) {
    // Some error checking first
    if (+num > 9999) {
        console.error('Error (fn convertToRoman(num)): Can\'t convert numbers greater than 9999. You provided: ' + num);
        return false;
    }
    if (!+num) {
        console.error('Error (fn convertToRoman(num)): \'num\' must be a number or number in a string. You provided: ' + num);
        return false;
    }

    // Convert the number into
    // an array of the numbers
    var arr = String(+num).split('').map((el) => +el );

    // Keys to the roman numbers
    var keys = {
        1: ['', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX'],
        2: ['', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC'],
        3: ['', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM'],
        4: ['', 'M', 'MM', 'MMM', 'MMMM', 'MMMMM', 'MMMMMM', 'MMMMMMM', 'MMMMMMMM', 'MMMMMMMMM'],
    };

    // Variables to help building the roman string
    var i = arr.length;
    var roman = '';

    // Iterate over each number in the array and
    // build the string with the corresponding
    // roman numeral
    arr.forEach(function (el) {
        roman += keys[i][el];
        i--;
    });

    // Return the string
    return roman;
}

It might seem like a limitation that it only can convert numbers up to 9 999. But the fact is that from 10 000 and above a line should be provided above the literals. And that I have not solved yet.

Hope this will help you.

Reading DataSet

DataSet resembles database. DataTable resembles database table, and DataRow resembles a record in a table. If you want to add filtering or sorting options, you then do so with a DataView object, and convert it back to a separate DataTable object.

If you're using database to store your data, then you first load a database table to a DataSet object in memory. You can load multiple database tables to one DataSet, and select specific table to read from the DataSet through DataTable object. Subsequently, you read a specific row of data from your DataTable through DataRow. Following codes demonstrate the steps:

SqlCeDataAdapter da = new SqlCeDataAdapter();
DataSet ds = new DataSet();
DataTable dt = new DataTable();

da.SelectCommand = new SqlCommand(@"SELECT * FROM FooTable", connString);
da.Fill(ds, "FooTable");
dt = ds.Tables["FooTable"];

foreach (DataRow dr in dt.Rows)
{
    MessageBox.Show(dr["Column1"].ToString());
}

To read a specific cell in a row:

int rowNum // row number
string columnName = "DepartureTime";  // database table column name
dt.Rows[rowNum][columnName].ToString();

Is it safe to delete the "InetPub" folder?

If you reconfigure IIS7 to use your new location, then there's no problem. Just test that the new location is working, before deleting the old location.

Change IIS7 Inetpub path

  • Open %windir%\system32\inetsrv\config\applicationhost.config and search for

%SystemDrive%\inetpub\wwwroot

  • Change the path.

Meaning of "referencing" and "dereferencing" in C

Referencing

& is the reference operator. It will refer the memory address to the pointer variable.

Example:

int *p;
int a=5;
p=&a; // Here Pointer variable p refers to the address of integer variable a.

Dereferencing

Dereference operator * is used by the pointer variable to directly access the value of the variable instead of its memory address.

Example:

int *p;
int a=5;
p=&a;
int value=*p; // Value variable will get the value of variable a that pointer variable p pointing to.

How can I get input radio elements to horizontally align?

This also works like a charm

_x000D_
_x000D_
<form>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio" checked>Option 1_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 2_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 3_x000D_
    </label>_x000D_
  </form>
_x000D_
_x000D_
_x000D_

How to convert timestamps to dates in Bash?

This version is similar to chiborg's answer, but it eliminates the need for the external tty and cat. It uses date, but could just as easily use gawk. You can change the shebang and replace the double square brackets with single ones and this will also run in sh.

#!/bin/bash
LANG=C
if [[ -z "$1" ]]
then
    if [[ -p /dev/stdin ]]    # input from a pipe
    then
        read -r p
    else
        echo "No timestamp given." >&2
        exit
    fi
else
    p=$1
fi
date -d "@$p" +%c

Concatenate string with field value in MySQL

SELECT ..., CONCAT( 'category_id=', tableOne.category_id) as query2  FROM tableOne 
LEFT JOIN tableTwo
ON tableTwo.query = query2

What's the difference between KeyDown and KeyPress in .NET?

The KeyPress event is not raised by noncharacter keys; however, the noncharacter keys do raise the KeyDown and KeyUp events.

https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.control.keypress

iPhone get SSID without private library

This works for me on the device (not simulator). Make sure you add the systemconfiguration framework.

#import <SystemConfiguration/CaptiveNetwork.h>

+ (NSString *)currentWifiSSID {
    // Does not work on the simulator.
    NSString *ssid = nil;
    NSArray *ifs = (__bridge_transfer id)CNCopySupportedInterfaces();
    for (NSString *ifnam in ifs) {
        NSDictionary *info = (__bridge_transfer id)CNCopyCurrentNetworkInfo((__bridge CFStringRef)ifnam);
        if (info[@"SSID"]) {
            ssid = info[@"SSID"];
        }
    }
    return ssid;
}

Socket accept - "Too many open files"

There are multiple places where Linux can have limits on the number of file descriptors you are allowed to open.

You can check the following:

cat /proc/sys/fs/file-max

That will give you the system wide limits of file descriptors.

On the shell level, this will tell you your personal limit:

ulimit -n

This can be changed in /etc/security/limits.conf - it's the nofile param.

However, if you're closing your sockets correctly, you shouldn't receive this unless you're opening a lot of simulataneous connections. It sounds like something is preventing your sockets from being closed appropriately. I would verify that they are being handled properly.

github markdown colspan

Compromise minimum solution:

| One    | Two | Three | Four    | Five  | Six 
| -
| Span <td colspan=3>triple  <td colspan=2>double

So you can omit closing </td> for speed, ?r can leave for consistency.

Result from http://markdown-here.com/livedemo.html : markdown table with colspan

Works in Jupyter Markdown.

Update:

As of 2019 year all pipes in the second line are compulsory in Jupyter Markdown.

| One    | Two | Three | Four    | Five  | Six
|-|-|-|-|-|-
| Span <td colspan=3>triple  <td colspan=2>double

minimally:

One    | Two | Three | Four    | Five  | Six
-|||||-
Span <td colspan=3>triple  <td colspan=2>double

Twitter Bootstrap hide css class and jQuery

I agree with dfsq if all you want to do is show the button. If you want to switch between hiding and showing the button however, it is easier to use:

$("#buttonEditComment").toggleClass("hide");

How do I select the "last child" with a specific class name in CSS?

This can be done using an attribute selector.

[class~='list']:last-of-type  {
    background: #000;
}

The class~ selects a specific whole word. This allows your list item to have multiple classes if need be, in various order. It'll still find the exact class "list" and apply the style to the last one.

See a working example here: http://codepen.io/chasebank/pen/ZYyeab

Read more on attribute selectors:

http://css-tricks.com/attribute-selectors/ http://www.w3schools.com/css/css_attribute_selectors.asp

Querying a linked sql server

If linked server name is IP address following code is true:

select * from [1.2.3.4,1433\MSSQLSERVER].test.dbo.Table1

It's just, note [] around IP address section.

Passing an Array as Arguments, not an Array, in PHP

For sake of completeness, as of PHP 5.1 this works, too:

<?php
function title($title, $name) {
    return sprintf("%s. %s\r\n", $title, $name);
}
$function = new ReflectionFunction('title');
$myArray = array('Dr', 'Phil');
echo $function->invokeArgs($myArray);  // prints "Dr. Phil"
?>

See: http://php.net/reflectionfunction.invokeargs

For methods you use ReflectionMethod::invokeArgs instead and pass the object as first parameter.

How to create a new schema/new user in Oracle Database 11g?

SQL> select Username from dba_users
  2  ;

USERNAME
------------------------------
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL
MDSYS

USERNAME
------------------------------
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR

16 rows selected.

SQL> create user testdb identified by password;

User created.

SQL> select username from dba_users;

USERNAME
------------------------------
TESTDB
SYS
SYSTEM
ANONYMOUS
APEX_PUBLIC_USER
FLOWS_FILES
APEX_040000
OUTLN
DIP
ORACLE_OCM
XS$NULL

USERNAME
------------------------------
MDSYS
CTXSYS
DBSNMP
XDB
APPQOSSYS
HR

17 rows selected.

SQL> grant create session to testdb;

Grant succeeded.

SQL> create tablespace testdb_tablespace
  2  datafile 'testdb_tabspace.dat'
  3  size 10M autoextend on;

Tablespace created.

SQL> create temporary tablespace testdb_tablespace_temp
  2  tempfile 'testdb_tabspace_temp.dat'
  3  size 5M autoextend on;

Tablespace created.

SQL> drop user testdb;

User dropped.

SQL> create user testdb
  2  identified by password
  3  default tablespace testdb_tablespace
  4  temporary tablespace testdb_tablespace_temp;

User created.

SQL> grant create session to testdb;

Grant succeeded.

SQL> grant create table to testdb;

Grant succeeded.

SQL> grant unlimited tablespace to testdb;

Grant succeeded.

SQL>

PHP array delete by value (not key)

One interesting way is by using array_keys():

foreach (array_keys($messages, 401, true) as $key) {
    unset($messages[$key]);
}

The array_keys() function takes two additional parameters to return only keys for a particular value and whether strict checking is required (i.e. using === for comparison).

This can also remove multiple array items with the same value (e.g. [1, 2, 3, 3, 4]).

CSS - how to make image container width fixed and height auto stretched

No, you can't make the img stretch to fit the div and simultaneously achieve the inverse. You would have an infinite resizing loop. However, you could take some notes from other answers and implement some min and max dimensions but that wasn't the question.

You need to decide if your image will scale to fit its parent or if you want the div to expand to fit its child img.

Using this block tells me you want the image size to be variable so the parent div is the width an image scales to. height: auto is going to keep your image aspect ratio in tact. if you want to stretch the height it needs to be 100% like this fiddle.

img {
    width: 100%;
    height: auto;
}

http://jsfiddle.net/D8uUd/1/

D3 transform scale and translate

Scott Murray wrote a great explanation of this[1]. For instance, for the code snippet:

svg.append("g")
    .attr("class", "axis")
    .attr("transform", "translate(0," + h + ")")
    .call(xAxis);

He explains using the following:

Note that we use attr() to apply transform as an attribute of g. SVG transforms are quite powerful, and can accept several different kinds of transform definitions, including scales and rotations. But we are keeping it simple here with only a translation transform, which simply pushes the whole g group over and down by some amount.

Translation transforms are specified with the easy syntax of translate(x,y), where x and y are, obviously, the number of horizontal and vertical pixels by which to translate the element.

[1]: From Chapter 8, "Cleaning it up" of Interactive Data Visualization for the Web, which used to be freely available and is now behind a paywall.

Force browser to refresh css, javascript, etc

I have decided that since browsers do not check for new versions of css and js files, I rename my css and js directories whenever I make a change. I use css1 to css9 and js1 to js9 as the directory names. When I get to 9, I next start over at 1. It is a pain, but it works perfectly every time. It is ridiculous to have to tell users to type .

"The semaphore timeout period has expired" error for USB connection

This error could also appear if you are having network latency or internet or local network problems. Bridged connections that have a failing counterpart may be the culprit as well.

Getting attribute of element in ng-click function in angularjs

Try passing it directly to the ng-click function:

<div class="col-lg-1 text-center">
    <span class="glyphicon glyphicon-trash" data="{{event.id}}"
          ng-click="deleteEvent(event.id)"></span>
</div>

Then it should be available in your handler:

$scope.deleteEvent=function(idPassedFromNgClick){
    console.log(idPassedFromNgClick);
}

Here's an example

In Node.js, how do I "include" functions from my other files?

Another method when using node.js and express.js framework

var f1 = function(){
   console.log("f1");
}
var f2 = function(){
   console.log("f2");
}

module.exports = {
   f1 : f1,
   f2 : f2
}

store this in a js file named s and in the folder statics

Now to use the function

var s = require('../statics/s');
s.f1();
s.f2();

Java: Identifier expected

Try it like this instead, move your myclass items inside a main method:

    class UserInput {
      public void name() {
        System.out.println("This is a test.");
      }
    }

    public class MyClass {

        public static void main( String args[] )
        {
            UserInput input = new UserInput();
            input.name();
        }

    }

Calling one method from another within same class in Python

To call the method, you need to qualify function with self.. In addition to that, if you want to pass a filename, add a filename parameter (or other name you want).

class MyHandler(FileSystemEventHandler):

    def on_any_event(self, event):
        srcpath = event.src_path
        print (srcpath, 'has been ',event.event_type)
        print (datetime.datetime.now())
        filename = srcpath[12:]
        self.dropbox_fn(filename) # <----

    def dropbox_fn(self, filename):  # <-----
        print('In dropbox_fn:', filename)

Query to check index on a table

If you're using MySQL you can run SHOW KEYS FROM table or SHOW INDEXES FROM table

Convert a Unicode string to a string in Python (containing extra symbols)

file contain unicode-esaped string

\"message\": \"\\u0410\\u0432\\u0442\\u043e\\u0437\\u0430\\u0446\\u0438\\u044f .....\",

for me

 f = open("56ad62-json.log", encoding="utf-8")
 qq=f.readline() 

 print(qq)                          
 {"log":\"message\": \"\\u0410\\u0432\\u0442\\u043e\\u0440\\u0438\\u0437\\u0430\\u0446\\u0438\\u044f \\u043f\\u043e\\u043b\\u044c\\u0437\\u043e\\u0432\\u0430\\u0442\\u0435\\u043b\\u044f\"}

(qq.encode().decode("unicode-escape").encode().decode("unicode-escape")) 
# '{"log":"message": "??????????? ????????????"}\n'

Easiest way to compare arrays in C#

If you don't want to compare the order but you do want to compare the count of each item, including handling null values, then I've written an extension method for this.

It gives for example the following results:

new int?[]{  }.IgnoreOrderComparison(new int?{ });                            // true
new int?[]{ 1 }.IgnoreOrderComparison(new int?{ });                           // false
new int?[]{ }.IgnoreOrderComparison(new int?{ 1 });                           // false
new int?[]{ 1 }.IgnoreOrderComparison(new int?{ 1 });                         // true
new int?[]{ 1, 2 }.IgnoreOrderComparison(new int?{ 2, 1 });                   // true
new int?[]{ 1, 2, null }.IgnoreOrderComparison(new int?{ 2, 1 });             // false
new int?[]{ 1, 2, null }.IgnoreOrderComparison(new int?{ null, 2, 1 });       // true
new int?[]{ 1, 2, null, null }.IgnoreOrderComparison(new int?{ null, 2, 1 }); // false
new int?[]{ 2 }.IgnoreOrderComparison(new int?{ 2, 2 });                      // false
new int?[]{ 2, 2 }.IgnoreOrderComparison(new int?{ 2, 2 });                   // true

Here is the code:

public static class ArrayComparisonExtensions
{
    public static bool IgnoreOrderComparison<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second) =>
        IgnoreOrderComparison(first, second, EqualityComparer<TSource>.Default);

    public static bool IgnoreOrderComparison<TSource>(this IEnumerable<TSource> first, IEnumerable<TSource> second, IEqualityComparer<TSource> comparer)
    {
        var a = ToDictionary(first, out var firstNullCount);
        var b = ToDictionary(second, out var secondNullCount);

        if (a.Count != b.Count)
            return false;

        if (firstNullCount != secondNullCount)
            return false;

        foreach (var item in a)
        {
            if (b.TryGetValue(item.Key, out var count) && item.Value == count)
                continue;
            return false;
        }


        return true;

        Dictionary<TSource, int> ToDictionary(IEnumerable<TSource> items, out int nullCount)
        {
            nullCount = 0;
            var result = new Dictionary<TSource, int>(comparer);
            foreach (var item in items)
            {
                if (item is null)
                    nullCount++;
                else if (result.TryGetValue(item, out var count))
                    result[item] = count + 1;
                else
                    result[item] = 1;
            }

            return result;
        }
    }
}

It only enumerates each enumerable once, but it does create a dictionary for each enumerable and iterates those once too. I'd be interested in ways to improve this.

Pass Additional ViewData to a Strongly-Typed Partial View

Create another class which contains your strongly typed class.

Add your new stuff to the class and return it in the view.

Then in the view, ensure you inherit your new class and change the bits of code that will now be in error. namely the references to your fields.

Hope this helps. If not then let me know and I'll post specific code.

Python - TypeError: 'int' object is not iterable

This is very simple you are trying to convert an integer to a list object !!! of course it will fail and it should ...

To demonstrate/prove this to you by using the example you provided ...just use type function for each case as below and the results will speak for itself !

>>> type(cow)
<class 'range'>
>>> 
>>> type(cow[0])
<class 'int'>
>>> 
>>> type(0)
<class 'int'>
>>> 
>>> >>> list(0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>> 

ActiveRecord: size vs count

As the other answers state:

  • count will perform an SQL COUNT query
  • length will calculate the length of the resulting array
  • size will try to pick the most appropriate of the two to avoid excessive queries

But there is one more thing. We noticed a case where size acts differently to count/lengthaltogether, and I thought I'd share it since it is rare enough to be overlooked.

  • If you use a :counter_cache on a has_many association, size will use the cached count directly, and not make an extra query at all.

    class Image < ActiveRecord::Base
      belongs_to :product, counter_cache: true
    end
    
    class Product < ActiveRecord::Base
      has_many :images
    end
    
    > product = Product.first  # query, load product into memory
    > product.images.size      # no query, reads the :images_count column
    > product.images.count     # query, SQL COUNT
    > product.images.length    # query, loads images into memory
    

This behaviour is documented in the Rails Guides, but I either missed it the first time or forgot about it.

Installing packages in Sublime Text 2

Here is a link to a shorter and to the point description: http://www.granneman.com/webdev/editors/sublime-text/packages/how-to-install-and-use-package-control/

The steps are:

  1. Install package control.
  2. Go to http://wbond.net/sublime_packages/package_control/installation and grab the install code.
  3. In Sublime Text 2 open the console (Ctrl+`) and paste the code.
  4. Restart Sublime Text 2.
  5. Open command palette via Command+Shift+P (Mac OSX) or Ctrl+Shift+P (Windows).
  6. Start typing Package Control and choose the package you are looking for.

C++ "Access violation reading location" Error

Vertex *f=(findvertex(from));
if(!f) {
    cerr << "vertex not found" << endl;
    exit(1) // or return;
}

Because findVertex can return NULL if it can't find the vertex.

Otherwise this f->adj; is trying to do

NULL->adj;

Which causes access violation.

How to move certain commits to be based on another branch in git?

You can use git cherry-pick to just pick the commit that you want to copy over.

Probably the best way is to create the branch out of master, then in that branch use git cherry-pick on the 2 commits from quickfix2 that you want.

How can I debug what is causing a connection refused or a connection time out?

Use a packet analyzer to intercept the packets to/from somewhere.com. Studying those packets should tell you what is going on.

Time-outs or connections refused could mean that the remote host is too busy.

How to implement infinity in Java?

Only Double and Float type support POSITIVE_INFINITY constant.

Convert Data URI to File then append to FormData

Thanks to @Stoive and @vava720 I combined the two in this way, avoiding to use the deprecated BlobBuilder and ArrayBuffer

function dataURItoBlob(dataURI) {
    'use strict'
    var byteString, 
        mimestring 

    if(dataURI.split(',')[0].indexOf('base64') !== -1 ) {
        byteString = atob(dataURI.split(',')[1])
    } else {
        byteString = decodeURI(dataURI.split(',')[1])
    }

    mimestring = dataURI.split(',')[0].split(':')[1].split(';')[0]

    var content = new Array();
    for (var i = 0; i < byteString.length; i++) {
        content[i] = byteString.charCodeAt(i)
    }

    return new Blob([new Uint8Array(content)], {type: mimestring});
}

Fixing a systemd service 203/EXEC failure (no such file or directory)

I ran across a Main process exited, code=exited, status=203/EXEC today as well and my bug was that I forgot to add the executable bit to the file.

regex error - nothing to repeat

Beyond the bug that was discovered and fixed, I'll just note that the error message sre_constants.error: nothing to repeat is a bit confusing. I was trying to use r'?.*' as a pattern, and thought it was complaining for some strange reason about the *, but the problem is actually that ? is a way of saying "repeat zero or one times". So I needed to say r'\?.*'to match a literal ?

SQL Server: Cannot insert an explicit value into a timestamp column

If you have a need to copy the exact same timestamp data, change the data type in the destination table from timestamp to binary(8) -- i used varbinary(8) and it worked fine.

This obviously breaks any timestamp functionality in the destination table, so make sure you're ok with that first.

How to split a string literal across multiple lines in C / Objective-C?

You can also do:

NSString * query = @"SELECT * FROM foo "
                   @"WHERE "
                     @"bar = 42 "
                     @"AND baz = datetime() "
                   @"ORDER BY fizbit ASC";

What is the best way to add options to a select from a JavaScript object with jQuery?

The simple way is:

$('#SelectId').html("<option value='0'>select</option><option value='1'>Laguna</option>");

What permission do I need to access Internet from an Android application?

To request for internet permission in your code you must add these to your AndroidManifest.xml file

<uses-permission android:name="android.permission.INTERNET" />

For more detail explanation goto https://developer.android.com/training/basics/network-ops/connecting

What is href="#" and why is it used?

About hyperlinks:

The main use of anchor tags - <a></a> - is as hyperlinks. That basically means that they take you somewhere. Hyperlinks require the href property, because it specifies a location.

Hash:

A hash - # within a hyperlink specifies an html element id to which the window should be scrolled.

href="#some-id" would scroll to an element on the current page such as <div id="some-id">.

href="//site.com/#some-id" would go to site.com and scroll to the id on that page.

Scroll to Top:

href="#" doesn't specify an id name, but does have a corresponding location - the top of the page. Clicking an anchor with href="#" will move the scroll position to the top.

See this demo.

This is the expected behavior according to the w3 documentation.

Hyperlink placeholders:

An example where a hyperlink placeholder makes sense is within template previews. On single page demos for templates, I have often seen <a href="#"> so that the anchor tag is a hyperlink, but doesn't go anywhere. Why not leave the href property blank? A blank href property is actually a hyperlink to the current page. In other words, it will cause a page refresh. As I discussed, href="#" is also a hyperlink, and causes scrolling. Therefore, the best solution for hyperlink placeholders is actually href="#!" The idea here is that there hopefully isn't an element on the page with id="!" (who does that!?) and the hyperlink therefore refers to nothing - so nothing happens.

About anchor tags:

Another question that you may be wondering is, "Why not just leave the href property off?". A common response I've heard is that the href property is required, so it "should" be present on anchors. This is FALSE! The href property is required only for an anchor to actually be a hyperlink! Read this from w3. So, why not just leave it off for placeholders? Browsers render default styles for elements and will change the default style of an anchor tag that doesn't have the href property. Instead, it will be considered like regular text. It even changes the browser's behavior regarding the element. The status bar (bottom of the screen) will not be displayed when hovering on an anchor without the href property. It is best to use a placeholder href value on an anchor to ensure it is treated as a hyperlink.

See this demo demonstrating style and behavior differences.

Bitwise and in place of modulus operator

This is specifically a special case because computers represent numbers in base 2. This is generalizable:

(number)base % basex

is equivilent to the last x digits of (number)base.

Submitting the value of a disabled input field

I wanna Disable an Input Field on a form and when i submit the form the values from the disabled form is not submitted.

Use Case: i am trying to get Lat Lng from Google Map and wanna Display it.. but dont want the user to edit it.

You can use the readonly property in your input field

<input type="text" readonly="readonly" />

Split string with multiple delimiters in Python

Here's a safe way for any iterable of delimiters, using regular expressions:

>>> import re
>>> delimiters = "a", "...", "(c)"
>>> example = "stackoverflow (c) is awesome... isn't it?"
>>> regexPattern = '|'.join(map(re.escape, delimiters))
>>> regexPattern
'a|\\.\\.\\.|\\(c\\)'
>>> re.split(regexPattern, example)
['st', 'ckoverflow ', ' is ', 'wesome', " isn't it?"]

re.escape allows to build the pattern automatically and have the delimiters escaped nicely.

Here's this solution as a function for your copy-pasting pleasure:

def split(delimiters, string, maxsplit=0):
    import re
    regexPattern = '|'.join(map(re.escape, delimiters))
    return re.split(regexPattern, string, maxsplit)

If you're going to split often using the same delimiters, compile your regular expression beforehand like described and use RegexObject.split.


If you'd like to leave the original delimiters in the string, you can change the regex to use a lookbehind assertion instead:

>>> import re
>>> delimiters = "a", "...", "(c)"
>>> example = "stackoverflow (c) is awesome... isn't it?"
>>> regexPattern = '|'.join('(?<={})'.format(re.escape(delim)) for delim in delimiters)
>>> regexPattern
'(?<=a)|(?<=\\.\\.\\.)|(?<=\\(c\\))'
>>> re.split(regexPattern, example)
['sta', 'ckoverflow (c)', ' is a', 'wesome...', " isn't it?"]

(replace ?<= with ?= to attach the delimiters to the righthand side, instead of left)

How to tell when UITableView has completed ReloadData?

Try this way it will work

[tblViewTerms performSelectorOnMainThread:@selector(dataLoadDoneWithLastTermIndex:) withObject:lastTermIndex waitUntilDone:YES];waitUntilDone:YES];

@interface UITableView (TableViewCompletion)

-(void)dataLoadDoneWithLastTermIndex:(NSNumber*)lastTermIndex;

@end

@implementation UITableView(TableViewCompletion)

-(void)dataLoadDoneWithLastTermIndex:(NSNumber*)lastTermIndex
{
    NSLog(@"dataLoadDone");


NSIndexPath* indexPath = [NSIndexPath indexPathForRow: [lastTermIndex integerValue] inSection: 0];

[self selectRowAtIndexPath:indexPath animated:YES scrollPosition:UITableViewScrollPositionNone];

}
@end

I will execute when table is completely loaded

Other Solution is you can subclass UITableView

How to overlay density plots in R?

You can use the ggjoy package. Let's say that we have three different beta distributions such as:

set.seed(5)
b1<-data.frame(Variant= "Variant 1", Values = rbeta(1000, 101, 1001))
b2<-data.frame(Variant= "Variant 2", Values = rbeta(1000, 111, 1011))
b3<-data.frame(Variant= "Variant 3", Values = rbeta(1000, 11, 101))


df<-rbind(b1,b2,b3)

You can get the three different distributions as follows:

library(tidyverse)
library(ggjoy)


ggplot(df, aes(x=Values, y=Variant))+
    geom_joy(scale = 2, alpha=0.5) +
    scale_y_discrete(expand=c(0.01, 0)) +
    scale_x_continuous(expand=c(0.01, 0)) +
    theme_joy()

enter image description here

What does the star operator mean, in a function call?

One small point: these are not operators. Operators are used in expressions to create new values from existing values (1+2 becomes 3, for example. The * and ** here are part of the syntax of function declarations and calls.

Evaluate if list is empty JSTL

There's also the function tags, a bit more flexible:

<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<c:if test="${fn:length(list) > 0}">

And here's the tag documentation.

How to pass an event object to a function in Javascript?

Although this is the accepted answer, toto_tico's answer below is better :)

Try making the onclick js use 'return' to ensure the desired return value gets used...

<button type="button" value="click me" onclick="return check_me();" />

Error in <my code> : object of type 'closure' is not subsettable

You don't define the vector, url, before trying to subset it. url is also a function in the base package, so url[i] is attempting to subset that function... which doesn't make sense.

You probably defined url in your prior R session, but forgot to copy that code to your script.

Node.js console.log() not logging anything

Using modern --inspect with node the console.log is captured and relayed to the browser.

node --inspect myApp.js

or to capture early logging --inspect-brk can be used to stop the program on the first line of the first module...

node --inspect-brk myApp.js

How to add button inside input

_x000D_
_x000D_
.flexContainer {_x000D_
    display: flex;_x000D_
}_x000D_
_x000D_
.inputField {_x000D_
    flex: 1;_x000D_
}
_x000D_
<div class="flexContainer">_x000D_
    <input type="password" class="inputField">_x000D_
    <button type="submit"><img src="arrow.png" alt="Arrow Icon"></button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Calling a Javascript Function from Console

you can invoke it using window.function_name() or directly function_name()

Equivalent of .bat in mac os

May be you can find answer here? Equivalent of double-clickable .sh and .bat on Mac?

Usually you can create bash script for Mac OS, where you put similar commands as in batch file. For your case create bash file and put same command, but change back-slashes with regular ones.

Your file will look something like:

#! /bin/bash
java -cp  ".;./supportlibraries/Framework_Core.jar;./supportlibraries/Framework_DataTable.jar;./supportlibraries/Framework_Reporting.jar;./supportlibraries/Framework_Utilities.jar;./supportlibraries/poi-3.8-20120326.jar;PATH_TO_YOUR_SELENIUM_SERVER_FOLDER/selenium-server-standalone-2.19.0.jar" allocator.testTrack

Change folders in path above to relevant one.

Then make this script executable: open terminal and navigate to folder with your script. Then change read-write-execute rights for this file running command:

chmod 755 scriptname.sh

Then you can run it like any other regular script: ./scriptname.sh

or you can run it passing file to bash:

bash scriptname.sh

Sort array of objects by string property value

Given the original example:

var objs = [ 
    { first_nom: 'Lazslo', last_nom: 'Jamf'     },
    { first_nom: 'Pig',    last_nom: 'Bodine'   },
    { first_nom: 'Pirate', last_nom: 'Prentice' }
];

Sort by multiple fields:

objs.sort(function(left, right) {
    var last_nom_order = left.last_nom.localeCompare(right.last_nom);
    var first_nom_order = left.first_nom.localeCompare(right.first_nom);
    return last_nom_order || first_nom_order;
});

Notes

  • a.localeCompare(b) is universally supported and returns -1,0,1 if a<b,a==b,a>b respectively.
  • || in the last line gives last_nom priority over first_nom.
  • Subtraction works on numeric fields: var age_order = left.age - right.age;
  • Negate to reverse order, return -last_nom_order || -first_nom_order || -age_order;

notifyDataSetChange not working from custom adapter

Add this code

runOnUiThread(new Runnable() { public void run() {
               adapter = new CustomAdapter(anotherdata);
            adapter.notifyDataSetChanged();
            }
        });

White space showing up on right side of page when background image should extend full length of page

This question has been hanging around for a while, but none of the fixes I could find worked for me (having the same issue with ipad), but I managed my own solution which should work for most people I imagine.

Here's my code:

html {
   background: url("../images/blahblah.jpg") repeat-y;
   min-width: 100%;
   background-size: contain;
}

Enjoy!

Where to put default parameter value in C++?

You can do either, but never both. Usually you do it at function declaration and then all callers can use that default value. However you can do that at function definition instead and then only those who see the definition will be able to use the default value.

Print very long string completely in pandas dataframe

In the newer version of pandas, use:

pd.set_option('display.max_colwidth', None)

How can I find the number of elements in an array?

void numel(int array1[100][100])
{
    int count=0;
    for(int i=0;i<100;i++)
    {
        for(int j=0;j<100;j++)
        {
            if(array1[i][j]!='\0') 
            {
                count++;
                //printf("\n%d-%d",array1[i][j],count);
            }
            else 
                break;
        }
    }
    printf("Number of elements=%d",count);
}
int main()
{   
    int r,arr[100][100]={0},c;
    printf("Enter the no. of rows: ");
    scanf("%d",&r);
    printf("\nEnter the no. of columns: ");
    scanf("%d",&c);
    printf("\nEnter the elements: ");
    for(int i=0;i<r;i++)
    {
        for(int j=0;j<c;j++)
        {
            scanf("%d",&arr[i][j]);
        }
    }
    numel(arr);
}

This shows the exact number of elements in matrix irrespective of the array size you mentioned while initilasing(IF that's what you meant)

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.10:test

This error occurs if some unit test cases are failing.

In my application, certain unit tests were not compatible with Java 8 so they were failing. My error was resolved after changing jdk1.8.0_92 to jdk1.7.0_80.

The build would succeed with mvn clean install -DskipTests but this will skip the unit tests. So just ensure that you run then separately after the build is complete.

How to get query params from url in Angular 2?

now it is:

this.activatedRoute.queryParams.subscribe((params: Params) => {
  console.log(params);
});

C# Validating input for textbox on winforms

Description

There are many ways to validate your TextBox. You can do this on every keystroke, at a later time, or on the Validating event.

The Validating event gets fired if your TextBox looses focus. When the user clicks on a other Control, for example. If your set e.Cancel = true the TextBox doesn't lose the focus.

MSDN - Control.Validating Event When you change the focus by using the keyboard (TAB, SHIFT+TAB, and so on), by calling the Select or SelectNextControl methods, or by setting the ContainerControl.ActiveControl property to the current form, focus events occur in the following order

Enter

GotFocus

Leave

Validating

Validated

LostFocus

When you change the focus by using the mouse or by calling the Focus method, focus events occur in the following order:

Enter

GotFocus

LostFocus

Leave

Validating

Validated

Sample Validating Event

private void textBox1_Validating(object sender, CancelEventArgs e)
{
    if (textBox1.Text != "something")
        e.Cancel = true;
}

Update

You can use the ErrorProvider to visualize that your TextBox is not valid. Check out Using Error Provider Control in Windows Forms and C#

More Information

Bootstrap row class contains margin-left and margin-right which creates problems

Are you using Bootstrap 3? My version of the css has -15px, not -13px. In any case, I've simply done what you've down, and overwritten the style. I believe it's because the .container class has a 15px padding on the left and right, and this negative margin on the rows will pull that content back out to the edge of the container.

Run-time error '3061'. Too few parameters. Expected 1. (Access 2007)

This Message is also possible to pop up, if there is a typo in the fields on which you define a join

What jar should I include to use javax.persistence package in a hibernate based application?

If you are developing an OSGi system I would recommend you to download the "bundlefied" version from Springsource Enterprise Bundle Repository.

Otherwise its ok to use a regular jar-file containing the javax.persistence package

WordPress is giving me 404 page not found for all pages except the homepage

You may have .htaccess disallowed in webhost settings. Setting to default permalinks would work in that case.

How to use string.substr() function?

Another interesting variant question can be:

How would you make "12345" as "12 23 34 45" without using another string?

Will following do?

    for(int i=0; i < a.size()-1; ++i)
    {
        //b = a.substr(i, 2);
        c = atoi((a.substr(i, 2)).c_str());
        cout << c << " ";
    }

Which Python memory profiler is recommended?

guppy3 is quite simple to use. At some point in your code, you have to write the following:

from guppy import hpy
h = hpy()
print(h.heap())

This gives you some output like this:

Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
0  35144  27  2140412  26   2140412  26 str
1  38397  29  1309020  16   3449432  42 tuple
2    530   0   739856   9   4189288  50 dict (no owner)

You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse.

There is a graphical browser as well, written in Tk.

For Python 2.x, use Heapy.

What is the best way to left align and right align two div tags?

I used the below. The genre element will start where the DJ element ends,

<div>
<div style="width:50%; float:left">DJ</div>
<div>genre</div>
</div>

pardon the inline css.

How to center a window on the screen in Tkinter?

The simplest (but possibly inaccurate) method is to use tk::PlaceWindow, which takes the pathname of a toplevel window as an argument. The main window's pathname is .

import tkinter

root = tkinter.Tk()
root.eval('tk::PlaceWindow . center')

second_win = tkinter.Toplevel(root)
root.eval(f'tk::PlaceWindow {str(second_win)} center')

root.mainloop()

The problem

Simple solutions ignore the outermost frame with the title bar and the menu bar, which leads to a slight offset from being truly centered.

The solution

import tkinter  # Python 3

def center(win):
    """
    centers a tkinter window
    :param win: the main window or Toplevel window to center
    """
    win.update_idletasks()
    width = win.winfo_width()
    frm_width = win.winfo_rootx() - win.winfo_x()
    win_width = width + 2 * frm_width
    height = win.winfo_height()
    titlebar_height = win.winfo_rooty() - win.winfo_y()
    win_height = height + titlebar_height + frm_width
    x = win.winfo_screenwidth() // 2 - win_width // 2
    y = win.winfo_screenheight() // 2 - win_height // 2
    win.geometry('{}x{}+{}+{}'.format(width, height, x, y))
    win.deiconify()

if __name__ == '__main__':
    root = tkinter.Tk()
    root.attributes('-alpha', 0.0)
    menubar = tkinter.Menu(root)
    filemenu = tkinter.Menu(menubar, tearoff=0)
    filemenu.add_command(label="Exit", command=root.destroy)
    menubar.add_cascade(label="File", menu=filemenu)
    root.config(menu=menubar)
    frm = tkinter.Frame(root, bd=4, relief='raised')
    frm.pack(fill='x')
    lab = tkinter.Label(frm, text='Hello World!', bd=4, relief='sunken')
    lab.pack(ipadx=4, padx=4, ipady=4, pady=4, fill='both')
    center(root)
    root.attributes('-alpha', 1.0)
    root.mainloop()

With tkinter you always want to call the update_idletasks() method
directly before retrieving any geometry, to ensure that the values returned are accurate.

There are four methods that allow us to determine the outer-frame's dimensions.
winfo_rootx() will give us the window's top left x coordinate, excluding the outer-frame.
winfo_x() will give us the outer-frame's top left x coordinate.
Their difference is the outer-frame's width.

frm_width = win.winfo_rootx() - win.winfo_x()
win_width = win.winfo_width() + (2*frm_width)

The difference between winfo_rooty() and winfo_y() will be our title-bar / menu-bar's height.

titlebar_height = win.winfo_rooty() - win.winfo_y()
win_height = win.winfo_height() + (titlebar_height + frm_width)

You set the window's dimensions and the location with the geometry method. The first half of the geometry string is the window's width and height excluding the outer-frame,
and the second half is the outer-frame's top left x and y coordinates.

win.geometry(f'{width}x{height}+{x}+{y}')

You see the window move

One way to prevent seeing the window move across the screen is to use .attributes('-alpha', 0.0) to make the window fully transparent and then set it to 1.0 after the window has been centered. Using withdraw() or iconify() later followed by deiconify() doesn't seem to work well, for this purpose, on Windows 7. I use deiconify() as a trick to activate the window.


Making it optional

You might want to consider providing the user with an option to center the window, and not center by default; otherwise, your code can interfere with the window manager's functions. For example, xfwm4 has smart placement, which places windows side by side until the screen is full. It can also be set to center all windows, in which case you won't have the problem of seeing the window move (as addressed above).


Multiple monitors

If the multi-monitor scenario concerns you, then you can either look into the screeninfo project, or look into what you can accomplish with Qt (PySide2) or GTK (PyGObject), and then use one of those toolkits instead of tkinter. Combining GUI toolkits results in an unreasonably large dependency.

Get the value of bootstrap Datetimepicker in JavaScript

I tried all the above methods and I did not get the value properly in the same format, then I found this.

$("#datetimepicker1").find("input")[1].value;

The above code will return the value in the same format as in the datetime picker.

This may help you guys in the future.

Hope this was helpful..

React router nav bar example

Yes, Daniel is correct, but to expand upon his answer, your primary app component would need to have a navbar component within it. That way, when you render the primary app (any page under the '/' path), it would also display the navbar. I am guessing that you wouldn't want your login page to display the navbar, so that shouldn't be a nested component, and should instead be by itself. So your routes would end up looking something like this:

<Router>
  <Route path="/" component={App}>
    <Route path="page1" component={Page1} />
    <Route path="page2" component={Page2} />
  </Route>
  <Route path="/login" component={Login} />
</Router>

And the other components would look something like this:

var NavBar = React.createClass({
  render() {
    return (
      <div>
        <ul>
          <a onClick={() => history.push('page1') }>Page 1</a>
          <a onClick={() => history.push('page2') }>Page 2</a>
        </ul>
      </div>
    )
  }
});

var App = React.createClass({
  render() {
    return (
      <div>
        <NavBar />
        <div>Other Content</div>
        {this.props.children}
      </div>
    )
  }
});

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

Instead of thinking of it as 'extracting', I like to think of it as 'isolating'. Once the desired bits are isolated, you can do what you will with them.

To isolate any set of bits, apply an AND mask.

If you want the last X bits of a value, there is a simple trick that can be used.

unsigned  mask;
mask = (1 << X) - 1;
lastXbits = value & mask;

If you want to isolate a run of X bits in the middle of 'value' starting at 'startBit' ...

unsigned  mask;
mask = ((1 << X) - 1) << startBit;
isolatedXbits = value & mask;

Hope this helps.

What are the differences between WCF and ASMX web services?

Keith Elder nicely compares ASMX to WCF here. Check it out.

Another comparison of ASMX and WCF can be found here - I don't 100% agree with all the points there, but it might give you an idea.

WCF is basically "ASMX on stereoids" - it can be all that ASMX could - plus a lot more!.

ASMX is:

  • easy and simple to write and configure
  • only available in IIS
  • only callable from HTTP

WCF can be:

  • hosted in IIS, a Windows Service, a Winforms application, a console app - you have total freedom
  • used with HTTP (REST and SOAP), TCP/IP, MSMQ and many more protocols

In short: WCF is here to replace ASMX fully.

Check out the WCF Developer Center on MSDN.

Update: link seems to be dead - try this: What Is Windows Communication Foundation?

PowerShell says "execution of scripts is disabled on this system."

In PowerShell 2.0, the execution policy was set to disabled by default.

From then on, the PowerShell team has made a lot of improvements, and they are confident that users will not break things much while running scripts. So from PowerShell 4.0 onward, it is enabled by default.

In your case, type Set-ExecutionPolicy RemoteSigned from the PowerShell console and say yes.

Try-catch speeding up my code?

I'd have put this in as a comment as I'm really not certain that this is likely to be the case, but as I recall it doesn't a try/except statement involve a modification to the way the garbage disposal mechanism of the compiler works, in that it clears up object memory allocations in a recursive way off the stack. There may not be an object to be cleared up in this case or the for loop may constitute a closure that the garbage collection mechanism recognises sufficient to enforce a different collection method. Probably not, but I thought it worth a mention as I hadn't seen it discussed anywhere else.

C++ preprocessor __VA_ARGS__ number of arguments

If you are using C++11, and you need the value as a C++ compile-time constant, a very elegant solution is this:

#include <tuple>

#define MACRO(...) \
    std::cout << "num args: " \
    << std::tuple_size<decltype(std::make_tuple(__VA_ARGS__))>::value \
    << std::endl;

Please note: the counting happens entirely at compile time, and the value can be used whenever compile-time integer is required, for instance as a template parameter to std::array.

What does a just-in-time (JIT) compiler do?

After the byte code (which is architecture neutral) has been generated by the Java compiler, the execution will be handled by the JVM (in Java). The byte code will be loaded in to JVM by the loader and then each byte instruction is interpreted.

When we need to call a method multiple times, we need to interpret the same code many times and this may take more time than is needed. So we have the JIT (just-in-time) compilers. When the byte has been is loaded in to JVM (its run time), the whole code will be compiled rather than interpreted, thus saving time.

JIT compilers works only during run time, so we do not have any binary output.

How to override the properties of a CSS class using another CSS class

There are different ways in which properties can be overridden. Assuming you have

.left { background: blue }

e.g. any of the following would override it:

a.background-none { background: none; }
body .background-none { background: none; }
.background-none { background: none !important; }

The first two “win” by selector specificity; the third one wins by !important, a blunt instrument.

You could also organize your style sheets so that e.g. the rule

.background-none { background: none; }

wins simply by order, i.e. by being after an otherwise equally “powerful” rule. But this imposes restrictions and requires you to be careful in any reorganization of style sheets.

These are all examples of the CSS Cascade, a crucial but widely misunderstood concept. It defines the exact rules for resolving conflicts between style sheet rules.

P.S. I used left and background-none as they were used in the question. They are examples of class names that should not be used, since they reflect specific rendering and not structural or semantic roles.

Changing all files' extensions in a folder with one command on Windows

I know this is so old, but i've landed on it , and the provided answers didn't works for me on powershell so after searching found this solution

to do it in powershell

Get-ChildItem -Path C:\Demo -Filter *.txt | Rename-Item -NewName {[System.IO.Path]::ChangeExtension($_.Name, ".old")}

credit goes to http://powershell-guru.com/powershell-tip-108-bulk-rename-extensions-of-files/

Python-Requests close http connection

please use response.close() to close to avoid "too many open files" error

for example:

r = requests.post("https://stream.twitter.com/1/statuses/filter.json", data={'track':toTrack}, auth=('username', 'passwd'))
....
r.close()

How to convert a Bitmap to Drawable in android?

Having seen a large amount of issues with bitmaps incorrectly scaling when converted to a BitmapDrawable, the general way to convert should be:

Drawable d = new BitmapDrawable(getResources(), bitmap);

Without the Resources reference, the bitmap may not render properly, even when scaled correctly. There are numerous questions on here which would be solved simply by using this method rather than a straight call with only the bitmap argument.

How to find the foreach index?

It should be noted that you can call key() on any array to find the current key its on. As you can guess current() will return the current value and next() will move the array's pointer to the next element.

What's the difference between unit, functional, acceptance, and integration tests?

I will explain you this with a practical example and no theory stuff:

A developer writes the code. No GUI is implemented yet. The testing at this level verifies that the functions work correctly and the data types are correct. This phase of testing is called Unit testing.

When a GUI is developed, and application is assigned to a tester, he verifies business requirements with a client and executes the different scenarios. This is called functional testing. Here we are mapping the client requirements with application flows.

Integration testing: let's say our application has two modules: HR and Finance. HR module was delivered and tested previously. Now Finance is developed and is available to test. The interdependent features are also available now, so in this phase, you will test communication points between the two and will verify they are working as requested in requirements.

Regression testing is another important phase, which is done after any new development or bug fixes. Its aim is to verify previously working functions.

How to make a launcher

They're examples provided by the Android team, if you've already loaded Samples, you can import Home screen replacement sample by following these steps.

File > New > Other >Android > Android Sample Project > Android x.x > Home > Finish

But if you do not have samples loaded, then download it using the below steps

Windows > Android SDK Manager > chooses "Sample for SDK" for SDK you need it > Install package > Accept License > Install

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

I find, if the data is imported, you may need to use the trim command on top of it, to get your details. =LEFT(TRIM(B2),8) In my case, I was using it to find a IP range. 10.3.44.44 with mask 255.255.255.0, so response is: 10.3.44 Kind of handy.

Draggable div without jQuery UI

Dragging like jQueryUI: JsFiddle

You can drag the element from any point without weird centering.

$(document).ready(function() {

        var $body = $('body');
        var $target = null;
        var isDraggEnabled = false;

        $body.on("mousedown", "div", function(e) {

            $this = $(this);
            isDraggEnabled = $this.data("draggable");

            if (isDraggEnabled) {
                if(e.offsetX==undefined){
                    x = e.pageX-$(this).offset().left;
                    y = e.pageY-$(this).offset().top;
                }else{
                    x = e.offsetX;
                    y = e.offsetY;
                };

                $this.addClass('draggable');
                $body.addClass('noselect');
                $target = $(e.target);
            };

        });

         $body.on("mouseup", function(e) {
            $target = null;
            $body.find(".draggable").removeClass('draggable');
            $body.removeClass('noselect');
        });

         $body.on("mousemove", function(e) {
            if ($target) {
                $target.offset({
                    top: e.pageY  - y,
                    left: e.pageX - x
                });
            };     
         });

    });

How to schedule a function to run every hour on Flask?

I'm a little bit new with the concept of application schedulers, but what I found here for APScheduler v3.3.1 , it's something a little bit different. I believe that for the newest versions, the package structure, class names, etc., have changed, so I'm putting here a fresh solution which I made recently, integrated with a basic Flask application:

#!/usr/bin/python3
""" Demonstrating Flask, using APScheduler. """

from apscheduler.schedulers.background import BackgroundScheduler
from flask import Flask

def sensor():
    """ Function for test purposes. """
    print("Scheduler is alive!")

sched = BackgroundScheduler(daemon=True)
sched.add_job(sensor,'interval',minutes=60)
sched.start()

app = Flask(__name__)

@app.route("/home")
def home():
    """ Function for test purposes. """
    return "Welcome Home :) !"

if __name__ == "__main__":
    app.run()

I'm also leaving this Gist here, if anyone have interest on updates for this example.

Here are some references, for future readings:

boundingRectWithSize for NSAttributedString returning wrong size

In case you'd like to get bounding box by truncating the tail, this question can help you out.

CGFloat maxTitleWidth = 200;

NSMutableParagraphStyle *paragraph = [[NSMutableParagraphStyle alloc] init];
paragraph.lineBreakMode = NSLineBreakByTruncatingTail;

NSDictionary *attributes = @{NSFontAttributeName : self.textLabel.font,
                             NSParagraphStyleAttributeName: paragraph};

CGRect box = [self.textLabel.text
              boundingRectWithSize:CGSizeMake(maxTitleWidth, CGFLOAT_MAX)
              options:(NSStringDrawingUsesLineFragmentOrigin | NSStringDrawingUsesFontLeading)
              attributes:attributes context:nil];

Loading another html page from javascript

You can use the following code :

<!DOCTYPE html>
<html>
    <body onLoad="triggerJS();">

    <script>
        function triggerJS(){
        location.replace("http://www.google.com");
        /*
        location.assign("New_WebSite_Url");
        //Use assign() instead of replace if you want to have the first page in the history (i.e if you want the user to be able to navigate back when New_WebSite_Url is loaded)
        */
        }
    </script>

    </body>
</html>

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

Posting this answer for folks wanting to initialize list with POCOs and also coz this is the first thing that pops up in search but all answers only for list of type string.

You can do this two ways one is directly setting the property by setter assignment or much cleaner by creating a constructor that takes in params and sets the properties.

class MObject {        
        public int Code { get; set; }
        public string Org { get; set; }
    }

List<MObject> theList = new List<MObject> { new MObject{ PASCode = 111, Org="Oracle" }, new MObject{ PASCode = 444, Org="MS"} };

OR by parameterized constructor

class MObject {
        public MObject(int code, string org)
        {
            Code = code;
            Org = org;
        }

        public int Code { get; set; }
        public string Org { get; set; }
    }

List<MObject> theList = new List<MObject> {new MObject( 111, "Oracle" ), new MObject(222,"SAP")};


        

How can I exclude $(this) from a jQuery selector?

You can use the not function rather than the :not selector:

$(".content a").not(this).hide("slow")

Start index for iterating Python list

islice has the advantage that it doesn't need to copy part of the list

from itertools import islice
for day in islice(days, 1, None):
    ...

What happens if you don't commit a transaction to a database (say, SQL Server)?

Transactions are intended to run completely or not at all. The only way to complete a transaction is to commit, any other way will result in a rollback.

Therefore, if you begin and then not commit, it will be rolled back on connection close (as the transaction was broken off without marking as complete).

filters on ng-model in an input

If you are using read only input field, you can use ng-value with filter.

for example:

ng-value="price | number:8"

Check if a key exists inside a json object

Type check also works :

if(typeof Obj.property == "undefined"){
    // Assign value to the property here
    Obj.property = someValue;
}

How to force the browser to reload cached CSS and JavaScript files

"Another idea which was suggested by SCdF would be to append a bogus query string to the file. (Some Python code to automatically use the timestamp as a bogus query string was submitted by pi.) However, there is some discussion as to whether or not the browser would cache a file with a query string. (Remember, we want the browser to cache the file and use it on future visits. We only want it to fetch the file again when it has changed.) Since it is not clear what happens with a bogus query string, I am not accepting that answer."

<link rel="stylesheet" href="file.css?<?=hash_hmac('sha1', session_id(), md5_file("file.css")); ?>" />

Hashing the file means when it has changed, the query string will have changed. If it hasn't, it will remain the same. Each session forces a reload too.

Optionally, you can also use rewrites to cause the browser to think it's a new URI.

How to put an image next to each other

try putting both images next to each other. Like this:

    <div id="icons"><a href="http://www.facebook.com/"><img src="images/facebook.png"></a><a href="https://twitter.com"><img src="images/twitter.png"></a>
    </div>

How to use Git and Dropbox together?

Now in 2014, I have been using Git and Dropbox for about one year and a half without problem. Some points though:

  • All my machines using Dropbox are on Windows, different versions (7 to 8) + 1 mac.
  • I do not share the repository with someone else, so I am the only one to modify it.
  • git push pushes to a remote repository, so that if it ever gets corrupted, I can easily recover it.
  • I had to create aliases in C:\Users with mklink /D link target because some libraries were pointed to absolute locations.

Set color of text in a Textbox/Label to Red and make it bold in asp.net C#

Try using the property ForeColor. Like this :

TextBox1.ForeColor = Color.Red;

Stopping a windows service when the stop option is grayed out

I solved the problem with the following steps:

  1. Open "services.msc" from command / Windows RUN.

  2. Find the service (which is greyed out).

  3. Double click on that service and go to the "Recovery" tab.

  4. Ensure that

    • First Failure action is selected as "Take No action".
    • Second Failure action is selected as "Take No action".
    • Subsequent Failures action is selected as "Take No action".

    and Press OK.

Now, the service will not try to restart and you can able to delete the greyed out service from services list (i.e. greyed out will be gone).

C# int to byte[]

When I look at this description, I have a feeling, that this xdr integer is just a big-endian "standard" integer, but it's expressed in the most obfuscated way. Two's complement notation is better know as U2, and it's what we are using on today's processors. The byte order indicates that it's a big-endian notation.
So, answering your question, you should inverse elements in your array (0 <--> 3, 1 <-->2), as they are encoded in little-endian. Just to make sure, you should first check BitConverter.IsLittleEndian to see on what machine you are running.

Generate getters and setters in NetBeans

Position the cursor inside the class, then press ALT + Ins and select Getters and Setters from the contextual menu.

Visual Studio 2010 shortcut to find classes and methods?

Try Alt+F12 in Visual Studio 2010.

It opens up the Find Symbol dialogue which allows you to search for methods, classes, etc.

Conveniently map between enum and int / String

enum ? int

yourEnum.ordinal()

int ? enum

EnumType.values()[someInt]

String ? enum

EnumType.valueOf(yourString)

enum ? String

yourEnum.name()

A side-note:
As you correctly point out, the ordinal() may be "unstable" from version to version. This is the exact reason why I always store constants as strings in my databases. (Actually, when using MySql, I store them as MySql enums!)

How to remove empty lines with or without whitespace in Python

Using regex:

if re.match(r'^\s*$', line):
    # line is empty (has only the following: \t\n\r and whitespace)

Using regex + filter():

filtered = filter(lambda x: not re.match(r'^\s*$', x), original)

As seen on codepad.

number of values in a list greater than a certain number

You could do something like this:

>>> j = [4, 5, 6, 7, 1, 3, 7, 5]
>>> sum(i > 5 for i in j)
3

It might initially seem strange to add True to True this way, but I don't think it's unpythonic; after all, bool is a subclass of int in all versions since 2.3:

>>> issubclass(bool, int)
True

Change column type in pandas

How about creating two dataframes, each with different data types for their columns, and then appending them together?

d1 = pd.DataFrame(columns=[ 'float_column' ], dtype=float)
d1 = d1.append(pd.DataFrame(columns=[ 'string_column' ], dtype=str))

Results

In[8}:  d1.dtypes
Out[8]: 
float_column     float64
string_column     object
dtype: object

After the dataframe is created, you can populate it with floating point variables in the 1st column, and strings (or any data type you desire) in the 2nd column.

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

Java: is there a map function?

Even though it's an old question I'd like to show another solution:

Just define your own operation using java generics and java 8 streams:

public static <S, T> List<T> map(Collection<S> collection, Function<S, T> mapFunction) {
   return collection.stream().map(mapFunction).collect(Collectors.toList());
}

Than you can write code like this:

List<String> hex = map(Arrays.asList(10, 20, 30, 40, 50), Integer::toHexString);

Auto-indent in Notepad++

This may seem silly, but in the original question, Turion was editing a plain text file. Make sure you choose the correct language from the Language menu

SSIS Excel Import Forcing Incorrect Column Type

Option 1. Use Visual Basic to iterate through each column and format each column as Text.

Use the Text-to-Columns menu, don't change the delimination, and change "General" to "Text"

Get img thumbnails from Vimeo?

If you are looking for an alternative solution and can manage the vimeo account there is another way, you simply add every video you want to show into an album and then use the API to request the album details - it then shows all the thumbnails and links. It's not ideal but might help.

API end point (playground)

Twitter convo with @vimeoapi

How do I get the title of the current active window using c#?

Use the Windows API. Call GetForegroundWindow().

GetForegroundWindow() will give you a handle (named hWnd) to the active window.

Documentation: GetForegroundWindow function | Microsoft Docs

Download files from SFTP with SSH.NET library

While the example works, its not the correct way to handle the streams...

You need to ensure the closing of the files/streams with the using clause.. Also, add try/catch to handle IO errors...

       public void DownloadAll()
    {
        string host = @"sftp.domain.com";
        string username = "myusername";
        string password = "mypassword";

        string remoteDirectory = "/RemotePath/";
        string localDirectory = @"C:\LocalDriveFolder\Downloaded\";

        using (var sftp = new SftpClient(host, username, password))
        {
            sftp.Connect();
            var files = sftp.ListDirectory(remoteDirectory);

            foreach (var file in files)
            {
                string remoteFileName = file.Name;
                if ((!file.Name.StartsWith(".")) && ((file.LastWriteTime.Date == DateTime.Today))

                    using (Stream file1 = File.OpenWrite(localDirectory + remoteFileName))
                    { 
                        sftp.DownloadFile(remoteDirectory + remoteFileName, file1);
                    }
            }

        }
    }

What does map(&:name) mean in Ruby?

Two things are happening here, and it's important to understand both.

As described in other answers, the Symbol#to_proc method is being called.

But the reason to_proc is being called on the symbol is because it's being passed to map as a block argument. Placing & in front of an argument in a method call causes it to be passed this way. This is true for any Ruby method, not just map with symbols.

def some_method(*args, &block)
  puts "args: #{args.inspect}"
  puts "block: #{block.inspect}"
end

some_method(:whatever)
# args: [:whatever]
# block: nil

some_method(&:whatever)
# args: []
# block: #<Proc:0x007fd23d010da8>

some_method(&"whatever")
# TypeError: wrong argument type String (expected Proc)
# (String doesn't respond to #to_proc)

The Symbol gets converted to a Proc because it's passed in as a block. We can show this by trying to pass a proc to .map without the ampersand:

arr = %w(apple banana)
reverse_upcase = proc { |i| i.reverse.upcase }
reverse_upcase.is_a?(Proc)
=> true

arr.map(reverse_upcase)
# ArgumentError: wrong number of arguments (1 for 0)
# (map expects 0 positional arguments and one block argument)

arr.map(&reverse_upcase)
=> ["ELPPA", "ANANAB"]

Even though it doesn't need to be converted, the method won't know how to use it because it expects a block argument. Passing it with & gives .map the block it expects.

How do I check if an element is really visible with JavaScript?

As jkl pointed out, checking the element's visibility or display is not enough. You do have to check its ancestors. Selenium does this when it verifies visibility on an element.

Check out the method Selenium.prototype.isVisible in the selenium-api.js file.

http://svn.openqa.org/svn/selenium-on-rails/selenium-on-rails/selenium-core/scripts/selenium-api.js

Opening a .ipynb.txt File

If you have a unix/linux system I'd just rename the file via command line

mv file_name.pynb.txt file_name.ipynb

worked like a charm for me!

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

How can I find the version of php that is running on a distinct domain name?

I suggest you much easier and platform independent solution to the problem - wappalyzer for Google Chrome:

See here

Compare data of two Excel Columns A & B, and show data of Column A that do not exist in B

Put this in C2 and copy down

=IF(ISNA(VLOOKUP(A2,$B$2:$B$65535,1,FALSE)),"not in B","")

Then if the value in A isn't in B the cell in column C will say "not in B".

How to search through all Git and Mercurial commits in the repository for a certain string?

Building on rq's answer, I found this line does what I want:

git grep "search for something" $(git log -g --pretty=format:%h -S"search for something")

Which will report the commit ID, filename, and display the matching line, like this:

91ba969:testFile:this is a test

... Does anyone agree that this would be a nice option to be included in the standard git grep command?

App.settings - the Angular way?

Poor man's configuration file:

Add to your index.html as first líne in the body tag:

<script lang="javascript" src="assets/config.js"></script>

Add assets/config.js:

var config = {
    apiBaseUrl: "http://localhost:8080"
}

Add config.ts:

export const config: AppConfig = window['config']

export interface AppConfig {
    apiBaseUrl: string
}

JavaScript array to CSV

ES6:

let csv = test_array.map(row=>row.join(',')).join('\n') 
//test_array being your 2D array

How to add (vertical) divider to a horizontal LinearLayout?

I just ran into the same problem today. As the previous answers indicate, the problem stems from the use of a color in the divider tag, rather than a drawable. However, instead of writing my own drawable xml, I prefer to use themed attributes as much as possible. You can use the android:attr/dividerHorizontal and android:attr/dividerVertical to get a predefined drawable instead:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:showDividers="middle"
    android:divider="?android:attr/dividerVertical"
    android:orientation="horizontal">
    <!-- other views -->
</LinearLayout>

The attributes are available in API 11 and above.

Also, as mentioned by bocekm in his answer, the dividerPadding property does NOT add extra padding on either side of a vertical divider, as one might assume. Instead it defines top and bottom padding and thus may truncate the divider if it's too large.