Programs & Examples On #Organized

Project vs Repository in GitHub

Fact 1: Projects and Repositories were always synonyms on GitHub.

Fact 2: This is no longer the case.

There is a lot of confusion about Repositories and Projects. In the past both terms were used pretty much interchangeably by the users and the GitHub's very own documentation. This is reflected by some of the answers and comments here that explain the subtle differences between those terms and when the one was preferred over the other. The difference were always subtle, e.g. like the issue tracker being part of the project but not part of the repository which might be thought of as a strictly git thing etc.

Not any more.

Currently repos and projects refer to a different kinds of entities that have separate APIs:

Since then it is no longer correct to call the repo a project or vice versa. Note that it is often confused in the official documentation and it is unfortunate that a term that was already widely used has been chosen as the name of the new entity but this is the case and we have to live with that.

The consequence is that repos and projects are usually confused and every time you read about GitHub projects you have to wonder if it's really about the projects or about repos. Had they chosen some other name or an abbreviation like "proj" then we could know that what is discussed is the new type of entity, a precise object with concrete properties, or a general speaking repo-like projectish kind of thingy.

The term that is usually unambiguous is "project board".

What can we learn from the API

The first endpoint in the documentation of the Projects API:

is described as: List repository projects. It means that a repository can have many projects. So those two cannot mean the same thing. It includes Response if projects are disabled:

{
  "message": "Projects are disabled for this repo",
  "documentation_url": "https://developer.github.com/v3"
}

which means that some repos can have projects disabled. Again, those cannot be the same thing when a repo can have projects disabled.

There are some other interesting endpoints:

  • Create a repository project - POST /repos/:owner/:repo/projects
  • Create an organization project - POST /orgs/:org/projects

but there is no:

  • Create a user's project - POST /users/:user/projects

Which leads us to another difference:

1. Repositories can belong to users or organizations
2. Projects can belong to repositories or organizations

or, more importantly:

1. Projects can belong to repositories but not the other way around
2. Projects can belong to organizations but not to users
3. Repositories can belong to organizations and to users

See also:

I know it's confusing. I tried to explain it as precisely as I could.

How to mount host volumes into docker containers in Dockerfile during build

It is not possible to use the VOLUME instruction to tell docker what to mount. That would seriously break portability. This instruction tells docker that content in those directories does not go in images and can be accessed from other containers using the --volumes-from command line parameter. You have to run the container using -v /path/on/host:/path/in/container to access directories from the host.

Mounting host volumes during build is not possible. There is no privileged build and mounting the host would also seriously degrade portability. You might want to try using wget or curl to download whatever you need for the build and put it in place.

Cannot find reference 'xxx' in __init__.py - Python / Pycharm

I know this is old, but Google sent me here so I guess others will come too like me.

The answer on 2018 is the selected one here: Pycharm: "unresolved reference" error on the IDE when opening a working project

Just be aware that you can only add one Content Root but you can add several Source Folders. No need to touch __init__.py files.

Concat scripts in order with Gulp

Apparently you can pass in the "nosort" option to gulp.src gulp.src.

Simplest way to set image as JPanel background

public demo1() {
    initComponents();
    ImageIcon img = new ImageIcon("C:\\Users\\AMIT TIWARI\\Documents\\NetBeansProjects\\try\\src\\com\\dd.jpeg"); //full path of image
    Image img2 = img.getImage().getScaledInstance(mylabel.getWidth(), mylabel.getHeight(),1);
    ImageIcon img3 = new ImageIcon(img2);
    mylabel.setIcon(img3);
}

Laravel Controller Subfolder routing

Add your controllers in your folders:

controllers\
---- folder1
---- folder2

Create your route not specifying the folder:

Route::get('/product/dashboard', 'MakeDashboardController@showDashboard');

Run

composer dump-autoload

And try again

Rails 4: how to use $(document).ready() with turbo-links

I found my functions doubled when using a function for ready and turbolinks:load so I used,

var ready = function() {
  // you code goes here
}

if (Turbolinks.supported == false) {
  $(document).on('ready', ready);
};
if (Turbolinks.supported == true) {
  $(document).on('turbolinks:load', ready);
};

That way your functions don't double if turbolinks is supported!

AttributeError: 'tuple' object has no attribute

You're returning a tuple. Index it.

obj=list_benefits()
print obj[0] + " is a benefit of functions!"
print obj[1] + " is a benefit of functions!"
print obj[2] + " is a benefit of functions!"

Shell script not running, command not found

There have been a few good comments about adding the shebang line to the beginning of the script. I'd like to add a recommendation to use the env command as well, for additional portability.

While #!/bin/bash may be the correct location on your system, that's not universal. Additionally, that may not be the user's preferred bash. #!/usr/bin/env bash will select the first bash found in the path.

Nested or Inner Class in PHP

You cannot do this in PHP. However, there are functional ways to accomplish this.

For more details please check this post: How to do a PHP nested class or nested methods?

This way of implementation is called fluent interface: http://en.wikipedia.org/wiki/Fluent_interface

"Large data" workflows using pandas

Consider Ruffus if you go the simple path of creating a data pipeline which is broken down into multiple smaller files.

Symfony 2 EntityManager injection in service

Note as of Symfony 3.3 EntityManager is depreciated. Use EntityManagerInterface instead.

namespace AppBundle\Service;

use Doctrine\ORM\EntityManagerInterface;

class Someclass {
    protected $em;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->em = $entityManager;
    }

    public function somefunction() {
        $em = $this->em;
        ...
    }
}

Inversion of Control vs Dependency Injection

I found best example on Dzone.com which is really helpfull to understand the real different between IOC and DI

“IoC is when you have someone else create objects for you.” So instead of writing "new " keyword (For example, MyCode c=new MyCode())in your code, the object is created by someone else. This ‘someone else’ is normally referred to as an IoC container. It means we handover the rrsponsibility (control )to the container to get instance of object is called Inversion of Control., means instead of you are creating object using new operator, let the container do that for you.

   DI(Dependency Injection):  Way of injecting properties to an object is 
   called 
  Dependency injection.
   We have three types of Dependency injection
    1)  Constructor Injection
    2)  Setter/Getter Injection
    3)  Interface Injection
   Spring will support only Constructor Injection and Setter/Getter Injection.

Read full article IOC and Read Full article DI

BeautifulSoup getting href

You can use find_all in the following way to find every a element that has an href attribute, and print each one:

from BeautifulSoup import BeautifulSoup

html = '''<a href="some_url">next</a>
<span class="class"><a href="another_url">later</a></span>'''

soup = BeautifulSoup(html)

for a in soup.find_all('a', href=True):
    print "Found the URL:", a['href']

The output would be:

Found the URL: some_url
Found the URL: another_url

Note that if you're using an older version of BeautifulSoup (before version 4) the name of this method is findAll. In version 4, BeautifulSoup's method names were changed to be PEP 8 compliant, so you should use find_all instead.


If you want all tags with an href, you can omit the name parameter:

href_tags = soup.find_all(href=True)

What are the options for storing hierarchical data in a relational database?

I am using PostgreSQL with closure tables for my hierarchies. I have one universal stored procedure for the whole database:

CREATE FUNCTION nomen_tree() RETURNS trigger
    LANGUAGE plpgsql
    AS $_$
DECLARE
  old_parent INTEGER;
  new_parent INTEGER;
  id_nom INTEGER;
  txt_name TEXT;
BEGIN
-- TG_ARGV[0] = name of table with entities with PARENT-CHILD relationships (TBL_ORIG)
-- TG_ARGV[1] = name of helper table with ANCESTOR, CHILD, DEPTH information (TBL_TREE)
-- TG_ARGV[2] = name of the field in TBL_ORIG which is used for the PARENT-CHILD relationship (FLD_PARENT)
    IF TG_OP = 'INSERT' THEN
    EXECUTE 'INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth) 
        SELECT $1.id,$1.id,0 UNION ALL
      SELECT $1.id,ancestor_id,depth+1 FROM ' || TG_ARGV[1] || ' WHERE child_id=$1.' || TG_ARGV[2] USING NEW;
    ELSE                                                           
    -- EXECUTE does not support conditional statements inside
    EXECUTE 'SELECT $1.' || TG_ARGV[2] || ',$2.' || TG_ARGV[2] INTO old_parent,new_parent USING OLD,NEW;
    IF COALESCE(old_parent,0) <> COALESCE(new_parent,0) THEN
      EXECUTE '
      -- prevent cycles in the tree
      UPDATE ' || TG_ARGV[0] || ' SET ' || TG_ARGV[2] || ' = $1.' || TG_ARGV[2]
        || ' WHERE id=$2.' || TG_ARGV[2] || ' AND EXISTS(SELECT 1 FROM '
        || TG_ARGV[1] || ' WHERE child_id=$2.' || TG_ARGV[2] || ' AND ancestor_id=$2.id);
      -- first remove edges between all old parents of node and its descendants
      DELETE FROM ' || TG_ARGV[1] || ' WHERE child_id IN
        (SELECT child_id FROM ' || TG_ARGV[1] || ' WHERE ancestor_id = $1.id)
        AND ancestor_id IN
        (SELECT ancestor_id FROM ' || TG_ARGV[1] || ' WHERE child_id = $1.id AND ancestor_id <> $1.id);
      -- then add edges for all new parents ...
      INSERT INTO ' || TG_ARGV[1] || ' (child_id,ancestor_id,depth) 
        SELECT child_id,ancestor_id,d_c+d_a FROM
        (SELECT child_id,depth AS d_c FROM ' || TG_ARGV[1] || ' WHERE ancestor_id=$2.id) AS child
        CROSS JOIN
        (SELECT ancestor_id,depth+1 AS d_a FROM ' || TG_ARGV[1] || ' WHERE child_id=$2.' 
        || TG_ARGV[2] || ') AS parent;' USING OLD, NEW;
    END IF;
  END IF;
  RETURN NULL;
END;
$_$;

Then for each table where I have a hierarchy, I create a trigger

CREATE TRIGGER nomenclature_tree_tr AFTER INSERT OR UPDATE ON nomenclature FOR EACH ROW EXECUTE PROCEDURE nomen_tree('my_db.nomenclature', 'my_db.nom_helper', 'parent_id');

For populating a closure table from existing hierarchy I use this stored procedure:

CREATE FUNCTION rebuild_tree(tbl_base text, tbl_closure text, fld_parent text) RETURNS void
    LANGUAGE plpgsql
    AS $$
BEGIN
    EXECUTE 'TRUNCATE ' || tbl_closure || ';
    INSERT INTO ' || tbl_closure || ' (child_id,ancestor_id,depth) 
        WITH RECURSIVE tree AS
      (
        SELECT id AS child_id,id AS ancestor_id,0 AS depth FROM ' || tbl_base || '
        UNION ALL 
        SELECT t.id,ancestor_id,depth+1 FROM ' || tbl_base || ' AS t
        JOIN tree ON child_id = ' || fld_parent || '
      )
      SELECT * FROM tree;';
END;
$$;

Closure tables are defined with 3 columns - ANCESTOR_ID, DESCENDANT_ID, DEPTH. It is possible (and I even advice) to store records with same value for ANCESTOR and DESCENDANT, and a value of zero for DEPTH. This will simplify the queries for retrieval of the hierarchy. And they are very simple indeed:

-- get all descendants
SELECT tbl_orig.*,depth FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth <> 0;
-- get only direct descendants
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON descendant_id = tbl_orig.id WHERE ancestor_id = XXX AND depth = 1;
-- get all ancestors
SELECT tbl_orig.* FROM tbl_closure LEFT JOIN tbl_orig ON ancestor_id = tbl_orig.id WHERE descendant_id = XXX AND depth <> 0;
-- find the deepest level of children
SELECT MAX(depth) FROM tbl_closure WHERE ancestor_id = XXX;

How to select following sibling/xml tag using xpath

How would I accomplish the nextsibling and is there an easier way of doing this?

You may use:

tr/td[@class='name']/following-sibling::td

but I'd rather use directly:

tr[td[@class='name'] ='Brand']/td[@class='desc']

This assumes that:

  1. The context node, against which the XPath expression is evaluated is the parent of all tr elements -- not shown in your question.

  2. Each tr element has only one td with class attribute valued 'name' and only one td with class attribute valued 'desc'.

Understanding CUDA grid dimensions, block dimensions and threads organization (simple explanation)

Hardware

If a GPU device has, for example, 4 multiprocessing units, and they can run 768 threads each: then at a given moment no more than 4*768 threads will be really running in parallel (if you planned more threads, they will be waiting their turn).

Software

threads are organized in blocks. A block is executed by a multiprocessing unit. The threads of a block can be indentified (indexed) using 1Dimension(x), 2Dimensions (x,y) or 3Dim indexes (x,y,z) but in any case xyz <= 768 for our example (other restrictions apply to x,y,z, see the guide and your device capability).

Obviously, if you need more than those 4*768 threads you need more than 4 blocks. Blocks may be also indexed 1D, 2D or 3D. There is a queue of blocks waiting to enter the GPU (because, in our example, the GPU has 4 multiprocessors and only 4 blocks are being executed simultaneously).

Now a simple case: processing a 512x512 image

Suppose we want one thread to process one pixel (i,j).

We can use blocks of 64 threads each. Then we need 512*512/64 = 4096 blocks (so to have 512x512 threads = 4096*64)

It's common to organize (to make indexing the image easier) the threads in 2D blocks having blockDim = 8 x 8 (the 64 threads per block). I prefer to call it threadsPerBlock.

dim3 threadsPerBlock(8, 8);  // 64 threads

and 2D gridDim = 64 x 64 blocks (the 4096 blocks needed). I prefer to call it numBlocks.

dim3 numBlocks(imageWidth/threadsPerBlock.x,  /* for instance 512/8 = 64*/
              imageHeight/threadsPerBlock.y); 

The kernel is launched like this:

myKernel <<<numBlocks,threadsPerBlock>>>( /* params for the kernel function */ );       

Finally: there will be something like "a queue of 4096 blocks", where a block is waiting to be assigned one of the multiprocessors of the GPU to get its 64 threads executed.

In the kernel the pixel (i,j) to be processed by a thread is calculated this way:

uint i = (blockIdx.x * blockDim.x) + threadIdx.x;
uint j = (blockIdx.y * blockDim.y) + threadIdx.y;

Including jars in classpath on commandline (javac or apt)

javac HelloWorld.java -classpath ./javax.jar , assuming javax is in current folder, and compile target is "HelloWorld.java", and you can compile without a main method

How to create Python egg file

I think you should use python wheels for distribution instead of egg now.

Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

Is it possible to forward-declare a function in Python?

What you can do is to wrap the invocation into a function of its own.

So that

foo()

def foo():
    print "Hi!"

will break, but

def bar():
    foo()

def foo():
    print "Hi!"

bar()

will be working properly.

General rule in Python is not that function should be defined higher in the code (as in Pascal), but that it should be defined before its usage.

Hope that helps.

Char to int conversion in C

Try this :

char c = '5' - '0';

What are some examples of commonly used practices for naming git branches?

I've mixed and matched from different schemes I've seen and based on the tooling I'm using.
So my completed branch name would be:

name/feature/issue-tracker-number/short-description

which would translate to:

mike/blogs/RSSI-12/logo-fix

The parts are separated by forward slashes because those get interpreted as folders in SourceTree for easy organization. We use Jira for our issue tracking so including the number makes it easier to look up in the system. Including that number also makes it searchable when trying to find that issue inside Github when trying to submit a pull request.

How do I import a pre-existing Java project into Eclipse and get up and running?

  1. Create a new Java project in Eclipse. This will create a src folder (to contain your source files).

  2. Also create a lib folder (the name isn't that important, but it follows standard conventions).

  3. Copy the ./com/* folders into the /src folder (you can just do this using the OS, no need to do any fancy importing or anything from the Eclipse GUI).

  4. Copy any dependencies (jar files that your project itself depends on) into /lib (note that this should NOT include the TGGL jar - thanks to commenter Mike Deck for pointing out my misinterpretation of the OPs post!)

  5. Copy the other TGGL stuff into the root project folder (or some other folder dedicated to licenses that you need to distribute in your final app)

  6. Back in Eclipse, select the project you created in step 1, then hit the F5 key (this refreshes Eclipse's view of the folder tree with the actual contents.

  7. The content of the /src folder will get compiled automatically (with class files placed in the /bin file that Eclipse generated for you when you created the project). If you have dependencies (which you don't in your current project, but I'll include this here for completeness), the compile will fail initially because you are missing the dependency jar files from the project classpath.

  8. Finally, open the /lib folder in Eclipse, right click on each required jar file and choose Build Path->Add to build path.

That will add that particular jar to the classpath for the project. Eclipse will detect the change and automatically compile the classes that failed earlier, and you should now have an Eclipse project with your app in it.

Best ways to teach a beginner to program?

At first I was interested in how different programs worked, so I started by looking at the source code. Then when I began to understand how the program worked, I would change certain parameters to see what would happen. So basically I learned how to read before I learned how to write. Which coincidently is how most people learn English.

So if I was trying to teach someone how to program I would give them a small program to try to read and understand how it works, and have them just just play around with the source code.

Only then would I give them "assignments" to try to accomplish.

Now if they had a particular reason for wanting to learn how to program, it would certainly be a good idea to start with something along the lines of what they want to accomplish. For example if they wanted to be proficient in an application like blender, it would definably be a good idea to start with Alice.

I would absolutely recommend sticking with a language that has garbage collection, like D, Perl, or some interpreted language like javascript. It might be a good idea to stay away from Perl until Perl 6 is closer to completion, because it fixes some of the difficulties of reading and understanding Perl.

Pandas: ValueError: cannot convert float NaN to integer

if you have null value then in doing mathematical operation you will get this error to resolve it use df[~df['x'].isnull()]df[['x']].astype(int) if you want your dataset to be unchangeable.

Moving Average Pandas

In case you are calculating more than one moving average:

for i in range(2,10):
   df['MA{}'.format(i)] = df.rolling(window=i).mean()

Then you can do an aggregate average of all the MA

df[[f for f in list(df) if "MA" in f]].mean(axis=1)

SQL like search string starts with

Aside from using %, age of empires III to lower case is age of empires iii so your query should be:

select *
from games
where lower(title) like 'age of empires iii%'

Get a list of checked checkboxes in a div using jQuery

function listselect() {
                var selected = [];
                $('.SelectPhone').prop('checked', function () {

                    selected.push($(this).val());
                });

                alert(selected.length);
     <input type="checkbox" name="SelectPhone" class="SelectPhone"  value="1" />
         <input type="checkbox" name="SelectPhone" class="SelectPhone"  value="2" />
         <input type="checkbox" name="SelectPhone" class="SelectPhone"  value="3" />
        <button onclick="listselect()">show count</button>

Python list of dictionaries search

One simple way using list comprehensions is , if l is the list

l = [
{"name": "Tom", "age": 10},
{"name": "Mark", "age": 5},
{"name": "Pam", "age": 7}
]

then

[d['age'] for d in l if d['name']=='Tom']

chart.js load totally new data

You need to destroy:

myLineChart.destroy();

Then re-initialize the chart:

var ctx = document.getElementById("myChartLine").getContext("2d");
myLineChart = new Chart(ctx).Line(data, options);

MAX(DATE) - SQL ORACLE

Try with:

select TO_CHAR(dates,'dd/MM/yyy hh24:mi') from (  SELECT min  (TO_DATE(a.PAYM_DATE)) as dates from user_payment a )

How to pass a parameter to Vue @click event handler

Just use a normal Javascript expression, no {} or anything necessary:

@click="addToCount(item.contactID)"

if you also need the event object:

@click="addToCount(item.contactID, $event)"

How can I convert a string to boolean in JavaScript?

A shorter way to write this, could be var isTrueSet = (myValue === "true") ? true : false; Presuming only "true" is true and other values are false.

Is there a command to restart computer into safe mode?

My first answer!

This will set the safemode switch:

bcdedit /set {current} safeboot minimal 

with networking:

bcdedit /set {current} safeboot network

then reboot the machine with

shutdown /r

to put back in normal mode via dos:

bcdedit /deletevalue {current} safeboot

TypeError: got multiple values for argument

This also happens if you forget selfdeclaration inside class methods.

Example:

class Example():
    def is_overlapping(x1, x2, y1, y2):
        # Thanks to https://stackoverflow.com/a/12888920/940592
        return max(x1, y1) <= min(x2, y2)

Fails calling it like self.is_overlapping(x1=2, x2=4, y1=3, y2=5) with:

{TypeError} is_overlapping() got multiple values for argument 'x1'

WORKS:

class Example():
    def is_overlapping(self, x1, x2, y1, y2):
        # Thanks to https://stackoverflow.com/a/12888920/940592
        return max(x1, y1) <= min(x2, y2)

In SQL Server, how to create while loop in select

  1. Create function that parses incoming string (say "AABBCC") as a table of strings (in particular "AA", "BB", "CC").
  2. Select IDs from your table and use CROSS APPLY the function with data as argument so you'll have as many rows as values contained in the current row's data. No need of cursors or stored procs.

Learning Ruby on Rails

The fastest way to learn anything, Ruby on Rails included, is pair programming.

Find someone who knows Rails, pick an example app, sit down, and work through fixing bugs, adding features.

The knowledge sharing is unbelievable.

What's the difference between ASCII and Unicode?

ASCII and Unicode are two character encodings. Basically, they are standards on how to represent difference characters in binary so that they can be written, stored, transmitted, and read in digital media. The main difference between the two is in the way they encode the character and the number of bits that they use for each. ASCII originally used seven bits to encode each character. This was later increased to eight with Extended ASCII to address the apparent inadequacy of the original. In contrast, Unicode uses a variable bit encoding program where you can choose between 32, 16, and 8-bit encodings. Using more bits lets you use more characters at the expense of larger files while fewer bits give you a limited choice but you save a lot of space. Using fewer bits (i.e. UTF-8 or ASCII) would probably be best if you are encoding a large document in English.

One of the main reasons why Unicode was the problem arose from the many non-standard extended ASCII programs. Unless you are using the prevalent page, which is used by Microsoft and most other software companies, then you are likely to encounter problems with your characters appearing as boxes. Unicode virtually eliminates this problem as all the character code points were standardized.

Another major advantage of Unicode is that at its maximum it can accommodate a huge number of characters. Because of this, Unicode currently contains most written languages and still has room for even more. This includes typical left-to-right scripts like English and even right-to-left scripts like Arabic. Chinese, Japanese, and the many other variants are also represented within Unicode. So Unicode won’t be replaced anytime soon.

In order to maintain compatibility with the older ASCII, which was already in widespread use at the time, Unicode was designed in such a way that the first eight bits matched that of the most popular ASCII page. So if you open an ASCII encoded file with Unicode, you still get the correct characters encoded in the file. This facilitated the adoption of Unicode as it lessened the impact of adopting a new encoding standard for those who were already using ASCII.

Summary:

1.ASCII uses an 8-bit encoding while Unicode uses a variable bit encoding.
2.Unicode is standardized while ASCII isn’t.
3.Unicode represents most written languages in the world while ASCII does not.
4.ASCII has its equivalent within Unicode.

Taken From: http://www.differencebetween.net/technology/software-technology/difference-between-unicode-and-ascii/#ixzz4zEjnxPhs

PageSpeed Insights 99/100 because of Google Analytics - How can I cache GA?

In the Google docs, they've identified a pagespeed filter that will load the script asynchronously:

ModPagespeedEnableFilters make_google_analytics_async

You can find the documentation here: https://developers.google.com/speed/pagespeed/module/filter-make-google-analytics-async

One thing to highlight is that the filter is considered high risk. From the docs:

The make_google_analytics_async filter is experimental and has not had extensive real-world testing. One case where a rewrite would cause errors is if the filter misses calls to Google Analytics methods that return values. If such methods are found, the rewrite is skipped. However, the disqualifying methods will be missed if they come before the load, are in attributes such as "onclick", or if they are in external resources. Those cases are expected to be rare.

CSS/HTML: Create a glowing border around an Input Field

This will create glowing input fields and textareas:

textarea,textarea:focus,input,input:focus{
    transition: border-color 0.15s ease-in-out 0s, box-shadow 0.15s ease-in-out 0s;
    border: 1px solid #c4c4c4;
    border-radius: 4px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    box-shadow: 0px 0px 8px #d9d9d9;
    -moz-box-shadow: 0px 0px 8px #d9d9d9;
    -webkit-box-shadow: 0px 0px 8px #d9d9d9;
}

input:focus,textarea:focus { 
    outline: none;
    border: 1px solid #7bc1f7;
    box-shadow: 0px 0px 8px #7bc1f7;
    -moz-box-shadow: 0px 0px 8px #7bc1f7;
    -webkit-box-shadow: 0px 0px 8px #7bc1f7;
}

What does "zend_mm_heap corrupted" mean

I've tried everything above and zend.enable_gc = 0 - the only config setting, that helped me.

PHP 5.3.10-1ubuntu3.2 with Suhosin-Patch (cli) (built: Jun 13 2012 17:19:58)

Writing Unicode text to a text file?

In case of writing in python3

>>> a = u'bats\u00E0'
>>> print a
batsà
>>> f = open("/tmp/test", "w")
>>> f.write(a)
>>> f.close()
>>> data = open("/tmp/test").read()
>>> data
'batsà'

In case of writing in python2:

>>> a = u'bats\u00E0'
>>> f = open("/tmp/test", "w")
>>> f.write(a)

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode character u'\xe0' in position 4: ordinal not in range(128)

To avoid this error you would have to encode it to bytes using codecs "utf-8" like this:

>>> f.write(a.encode("utf-8"))
>>> f.close()

and decode the data while reading using the codecs "utf-8":

>>> data = open("/tmp/test").read()
>>> data.decode("utf-8")
u'bats\xe0'

And also if you try to execute print on this string it will automatically decode using the "utf-8" codecs like this

>>> print a
batsà

PhpMyAdmin not working on localhost

All I had to do was load localhost:80/phpmyadmin and then the browser figured it out. After that, localhost/phpmyadmin worked.

How to sum digits of an integer in java?

This should be working fine for any number of digits and it will return individual digit's sum

public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    System.out.println("enter a string");
    String numbers = input.nextLine();  //String would be 55
    int sum = 0;
    for (char c : numbers.toCharArray()) {
        sum += c - '0';
    }
    System.out.println(sum); //the answer is 10
}

Scale Image to fill ImageView width and keep aspect ratio

I had a similar issue, I found the reason for this is because you need to calculate the dp. Android studio is calculating the ImageView when you load it from the drawable, but when you are using another method, like loading from bitmap the dp is not automatically accounted for,

Here is my xml

<ImageView
  android:id="@+id/imageViewer"
  android:layout_width="match_parent"
  android:layout_height="match_parent"//dp is not automaticly updated, when loading from a other source
  android:scaleType="fitCenter"
  tools:srcCompat="@drawable/a8" />

I'm using Kotlin, and loading drawable from an asset file, here's how I calculate this

val d = Drawable.createFromStream(assets.open("imageData/${imageName}.png"), null)
bitHeight = d.minimumHeight//get the image height
imageViewer.layoutParams.height = (bitHeight * resources.displayMetrics.density).toInt()//set the height
imageViewer.setImageDrawable(d)//set the image from the drawable
imageViewer.requestLayout()//here I apply it to the layout

HTML input field hint

With a bit of JavaScript:

<input 
  value="Enter username..." 
  onfocus="if (this.value === 'Enter username...') this.value=''" ... />

HTML5 has a nice attribute for this, called placeholder:

<input placeholder="Enter username.." ... />

but this attribute is not supported in old browsers.

How do I get the last inserted ID of a MySQL table in PHP?

To get last inserted id in codeigniter After executing insert query just use one function called insert_id() on database, it will return last inserted id

Ex:

$this->db->insert('mytable',$data);
echo $this->db->insert_id(); //returns last inserted id

in one line

echo $this->db->insert('mytable',$data)->insert_id();

How can I count the number of elements with same class?

$('#maindivid').find('input .inputclass').length

What are advantages of Artificial Neural Networks over Support Vector Machines?

If you want to use a kernel SVM you have to guess the kernel. However, ANNs are universal approximators with only guessing to be done is the width (approximation accuracy) and height (approximation efficiency). If you design the optimization problem correctly you do not over-fit (please see bibliography for over-fitting). It also depends on the training examples if they scan correctly and uniformly the search space. Width and depth discovery is the subject of integer programming.

Suppose you have bounded functions f(.) and bounded universal approximators on I=[0,1] with range again I=[0,1] for example that are parametrized by a real sequence of compact support U(.,a) with the property that there exists a sequence of sequences with

lim sup { |f(x) - U(x,a(k) ) | : x } =0

and you draw examples and tests (x,y) with a distribution D on IxI.

For a prescribed support, what you do is to find the best a such that

sum {  ( y(l) - U(x(l),a) )^{2} | : 1<=l<=N } is minimal

Let this a=aa which is a random variable!, the over-fitting is then

average using D and D^{N} of ( y - U(x,aa) )^{2}

Let me explain why, if you select aa such that the error is minimized, then for a rare set of values you have perfect fit. However, since they are rare the average is never 0. You want to minimize the second although you have a discrete approximation to D. And keep in mind that the support length is free.

How to change UINavigationBar background color from the AppDelegate

The colour code is the issue here. Instead of using 195/255, use 0.7647 or 195.f/255.f The problem is converting the float is not working properly. Try using exact float value.

Mongodb find() query : return only unique values (no duplicates)

I think you can use db.collection.distinct(fields,query)

You will be able to get the distinct values in your case for NetworkID.

It should be something like this :

Db.collection.distinct('NetworkID')

How do you programmatically update query params in react-router?

From DimitriDushkin on GitHub:

import { browserHistory } from 'react-router';

/**
 * @param {Object} query
 */
export const addQuery = (query) => {
  const location = Object.assign({}, browserHistory.getCurrentLocation());

  Object.assign(location.query, query);
  // or simple replace location.query if you want to completely change params

  browserHistory.push(location);
};

/**
 * @param {...String} queryNames
 */
export const removeQuery = (...queryNames) => {
  const location = Object.assign({}, browserHistory.getCurrentLocation());
  queryNames.forEach(q => delete location.query[q]);
  browserHistory.push(location);
};

or

import { withRouter } from 'react-router';
import { addQuery, removeQuery } from '../../utils/utils-router';

function SomeComponent({ location }) {
  return <div style={{ backgroundColor: location.query.paintRed ? '#f00' : '#fff' }}>
    <button onClick={ () => addQuery({ paintRed: 1 })}>Paint red</button>
    <button onClick={ () => removeQuery('paintRed')}>Paint white</button>
  </div>;
}

export default withRouter(SomeComponent);

Using jQuery to center a DIV on the screen

i use this:

$(function() {
   $('#divId').css({
    'left' : '50%',
    'top' : '50%',
    'position' : 'absolute',
    'margin-left' : -$('#divId').outerWidth()/2,
    'margin-top' : -$('#divId').outerHeight()/2
  });
});

Is it possible to have multiple statements in a python lambda expression?

A Hacky way to combine multiple statements into a single statement in python is to use the "and" keyword as a short-circuit operator. Then you can use this single statement directly as part of the lambda expression.

This is similar to using "&&" as the short-circuit operator in shell languages such as bash.

Also note: You can always fix a function statement to return a true value by wrapping the function.

Example:

def p2(*args):
    print(*args)
    return 1 # a true value

junky = lambda x, y: p2('hi') and p2('there') and p2(x) and p2(y)

junky("a", "b")

On second thought, its probably better to use 'or' instead of 'and' since many functions return '0' or None on success. Then you can get rid of the wrapper function in the above example:

junky = lambda x, y: print('hi') or print('there') or print(x) or print(y)

junky("a", "b")

'and' operate will evaluate the expressions until it gets to the first zero return value. after which it short-circuits. 1 and 1 and 0 and 1 evaluates: 1 and 1 and 0, and drops 1

'or' operate will evaluate the expressions until it gets to the first non-zero return value. after which it short-circuits.

0 or 0 or 1 or 0 evaluates 0 or 0 or 1, and drops 0

Display / print all rows of a tibble (tbl_df)

you can print it in Rstudio with View() more convenient:

df %>% View()

View(df)

Multiple SQL joins

 SELECT
 B.Title, B.Edition, B.Year, B.Pages, B.Rating     --from Books
, C.Category                                        --from Categories
, P.Publisher                                       --from Publishers
, W.LastName                                        --from Writers

FROM Books B

JOIN Categories_Books CB ON B._ISBN = CB._Books_ISBN
JOIN Categories_Books CB ON CB.__Categories_Category_ID = C._CategoryID
JOIN Publishers P ON B.PublisherID = P._Publisherid
JOIN Writers_Books WB ON B._ISBN = WB._Books_ISBN
JOIN Writers W ON WB._Writers_WriterID = W._WriterID

get next sequence value from database using hibernate

Your idea with the SequenceGenerator fake entity is good.

@Id
@GenericGenerator(name = "my_seq", strategy = "sequence", parameters = {
        @org.hibernate.annotations.Parameter(name = "sequence_name", value = "MY_CUSTOM_NAMED_SQN"),
})
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_seq")

It is important to use the parameter with the key name "sequence_name". Run a debugging session on the hibernate class SequenceStyleGenerator, the configure(...) method at the line final QualifiedName sequenceName = determineSequenceName( params, dialect, jdbcEnvironment ); to see more details about how the sequence name is computed by Hibernate. There are some defaults in there you could also use.

After the fake entity, I created a CrudRepository:

public interface SequenceRepository extends CrudRepository<SequenceGenerator, Long> {}

In the Junit, I call the save method of the SequenceRepository.

SequenceGenerator sequenceObject = new SequenceGenerator(); SequenceGenerator result = sequenceRepository.save(sequenceObject);

If there is a better way to do this (maybe support for a generator on any type of field instead of just Id), I would be more than happy to use it instead of this "trick".

Apache giving 403 forbidden errors

In my case it was failing as the IP of my source server was not whitelisted in the target server.

For e.g. I was trying to access https://prodcat.ref.test.co.uk from application running on my source server. On source server find IP by ifconfig

This IP should be whitelisted in the target Server's apache config file. If its not then get it whitelist.

Steps to add a IP for whitelisting (if you control the target server as well) ssh to the apache server sudo su - cd /usr/local/apache/conf/extra (actual directories can be different based on your config)

Find the config file for the target application for e.g. prodcat-443.conf

RewriteCond %{REMOTE_ADDR} <YOUR Server's IP> 
for e.g.
RewriteCond %{REMOTE_ADDR} !^192\.68\.2\.98

Hope this helps someone

python: unhashable type error

counter[row[11]]+=1

You don't show what data is, but apparently when you loop through its rows, row[11] is turning out to be a list. Lists are mutable objects which means they cannot be used as dictionary keys. Trying to use row[11] as a key causes the defaultdict to complain that it is a mutable, i.e. unhashable, object.

The easiest fix is to change row[11] from a list to a tuple. Either by doing

counter[tuple(row[11])] += 1

or by fixing it in the caller before data is passed to medications_minimum3. A tuple simply an immutable list, so it behaves exactly like a list does except you cannot change it once it is created.

Find the day of a week

Let's say you additionally want the week to begin on Monday (instead of default on Sunday), then the following is helpful:

require(lubridate)
df$day = ifelse(wday(df$time)==1,6,wday(df$time)-2)

The result is the days in the interval [0,..,6].

If you want the interval to be [1,..7], use the following:

df$day = ifelse(wday(df$time)==1,7,wday(df$time)-1)

... or, alternatively:

df$day = df$day + 1

Why es6 react component works only with "export default"?

Add { } while importing and exporting: export { ... }; | import { ... } from './Template';

exportimport { ... } from './Template'

export defaultimport ... from './Template'


Here is a working example:

// ExportExample.js
import React from "react";

function DefaultExport() {
  return "This is the default export";
}

function Export1() {
  return "Export without default 1";
}

function Export2() {
  return "Export without default 2";
}

export default DefaultExport;
export { Export1, Export2 };

// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";

export default function App() {
  return (
    <>
      <strong>
        <DefaultExport />
      </strong>
      <br />
      <Export1 />
      <br />
      <Export2 />
    </>
  );
}

??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark

Dealing with "java.lang.OutOfMemoryError: PermGen space" error

Assigning Tomcat more memory is NOT the proper solution.

The correct solution is to do a cleanup after the context is destroyed and recreated (the hot deploy). The solution is to stop the memory leaks.

If your Tomcat/Webapp Server is telling you that failed to unregister drivers (JDBC), then unregister them. This will stop the memory leaks.

You can create a ServletContextListener and configure it in your web.xml. Here is a sample ServletContextListener:

import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Enumeration;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;

import com.mysql.jdbc.AbandonedConnectionCleanupThread;

/**
 * 
 * @author alejandro.tkachuk / calculistik.com
 *
 */
public class AppContextListener implements ServletContextListener {

    private static final Logger logger = Logger.getLogger(AppContextListener.class);

    @Override
    public void contextInitialized(ServletContextEvent arg0) {
        logger.info("AppContextListener started");
    }

    @Override
    public void contextDestroyed(ServletContextEvent arg0) {
        logger.info("AppContextListener destroyed");

        // manually unregister the JDBC drivers
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while (drivers.hasMoreElements()) {
            Driver driver = drivers.nextElement();
            try {
                DriverManager.deregisterDriver(driver);
                logger.info(String.format("Unregistering jdbc driver: %s", driver));
            } catch (SQLException e) {
                logger.info(String.format("Error unregistering driver %s", driver), e);
            }

        }

        // manually shutdown clean up threads
        try {
            AbandonedConnectionCleanupThread.shutdown();
            logger.info("Shutting down AbandonedConnectionCleanupThread");
        } catch (InterruptedException e) {
            logger.warn("SEVERE problem shutting down AbandonedConnectionCleanupThread: ", e);
            e.printStackTrace();
        }        
    }
}

And here you configure it in your web.xml:

<listener>
    <listener-class>
        com.calculistik.mediweb.context.AppContextListener 
    </listener-class>
</listener>  

SQL Server Group By Month

Now your query is explicitly looking at only payments for year = 2010, however, I think you meant to have your Jan/Feb/Mar actually represent 2009. If so, you'll need to adjust this a bit for that case. Don't keep requerying the sum values for every column, just the condition of the date difference in months. Put the rest in the WHERE clause.

SELECT 
      SUM( case when DateDiff(m, PaymentDate, @start) = 0 
           then Amount else 0 end ) AS "Apr",
      SUM( case when DateDiff(m, PaymentDate, @start) = 1 
           then Amount else 0 end ) AS "May",
      SUM( case when DateDiff(m, PaymentDate, @start) = 2 
           then Amount else 0 end ) AS "June",
      SUM( case when DateDiff(m, PaymentDate, @start) = 3 
           then Amount else 0 end ) AS "July",
      SUM( case when DateDiff(m, PaymentDate, @start) = 4 
           then Amount else 0 end ) AS "Aug",
      SUM( case when DateDiff(m, PaymentDate, @start) = 5 
           then Amount else 0 end ) AS "Sep",
      SUM( case when DateDiff(m, PaymentDate, @start) = 6 
           then Amount else 0 end ) AS "Oct",
      SUM( case when DateDiff(m, PaymentDate, @start) = 7 
           then Amount else 0 end ) AS "Nov",
      SUM( case when DateDiff(m, PaymentDate, @start) = 8 
           then Amount else 0 end ) AS "Dec",
      SUM( case when DateDiff(m, PaymentDate, @start) = 9 
           then Amount else 0 end ) AS "Jan",
      SUM( case when DateDiff(m, PaymentDate, @start) = 10 
           then Amount else 0 end ) AS "Feb",
      SUM( case when DateDiff(m, PaymentDate, @start) = 11 
           then Amount else 0 end ) AS "Mar"
   FROM 
      Payments I
         JOIN Live L
            on I.LiveID = L.Record_Key
   WHERE 
          Year = 2010 
      AND UserID = 100

Convert XLS to CSV on command line

How about with PowerShell?

Code should be looks like this, not tested though

$xlCSV = 6
$Excel = New-Object -Com Excel.Application 
$Excel.visible = $False 
$Excel.displayalerts=$False 
$WorkBook = $Excel.Workbooks.Open("YOUDOC.XLS") 
$Workbook.SaveAs("YOURDOC.csv",$xlCSV) 
$Excel.quit()

Here is a post explaining how to use it

How Can I Use Windows PowerShell to Automate Microsoft Excel?

How do I unload (reload) a Python module?

Other option. See that Python default importlib.reload will just reimport the library passed as an argument. It won't reload the libraries that your lib import. If you changed a lot of files and have a somewhat complex package to import, you must do a deep reload.

If you have IPython or Jupyter installed, you can use a function to deep reload all libs:

from IPython.lib.deepreload import reload as dreload
dreload(foo)

If you don't have Jupyter, install it with this command in your shell:

pip3 install jupyter

What is the difference between a Relational and Non-Relational Database?

The difference between relational and non-relational is exactly that. The relational database architecture provides with constraints objects such as primary keys, foreign keys, etc that allows one to tie two or more tables in a relation. This is good so that we normalize our tables which is to say split information about what the database represents into many different tables, once can keep the integrity of the data.

For example, say you have a series of table that houses information about an employee. You could not delete a record from a table without deleting all the records that pertain to such record from the other tables. In this way you implement data integrity. The non-relational database doesn't provide this constraints constructs that will allow you to implement data integrity.

Unless you don't implement this constraint in the front end application that is utilized to populate the databases' tables, you are implementing a mess that can be compared with the wild west.

How to iterate over columns of pandas dataframe to run regression

This answer is to iterate over selected columns as well as all columns in a DF.

df.columns gives a list containing all the columns' names in the DF. Now that isn't very helpful if you want to iterate over all the columns. But it comes in handy when you want to iterate over columns of your choosing only.

We can use Python's list slicing easily to slice df.columns according to our needs. For eg, to iterate over all columns but the first one, we can do:

for column in df.columns[1:]:
    print(df[column])

Similarly to iterate over all the columns in reversed order, we can do:

for column in df.columns[::-1]:
    print(df[column])

We can iterate over all the columns in a lot of cool ways using this technique. Also remember that you can get the indices of all columns easily using:

for ind, column in enumerate(df.columns):
    print(ind, column)

jQuery.animate() with css class only, without explicit styles

Check out James Padolsey's animateToSelector

Intro: This jQuery plugin will allow you to animate any element to styles specified in your stylesheet. All you have to do is pass a selector and the plugin will look for that selector in your StyleSheet and will then apply it as an animation.

Stopping a CSS3 Animation on last frame

-webkit-animation-fill-mode: forwards; /* Safari 4.0 - 8.0 */
animation-fill-mode: forwards;

Browser Support

  • Chrome 43.0 (4.0 -webkit-)
  • IE 10.0
  • Mozilla 16.0 ( 5.0 -moz-)
  • Shafari 4.0 -webkit-
  • Opera 15.0 -webkit- (12.112.0 -o-)

Usage:-

.fadeIn {
  animation-name: fadeIn;
    -webkit-animation-name: fadeIn;

    animation-duration: 1.5s;
    -webkit-animation-duration: 1.5s;

    animation-timing-function: ease;
    -webkit-animation-timing-function: ease;

     animation-fill-mode: forwards;
    -webkit-animation-fill-mode: forwards;
}


@keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

@-webkit-keyframes fadeIn {
  from {
    opacity: 0;
  }

  to {
    opacity: 1;
  }
}

Deprecation warning in Moment.js - Not in a recognized ISO format

Add the following line in your code to Suppress the warnings:

const moment = require('moment');

moment.suppressDeprecationWarnings = true;

Eclipse plugin for generating a class diagram

Try eUML2. its a single click generator no need to drag n drop.

Microsoft Excel mangles Diacritics in .csv files?

UTF-8 doesn't work for me in office 2007 without any service pack, with or without BOM (U+ffef or 0xEF,0xBB,0xBF , neither works) installing sp3 makes UTF-8 work when 0xEF,0xBB,0xBF BOM is prepended.

UTF-16 works when encoding in python using "utf-16-le" with a 0xff 0xef BOM prepended, and using tab as seperator. I had to manually write out the BOM, and then use "utf-16-le" rather then "utf-16", otherwise each encode() prepended the BOM to every row written out which appeared as garbage on the first column of the second line and after.

can't tell whether UTF-16 would work without any sp installed, since I can't go back now. sigh

This is on windows, dunno about office for MAC.

for both working cases, the import works when launching a download directly from the browser and the text import wizard doesn't intervence, it works like you would expect.

How can I add new dimensions to a Numpy array?

Consider Approach 1 with reshape method and Approach 2 with np.newaxis method that produce the same outcome:

#Lets suppose, we have:
x = [1,2,3,4,5,6,7,8,9]
print('I. x',x)

xNpArr = np.array(x)
print('II. xNpArr',xNpArr)
print('III. xNpArr', xNpArr.shape)

xNpArr_3x3 = xNpArr.reshape((3,3))
print('IV. xNpArr_3x3.shape', xNpArr_3x3.shape)
print('V. xNpArr_3x3', xNpArr_3x3)

#Approach 1 with reshape method
xNpArrRs_1x3x3x1 = xNpArr_3x3.reshape((1,3,3,1))
print('VI. xNpArrRs_1x3x3x1.shape', xNpArrRs_1x3x3x1.shape)
print('VII. xNpArrRs_1x3x3x1', xNpArrRs_1x3x3x1)

#Approach 2 with np.newaxis method
xNpArrNa_1x3x3x1 = xNpArr_3x3[np.newaxis, ..., np.newaxis]
print('VIII. xNpArrNa_1x3x3x1.shape', xNpArrNa_1x3x3x1.shape)
print('IX. xNpArrNa_1x3x3x1', xNpArrNa_1x3x3x1)

We have as outcome:

I. x [1, 2, 3, 4, 5, 6, 7, 8, 9]

II. xNpArr [1 2 3 4 5 6 7 8 9]

III. xNpArr (9,)

IV. xNpArr_3x3.shape (3, 3)

V. xNpArr_3x3 [[1 2 3]
 [4 5 6]
 [7 8 9]]

VI. xNpArrRs_1x3x3x1.shape (1, 3, 3, 1)

VII. xNpArrRs_1x3x3x1 [[[[1]
   [2]
   [3]]

  [[4]
   [5]
   [6]]

  [[7]
   [8]
   [9]]]]

VIII. xNpArrNa_1x3x3x1.shape (1, 3, 3, 1)

IX. xNpArrNa_1x3x3x1 [[[[1]
   [2]
   [3]]

  [[4]
   [5]
   [6]]

  [[7]
   [8]
   [9]]]]

Loop through files in a folder using VBA?

Here's my interpretation as a Function Instead:

'#######################################################################
'# LoopThroughFiles
'# Function to Loop through files in current directory and return filenames
'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile
'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'#######################################################################
Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String

    Dim StrFile As String
    'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile

    StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir

    Loop

End Function

Displaying a Table in Django from Database

$ pip install django-tables2

settings.py

INSTALLED_APPS , 'django_tables2'
TEMPLATES.OPTIONS.context-processors , 'django.template.context_processors.request'

models.py

class hotel(models.Model):
     name = models.CharField(max_length=20)

views.py

from django.shortcuts import render

def people(request):
    istekler = hotel.objects.all()
    return render(request, 'list.html', locals())

list.html

{# yonetim/templates/list.html #}
{% load render_table from django_tables2 %}
{% load static %}
<!doctype html>
<html>
    <head>
        <link rel="stylesheet" href="{% static 
'ticket/static/css/screen.css' %}" />
    </head>
    <body>
        {% render_table istekler %}
    </body>
</html>

CSS '>' selector; what is it?

It declares parent reference, look at this page for definition:

http://www.w3.org/TR/CSS2/selector.html#child-selectors

How can I tell if a VARCHAR variable contains a substring?

CONTAINS is for a Full Text Indexed field - if not, then use LIKE

Java Generate Random Number Between Two Given Values

You could use e.g. r.nextInt(101)

For a more generic "in between two numbers" use:

Random r = new Random();
int low = 10;
int high = 100;
int result = r.nextInt(high-low) + low;

This gives you a random number in between 10 (inclusive) and 100 (exclusive)

How do I Merge two Arrays in VBA?

Here's a version that uses a collection object to combine two 1-d arrays and pass them to a 3rd array. Doesn't work for multi-dimensional arrays.

Function joinArrays(arr1 As Variant, arr2 As Variant) As Variant
 Dim arrToReturn() As Variant, myCollection As New Collection
 For Each x In arr1: myCollection.Add x: Next
 For Each y In arr2: myCollection.Add y: Next

 ReDim arrToReturn(1 To myCollection.Count)
 For i = 1 To myCollection.Count: arrToReturn(i) = myCollection.Item(i): Next
 joinArrays = arrToReturn
End Function

How to automate drag & drop functionality using Selenium WebDriver Java

I used below piece of code. Here dragAndDrop(x,y) is a method of Action class. Which takes two parameters (x,y), source location, and target location respectively

try {
                System.out.println("Drag and Drom started :");
                Thread.sleep(12000);
                Actions actions = new Actions(webdriver);
                WebElement srcElement = webdriver.findElement(By.xpath("source Xpath"));
                WebElement targetElement = webdriver.findElement(By.xpath("Target Xpath"));
                actions.dragAndDrop(srcElement, targetElement); 
                actions.build().perform();
                System.out.println("Drag and Drom complated :");
            } catch (Exception e) {
                System.out.println(e.getMessage());
                resultDetails.setFlag(true);
            }

How do I use reflection to invoke a private method?

Simply change your code to use the overloaded version of GetMethod that accepts BindingFlags:

MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType, 
    BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(this, new object[] { methodParams });

Here's the BindingFlags enumeration documentation.

R Not in subset

The expression df1$id %in% idNums1 produces a logical vector. To negate it, you need to negate the whole vector:

!(df1$id %in% idNums1)

Qt: How do I handle the event of the user pressing the 'X' (close) button?

Well, I got it. One way is to override the QWidget::closeEvent(QCloseEvent *event) method in your class definition and add your code into that function. Example:

class foo : public QMainWindow
{
    Q_OBJECT
private:
    void closeEvent(QCloseEvent *bar);
    // ...
};


void foo::closeEvent(QCloseEvent *bar)
{
    // Do something
    bar->accept();
}

What is the easiest way to initialize a std::vector with hardcoded elements?

It is pretty convenient to create a vector inline without defining variable when writing test, for example:

assert(MyFunction() == std::vector<int>{1, 3, 4}); // <- this.

Windows command to get service status?

If PowerShell is available to you...

Get-Service -DisplayName *Network* | ForEach-Object{Write-Host $_.Status : $_.Name}

Will give you...

Stopped : napagent
Stopped : NetDDE
Stopped : NetDDEdsdm
Running : Netman
Running : Nla
Stopped : WMPNetworkSvc
Stopped : xmlprov

You can replace the ****Network**** with a specific service name if you just need to check one service.

How do I perform HTML decoding/encoding using Python/Django?

Given the Django use case, there are two answers to this. Here is its django.utils.html.escape function, for reference:

def escape(html):
    """Returns the given HTML with ampersands, quotes and carets encoded."""
    return mark_safe(force_unicode(html).replace('&', '&amp;').replace('<', '&l
t;').replace('>', '&gt;').replace('"', '&quot;').replace("'", '&#39;'))

To reverse this, the Cheetah function described in Jake's answer should work, but is missing the single-quote. This version includes an updated tuple, with the order of replacement reversed to avoid symmetric problems:

def html_decode(s):
    """
    Returns the ASCII decoded version of the given HTML string. This does
    NOT remove normal HTML tags like <p>.
    """
    htmlCodes = (
            ("'", '&#39;'),
            ('"', '&quot;'),
            ('>', '&gt;'),
            ('<', '&lt;'),
            ('&', '&amp;')
        )
    for code in htmlCodes:
        s = s.replace(code[1], code[0])
    return s

unescaped = html_decode(my_string)

This, however, is not a general solution; it is only appropriate for strings encoded with django.utils.html.escape. More generally, it is a good idea to stick with the standard library:

# Python 2.x:
import HTMLParser
html_parser = HTMLParser.HTMLParser()
unescaped = html_parser.unescape(my_string)

# Python 3.x:
import html.parser
html_parser = html.parser.HTMLParser()
unescaped = html_parser.unescape(my_string)

# >= Python 3.5:
from html import unescape
unescaped = unescape(my_string)

As a suggestion: it may make more sense to store the HTML unescaped in your database. It'd be worth looking into getting unescaped results back from BeautifulSoup if possible, and avoiding this process altogether.

With Django, escaping only occurs during template rendering; so to prevent escaping you just tell the templating engine not to escape your string. To do that, use one of these options in your template:

{{ context_var|safe }}
{% autoescape off %}
    {{ context_var }}
{% endautoescape %}

How do I make a simple makefile for gcc on Linux?

all: program
program.o: program.h headers.h

is enough. the rest is implicit

angular-cli server - how to proxy API requests to another server?

This was close to working for me. Also had to add:

"changeOrigin": true,
"pathRewrite": {"^/proxy" : ""}

Full proxy.conf.json shown below:

{
    "/proxy/*": {
        "target": "https://url.com",
        "secure": false,
        "changeOrigin": true,
        "logLevel": "debug",
        "pathRewrite": {
            "^/proxy": ""
        }
    }
}

Can't connect to MySQL server error 111

If all the previous answers didn't give any solution, you should check your user privileges.

If you could login as root to mysql then you should add this:

CREATE USER 'root'@'192.168.1.100' IDENTIFIED BY  '***';
GRANT ALL PRIVILEGES ON * . * TO  'root'@'192.168.1.100' IDENTIFIED BY  '***' WITH GRANT OPTION MAX_QUERIES_PER_HOUR 0 MAX_CONNECTIONS_PER_HOUR 0 MAX_UPDATES_PER_HOUR 0 MAX_USER_CONNECTIONS 0 ;

Then try to connect again using mysql -ubeer -pbeer -h192.168.1.100. It should work.

How to add dll in c# project

In the right hand column under your solution explorer, you can see next to the reference to "Science" its marked as a warning. Either that means it cant find it, or its objecting to it for some other reason. While this is the case and your code requires it (and its not just in the references list) it wont compile.

Please post the warning message, we can try help you further.

How to check if current thread is not main thread

you can verify it in android ddms logcat where process id will be same but thread id will be different.

Reload the page after ajax success

You use the ajaxStop to execute code when the ajax are completed:

$(document).ajaxStop(function(){
  setTimeout("window.location = 'otherpage.html'",100);
});

Python SQLite: database is locked

I'm presuming you are actually using sqlite3 even though your code says otherwise. Here are some things to check:

  1. That you don't have a hung process sitting on the file (unix: $ fuser cache.db should say nothing)
  2. There isn't a cache.db-journal file in the directory with cache.db; this would indicate a crashed session that hasn't been cleaned up properly.
  3. Ask the database shell to check itself: $ sqlite3 cache.db "pragma integrity_check;"
  4. Backup the database $ sqlite3 cache.db ".backup cache.db.bak"
  5. Remove cache.db as you probably have nothing in it (if you are just learning) and try your code again
  6. See if the backup works $ sqlite3 cache.db.bak ".schema"

Failing that, read Things That Can Go Wrong and How to Corrupt Your Database Files

Remove stubborn underline from link

set text-decoration: none; for anchor tag.

Example html.

<body>
    <ul class="nav-tabs">
        <li><a href="#"><i class="fas fa-th"></i>Business</a></li>
        <li><a href="#"><i class="fas fa-th"></i>Expertise</a></li>
        <li><a href="#"><i class="fas fa-th"></i>Quality</a></li>
    </ul>
</body>

Example CSS:

.nav-tabs li a{
  text-decoration: none;
}

Print page numbers on pages when printing html

Can you try this, you can use content: counter(page);

     @page {
       @bottom-left {
            content: counter(page) "/" counter(pages);
        }
     }

Ref: http://www.w3.org/TR/CSS21/generate.html#counters

http://www.princexml.com/doc/9.0/page-numbers/

Using iText to convert HTML to PDF

When I needed HTML to PDF conversion earlier this year, I tried the trial of Winnovative HTML to PDF converter (I think ExpertPDF is the same product, too). It worked great so we bought a license at that company. I don't go into it too in depth after that.

How can I get the current contents of an element in webdriver

I believe prestomanifesto was on the right track. It depends on what kind of element it is. You would need to use element.get_attribute('value') for input elements and element.text to return the text node of an element.

You could check the WebElement object with element.tag_name to find out what kind of element it is and return the appropriate value.

This should help you figure out:

driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')

element_text = element.text
element_attribute_value = element.get_attribute('value')

print element
print 'element.text: {0}'.format(element_text)
print 'element.get_attribute(\'value\'): {0}'.format(element_attribute_value)
driver.quit()

How do I execute a PowerShell script automatically using Windows task scheduler?

I also could not launch scripts, after heavy searching nothing helped. No -ExecutionPolicy, no commands, no files and no difference between "" and ''.

I simply put the command I ran in powershell in the argument tab: ./scripts.ps1 parameter1 11 parameter2 xx and so on. Now the scheduler works. Program: Powershell.exe Start in: C:/location/of/script/

unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

Try this. For python 2.7.12 we need to define constructor or need to add self to each methods followed by defining an instance of an class called object.

import cv2

class calculator:

#   def __init__(self):

def multiply(self, a, b):
    x= a*b
    print(x)

def subtract(self, a,b):
    x = a-b
    print(x)

def add(self, a,b):
    x = a+b
    print(x)

def div(self, a,b):
    x = a/b
    print(x)

 calc = calculator()
 calc.multiply(2,3)
 calc.add(2,3)
 calc.div(10,5)
 calc.subtract(2,3)

Jquery select this + class

Well using find is the best option here

just simply use like this

$(".class").click(function(){
        $("this").find('.subclass').css("visibility","visible");
})

and if there are many classes with the same name class its always better to give the class name of parent class like this

$(".parent .class").click(function(){
            $("this").find('.subclass').css("visibility","visible");
    })

Java Replace Character At Specific Position Of String?

Kay!

First of all, when dealing with strings you have to refer to their positions in 0 base convention. This means that if you have a string like this:

String str = "hi";
//str length is equal 2 but the character
//'h' is in the position 0 and character 'i' is in the postion 1


With that in mind, the best way to tackle this problem is creating a method to replace a character at a given position in a string like this:

Method:

public String changeCharInPosition(int position, char ch, String str){
    char[] charArray = str.toCharArray();
    charArray[position] = ch;
    return new String(charArray);
}

Then you should call the method 'changeCharInPosition' in this way:

String str = "hi";
str = changeCharInPosition(1, 'k', str);
System.out.print(str); //this will return "hk"

If you have any questions, don't hesitate, post something!

jquery: change the URL address without redirecting?

No, because that would open up the floodgates for phishing. The only part of the URI you can change is the fragment (everything after the #). You can do so by setting window.location.hash.

Cannot use Server.MapPath

Firt add a reference to System.web, if you don't have. Do that in the References folder.

You can then use Hosting.HostingEnvironment.MapPath(path);

Color text in terminal applications in UNIX

You probably want ANSI color codes. Most *nix terminals support them.

How to avoid Sql Query Timeout

You could put an index on MemberType.

For loop in Oracle SQL

You will certainly be able to do that using WITH clause, or use analytic functions available in Oracle SQL.

With some effort you'd be able to get anything out of them in terms of cycles as in ordinary procedural languages. Both approaches are pretty powerful compared to ordinary SQL.

http://www.dba-oracle.com/t_with_clause.htm

http://www.orafaq.com/node/55

It requires some effort though. Don't be afraid to post a concrete example.

Using simple pseudo table DUAL helps too.

Angular 2 - View not updating after model changes

It might be that the code in your service somehow breaks out of Angular's zone. This breaks change detection. This should work:

import {Component, OnInit, NgZone} from 'angular2/core';

export class RecentDetectionComponent implements OnInit {

    recentDetections: Array<RecentDetection>;

    constructor(private zone:NgZone, // <== added
        private recentDetectionService: RecentDetectionService) {
        this.recentDetections = new Array<RecentDetection>();
    }

    getRecentDetections(): void {
        this.recentDetectionService.getJsonFromApi()
            .subscribe(recent => { 
                 this.zone.run(() => { // <== added
                     this.recentDetections = recent;
                     console.log(this.recentDetections[0].macAddress) 
                 });
        });
    }

    ngOnInit() {
        this.getRecentDetections();
        let timer = Observable.timer(2000, 5000);
        timer.subscribe(() => this.getRecentDetections());
    }
}

For other ways to invoke change detection see Triggering change detection manually in Angular

Alternative ways to invoke change detection are

ChangeDetectorRef.detectChanges()

to immediately run change detection for the current component and its children

ChangeDetectorRef.markForCheck()

to include the current component the next time Angular runs change detection

ApplicationRef.tick()

to run change detection for the whole application

Is there a way to include commas in CSV columns without breaking the formatting?

May not be what is needed here but it's a very old question and the answer may help others. A tip I find useful with importing into Excel with a different separator is to open the file in a text editor and add a first line like:

sep=|

where | is the separator you wish Excel to use. Alternatively you can change the default separator in Windows but a bit long-winded:

Control Panel>Clock & region>Region>Formats>Additional>Numbers>List separator [change from comma to your preferred alternative]. That means Excel will also default to exporting CSVs using the chosen separator.

How to close a GUI when I push a JButton?

Create a method and call it to close the JFrame, for example:

public void CloseJframe(){
    super.dispose();
}

HTTP get with headers using RestTemplate

Take a look at the JavaDoc for RestTemplate.

There is the corresponding getForObject methods that are the HTTP GET equivalents of postForObject, but they doesn't appear to fulfil your requirements of "GET with headers", as there is no way to specify headers on any of the calls.

Looking at the JavaDoc, no method that is HTTP GET specific allows you to also provide header information. There are alternatives though, one of which you have found and are using. The exchange methods allow you to provide an HttpEntity object representing the details of the request (including headers). The execute methods allow you to specify a RequestCallback from which you can add the headers upon its invocation.

Java IOException "Too many open files"

For UNIX:

As Stephen C has suggested, changing the maximum file descriptor value to a higher value avoids this problem.

Try looking at your present file descriptor capacity:

   $ ulimit -n

Then change the limit according to your requirements.

   $ ulimit -n <value>

Note that this just changes the limits in the current shell and any child / descendant process. To make the change "stick" you need to put it into the relevant shell script or initialization file.

How do I check if the mouse is over an element in jQuery?

I combined ideas from this topic and came up with this, which is useful for showing/hiding a submenu:

$("#menu_item_a").mouseenter(function(){
   clearTimeout($(this).data('timeoutId'));
   $("#submenu_a").fadeIn("fast");
}).mouseleave(function(){
   var menu_item = $(this);

   var timeoutId = setTimeout(function(){
      if($('#submenu_a').is(':hover'))
      {
        clearTimeout(menu_item.data('timeoutId'));
      }
      else
      {
        $("#submenu_a").fadeOut("fast");
      }
   }, 650);

    menu_item.data('timeoutId', timeoutId); 
});

 $("#submenu_a").mouseleave(function(){
   $(this).fadeOut("fast");
 });

Seems to work for me. Hope this helps someone.

EDIT: Now realizing this approach is not working correctly in IE.

Showing percentages above bars on Excel column graph

Either

  1. Use a line series to show the %
  2. Update the data labels above the bars to link back directly to other cells

Method 2 by step

  • add data-lables
  • right-click the data lable
  • goto the edit bar and type in a refence to a cell (C4 in this example)
  • this changes the data lable from the defulat value (2000) to a linked cell with the 15%

enter image description here

How to remove an id attribute from a div using jQuery?

I'm not sure what jQuery api you're looking at, but you should only have to specify id.

$('#thumb').removeAttr('id');

What does if [ $? -eq 0 ] mean for shell scripts?

$? is the exit status of the most recently-executed command; by convention, 0 means success and anything else indicates failure. That line is testing whether the grep command succeeded.

The grep manpage states:

The exit status is 0 if selected lines are found, and 1 if not found. If an error occurred the exit status is 2. (Note: POSIX error handling code should check for '2' or greater.)

So in this case it's checking whether any ERROR lines were found.

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

Don't use wsgiref for production. Use Apache and mod_wsgi, or something else.

We continue to see these connection resets, sometimes frequently, with wsgiref (the backend used by the werkzeug test server, and possibly others like the Django test server). Our solution was to log the error, retry the call in a loop, and give up after ten failures. httplib2 tries twice, but we needed a few more. They seem to come in bunches as well - adding a 1 second sleep might clear the issue.

We've never seen a connection reset when running through Apache and mod_wsgi. I don't know what they do differently, (maybe they just mask them), but they don't appear.

When we asked the local dev community for help, someone confirmed that they see a lot of connection resets with wsgiref that go away on the production server. There's a bug there, but it is going to be hard to find it.

How to align an image dead center with bootstrap

You should use

<div class="row fluid-img">
  <img class="col-lg-12 col-xs-12" src="src.png">
</div>

.fluid-img {
    margin: 60px auto;
}

@media( min-width: 768px ){
        .fluid-img {
            max-width: 768px;
        }
}
@media screen and (min-width: 768px) {
        .fluid-img {
            padding-left: 0;
            padding-right: 0;
        }
}

How to unpack pkl file?

Generally

Your pkl file is, in fact, a serialized pickle file, which means it has been dumped using Python's pickle module.

To un-pickle the data you can:

import pickle


with open('serialized.pkl', 'rb') as f:
    data = pickle.load(f)

For the MNIST data set

Note gzip is only needed if the file is compressed:

import gzip
import pickle


with gzip.open('mnist.pkl.gz', 'rb') as f:
    train_set, valid_set, test_set = pickle.load(f)

Where each set can be further divided (i.e. for the training set):

train_x, train_y = train_set

Those would be the inputs (digits) and outputs (labels) of your sets.

If you want to display the digits:

import matplotlib.cm as cm
import matplotlib.pyplot as plt


plt.imshow(train_x[0].reshape((28, 28)), cmap=cm.Greys_r)
plt.show()

mnist_digit

The other alternative would be to look at the original data:

http://yann.lecun.com/exdb/mnist/

But that will be harder, as you'll need to create a program to read the binary data in those files. So I recommend you to use Python, and load the data with pickle. As you've seen, it's very easy. ;-)

Android - Set text to TextView

In layout file.

<TextView
   android:id="@+id/myTextView"
   android:layout_width="match_parent"
   android:layout_height="wrap_content"
   android:text="Some Text"
   android:textSize="18sp"
   android:textColor="#000000"/>

In Activity

TextView myTextView = (TextView)findViewById(R.id.myTextView);
myTextView.setText("Hello World!");

How to ensure that there is a delay before a service is started in systemd?

You can run the sleep command before your ExecStart with ExecStartPre :

[Service]
ExecStartPre=/bin/sleep 30

Remove the first character of a string

python 2.x

s = ":dfa:sif:e"
print s[1:]

python 3.x

s = ":dfa:sif:e"
print(s[1:])

both prints

dfa:sif:e

How do I set the path to a DLL file in Visual Studio?

I had the same problem and my problem had nothing to do with paths. One of my dll-s was written in c++ and it turnes out that if your visual studio doesn't know how to open a dll file it will say that it did not find it. What i did was locate which dll it did not find, than searched for that dll in my directories and opened it in a separate visual studio window. When trying to navigate through Solution explorer of that project, visual studio said that it cannot show what is inside and that i need some extra extensions, so that it can open those files. Surely enough, after installing the recomended extension (in my case something to do with c++) the

"This application has failed to start because xxx.dll was not found."

error miraculously dissapeared.

When should you use a class vs a struct in C++?

One place where a struct has been helpful for me is when I have a system that's receiving fixed format messages (over say, a serial port) from another system. You can cast the stream of bytes into a struct that defines your fields, and then easily access the fields.

typedef struct
{
    int messageId;
    int messageCounter;
    int messageData;
} tMessageType;

void processMessage(unsigned char *rawMessage)
{
    tMessageType *messageFields = (tMessageType *)rawMessage;
    printf("MessageId is %d\n", messageFields->messageId);
}

Obviously, this is the same thing you would do in C, but I find that the overhead of having to decode the message into a class is usually not worth it.

How to give a Blob uploaded as FormData a file name?

That name looks derived from an object URL GUID. Do the following to get the object URL that the name was derived from.

var URL = self.URL || self.webkitURL || self;
var object_url = URL.createObjectURL(blob);
URL.revokeObjectURL(object_url);

object_url will be formatted as blob:{origin}{GUID} in Google Chrome and moz-filedata:{GUID} in Firefox. An origin is the protocol+host+non-standard port for the protocol. For example, blob:http://stackoverflow.com/e7bc644d-d174-4d5e-b85d-beeb89c17743 or blob:http://[::1]:123/15111656-e46c-411d-a697-a09d23ec9a99. You probably want to extract the GUID and strip any dashes.

byte[] to file in Java

Use Apache Commons IO

FileUtils.writeByteArrayToFile(new File("pathname"), myByteArray)

Or, if you insist on making work for yourself...

try (FileOutputStream fos = new FileOutputStream("pathname")) {
   fos.write(myByteArray);
   //fos.close(); There is no more need for this line since you had created the instance of "fos" inside the try. And this will automatically close the OutputStream
}

Join two data frames, select all columns from one and some columns from the other

function to drop duplicate columns after joining.

check it

def dropDupeDfCols(df): newcols = [] dupcols = []

for i in range(len(df.columns)):
    if df.columns[i] not in newcols:
        newcols.append(df.columns[i])
    else:
        dupcols.append(i)

df = df.toDF(*[str(i) for i in range(len(df.columns))])
for dupcol in dupcols:
    df = df.drop(str(dupcol))

return df.toDF(*newcols)

Why is setTimeout(fn, 0) sometimes useful?

setTimout on 0 is also very useful in the pattern of setting up a deferred promise, which you want to return right away:

myObject.prototype.myMethodDeferred = function() {
    var deferredObject = $.Deferred();
    var that = this;  // Because setTimeout won't work right with this
    setTimeout(function() { 
        return myMethodActualWork.call(that, deferredObject);
    }, 0);
    return deferredObject.promise();
}

How to find the largest file in a directory and its subdirectories?

ls -alR|awk '{ if ($5 > max) {max=$5;ff=$9}} END {print max "\t" ff;}'

Configure DataSource programmatically in Spring Boot

If you want more datesource configs e.g.

spring.datasource.test-while-idle=true 
spring.datasource.time-between-eviction-runs-millis=30000
spring.datasource.validation-query=select 1

you could use below code

@Bean
public DataSource dataSource() {
    DataSource dataSource = new DataSource(); // org.apache.tomcat.jdbc.pool.DataSource;
    dataSource.setDriverClassName(driverClassName);
    dataSource.setUrl(url);
    dataSource.setUsername(username);
    dataSource.setPassword(password);
    dataSource.setTestWhileIdle(testWhileIdle);     
    dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMills);
    dataSource.setValidationQuery(validationQuery);
    return dataSource;
}

refer: Spring boot jdbc Connection

Unresponsive KeyListener for JFrame

You must add your keyListener to every component that you need. Only the component with the focus will send these events. For instance, if you have only one TextBox in your JFrame, that TextBox has the focus. So you must add a KeyListener to this component as well.

The process is the same:

myComponent.addKeyListener(new KeyListener ...);

Note: Some components aren't focusable like JLabel.

For setting them to focusable you need to:

myComponent.setFocusable(true);

What is the Git equivalent for revision number?

I wrote some PowerShell utilities for retrieving version information from Git and simplifying tagging

functions: Get-LastVersion, Get-Revision, Get-NextMajorVersion, Get-NextMinorVersion, TagNextMajorVersion, TagNextMinorVersion:

# Returns the last version by analysing existing tags,
# assumes an initial tag is present, and
# assumes tags are named v{major}.{minor}.[{revision}]
#
function Get-LastVersion(){
  $lastTagCommit = git rev-list --tags --max-count=1
  $lastTag = git describe --tags $lastTagCommit
  $tagPrefix = "v"
  $versionString = $lastTag -replace "$tagPrefix", ""
  Write-Host -NoNewline "last tagged commit "
  Write-Host -NoNewline -ForegroundColor "yellow" $lastTag
  Write-Host -NoNewline " revision "
  Write-Host -ForegroundColor "yellow" "$lastTagCommit"
  [reflection.assembly]::LoadWithPartialName("System.Version")

  $version = New-Object System.Version($versionString)
  return $version;
}

# Returns current revision by counting the number of commits to HEAD
function Get-Revision(){
   $lastTagCommit = git rev-list HEAD
   $revs  = git rev-list $lastTagCommit |  Measure-Object -Line
   return $revs.Lines
}

# Returns the next major version {major}.{minor}.{revision}
function Get-NextMajorVersion(){
    $version = Get-LastVersion;
    [reflection.assembly]::LoadWithPartialName("System.Version")
    [int] $major = $version.Major+1;
    $rev = Get-Revision
    $nextMajor = New-Object System.Version($major, 0, $rev);
    return $nextMajor;
}

# Returns the next minor version {major}.{minor}.{revision}
function Get-NextMinorVersion(){
    $version = Get-LastVersion;
    [reflection.assembly]::LoadWithPartialName("System.Version")
    [int] $minor = $version.Minor+1;
    $rev = Get-Revision
    $next = New-Object System.Version($version.Major, $minor, $rev);
    return $next;
}

# Creates a tag with the next minor version
function TagNextMinorVersion($tagMessage){
    $version = Get-NextMinorVersion;
    $tagName = "v{0}" -f "$version".Trim();
    Write-Host -NoNewline "Tagging next minor version to ";
    Write-Host -ForegroundColor DarkYellow "$tagName";
    git tag -a $tagName -m $tagMessage
}

# Creates a tag with the next major version (minor version starts again at 0)
function TagNextMajorVersion($tagMessage){
    $version = Get-NextMajorVersion;
    $tagName = "v{0}" -f "$version".Trim();
    Write-Host -NoNewline "Tagging next majo version to ";
    Write-Host -ForegroundColor DarkYellow "$tagName";
    git tag -a $tagName -m $tagMessage
}

Creating watermark using html and css

Other solutions are great but they didn't take care of the fact that watermark shouldn't get selected on selection from the mouse. This fiddle takes care or that: https://jsfiddle.net/MiKr13/d1r4o0jg/9/

This will be better option for pdf or static html.

CSS:

#watermark {
  opacity: 0.2;
  font-size: 52px;
  color: 'black';
  background: '#ccc';
  position: absolute;
  cursor: default;
  user-select: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  right: 5px;
  bottom: 5px;
}

How to query nested objects?

db.messages.find( { headers : { From: "[email protected]" } } )

This queries for documents where headers equals { From: ... }, i.e. contains no other fields.


db.messages.find( { 'headers.From': "[email protected]" } )

This only looks at the headers.From field, not affected by other fields contained in, or missing from, headers.


Dot-notation docs

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

The most straightforward answer which worked for me was this

sudo apt-get install openssl ca-certificates

And voila!!!

Get checkbox list values with jQuery

You can try this...

$(document).ready(function() {
        $("button").click(function(){
            var checkBoxValues = [];
            $.each($("input[name='check_name']:checked"), function(){
                checkBoxValues.push($(this).val());
            });

            console.log(checkBoxValues);

        });
    });

How can I tell which button was clicked in a PHP form submit?

Are you asking in php or javascript.

If it is in php, give the name of that and use the post or get method, after that you can use the option of isset or that particular button name is checked to that value.

If it is in js, use getElementById for that

How do I see the extensions loaded by PHP?

Are you looking for a particular extension? In your phpinfo();, just hit Ctrl+F in your web browser, type in the first 3-4 letters of the extension you're looking for, and it should show you whether or not its loaded.

Usually in phpinfo() it doesn't show you all the loaded extensions in one location, it has got a separate section for each loaded extension where it shows all of its variables, file paths, etc, so if there is no section for your extension name it probably means it isn't loaded.

Alternatively you can open your php.ini file and use the Ctrl+F method to find your extension, and see if its been commented out (usually by a semicolon near the start of the line).

How can I force browsers to print background images in CSS?

Browsers, by default, have their option to print background-colors and images turned off. You can add some lines in CSS to bypass this. Just add:

* {
    -webkit-print-color-adjust: exact !important;   /* Chrome, Safari */
    color-adjust: exact !important;                 /*Firefox*/
}

Note: It's not working on the entire body but you could speciy it for a inner element or a container div element.

Can I dispatch an action in reducer?

You might try using a library like redux-saga. It allows for a very clean way to sequence async functions, fire off actions, use delays and more. It is very powerful!

Loading a .json file into c# program

As mentioned in the other answer I would recommend using json.NET. You can download the package using NuGet. Then to deserialize your json files into C# objects you can do something like;

   JsonSerializer serializer = new JsonSerializer();
   MyObject obj = serializer.Deserialize<MyObject>(File.ReadAllText(@".\path\to\json\config\file.json");

The above code assumes that you have something like

public class MyObject
{
    public string prop1 { get; set; };
    public string prop2 { get; set; };
}

And your json looks like;

{
      "prop1":"value1",
      "prop2":"value2"
}

I prefer using the generic deserialize method which will deserialize json into an object assuming that you provide it with a type who's definition matches the json's. If there are discrepancies between the two it could throw, or not set values, or just ignore things in the json, depends on what the problem is. If the json definition exactly matches the C# types definition then it just works.

Fetching data from MySQL database using PHP, Displaying it in a form for editing

<form action="Delegate_update.php" method="post">
  Name
  <input type="text" name= "Name" value= "<?php echo $row['Name']; ?> "size=10>
  Username
  <input type="text" name= "Username" value= "<?php echo $row['Username']; ?> "size=10>
  Password
  <input type="text" name= "Password" value= "<?php echo $row['Password']; ?>" size=17>
  <input type="submit" name= "submit" value="Update">
</form>

look into this

C++ template constructor

template<class...>struct types{using type=types;};
template<class T>struct tag{using type=T;};
template<class Tag>using type_t=typename Tag::type;

the above helpers let you work with types as values.

class A {
  template<class T>
  A( tag<T> );
};

the tag<T> type is a variable with no state besides the type it caries. You can use this to pass a pure-type value into a template function and have the type be deduced by the template function:

auto a = A(tag<int>{});

You can pass in more than one type:

class A {
  template<class T, class U, class V>
  A( types<T,U,V> );
};
auto a = A(types<int,double,std::string>{});

JQuery How to extract value from href tag?

Here's a method that works by transforming the querystring into JSON...

var link = $('a').attr('href');

if (link.indexOf("?") != -1) {
    var query = link.split("?")[1];

    eval("query = {" + query.replace(/&/ig, "\",").replace(/=/ig, ":\"") + "\"};");

    if (query.page)
        alert(unescape(query.page));
    else
        alert('No page parameter');

} else {
    alert('No querystring');
}

I'd go with a library like the others suggest though... =)

What is the default value for Guid?

The default value for a GUID is empty. (eg: 00000000-0000-0000-0000-000000000000)

This can be invoked using Guid.Empty or new Guid()

If you want a new GUID, you use Guid.NewGuid()

When to use the JavaScript MIME type application/javascript instead of text/javascript?

application because .js-Files aren't something a user wants to read but something that should get executed.

"Items collection must be empty before using ItemsSource."

Perhaps not such an useful answer, but I had the same problem when changing column order and made mistake like the one in the following sample. Having a lot of columns, I reordered them and somehow pasted one after closing tag /DataGrid.Columns:

       <DataGridTemplateColumn x:Name="addedDateColumn" Header="Added Date" Width="SizeToHeader">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=AddedDate}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
        </DataGrid.Columns>
            <DataGridTemplateColumn x:Name="rowguidColumn" Header="rowguid" Width="SizeToHeader">
                <DataGridTemplateColumn.CellTemplate>
                    <DataTemplate>
                        <TextBlock Text="{Binding Path=rowguid}" />
                    </DataTemplate>
                </DataGridTemplateColumn.CellTemplate>
            </DataGridTemplateColumn>
    </DataGrid>

Anyway, lost half an hour because of this. Hope this helps others.

RequiredIf Conditional Validation Attribute

If you try to use "ModelState.Remove" or "ModelState["Prop"].Errors.Clear()" the "ModelState.IsValid" stil returns false.

Why not just removing the default "Required" Annotation from Model and make your custom validation before the "ModelState.IsValid" on Controller 'Post' action? Like this:

if (!String.IsNullOrEmpty(yourClass.Property1) && String.IsNullOrEmpty(yourClass.dependantProperty))            
            ModelState.AddModelError("dependantProperty", "It´s necessary to select some 'dependant'.");

How can I indent multiple lines in Xcode?

Shortcut key:

ctrl + i

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

Multi-dimensional arraylist or list in C#?

you just make a list of lists like so:

List<List<string>> results = new List<List<string>>();

and then it's just a matter of using the functionality you want

results.Add(new List<string>()); //adds a new list to your list of lists
results[0].Add("this is a string"); //adds a string to the first list
results[0][0]; //gets the first string in your first list

Building with Lombok's @Slf4j and Intellij: Cannot find symbol log

I had the same kind of error, right after a warning like the following:

java: You aren't using a compiler supported by lombok, so lombok will not work and has been disabled.
  Your processor is: com.sun.proxy.$Proxy27
  Lombok supports: OpenJDK javac, ECJ

In my case, it was an unfortunate combination of lombok < 1.18.16 and IDEA 2020.3.

No 'Access-Control-Allow-Origin' - Node / Apache Port Issue

All the other answers didn't work for me. (including cors package, or setting headers through middleware)

For socket.io 3^ this worked without any extra packages.

const express = require('express');
const app = express();

const server = require('http').createServer(app);
const io = require('socket.io')(server, {
    cors: {
        origin: "*",
        methods: ["GET", "POST"]
    }
});

JUnit Testing private variables?

I can't tell if you've found some special case code which requires you to test against private fields. But in my experience you never have to test something private - always public. Maybe you could give an example of some code where you need to test private?

Read .csv file in C

With fscanf read the file until you encounter ';' or \n, then you can just skip it with fscang(f, "%*c").

int main()
{
    char str[128];
    int result;
    FILE* f = fopen("test.txt", "r");
    ...
    
    do {
        result = fscanf(f, "%127[^;\n]", str);
        
        if(result == 0)
        {
            result = fscanf(f, "%*c");
        }
        else
        {
            //whatever you want to do with your value
            printf("%s\n", str);
        }
        
    } while(result != EOF);

    return 0;
}

Rails filtering array of objects by attribute value

have you tried eager loading?

@attachments = Job.includes(:attachments).find(1).attachments

Branch from a previous commit using Git

if you use source tree that is pretty straight forward.

  • Right click the commit from where you need to create a new branch
  • Click on 'branch'
  • Type name of new branch in the dialog appeared and click 'create branch'

Why does git perform fast-forward merges by default?

Fast-forward merging makes sense for short-lived branches, but in a more complex history, non-fast-forward merging may make the history easier to understand, and make it easier to revert a group of commits.

Warning: Non-fast-forwarding has potential side effects as well. Please review https://sandofsky.com/blog/git-workflow.html, avoid the 'no-ff' with its "checkpoint commits" that break bisect or blame, and carefully consider whether it should be your default approach for master.

alt text
(From nvie.com, Vincent Driessen, post "A successful Git branching model")

Incorporating a finished feature on develop

Finished features may be merged into the develop branch to add them to the upcoming release:

$ git checkout develop
Switched to branch 'develop'
$ git merge --no-ff myfeature
Updating ea1b82a..05e9557
(Summary of changes)
$ git branch -d myfeature
Deleted branch myfeature (was 05e9557).
$ git push origin develop

The --no-ff flag causes the merge to always create a new commit object, even if the merge could be performed with a fast-forward. This avoids losing information about the historical existence of a feature branch and groups together all commits that together added the feature.

Jakub Narebski also mentions the config merge.ff:

By default, Git does not create an extra merge commit when merging a commit that is a descendant of the current commit. Instead, the tip of the current branch is fast-forwarded.
When set to false, this variable tells Git to create an extra merge commit in such a case (equivalent to giving the --no-ff option from the command line).
When set to 'only', only such fast-forward merges are allowed (equivalent to giving the --ff-only option from the command line).


The fast-forward is the default because:

  • short-lived branches are very easy to create and use in Git
  • short-lived branches often isolate many commits that can be reorganized freely within that branch
  • those commits are actually part of the main branch: once reorganized, the main branch is fast-forwarded to include them.

But if you anticipate an iterative workflow on one topic/feature branch (i.e., I merge, then I go back to this feature branch and add some more commits), then it is useful to include only the merge in the main branch, rather than all the intermediate commits of the feature branch.

In this case, you can end up setting this kind of config file:

[branch "master"]
# This is the list of cmdline options that should be added to git-merge 
# when I merge commits into the master branch.

# The option --no-commit instructs git not to commit the merge
# by default. This allows me to do some final adjustment to the commit log
# message before it gets commited. I often use this to add extra info to
# the merge message or rewrite my local branch names in the commit message
# to branch names that are more understandable to the casual reader of the git log.

# Option --no-ff instructs git to always record a merge commit, even if
# the branch being merged into can be fast-forwarded. This is often the
# case when you create a short-lived topic branch which tracks master, do
# some changes on the topic branch and then merge the changes into the
# master which remained unchanged while you were doing your work on the
# topic branch. In this case the master branch can be fast-forwarded (that
# is the tip of the master branch can be updated to point to the tip of
# the topic branch) and this is what git does by default. With --no-ff
# option set, git creates a real merge commit which records the fact that
# another branch was merged. I find this easier to understand and read in
# the log.

mergeoptions = --no-commit --no-ff

The OP adds in the comments:

I see some sense in fast-forward for [short-lived] branches, but making it the default action means that git assumes you... often have [short-lived] branches. Reasonable?

Jefromi answers:

I think the lifetime of branches varies greatly from user to user. Among experienced users, though, there's probably a tendency to have far more short-lived branches.

To me, a short-lived branch is one that I create in order to make a certain operation easier (rebasing, likely, or quick patching and testing), and then immediately delete once I'm done.
That means it likely should be absorbed into the topic branch it forked from, and the topic branch will be merged as one branch. No one needs to know what I did internally in order to create the series of commits implementing that given feature.

More generally, I add:

it really depends on your development workflow:

  • if it is linear, one branch makes sense.
  • If you need to isolate features and work on them for a long period of time and repeatedly merge them, several branches make sense.

See "When should you branch?"

Actually, when you consider the Mercurial branch model, it is at its core one branch per repository (even though you can create anonymous heads, bookmarks and even named branches)
See "Git and Mercurial - Compare and Contrast".

Mercurial, by default, uses anonymous lightweight codelines, which in its terminology are called "heads".
Git uses lightweight named branches, with injective mapping to map names of branches in remote repository to names of remote-tracking branches.
Git "forces" you to name branches (well, with the exception of a single unnamed branch, which is a situation called a "detached HEAD"), but I think this works better with branch-heavy workflows such as topic branch workflow, meaning multiple branches in a single repository paradigm.

converting a javascript string to a html object

var s = '<div id="myDiv"></div>';
var htmlObject = document.createElement('div');
htmlObject.innerHTML = s;
htmlObject.getElementById("myDiv").style.marginTop = something;

OR operator in switch-case?

What are the backgrounds for a switch-case to not accept this operator?

Because case requires constant expression as its value. And since an || expression is not a compile time constant, it is not allowed.

From JLS Section 14.11:

Switch label should have following syntax:

SwitchLabel:
case ConstantExpression :
case EnumConstantName :
default :


Under the hood:

The reason behind allowing just constant expression with cases can be understood from the JVM Spec Section 3.10 - Compiling Switches:

Compilation of switch statements uses the tableswitch and lookupswitch instructions. The tableswitch instruction is used when the cases of the switch can be efficiently represented as indices into a table of target offsets. The default target of the switch is used if the value of the expression of the switch falls outside the range of valid indices.

So, for the cases label to be used by tableswitch as a index into the table of target offsets, the value of the case should be known at compile time. That is only possible if the case value is a constant expression. And || expression will be evaluated at runtime, and the value will only be available at that time.

From the same JVM section, the following switch-case:

switch (i) {
    case 0:  return  0;
    case 1:  return  1;
    case 2:  return  2;
    default: return -1;
}

is compiled to:

0   iload_1             // Push local variable 1 (argument i)
1   tableswitch 0 to 2: // Valid indices are 0 through 2  (NOTICE This instruction?)
      0: 28             // If i is 0, continue at 28
      1: 30             // If i is 1, continue at 30
      2: 32             // If i is 2, continue at 32
      default:34        // Otherwise, continue at 34
28  iconst_0            // i was 0; push int constant 0...
29  ireturn             // ...and return it
30  iconst_1            // i was 1; push int constant 1...
31  ireturn             // ...and return it
32  iconst_2            // i was 2; push int constant 2...
33  ireturn             // ...and return it
34  iconst_m1           // otherwise push int constant -1...
35  ireturn             // ...and return it

So, if the case value is not a constant expressions, compiler won't be able to index it into the table of instruction pointers, using tableswitch instruction.

Set The Window Position of an application via command line

You'll need an additional utility such as cmdow.exe to accomplish this. Look specifically at the /mov switch. You can either launch your program from cmdow or run it separately and then invoke cmdow to move/resize it as desired.

Get Absolute URL from Relative path (refactored method)

If you're in the context of an MVC Controller or View you can use the UrlHelper which should be accessible via just Url

Url.Content("~/content/images/myimage.jpg")

Which will be fully expanded to /virtual_directoryname/content/images/myimage.jpg

This can be used in a controller or .cshtml file

Yes it is a little odd that it's called Content but it's meant to be used to get an absolute path to a resource so it makes sense

Random String Generator Returning Same String

This is my solution:

private string RandomString(int length)
{
    char[] symbols = { 
                            '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                            'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
                            'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'                             
                        };

    Stack<byte> bytes = new Stack<byte>();
    string output = string.Empty;

    for (int i = 0; i < length; i++)
    {
        if (bytes.Count == 0)
        {
            bytes = new Stack<byte>(Guid.NewGuid().ToByteArray());
        }
        byte pop = bytes.Pop();
        output += symbols[(int)pop % symbols.Length];
    }
    return output;
}

// get 1st random string 
string Rand1 = RandomString(4);

// get 2nd random string 
string Rand2 = RandomString(4);

// create full rand string
string docNum = Rand1 + "-" + Rand2;

Computed / calculated / virtual / derived columns in PostgreSQL

PostgreSQL 12 supports generated columns:

PostgreSQL 12 Beta 1 Released!

Generated Columns

PostgreSQL 12 allows the creation of generated columns that compute their values with an expression using the contents of other columns. This feature provides stored generated columns, which are computed on inserts and updates and are saved on disk. Virtual generated columns, which are computed only when a column is read as part of a query, are not implemented yet.


Generated Columns

A generated column is a special column that is always computed from other columns. Thus, it is for columns what a view is for tables.

CREATE TABLE people (
    ...,
    height_cm numeric,
    height_in numeric GENERATED ALWAYS AS (height_cm * 2.54) STORED
);

db<>fiddle demo

Pyspark: display a spark data frame in a table format

The show method does what you're looking for.

For example, given the following dataframe of 3 rows, I can print just the first two rows like this:

df = sqlContext.createDataFrame([("foo", 1), ("bar", 2), ("baz", 3)], ('k', 'v'))
df.show(n=2)

which yields:

+---+---+
|  k|  v|
+---+---+
|foo|  1|
|bar|  2|
+---+---+
only showing top 2 rows

Setting a backgroundImage With React Inline Styles

You can also bring the image into the component by using the require() function.

<div style={{ backgroundImage: `url(require("images/img.svg"))` }}>

Note the two sets of curly brackets. The first set is for entering react mode and the second is for denoting object

Get the cell value of a GridView row

I had the same problem as yours. I found that when i use the BoundField tag in GridView to show my data. The row.Cells[1].Text is working in:

GridViewRow row = dgCustomer.SelectedRow;
TextBox1.Text = "Cell Value" + row.Cells[1].Text + "";

But when i use TemplateField tag to show data like this:

 <asp:TemplateField HeaderText="??">
    <ItemTemplate>
    <asp:Label ID="Part_No" runat="server" Text='<%# Eval("Part_No")%>' ></asp:Label>
    </ItemTemplate>
    <HeaderStyle CssClass="bhead" />
    <ItemStyle CssClass="bbody" />
    </asp:TemplateField>

The row.Cells[1].Text just return null. I got stuck in this problem for a long time. I figur out recently and i want to share with someone who have the same problem my solution. Please feel free to edit this post and/or correct me.

My Solution:

Label lbCod = GridView1.Rows["AnyValidIndex"].Cells["AnyValidIndex"].Controls["AnyValidIndex"] as Label;

I use Controls attribute to find the Label control which i use to show data, and you can find yours. When you find it and convert to the correct type object than you can extract text and so on. Ex:

string showText = lbCod.Text;

Reference: reference

NSRange to Range<String.Index>

func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool {

       let strString = ((textField.text)! as NSString).stringByReplacingCharactersInRange(range, withString: string)

 }

Resize an Array while keeping current elements in Java?

You can't resize an array in Java. You'd need to either:

  1. Create a new array of the desired size, and copy the contents from the original array to the new array, using java.lang.System.arraycopy(...);

  2. Use the java.util.ArrayList<T> class, which does this for you when you need to make the array bigger. It nicely encapsulates what you describe in your question.

  3. Use java.util.Arrays.copyOf(...) methods which returns a bigger array, with the contents of the original array.

jQuery - How to dynamically add a validation rule

To validate all dynamically generated elements could add a special class to each of these elements and use each() function, something like

$("#DivIdContainer .classToValidate").each(function () {
    $(this).rules('add', {
        required: true
    });
});

AngularJS ng-style with a conditional expression

if you want use with expression, the rigth way is :

<span class="ng-style: yourCondition && {color:'red'};">Sample Text</span>

but the best way is using ng-class

Python strptime() and timezones?

Since strptime returns a datetime object which has tzinfo attribute, We can simply replace it with desired timezone.

>>> import datetime

>>> date_time_str = '2018-06-29 08:15:27.243860'
>>> date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc)
>>> date_time_obj.tzname()
'UTC'

Sending and receiving UDP packets?

The receiver must set port of receiver to match port set in sender DatagramPacket. For debugging try listening on port > 1024 (e.g. 8000 or 9000). Ports < 1024 are typically used by system services and need admin access to bind on such a port.

If the receiver sends packet to the hard-coded port it's listening to (e.g. port 57) and the sender is on the same machine then you would create a loopback to the receiver itself. Always use the port specified from the packet and in case of production software would need a check in any case to prevent such a case.

Another reason a packet won't get to destination is the wrong IP address specified in the sender. UDP unlike TCP will attempt to send out a packet even if the address is unreachable and the sender will not receive an error indication. You can check this by printing the address in the receiver as a precaution for debugging.

In the sender you set:

 byte [] IP= { (byte)192, (byte)168, 1, 106 };
 InetAddress address = InetAddress.getByAddress(IP);

but might be simpler to use the address in string form:

 InetAddress address = InetAddress.getByName("192.168.1.106");

In other words, you set target as 192.168.1.106. If this is not the receiver then you won't get the packet.

Here's a simple UDP Receiver that works :

import java.io.IOException;
import java.net.*;

public class Receiver {

    public static void main(String[] args) {
        int port = args.length == 0 ? 57 : Integer.parseInt(args[0]);
        new Receiver().run(port);
    }

    public void run(int port) {    
      try {
        DatagramSocket serverSocket = new DatagramSocket(port);
        byte[] receiveData = new byte[8];
        String sendString = "polo";
        byte[] sendData = sendString.getBytes("UTF-8");

        System.out.printf("Listening on udp:%s:%d%n",
                InetAddress.getLocalHost().getHostAddress(), port);     
        DatagramPacket receivePacket = new DatagramPacket(receiveData,
                           receiveData.length);

        while(true)
        {
              serverSocket.receive(receivePacket);
              String sentence = new String( receivePacket.getData(), 0,
                                 receivePacket.getLength() );
              System.out.println("RECEIVED: " + sentence);
              // now send acknowledgement packet back to sender     
              DatagramPacket sendPacket = new DatagramPacket(sendData, sendData.length,
                   receivePacket.getAddress(), receivePacket.getPort());
              serverSocket.send(sendPacket);
        }
      } catch (IOException e) {
              System.out.println(e);
      }
      // should close serverSocket in finally block
    }
}

Converting data frame column from character to numeric

If we need only one column to be numeric

yyz$b <- as.numeric(as.character(yyz$b))

But, if all the columns needs to changed to numeric, use lapply to loop over the columns and convert to numeric by first converting it to character class as the columns were factor.

yyz[] <- lapply(yyz, function(x) as.numeric(as.character(x)))

Both the columns in the OP's post are factor because of the string "n/a". This could be easily avoided while reading the file using na.strings = "n/a" in the read.table/read.csv or if we are using data.frame, we can have character columns with stringsAsFactors=FALSE (the default is stringsAsFactors=TRUE)


Regarding the usage of apply, it converts the dataset to matrix and matrix can hold only a single class. To check the class, we need

lapply(yyz, class)

Or

sapply(yyz, class)

Or check

str(yyz)

Visual Studio 2010 shortcut to find classes and methods?

Left click on a method and press the F12 key to Go To Definition. Other Actions also available

Listening for variable changes in JavaScript

In my case, I was trying to find out if any library I was including in my project was redefining my window.player. So, at the begining of my code, I just did:

Object.defineProperty(window, 'player', {
  get: () => this._player,
  set: v => {
    console.log('window.player has been redefined!');
    this._player = v;
  }
});

UnicodeDecodeError, invalid continuation byte

It is invalid UTF-8. That character is the e-acute character in ISO-Latin1, which is why it succeeds with that codeset.

If you don't know the codeset you're receiving strings in, you're in a bit of trouble. It would be best if a single codeset (hopefully UTF-8) would be chosen for your protocol/application and then you'd just reject ones that didn't decode.

If you can't do that, you'll need heuristics.

Get list of passed arguments in Windows batch script (.bat)

If you have parameters in quotes that containing spaces, %* will not work correctly. The best solution I found is to have a loop that joins all arguments: https://serverfault.com/a/22541

set args=%1
shift
:start
if [%1] == [] goto done
set args=%args% %1
shift
goto start

:done
(use %args% here)

How to solve SQL Server Error 1222 i.e Unlock a SQL Server table

To prevent this, make sure every BEGIN TRANSACTION has COMMIT

The following will say successful but will leave uncommitted transactions:

BEGIN TRANSACTION
BEGIN TRANSACTION
<SQL_CODE?
COMMIT

Closing query windows with uncommitted transactions will prompt you to commit your transactions. This will generally resolve the Error 1222 message.

Spring Boot yaml configuration for a list of strings

use comma separated values in application.yml

ignoreFilenames: .DS_Store, .hg

java code for access

@Value("${ignoreFilenames}")    
String[] ignoreFilenames

It is working ;)

Conda activate not working?

As of conda 4.4, the command

conda activate <envname>

is the same on all platforms. The procedure to add conda to the PATH environment variable for non-Windows platforms (on Windows you should use the Anaconda Prompt), as well as the change in environment activation procedure, is detailed in the release notes for conda 4.4.0.


For conda versions older than 4.4, command is either

source activate <envname>

on Linux and macOS or

activate <envname>

on Windows. You need to remove the conda.

Is JavaScript a pass-by-reference or pass-by-value language?

An object outside a function is passed into a function by giving a reference to the outside object.

When you use that reference to manipulate its object, the object outside is thus affected. However, if inside the function you decided to point the reference to something else, you did not affect the object outside at all, because all you did was re-direct the reference to something else.

How to trigger button click in MVC 4

MVC doesn't do events. Just put a form and submit button on the page and the method decorated with the HttpPost attribute will process that request.

You might want to read a tutorial or two on how to create views, forms and controllers.

Java, List only subdirectories from a directory, not files

The solution that worked for me, is missing from the list of answers. Hence I am posting this solution here:

File[]dirs = new File("/mypath/mydir/").listFiles((FileFilter)FileFilterUtils.directoryFileFilter());

Here I have used org.apache.commons.io.filefilter.FileFilterUtils from Apache commons-io-2.2.jar. Its documentation is available here: https://commons.apache.org/proper/commons-io/javadocs/api-2.2/org/apache/commons/io/filefilter/FileFilterUtils.html

What is the difference between an expression and a statement in Python?

Python calls expressions "expression statements", so the question is perhaps not fully formed.

A statement consists of pretty much anything you can do in Python: calculating a value, assigning a value, deleting a variable, printing a value, returning from a function, raising an exception, etc. The full list is here: http://docs.python.org/reference/simple_stmts.html#

An expression statement is limited to calling functions (e.g., math.cos(theta)"), operators ( e.g., "2+3"), etc. to produce a value.

Is it possible to write data to file using only JavaScript?

Yes its possible Here the code is

_x000D_
_x000D_
const fs = require('fs') 
let data = "Learning how to write in a file."
fs.writeFile('Output.txt', data, (err) => { 
      
    // In case of a error throw err. 
    if (err) throw err; 
}) 
_x000D_
_x000D_
_x000D_

CMake link to external library

One more alternative, in the case you are working with the Appstore, need "Entitlements" and as such need to link with an Apple-Framework.

For Entitlements to work (e.g. GameCenter) you need to have a "Link Binary with Libraries"-buildstep and then link with "GameKit.framework". CMake "injects" the libraries on a "low level" into the commandline, hence Xcode doesn't really know about it, and as such you will not get GameKit enabled in the Capabilities screen.

One way to use CMake and have a "Link with Binaries"-buildstep is to generate the xcodeproj with CMake, and then use 'sed' to 'search & replace' and add the GameKit in the way XCode likes it...

The script looks like this (for Xcode 6.3.1).

s#\/\* Begin PBXBuildFile section \*\/#\/\* Begin PBXBuildFile section \*\/\
    26B12AA11C10544700A9A2BA \/\* GameKit.framework in Frameworks \*\/ = {isa = PBXBuildFile; fileRef = 26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/; };#g

s#\/\* Begin PBXFileReference section \*\/#\/\* Begin PBXFileReference section \*\/\
    26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = GameKit.framework; path = System\/Library\/Frameworks\/GameKit.framework; sourceTree = SDKROOT; };#g

s#\/\* End PBXFileReference section \*\/#\/\* End PBXFileReference section \*\/\
\
\/\* Begin PBXFrameworksBuildPhase section \*\/\
    26B12A9F1C10543B00A9A2BA \/\* Frameworks \*\/ = {\
        isa = PBXFrameworksBuildPhase;\
        buildActionMask = 2147483647;\
        files = (\
            26B12AA11C10544700A9A2BA \/\* GameKit.framework in Frameworks xxx\*\/,\
        );\
        runOnlyForDeploymentPostprocessing = 0;\
    };\
\/\* End PBXFrameworksBuildPhase section \*\/\
#g

s#\/\* CMake PostBuild Rules \*\/,#\/\* CMake PostBuild Rules \*\/,\
            26B12A9F1C10543B00A9A2BA \/\* Frameworks xxx\*\/,#g
s#\/\* Products \*\/,#\/\* Products \*\/,\
            26B12AA01C10544700A9A2BA \/\* GameKit.framework xxx\*\/,#g

save this to "gamecenter.sed" and then "apply" it like this ( it changes your xcodeproj! )

sed -i.pbxprojbak -f gamecenter.sed myproject.xcodeproj/project.pbxproj

You might have to change the script-commands to fit your need.

Warning: it's likely to break with different Xcode-version as the project-format could change, the (hardcoded) unique number might not really by unique - and generally the solutions by other people are better - so unless you need to Support the Appstore + Entitlements (and automated builds), don't do this.

This is a CMake bug, see http://cmake.org/Bug/view.php?id=14185 and http://gitlab.kitware.com/cmake/cmake/issues/14185

Change language for bootstrap DateTimePicker

If you use moment.js the you need to load moment-with-locales.min.js not moment.min.js. Otherwise, your locale: 'ru' will not work.

Rails Active Record find(:all, :order => ) issue

This might help too:

Post.order(created_at: :desc)

Disabling user input for UITextfield in swift

If you want to do it while keeping the user interaction on. In my case I am using (or rather misusing) isFocused

self.myField.inputView = UIView()

This way it will focus but keyboard won't show up.

Psql could not connect to server: No such file or directory, 5432 error?

I'm on Kali Linux. I had to remove the brew version of postgresql with

brew uninstall postgresql

sudo -u postgres psql got me into root postgres

How to darken an image on mouseover?

How about this...

<style type="text/css">
    div.frame { background-color: #000; }
    img.pic:hover {
      opacity: .6;
      filter:alpha(opacity=60);
    }
</style>

<div class="frame">
    <img class="pic" src="path/to/image" />
</div>

Why isn't this code to plot a histogram on a continuous value Pandas column working?

EDIT:

After your comments this actually makes perfect sense why you don't get a histogram of each different value. There are 1.4 million rows, and ten discrete buckets. So apparently each bucket is exactly 10% (to within what you can see in the plot).


A quick rerun of your data:

In [25]: df.hist(column='Trip_distance')

enter image description here

Prints out absolutely fine.

The df.hist function comes with an optional keyword argument bins=10 which buckets the data into discrete bins. With only 10 discrete bins and a more or less homogeneous distribution of hundreds of thousands of rows, you might not be able to see the difference in the ten different bins in your low resolution plot:

In [34]: df.hist(column='Trip_distance', bins=50)

enter image description here

How to install/start Postman native v4.10.3 on Ubuntu 16.04 LTS 64-bit?

Don't forget to add sudo otherwise you will get postman.tar.gz: Permission denied error. And unlink postman if you get error like failed to create symbolic link /usr/bin/postman: File exists. So below is the full code:

sudo wget https://dl.pstmn.io/download/latest/linux64 -O postman.tar.gz
sudo tar -xzf postman.tar.gz -C /opt
sudo rm postman.tar.gz

sudo unlink /usr/bin/postman
sudo ln -s /opt/Postman/Postman /usr/bin/postman

Then just run postman in the terminal.

Screen width in React Native

React Native comes with "Dimensions" api which we need to import from 'react-native'

import { Dimensions } from 'react-native';

Then,

<Image source={pic} style={{width: Dimensions.get('window').width, height: Dimensions.get('window').height}}></Image>

Can't run Curl command inside my Docker Container

So I added curl AFTER my docker container was running.

(This was for debugging the container...I did not need a permanent addition)

I ran my image

docker run -d -p 8899:8080 my-image:latest

(the above makes my "app" available on my machine on port 8899) (not important to this question)

Then I listed and created terminal into the running container.

docker ps
docker exec -it my-container-id-here /bin/sh

If the exec command above does not work, check this SOF article:

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

then I ran:

apk

just to prove it existed in the running container, then i ran:

apk add curl

and got the below:

apk add curl

fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/main/x86_64/APKINDEX.tar.gz

fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/community/x86_64/APKINDEX.tar.gz

(1/5) Installing ca-certificates (20171114-r3)

(2/5) Installing nghttp2-libs (1.32.0-r0)

(3/5) Installing libssh2 (1.8.0-r3)

(4/5) Installing libcurl (7.61.1-r1)

(5/5) Installing curl (7.61.1-r1)

Executing busybox-1.28.4-r2.trigger

Executing ca-certificates-20171114-r3.trigger

OK: 18 MiB in 35 packages

then i ran curl:

/ # curl
curl: try 'curl --help' or 'curl --manual' for more information
/ # 

Note, to get "out" of the drilled-in-terminal-window, I had to open a new terminal window and stop the running container:

docker ps
docker stop my-container-id-here

APPEND:

If you don't have "apk" (which depends on which base image you are using), then try to use "another" installer. From other answers here, you can try:

apt-get -qq update

apt-get -qq -y install curl

`node-pre-gyp install --fallback-to-build` failed during MeanJS installation on OSX

Just use this command and it will handle this error npm install --unsafe-perm --allow-root

In Visual Basic how do you create a block comment

There's not a way as of 11/2012, HOWEVER

Highlight Text (In visual Studio.net)

ctrl + k + c, ctrl + k + u

Will comment / uncomment, respectively

Socket File "/var/pgsql_socket/.s.PGSQL.5432" Missing In Mountain Lion (OS X Server)

First remove the installed postgres:

sudo apt-get purge postgr*
sudo apt-get autoremove

Then install 'synaptic':

sudo apt-get install synaptic
sudo apt-get update

Then install Postgres

sudo apt-get install postgresql postgresql-contrib

Commit empty folder structure (with git)

Just add a file .gitkeep in every folder you want committed.

On windows do so by right clicking when in the folder and select: Git bash from here. Then type: touch .gitkeep

Way to create multiline comments in Bash?

Here's how I do multiline comments in bash.

This mechanism has two advantages that I appreciate. One is that comments can be nested. The other is that blocks can be enabled by simply commenting out the initiating line.

#!/bin/bash
# : <<'####.block.A'
echo "foo {" 1>&2
fn data1
echo "foo }" 1>&2
: <<'####.block.B'
fn data2 || exit
exit 1
####.block.B
echo "can't happen" 1>&2
####.block.A

In the example above the "B" block is commented out, but the parts of the "A" block that are not the "B" block are not commented out.

Running that example will produce this output:

foo {
./example: line 5: fn: command not found
foo }
can't happen

Using $_POST to get select option value from HTML

<select name="taskOption">
<option value="1">First</option>
<option value="2">Second</option>
<option value="3">Third</option>
</select>

try this

<?php 
if(isset($_POST['button_name'])){
$var = $_POST['taskOption']
if($var == "1"){
echo"your data here";
}
}?>

How to pass table value parameters to stored procedure from .net code

Generic

   public static DataTable ToTableValuedParameter<T, TProperty>(this IEnumerable<T> list, Func<T, TProperty> selector)
    {
        var tbl = new DataTable();
        tbl.Columns.Add("Id", typeof(T));

        foreach (var item in list)
        {
            tbl.Rows.Add(selector.Invoke(item));

        }

        return tbl;

    }

How to increase apache timeout directive in .htaccess?

Just in case this helps anyone else:

If you're going to be adding the TimeOut directive, and your website uses multiple vhosts (eg. one for port 80, one for port 443), then don't forget to add the directive to all of them!

javascript code to check special characters

If you don't want to include any special character, then try this much simple way for checking special characters using RegExp \W Metacharacter.

var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
if(!(iChars.match(/\W/g)) == "") {
    alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
    return false;
}

Delete a row from a SQL Server table

As you have stated that all column names are of TEXT type, So, there is need to use IDNumber as Text by using single quote around IDNumber.....

    public static void deleteRow(string table, string columnName, string IDNumber)
    {
    try
    {
    using (SqlConnection con = new SqlConnection(Global.connectionString))
    {
         con.Open();
         using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = '" + IDNumber+"'", con))
         {
               command.ExecuteNonQuery();
         }
         con.Close();
    }
    }
    catch (SystemException ex)
       {
       MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));
       }
    }
 }

Replace HTML page with contents retrieved via AJAX

Can't you just try to replace the body content with the document.body handler?

if your page is this:

<html>
<body>
blablabla
<script type="text/javascript">
document.body.innerHTML="hi!";
</script>
</body>
</html>

Just use the document.body to replace the body.

This works for me. All the content of the BODY tag is replaced by the innerHTML you specify. If you need to even change the html tag and all childs you should check out which tags of the 'document.' are capable of doing so.

An example with javascript scripting inside it:

<html>
<body>
blablabla
<script type="text/javascript">
var changeme = "<button onClick=\"document.bgColor = \'#000000\'\">click</button>";
document.body.innerHTML=changeme;
</script>
</body>

This way you can do javascript scripting inside the new content. Don't forget to escape all double and single quotes though, or it won't work. escaping in javascript can be done by traversing your code and putting a backslash in front of all singe and double quotes.

Bare in mind that server side scripting like php doesn't work this way. Since PHP is server-side scripting it has to be processed before a page is loaded. Javascript is a language which works on client-side and thus can not activate the re-processing of php code.

How to refresh Gridview after pressed a button in asp.net

All you have to do is In your bLoanButton_Click , add a line to rebind the Grid to the SqlDataSource :

protected void bLoanButton_Click(object sender, EventArgs e)
{

//your same code
........

GridView1.DataBind();


}

regards

dpi value of default "large", "medium" and "small" text views android

To put it in another way, can we replicate the appearance of these text views without using the android:textAppearance attribute?

Like biegleux already said:

  • small represents 14sp
  • medium represents 18sp
  • large represents 22sp

If you want to use the small, medium or large value on any text in your Android app, you can just create a dimens.xml file in your values folder and define the text size there with the following 3 lines:

<dimen name="text_size_small">14sp</dimen>
<dimen name="text_size_medium">18sp</dimen>
<dimen name="text_size_large">22sp</dimen>

Here is an example for a TextView with large text from the dimens.xml file:

<TextView
  android:id="@+id/hello_world"
  android:text="hello world"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:textSize="@dimen/text_size_large"/>

Using HttpClient and HttpPost in Android with post parameters

You can actually send it as JSON the following way:

// Build the JSON object to pass parameters
JSONObject jsonObj = new JSONObject();
jsonObj.put("username", username);
jsonObj.put("apikey", apikey);
// Create the POST object and add the parameters
HttpPost httpPost = new HttpPost(url);
StringEntity entity = new StringEntity(jsonObj.toString(), HTTP.UTF_8);
entity.setContentType("application/json");
httpPost.setEntity(entity);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(httpPost);

How can I remove the top and right axis in matplotlib?

(This is more of an extension comment, in addition to the comprehensive answers here.)


Note that we can hide each of these three elements independently of each other:

  • To hide the border (aka "spine"): ax.set_frame_on(False) or ax.spines['top'].set_visible(False)

  • To hide the ticks: ax.tick_params(top=False)

  • To hide the labels: ax.tick_params(labeltop=False)

Changing an element's ID with jQuery

I did something similar with this construct

$('li').each(function(){
  if(this.id){
    this.id = this.id+"something";
  }
});

Create a directly-executable cross-platform GUI app using Python

For the GUI itself:

PyQT is pretty much the reference.

Another way to develop a rapid user interface is to write a web app, have it run locally and display the app in the browser.

Plus, if you go for the Tkinter option suggested by lubos hasko you may want to try portablepy to have your app run on Windows environment without Python.

How to update UI from another thread running in another class

Thank God, Microsoft got that figured out in WPF :)

Every Control, like a progress bar, button, form, etc. has a Dispatcher on it. You can give the Dispatcher an Action that needs to be performed, and it will automatically call it on the correct thread (an Action is like a function delegate).

You can find an example here.

Of course, you'll have to have the control accessible from other classes, e.g. by making it public and handing a reference to the Window to your other class, or maybe by passing a reference only to the progress bar.

How to compare data between two table in different databases using Sql Server 2008?

If both database on same server. You can check similar tables by using following query :

select 
      fdb.name, sdb.name 
from 
      FIRSTDBNAME.sys.tables fdb 
      join SECONDDBNAME.sys.tables sdb
      on fdb.name = sdb.name -- compare same name tables
order by 
      1     

By listing out similar table you can compare columns schema using sys.columns view.

Hope this helps you.

How to set -source 1.7 in Android Studio and Gradle

Latest Android Studio 1.4.

Click File->Project Structure->SDK Location->JDK Location.

You could also set individual module JDK Version compatibility by going to the Module (below the SDK Location), and edit the Source Compatibility accordingly. (note, this only applies to Android Module).

Is it safe to clean docker/overlay2/

Everything in /var/lib/docker are filesystems of containers. If you stop all your containers and prune them, you should end up with the folder being empty. You probably don't really want that, so don't go randomly deleting stuff in there. Do not delete things in /var/lib/docker directly. You may get away with it sometimes, but it's inadvisable for so many reasons.

Do this instead:

sudo bash
cd /var/lib/docker
find . -type f | xargs du -b  | sort -n

What you will see is the largest files shown at the bottom. If you want, figure out what containers those files are in, enter those containers with docker exec -ti containername -- /bin/sh and delete some files.

You can also put docker system prune -a -f on a daily/weekly cron job as long as you aren't leaving stopped containers and volumes around that you care about. It's better to figure out the reasons why it's growing, and correct them at the container level.

jQuery ajax request being block because Cross-Origin

There is nothing you can do on your end (client side). You can not enable crossDomain calls yourself, the source (dailymotion.com) needs to have CORS enabled for this to work.

The only thing you can really do is to create a server side proxy script which does this for you. Are you using any server side scripts in your project? PHP, Python, ASP.NET etc? If so, you could create a server side "proxy" script which makes the HTTP call to dailymotion and returns the response. Then you call that script from your Javascript code, since that server side script is on the same domain as your script code, CORS will not be a problem.

source of historical stock data

We have purchased 12 years of intraday data from Kibot.com and are pretty satisfied with the quality.

As for storage requirements: 12 years of 1-minute data for all USA equities (more than 8000 symbols) is about 100GB.

With tick-by-tick data situation is little different. If you record time and sales only, that would be about 30GB of data per month for all USA equities. If you want to store bid / ask changes together with transactions, you can expect about 150GB per month.

I hope this helps. Please let me know if there is anything else I can assist you with.

How to exit from Python without traceback?

Perhaps you're trying to catch all exceptions and this is catching the SystemExit exception raised by sys.exit()?

import sys

try:
    sys.exit(1) # Or something that calls sys.exit()
except SystemExit as e:
    sys.exit(e)
except:
    # Cleanup and reraise. This will print a backtrace.
    # (Insert your cleanup code here.)
    raise

In general, using except: without naming an exception is a bad idea. You'll catch all kinds of stuff you don't want to catch -- like SystemExit -- and it can also mask your own programming errors. My example above is silly, unless you're doing something in terms of cleanup. You could replace it with:

import sys
sys.exit(1) # Or something that calls sys.exit().

If you need to exit without raising SystemExit:

import os
os._exit(1)

I do this, in code that runs under unittest and calls fork(). Unittest gets when the forked process raises SystemExit. This is definitely a corner case!

How to use Python to execute a cURL command?

Just use this website. It'll convert any curl command into Python, Node.js, PHP, R, or Go.

Example:

curl -X POST -H 'Content-type: application/json' --data '{"text":"Hello, World!"}' https://hooks.slack.com/services/asdfasdfasdf

Becomes this in Python,

import requests

headers = {
    'Content-type': 'application/json',
}

data = '{"text":"Hello, World!"}'

response = requests.post('https://hooks.slack.com/services/asdfasdfasdf', headers=headers, data=data)

Closing Application with Exit button

You cannot exit your application. Using android.finish() won't exit the application, it just kills the activity. It's used when we don't want to see the previous activity on back button click. The application automatically exits when you switch off the device. The Android architecture does not support exiting the app. If you want, you can forcefully exit the app, but that's not considered good practice.