Programs & Examples On #Capybara

Capybara is a web application testing framework for Rack applications, such as Rails, Sinatra and Merb.

setting request headers in selenium

Had the same issue today, except that I needed to set different referer per test. I ended up using a middleware and a class to pass headers to it. Thought I'd share (or maybe there's a cleaner solution?):

lib/request_headers.rb:

class CustomHeadersHelper
  cattr_accessor :headers
end

class RequestHeaders
  def initialize(app, helper = nil)
    @app, @helper = app, helper
  end

  def call(env)
    if @helper
      headers = @helper.headers

      if headers.is_a?(Hash)
        headers.each do |k,v|
          env["HTTP_#{k.upcase.gsub("-", "_")}"] = v
        end
      end
    end

    @app.call(env)
  end
end

config/initializers/middleware.rb

require 'request_headers'

if %w(test cucumber).include?(Rails.env)
  Rails.application.config.middleware.insert_before Rack::Lock, "RequestHeaders", CustomHeadersHelper
end

spec/support/capybara_headers.rb

require 'request_headers'

module CapybaraHeaderHelpers
  shared_context "navigating within the site" do
    before(:each) { add_headers("Referer" => Capybara.app_host + "/") }
  end

  def add_headers(custom_headers)
    if Capybara.current_driver == :rack_test
      custom_headers.each do |name, value|
        page.driver.browser.header(name, value)
      end
    else
      CustomHeadersHelper.headers = custom_headers
    end
  end
end

spec/spec_helper.rb

...
config.include CapybaraHeaderHelpers

Then I can include the shared context wherever I need, or pass different headers in another before block. I haven't tested it with anything other than Selenium and RackTest, but it should be transparent, as header injection is done before the request actually hits the application.

How to select option in drop down using Capybara

It is not a direct answer, but you can (if your server permit):

1) Create a model for your Organization; extra: It will be easier to populate your HTML.

2) Create a factory (FactoryGirl) for your model;

3) Create a list (create_list) with the factory;

4) 'pick' (sample) a Organization from the list with:

# Random select
option = Organization.all.sample 

# Select the FIRST(0) by id
option = Organization.all[0] 

# Select the SECOND(1) after some restriction
option = Organization.where(some_attr: some_value)[2]
option = Organization.where("some_attr OP some_value")[2] #OP is "=", "<", ">", so on... 

How to ftp with a batch file?

Using the Windows FTP client you would want to use the -s:filename option to specify a script for the FTP client to run. The documentation specifically points out that you should not try to pipe input into the FTP client with a < character.

Execution of the script will start immediately, so it does work for username/password.

However, the security of this setup is questionable since you now have a username and password for the FTP server visible to anyone who decides to look at your batch file.

Either way, you can generate the script file on the fly from the batch file and then pass it to the FTP client like so:

@echo off

REM Generate the script. Will overwrite any existing temp.txt
echo open servername> temp.txt
echo username>> temp.txt
echo password>> temp.txt
echo get %1>> temp.txt
echo quit>> temp.txt

REM Launch FTP and pass it the script
ftp -s:temp.txt

REM Clean up.
del temp.txt

Replace servername, username, and password with your details and the batch file will generate the script as temp.txt launch ftp with the script and then delete the script.

If you are always getting the same file you can replace the %1 with the file name. If not you just launch the batchfile and provide the name of the file to get as an argument.

Calling stored procedure from another stored procedure SQL Server

Simply call test2 from test1 like:

EXEC test2 @newId, @prod, @desc;

Make sure to get @id using SCOPE_IDENTITY(), which gets the last identity value inserted into an identity column in the same scope:

SELECT @newId = SCOPE_IDENTITY()

How to pass values between Fragments

I´ve made something really easy for begginers like me. I made a textview in my activity_main.xml and put

id=index
visibility=invisible

then I get this textview from the first fragment

index= (Textview) getActivity().findviewbyid(R.id.index)
index.setText("fill me with the value")

and then in the second fragment I get the value

index= (Textview) getActivity().findviewbyid(R.id.index)
String get_the_value= index.getText().toString();

How do you select a particular option in a SELECT element in jQuery?

By value, what worked for me with jQuery 1.7 was the below code, try this:

$('#id option[value=theOptionValue]').prop('selected', 'selected').change();

jQuery limit to 2 decimal places

You could use a variable to make the calculation and use toFixed when you set the #diskamountUnit element value:

var amount = $("#disk").slider("value") * 1.60;
$("#diskamountUnit").val('$' + amount.toFixed(2));

You can also do that in one step, in the val method call but IMO the first way is more readable:

$("#diskamountUnit").val('$' + ($("#disk").slider("value") * 1.60).toFixed(2));

What does the red exclamation point icon in Eclipse mean?

I had the same problem and Andrew is correct. Check your classpath variable "M2_REPO". It probably points to an invalid location of your local maven repo.

In my case I was using mvn eclipse:eclipse on the command line and this plugin was setting the M2_REPO classpath variable. Eclipse couldn't find my maven settings.xml in my home directory and as a result was incorrectly the M2_REPO classpath variable. My solution was to restart eclipse and it picked up my settings.xml and removed the red exclamation on my projects.

I got some more information from this guy: http://www.mkyong.com/maven/how-to-configure-m2_repo-variable-in-eclipse-ide/

Create a global variable in TypeScript

im using only this

import {globalVar} from "./globals";
declare let window:any;
window.globalVar = globalVar;

How to scroll the window using JQuery $.scrollTo() function

If it's not working why don't you try using jQuery's scrollTop method?

$("#id").scrollTop($("#id").scrollTop() + 100);

If you're looking to scroll smoothly you could use basic javascript setTimeout/setInterval function to make it scroll in increments of 1px over a set length of time.

CSS performance relative to translateZ(0)

I can attest to the fact that -webkit-transform: translate3d(0, 0, 0); will mess with the new position: -webkit-sticky; property. With a left drawer navigation pattern that I was working on, the hardware acceleration I wanted with the transform property was messing with the fixed positioning of my top nav bar. I turned off the transform and the positioning worked fine.

Luckily, I seem to have had hardware acceleration on already, because I had -webkit-font-smoothing: antialiased on the html element. I was testing this behavior in iOS7 and Android.

How to delete object from array inside foreach loop?

This should do the trick.....

reset($array);
while (list($elementKey, $element) = each($array)) {
    while (list($key, $value2) = each($element)) {
        if($key == 'id' && $value == 'searched_value') {
            unset($array[$elementKey]);
        }
    }
}

IntelliJ - Convert a Java project/module into a Maven project/module

I had a different scenario, but still landed on this answer.
I had imported my root project folder containing multiple Maven projects but also some other stuff used in this project.
IntelliJ recognised the Java files, but didn't resolve the Maven dependencies.

I fixed this by performing a right-click on each pom and then "Add as maven project"

How to use ArrayAdapter<myClass>

Here's a quick and dirty example of how to use an ArrayAdapter if you don't want to bother yourself with extending the mother class:

class MyClass extends Activity {
    private ArrayAdapter<String> mAdapter = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        mAdapter = new ArrayAdapter<String>(getApplicationContext(),
            android.R.layout.simple_dropdown_item_1line, android.R.id.text1);

        final ListView list = (ListView) findViewById(R.id.list);
        list.setAdapter(mAdapter);

        //Add Some Items in your list:
        for (int i = 1; i <= 10; i++) {
            mAdapter.add("Item " + i);
        }

        // And if you want selection feedback:
        list.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //Do whatever you want with the selected item
                Log.d(TAG, mAdapter.getItem(position) + " has been selected!");
            }
        });
    }
}

How to make the first option of <select> selected with jQuery

One subtle point I think I've discovered about the top voted answers is that even though they correctly change the selected value, they do not update the element that the user sees (only when they click the widget will they see a check next to the updated element).

Chaining a .change() call to the end will also update the UI widget as well.

$("#target").val($("#target option:first").val()).change();

(Note that I noticed this while using jQuery Mobile and a box on Chrome desktop, so this may not be the case everywhere).

Getting a map() to return a list in Python 3.x

Converting my old comment for better visibility: For a "better way to do this" without map entirely, if your inputs are known to be ASCII ordinals, it's generally much faster to convert to bytes and decode, a la bytes(list_of_ordinals).decode('ascii'). That gets you a str of the values, but if you need a list for mutability or the like, you can just convert it (and it's still faster). For example, in ipython microbenchmarks converting 45 inputs:

>>> %%timeit -r5 ordinals = list(range(45))
... list(map(chr, ordinals))
...
3.91 µs ± 60.2 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*map(chr, ordinals)]
...
3.84 µs ± 219 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*bytes(ordinals).decode('ascii')]
...
1.43 µs ± 49.7 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... bytes(ordinals).decode('ascii')
...
781 ns ± 15.9 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

If you leave it as a str, it takes ~20% of the time of the fastest map solutions; even converting back to list it's still less than 40% of the fastest map solution. Bulk convert via bytes and bytes.decode then bulk converting back to list saves a lot of work, but as noted, only works if all your inputs are ASCII ordinals (or ordinals in some one byte per character locale specific encoding, e.g. latin-1).

HttpWebRequest using Basic authentication

First thing, for me ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 worked instead of Ssl3.

Secondly, I had to send the Basic Auth request along with some data (form-urlencoded). Here is the complete sample which worked for me perfectly, after trying many solutions.

Disclaimer: The code below is a mixture of solutions found on this link and some other stackoverflow links, thanks for the useful information.

        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        String username = "user_name";
        String password = "password";
        String encoded = System.Convert.ToBase64String(System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(username + ":" + password));

        //Form Data
        var formData = "var1=val1&var2=val2";
        var encodedFormData = Encoding.ASCII.GetBytes(formData);

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create("THE_URL");
        request.ContentType = "application/x-www-form-urlencoded";
        request.Method = "POST";
        request.ContentLength = encodedFormData.Length;
        request.Headers.Add("Authorization", "Basic " + encoded);
        request.PreAuthenticate = true;

        using (var stream = request.GetRequestStream())
        {
            stream.Write(encodedFormData, 0, encodedFormData.Length);
        }

        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

How do I add files and folders into GitHub repos?

I'm using VS SSDT on Windows. I started a project and set up local version control. I later installed git and and created a Github repo. Once I had my repo on Github I grabbed the URL and put that into VS when it asked me for the URL when I hit the "publish to Github" button.

Should each and every table have a primary key?

Except for a few very rare cases (possibly a many-to-many relationship table, or a table you temporarily use for bulk-loading huge amounts of data), I would go with the saying:

If it doesn't have a primary key, it's not a table!

Marc

set default schema for a sql query

What i sometimes do when i need a lot of tablenames ill just get them plus their schema from the INFORMATION_SCHEMA system table: value


select  TABLE_SCHEMA + '.' + TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME in
(*select your table names*)

Modify tick label text

This also works in matplotlib 3:

x1 = [0,1,2,3]
squad = ['Fultz','Embiid','Dario','Simmons']

plt.xticks(x1, squad, rotation=45)

How to apply bold text style for an entire row using Apache POI?

A worked, completed and simple example:

package io.github.baijifeilong.excel;

import lombok.SneakyThrows;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.FileOutputStream;

/**
 * Created by [email protected] at 2019/12/6 11:41
 */
public class ExcelBoldTextDemo {

    @SneakyThrows
    public static void main(String[] args) {

        new XSSFWorkbook() {{
            XSSFRow row = createSheet().createRow(0);
            row.setRowStyle(createCellStyle());
            row.getRowStyle().getFont().setBold(true);
            row.createCell(0).setCellValue("Alpha");
            row.createCell(1).setCellValue("Beta");
            row.createCell(2).setCellValue("Gamma");
        }}.write(new FileOutputStream("demo.xlsx"));
    }
}

Why is there no xrange function in Python3?

Some performance measurements, using timeit instead of trying to do it manually with time.

First, Apple 2.7.2 64-bit:

In [37]: %timeit collections.deque((x for x in xrange(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.05 s per loop

Now, python.org 3.3.0 64-bit:

In [83]: %timeit collections.deque((x for x in range(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.32 s per loop

In [84]: %timeit collections.deque((x for x in xrange(10000000) if x%4 == 0), maxlen=0)
1 loops, best of 3: 1.31 s per loop

In [85]: %timeit collections.deque((x for x in iter(range(10000000)) if x%4 == 0), maxlen=0) 
1 loops, best of 3: 1.33 s per loop

Apparently, 3.x range really is a bit slower than 2.x xrange. And the OP's xrange function has nothing to do with it. (Not surprising, as a one-time call to the __iter__ slot isn't likely to be visible among 10000000 calls to whatever happens in the loop, but someone brought it up as a possibility.)

But it's only 30% slower. How did the OP get 2x as slow? Well, if I repeat the same tests with 32-bit Python, I get 1.58 vs. 3.12. So my guess is that this is yet another of those cases where 3.x has been optimized for 64-bit performance in ways that hurt 32-bit.

But does it really matter? Check this out, with 3.3.0 64-bit again:

In [86]: %timeit [x for x in range(10000000) if x%4 == 0]
1 loops, best of 3: 3.65 s per loop

So, building the list takes more than twice as long than the entire iteration.

And as for "consumes much more resources than Python 2.6+", from my tests, it looks like a 3.x range is exactly the same size as a 2.x xrange—and, even if it were 10x as big, building the unnecessary list is still about 10000000x more of a problem than anything the range iteration could possibly do.

And what about an explicit for loop instead of the C loop inside deque?

In [87]: def consume(x):
   ....:     for i in x:
   ....:         pass
In [88]: %timeit consume(x for x in range(10000000) if x%4 == 0)
1 loops, best of 3: 1.85 s per loop

So, almost as much time wasted in the for statement as in the actual work of iterating the range.

If you're worried about optimizing the iteration of a range object, you're probably looking in the wrong place.


Meanwhile, you keep asking why xrange was removed, no matter how many times people tell you the same thing, but I'll repeat it again: It was not removed: it was renamed to range, and the 2.x range is what was removed.

Here's some proof that the 3.3 range object is a direct descendant of the 2.x xrange object (and not of the 2.x range function): the source to 3.3 range and 2.7 xrange. You can even see the change history (linked to, I believe, the change that replaced the last instance of the string "xrange" anywhere in the file).

So, why is it slower?

Well, for one, they've added a lot of new features. For another, they've done all kinds of changes all over the place (especially inside iteration) that have minor side effects. And there'd been a lot of work to dramatically optimize various important cases, even if it sometimes slightly pessimizes less important cases. Add this all up, and I'm not surprised that iterating a range as fast as possible is now a bit slower. It's one of those less-important cases that nobody would ever care enough to focus on. No one is likely to ever have a real-life use case where this performance difference is the hotspot in their code.

How do I auto-hide placeholder text upon focus using css or jquery?

To further refine Wallace Sidhrée's code sample:

$(function()
{  
      $('input').focusin(function()
      {
        input = $(this);
        input.data('place-holder-text', input.attr('placeholder'))
        input.attr('placeholder', '');
      });

      $('input').focusout(function()
      {
          input = $(this);
          input.attr('placeholder', input.data('place-holder-text'));
      });
})

This ensures that each input stores the correct placeholder text in the data attribute.

See a working example here in jsFiddle.

Make install, but not to default directories?

It depends on the package. If the Makefile is generated by GNU autotools (./configure) you can usually set the target location like so:

./configure --prefix=/somewhere/else/than/usr/local

If the Makefile is not generated by autotools, but distributed along with the software, simply open it up in an editor and change it. The install target directory is probably defined in a variable somewhere.

How to undo a SQL Server UPDATE query?

If you already have a full backup from your database, fortunately, you have an option in SQL Management Studio. In this case, you can use the following steps:

  1. Right click on database -> Tasks -> Restore -> Database.

  2. In General tab, click on Timeline -> select Specific date and time option.

  3. Move the timeline slider to before update command time -> click OK.

  4. In the destination database name, type a new name.

  5. In the Files tab, check in Reallocate all files to folder and then select a new path to save your recovered database.

  6. In the options tab, check in Overwrite ... and remove Take tail-log... check option.

  7. Finally, click on OK and wait until the recovery process is over.

I have used this method myself in an operational database and it was very useful.

Array to Collection: Optimized code

Based on the reference of java.util.Collections.addAll(Collection<? super String> c, String... elements) its implementation is similar to your first method, it says

Adds all of the specified elements to the specified collection. Elements to be added may be specified individually or as an array. The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

Its implementation in jdk is (jdk7)

public static <T> boolean addAll(Collection<? super T> c, T... elements) {
    boolean result = false;
    for (T element : elements)
        result |= c.add(element);
    return result;
}

So among your samples the better approach must be Collections.addAll(list, array);

Since Java 8, we can use Stream api which may perform better

Eg:-

String[] array = {"item1", "item2", "item3"};

Stream<String> stream = Stream.of(array);

//if the array is extremely large 
stream = stream.parallel();

final List<String> list = stream.collect(Collectors.toList());

If the array is very large we can do it as a batch operation in parallel using parallel stream (stream = stream.parallel()) that will utilize all CPUs to finish the task quickly. If the array length is very small parallel stream will take more time than sequential stream.

Fixed point vs Floating point number

The term ‘fixed point’ refers to the corresponding manner in which numbers are represented, with a fixed number of digits after, and sometimes before, the decimal point. With floating-point representation, the placement of the decimal point can ‘float’ relative to the significant digits of the number. For example, a fixed-point representation with a uniform decimal point placement convention can represent the numbers 123.45, 1234.56, 12345.67, etc, whereas a floating-point representation could in addition represent 1.234567, 123456.7, 0.00001234567, 1234567000000000, etc.

TypeError: window.initMap is not a function

In my case there was a formatting issue earlier on, so the error was a consequence of something else. My server was rendering the lat/lon values with commas instead of periods, because of different regional settings.

How do I position one image on top of another in HTML?

It may be a little late but for this you can do:

enter image description here

HTML

<!-- html -->
<div class="images-wrapper">
  <img src="images/1" alt="image 1" />
  <img src="images/2" alt="image 2" />
  <img src="images/3" alt="image 3" />
  <img src="images/4" alt="image 4" />
</div>

SASS

// In _extra.scss
$maxImagesNumber: 5;

.images-wrapper {
  img {
    position: absolute;
    padding: 5px;
    border: solid black 1px;
  }

  @for $i from $maxImagesNumber through 1 {
    :nth-child(#{ $i }) {
      z-index: #{ $maxImagesNumber - ($i - 1) };
      left: #{ ($i - 1) * 30 }px;
    }
  }
}

python convert list to dictionary

If you are still thinking what the! You would not be alone, its actually not that complicated really, let me explain.

How to turn a list into a dictionary using built-in functions only

We want to turn the following list into a dictionary using the odd entries (counting from 1) as keys mapped to their consecutive even entries.

l = ["a", "b", "c", "d", "e"]

dict()

To create a dictionary we can use the built in dict function for Mapping Types as per the manual the following methods are supported.

dict(one=1, two=2)
dict({'one': 1, 'two': 2})
dict(zip(('one', 'two'), (1, 2)))
dict([['two', 2], ['one', 1]])

The last option suggests that we supply a list of lists with 2 values or (key, value) tuples, so we want to turn our sequential list into:

l = [["a", "b"], ["c", "d"], ["e",]]

We are also introduced to the zip function, one of the built-in functions which the manual explains:

returns a list of tuples, where the i-th tuple contains the i-th element from each of the arguments

In other words if we can turn our list into two lists a, c, e and b, d then zip will do the rest.

slice notation

Slicings which we see used with Strings and also further on in the List section which mainly uses the range or short slice notation but this is what the long slice notation looks like and what we can accomplish with step:

>>> l[::2]
['a', 'c', 'e']

>>> l[1::2]
['b', 'd']

>>> zip(['a', 'c', 'e'], ['b', 'd'])
[('a', 'b'), ('c', 'd')]

>>> dict(zip(l[::2], l[1::2]))
{'a': 'b', 'c': 'd'}

Even though this is the simplest way to understand the mechanics involved there is a downside because slices are new list objects each time, as can be seen with this cloning example:

>>> a = [1, 2, 3]
>>> b = a
>>> b
[1, 2, 3]

>>> b is a
True

>>> b = a[:]
>>> b
[1, 2, 3]

>>> b is a
False

Even though b looks like a they are two separate objects now and this is why we prefer to use the grouper recipe instead.

grouper recipe

Although the grouper is explained as part of the itertools module it works perfectly fine with the basic functions too.

Some serious voodoo right? =) But actually nothing more than a bit of syntax sugar for spice, the grouper recipe is accomplished by the following expression.

*[iter(l)]*2

Which more or less translates to two arguments of the same iterator wrapped in a list, if that makes any sense. Lets break it down to help shed some light.

zip for shortest

>>> l*2
['a', 'b', 'c', 'd', 'e', 'a', 'b', 'c', 'd', 'e']

>>> [l]*2
[['a', 'b', 'c', 'd', 'e'], ['a', 'b', 'c', 'd', 'e']]

>>> [iter(l)]*2
[<listiterator object at 0x100486450>, <listiterator object at 0x100486450>]

>>> zip([iter(l)]*2)
[(<listiterator object at 0x1004865d0>,),(<listiterator object at 0x1004865d0>,)]

>>> zip(*[iter(l)]*2)
[('a', 'b'), ('c', 'd')]

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd'}

As you can see the addresses for the two iterators remain the same so we are working with the same iterator which zip then first gets a key from and then a value and a key and a value every time stepping the same iterator to accomplish what we did with the slices much more productively.

You would accomplish very much the same with the following which carries a smaller What the? factor perhaps.

>>> it = iter(l)     
>>> dict(zip(it, it))
{'a': 'b', 'c': 'd'}

What about the empty key e if you've noticed it has been missing from all the examples which is because zip picks the shortest of the two arguments, so what are we to do.

Well one solution might be adding an empty value to odd length lists, you may choose to use append and an if statement which would do the trick, albeit slightly boring, right?

>>> if len(l) % 2:
...     l.append("")

>>> l
['a', 'b', 'c', 'd', 'e', '']

>>> dict(zip(*[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': ''}

Now before you shrug away to go type from itertools import izip_longest you may be surprised to know it is not required, we can accomplish the same, even better IMHO, with the built in functions alone.

map for longest

I prefer to use the map() function instead of izip_longest() which not only uses shorter syntax doesn't require an import but it can assign an actual None empty value when required, automagically.

>>> l = ["a", "b", "c", "d", "e"]
>>> l
['a', 'b', 'c', 'd', 'e']

>>> dict(map(None, *[iter(l)]*2))
{'a': 'b', 'c': 'd', 'e': None} 

Comparing performance of the two methods, as pointed out by KursedMetal, it is clear that the itertools module far outperforms the map function on large volumes, as a benchmark against 10 million records show.

$ time python -c 'dict(map(None, *[iter(range(10000000))]*2))'
real    0m3.755s
user    0m2.815s
sys     0m0.869s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(10000000))]*2, fillvalue=None))'
real    0m2.102s
user    0m1.451s
sys     0m0.539s

However the cost of importing the module has its toll on smaller datasets with map returning much quicker up to around 100 thousand records when they start arriving head to head.

$ time python -c 'dict(map(None, *[iter(range(100))]*2))'
real    0m0.046s
user    0m0.029s
sys     0m0.015s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100))]*2, fillvalue=None))'
real    0m0.067s
user    0m0.042s
sys     0m0.021s

$ time python -c 'dict(map(None, *[iter(range(100000))]*2))'
real    0m0.074s
user    0m0.050s
sys     0m0.022s
$ time python -c 'from itertools import izip_longest; dict(izip_longest(*[iter(range(100000))]*2, fillvalue=None))'
real    0m0.075s
user    0m0.047s
sys     0m0.024s

See nothing to it! =)

nJoy!

python NameError: name 'file' is not defined

file is not defined in Python3, which you are using apparently. The package you're instaling is not suitable for Python 3, instead, you should install Python 2.7 and try again.

See: http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins

Get height and width of a layout programmatically

try with this metods:

int width = mView.getMeasuredWidth();

int height = mView.getMeasuredHeight();

Or

int width = mTextView.getMeasuredWidth();

int height = mTextView.getMeasuredHeight();

Toggle input disabled attribute using jQuery

Quite a while later, and thanks to @arne, I created this similar small function to handle where the input should be disabled AND hidden, or enabled AND shown:

function toggleInputState(el, on) {
  // 'on' = true(visible) or false(hidden)
  // If a field is to be shown, enable it; if hidden, disable it.
  // Disabling will prevent the field's value from being submitted
  $(el).prop('disabled', !on).toggle(on);
}

Then a jQuery object (such as $('input[name="something"]') ) is simply switched using:

toggleInputState(myElement, myBoolean)

Why I cannot cout a string?

Above answers are good but If you do not want to add string include, you can use the following

ostream& operator<<(ostream& os, string& msg)
{
os<<msg.c_str();

return os;
}

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

Warning: Found conflicts between different versions of the same dependent assembly

I had the same issue and I resolved by changing the following in web.config.

It happened to me because I am running the application using Newtonsoft.Json 4.0

From:

<dependentAssembly>
  <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
</dependentAssembly>

To:

<dependentAssembly>
  <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="4.5.0.0" />
</dependentAssembly>

how to create dynamic two dimensional array in java?

Try to make Treemap < Integer, Treemap<Integer, obj> >

In java, Treemap is sorted map. And the number of item in row and col wont screw the 2D-index you want to set. Then you can get a col-row table like structure.

Adding elements to a C# array

Don't use an array - use a generic List<T> which allows you to add items dynamically.

If this is not an option, you can use Array.Copy or Array.CopyTo to copy the array into a larger array.

SQL How to correctly set a date variable value and use it?

Your syntax is fine, it will return rows where LastAdDate lies within the last 6 months;

select cast('01-jan-1970' as datetime) as LastAdDate into #PubAdvTransData 
    union select GETDATE()
    union select NULL
    union select '01-feb-2010'

DECLARE @sp_Date DATETIME = DateAdd(m, -6, GETDATE())

SELECT * FROM #PubAdvTransData pat
     WHERE (pat.LastAdDate > @sp_Date)

>2010-02-01 00:00:00.000
>2010-04-29 21:12:29.920

Are you sure LastAdDate is of type DATETIME?

How to putAll on Java hashMap contents of one to another, but not replace existing keys and values?

You can make it in just 1 line if you change maps order in @erickson's solution:

mapWithNotSoImportantValues.putAll( mapWithImportantValues );

In this case you replace values in mapWithNotSoImportantValues with value from mapWithImportantValues with the same keys.

How can I make a thumbnail <img> show a full size image when clicked?

Here is the Angular version of LightBox. Just Awesome :)

Note : I have put this answer hence No Js library has been mentioned under the Tags.

angular-bootstrap-lightbox

<ul ng-controller="GalleryCtrl">
  <li ng-repeat="image in images">
    <a ng-click="openLightboxModal($index)">
      <img ng-src="{{image.thumbUrl}}" class="img-thumbnail">
    </a>
  </li>
</ul>

Can't get value of input type="file"?

$('input[type=file]').val()

That'll get you the file selected.

However, you can't set the value yourself.

jQuery: how to trigger anchor link's click event

There's a difference in invoking the click event (does not do the redirect), and navigating to the href location.

Navigate:

 window.location = $('#myanchor').attr('href');

Open in new tab or window:

 window.open($('#myanchor').attr('href'));

invoke click event (call the javascript):

 $('#myanchor').click();

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

For windows open git bash and try

NODE_ENV=production node app.js

Volatile vs Static in Java

If we declare a variable as static, there will be only one copy of the variable. So, whenever different threads access that variable, there will be only one final value for the variable(since there is only one memory location allocated for the variable).

If a variable is declared as volatile, all threads will have their own copy of the variable but the value is taken from the main memory.So, the value of the variable in all the threads will be the same.

So, in both cases, the main point is that the value of the variable is same across all threads.

Simple post to Web Api

It's been quite sometime since I asked this question. Now I understand it more clearly, I'm going to put a more complete answer to help others.

In Web API, it's very simple to remember how parameter binding is happening.

  • if you POST simple types, Web API tries to bind it from the URL
  • if you POST complex type, Web API tries to bind it from the body of the request (this uses a media-type formatter).

  • If you want to bind a complex type from the URL, you'll use [FromUri] in your action parameter. The limitation of this is down to how long your data going to be and if it exceeds the url character limit.

    public IHttpActionResult Put([FromUri] ViewModel data) { ... }

  • If you want to bind a simple type from the request body, you'll use [FromBody] in your action parameter.

    public IHttpActionResult Put([FromBody] string name) { ... }

as a side note, say you are making a PUT request (just a string) to update something. If you decide not to append it to the URL and pass as a complex type with just one property in the model, then the data parameter in jQuery ajax will look something like below. The object you pass to data parameter has only one property with empty property name.

var myName = 'ABC';
$.ajax({url:.., data: {'': myName}});

and your web api action will look something like below.

public IHttpActionResult Put([FromBody] string name){ ... }

This asp.net page explains it all. http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

webpack: Module not found: Error: Can't resolve (with relative path)

while importing libraries use the exact path to a file, including the directory relative to the current file, for example:

import Footer from './Footer/index.jsx'
import AddTodo from '../containers/AddTodo/index.jsx'
import VisibleTodoList from '../containers/VisibleTodoList/index.jsx'

Hope this may help

How to check if another instance of the application is running

Want some serious code? Here it is.

var exists = System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1;

This works for any application (any name) and will become true if there is another instance running of the same application.

Edit: To fix your needs you can use either of these:

if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) return;

from your Main method to quit the method... OR

if (System.Diagnostics.Process.GetProcessesByName(System.IO.Path.GetFileNameWithoutExtension(System.Reflection.Assembly.GetEntryAssembly().Location)).Count() > 1) System.Diagnostics.Process.GetCurrentProcess().Kill();

which will kill the currently loading process instantly.


You need to add a reference to System.Core.dll for the .Count() extension method. Alternatively, you can use the .Length property.

How do I parse command line arguments in Bash?

Here is my improved solution of Bruno Bronosky's answer using variable arrays.

it lets you mix parameters position and give you a parameter array preserving the order without the options

#!/bin/bash

echo $@

PARAMS=()
SOFT=0
SKIP=()
for i in "$@"
do
case $i in
    -n=*|--skip=*)
    SKIP+=("${i#*=}")
    ;;
    -s|--soft)
    SOFT=1
    ;;
    *)
        # unknown option
        PARAMS+=("$i")
    ;;
esac
done
echo "SKIP            = ${SKIP[@]}"
echo "SOFT            = $SOFT"
    echo "Parameters:"
    echo ${PARAMS[@]}

Will output for example:

$ ./test.sh parameter -s somefile --skip=.c --skip=.obj
parameter -s somefile --skip=.c --skip=.obj
SKIP            = .c .obj
SOFT            = 1
Parameters:
parameter somefile

Download a file from NodeJS Server using Express

There are several ways to do it This is the better way

res.download('/report-12345.pdf')

or in your case this might be

app.get('/download', function(req, res){
  const file = `${__dirname}/upload-folder/dramaticpenguin.MOV`;
  res.download(file); // Set disposition and send it.
});

Know More

How can I change Eclipse theme?

In the eclipse Version: 2019-09 R (4.13.0) on windows Go to Window > preferences > Appearance Select the required theme for dark theme to choose Dark and click on Ok. enter image description here

In c, in bool, true == 1 and false == 0?

More accurately anything that is not 0 is true.

So 1 is true, but so is 2, 3 ... etc.

How can I adjust DIV width to contents

One way you can achieve this is setting display: inline-block; on the div. It is by default a block element, which will always fill the width it can fill (unless specifying width of course).

inline-block's only downside is that IE only supports it correctly from version 8. IE 6-7 only allows setting it on naturally inline elements, but there are hacks to solve this problem.

There are other options you have, you can either float it, or set position: absolute on it, but these also have other effects on layout, you need to decide which one fits your situation better.

PHPExcel How to apply styles and set cell width and cell height to cell generated dynamically

You can use

$objWorksheet->getActiveSheet()->getRowDimension('1')->setRowHeight(40);
$objWorksheet->getActiveSheet()->getColumnDimension('A')->setWidth(100);

or define auto-size:

$objWorksheet->getRowDimension('1')->setRowHeight(-1);

How to implement debounce in Vue2?

Although pretty much all answers here are already correct, if anyone is in search of a quick solution I have a directive for this. https://www.npmjs.com/package/vue-lazy-input

It applies to @input and v-model, supports custom components and DOM elements, debounce and throttle.

_x000D_
_x000D_
Vue.use(VueLazyInput)_x000D_
  new Vue({_x000D_
    el: '#app', _x000D_
    data() {_x000D_
      return {_x000D_
        val: 42_x000D_
      }_x000D_
    },_x000D_
    methods:{_x000D_
      onLazyInput(e){_x000D_
        console.log(e.target.value)_x000D_
      }_x000D_
    }_x000D_
  })
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>_x000D_
<script src="https://unpkg.com/lodash/lodash.min.js"></script><!-- dependency -->_x000D_
<script src="https://unpkg.com/vue-lazy-input@latest"></script> _x000D_
_x000D_
<div id="app">_x000D_
  <input type="range" v-model="val" @input="onLazyInput" v-lazy-input /> {{val}}_x000D_
</div>
_x000D_
_x000D_
_x000D_

Call two functions from same onclick

Try this

<input id ="btn" type="button" value="click" onclick="pay();cls()"/>

Automatically resize images with browser size using CSS

The following works on all browsers for my 200 figures, for any width percentage -- despite being illegal. Jukka said 'Use it anyway.' (The class just floats the image left or right and sets margins.) I can't imagine why this isn't the standard approach!

<img class="fl" width="66%"
src="A-Images/0.5_Saltation.jpg"
alt="Schematic models of chromosomes ..." />

Change the window width and the image scales obligingly.

'System.Net.Http.HttpContent' does not contain a definition for 'ReadAsAsync' and no extension method

After a long struggle, I found the solution.

Solution: Add a reference to System.Net.Http.Formatting.dll. This assembly is also available in the C:\Program Files\Microsoft ASP.NET\ASP.NET MVC 4\Assemblies folder.

The method ReadAsAsync is an extension method declared in the class HttpContentExtensions, which is in the namespace System.Net.Http in the library System.Net.Http.Formatting.

Reflector came to rescue!

How to force Laravel Project to use HTTPS for all routes?

Using the following code in your .htaccess file automatically redirects visitors to the HTTPS version of your site:

RewriteEngine On
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Calling a JSON API with Node.js

Another solution is to user axios:

npm install axios

Code will be like:

const url = `${this.env.someMicroservice.address}/v1/my-end-point`;

const { data } = await axios.get<MyInterface>(url, {
  auth: {
    username: this.env.auth.user,
    password: this.env.auth.pass
  }
});

return data;

How to push elements in JSON from javascript array

var arr = [ 'a', 'b', 'c'];
arr.push('d'); // insert as last item

How to generate .NET 4.0 classes from xsd?

Along with WSDL, I had xsd files. The above did not work in my case gave error. It worked as follows

wsdl /l:C# /out:D:\FileName.cs D:\NameApi\wsdl_1_1\RESAdapterService.wsdl 
D:\CXTypes.xsd D:\CTypes.xsd 
D:\Preferences.xsd 

Upgrading PHP in XAMPP for Windows?

Take a backup of your htdocs and data folder (subfolder of MySQL folder), reinstall upgraded version and replace those folders.

Note: In case you have changed config files like PHP (php.ini), Apache (httpd.conf) or any other, please take back up of those files as well and replace them with newly installed version.

Print specific part of webpage

You can use simple JavaScript to print a specific div from a page.

var prtContent = document.getElementById("your div id");
var WinPrint = window.open('', '', 'left=0,top=0,width=800,height=900,toolbar=0,scrollbars=0,status=0');
WinPrint.document.write(prtContent.innerHTML);
WinPrint.document.close();
WinPrint.focus();
WinPrint.print();
WinPrint.close();

Batch file FOR /f tokens

for /f "tokens=* delims= " %%f in (myfile) do

This reads a file line-by-line, removing leading spaces (thanks, jeb).

set line=%%f

sets then the line variable to the line just read and

call :procesToken

calls a subroutine that does something with the line

:processToken

is the start of the subroutine mentioned above.

for /f "tokens=1* delims=/" %%a in ("%line%") do

will then split the line at /, but stopping tokenization after the first token.

echo Got one token: %%a

will output that first token and

set line=%%b

will set the line variable to the rest of the line.

if not "%line%" == "" goto :processToken

And if line isn't yet empty (i.e. all tokens processed), it returns to the start, continuing with the rest of the line.

Determining if Swift dictionary contains key and obtaining any of its values

You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value).

So, if you just want to answer the question whether the dictionary contains the key, ask:

let keyExists = dict[key] != nil

If you want the value and you know the dictionary contains the key, say:

let val = dict[key]!

But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let:

if let val = dict[key] {
    // now val is not nil and the Optional has been unwrapped, so use it
}

Lining up labels with radio buttons in bootstrap

Key insights for me were: - ensure that label content comes after the input-radio field - I tweaked my css to make everything a little closer

.radio-inline+.radio-inline {
    margin-left: 5px;
}

Chrome - ERR_CACHE_MISS

This is a known issue in Chrome and resolved in latest versions. Please refer https://bugs.chromium.org/p/chromium/issues/detail?id=942440 for more details.

Writing Unicode text to a text file?

The file opened by codecs.open is a file that takes unicode data, encodes it in iso-8859-1 and writes it to the file. However, what you try to write isn't unicode; you take unicode and encode it in iso-8859-1 yourself. That's what the unicode.encode method does, and the result of encoding a unicode string is a bytestring (a str type.)

You should either use normal open() and encode the unicode yourself, or (usually a better idea) use codecs.open() and not encode the data yourself.

JavaScript code to stop form submission

The following works as of now (tested in Chrome and Firefox):

<form onsubmit="event.preventDefault(); validateMyForm();">

Where validateMyForm() is a function that returns false if validation fails. The key point is to use the name event. We cannot use for e.g. e.preventDefault().

Eclipse+Maven src/main/java not visible in src folder in Package Explorer

Eclipse filters out folders that are marked as source from the "raw" folder path. That is, they are visible only as source folders:

example project

If you can't see them in either place, then they

  • are either filtered out in the settings: check your settings for Package Explorer (the Package Explorer bar, downwards menu arrow -> Filters...)
  • or they were created externally and Eclipse haven't noticed them: Refresh your project in this case.
  • or they don't exist: right-click on the project, select New->Folder and input the path, e.g. src/test/java (not "Source Folder"). After you use Maven->Update Project... on the project, they will be automatically added as source folders, provided you have the default configuration.

Now, as I said, those folder will only be used as source if you preserved the default configuration in your POM. If you defined other resources and/or testResources, those will be used instead. In general, Eclipse m2e synchronizes Eclipse's project source folder configuration with what's in your POM.

EDIT: maybe this is unclear - see those folders at the top? The ones labeled with the /-separated paths? These are your folders. These are the same folders that you would expect to find in main and test, just represented differently.

How to customize a Spinner in Android

Create a custom adapter with a custom layout for your spinner.

Spinner spinner = (Spinner) findViewById(R.id.pioedittxt5);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
        R.array.travelreasons, R.layout.simple_spinner_item);
adapter.setDropDownViewResource(R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);

R.layout.simple_spinner_item

<TextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/text1"
    style="@style/spinnerItemStyle"
    android:maxLines="1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:ellipsize="marquee" />

R.layout.simple_spinner_dropdown_item

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@android:id/text1"
    style="@style/spinnerDropDownItemStyle"
    android:maxLines="1"
    android:layout_width="match_parent"
    android:layout_height="?android:attr/dropdownListPreferredItemHeight"
    android:ellipsize="marquee" />

In styles add your custom dimensions and height as per your requirement.

 <style name="spinnerItemStyle" parent="android:Widget.TextView.SpinnerItem">

  </style>

  <style name="spinnerDropDownItemStyle" parent="android:TextAppearance.Widget.TextView.SpinnerItem">

  </style>

"Couldn't read dependencies" error with npm

I got this error when I had a space in my "name" within the packagae.json file.

"NPM Project" rather than "NPMProject"

Darken CSS background image?

You can use the CSS3 Linear Gradient property along with your background-image like this:

#landing-wrapper {
    display:table;
    width:100%;
    background: linear-gradient( rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5) ), url('landingpagepic.jpg');
    background-position:center top;
    height:350px;
}

Here's a demo:

_x000D_
_x000D_
#landing-wrapper {_x000D_
  display: table;_x000D_
  width: 100%;_x000D_
  background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url('http://placehold.it/350x150');_x000D_
  background-position: center top;_x000D_
  height: 350px;_x000D_
  color: white;_x000D_
}
_x000D_
<div id="landing-wrapper">Lorem ipsum dolor ismet.</div>
_x000D_
_x000D_
_x000D_

two divs the same line, one dynamic width, one fixed

So left div style depends on the presence of right div. I can't think of a CSS selector allowing that kind of behavior yet.

Thus it seems to me that you'll need to programmatically add a class server side (or in JS) on parent div or left div to do that.

<div id="parent twocols">
  <div class="left"></div>
  <div class="right"></div>
</div>

or

<div id="parent">
  <div class="left"></div>
</div>

So right style is always :

.right {
    float: right;
    width: 200px; /* or whatever value you need */
    /* margin and padding at your discretion */
}

and left style is :

.parent.twocols .left {
    margin-right: 200px; /* according to right div width + margin + padding*/
}

How do I 'svn add' all unversioned files to SVN?

You can use command

svn add * force--

or

svn add <directory/file name>

If your files/directories are not adding recursively. Then check this.

Recursive adding is default property. You can see in SVN book.

Issue can be in your ignore list or global properties.

I got solution google issue tracker

Check global properties for ignoring star(*)

  • Right click in your repo in window. Select TortoiseSVN > Properties.
  • See if you don't have a property svn:global-ignores with a value of *
  • If you have property with star(*) then it will ignore recursive adding. So remove this property.

Check global ignore pattern for ignoring star(*)

  • Right click in your repo in window. Select TortoiseSVN > Settings > General.
  • See in Global Ignore Pattern, if you don't have set star(*) there.
  • If you found star(*), remove this property.

This guy also explained why this property added in my project.

The most like way that it got there is that someone right-clicked a file without any extension and selected TortoiseSVN -> SVN Ignore -> * (recursively), and then committed this.

You can check the log to see who committed that property change, find out what they were actually trying to do, and ask them to be more careful in future. :)

When to use extern in C++

This comes in useful when you have global variables. You declare the existence of global variables in a header, so that each source file that includes the header knows about it, but you only need to “define” it once in one of your source files.

To clarify, using extern int x; tells the compiler that an object of type int called x exists somewhere. It's not the compilers job to know where it exists, it just needs to know the type and name so it knows how to use it. Once all of the source files have been compiled, the linker will resolve all of the references of x to the one definition that it finds in one of the compiled source files. For it to work, the definition of the x variable needs to have what's called “external linkage”, which basically means that it needs to be declared outside of a function (at what's usually called “the file scope”) and without the static keyword.

header:

#ifndef HEADER_H
#define HEADER_H

// any source file that includes this will be able to use "global_x"
extern int global_x;

void print_global_x();

#endif

source 1:

#include "header.h"

// since global_x still needs to be defined somewhere,
// we define it (for example) in this source file
int global_x;

int main()
{
    //set global_x here:
    global_x = 5;

    print_global_x();
}

source 2:

#include <iostream>
#include "header.h"

void print_global_x()
{
    //print global_x here:
    std::cout << global_x << std::endl;
}

How to decode encrypted wordpress admin password?

MD5 encrypting is possible, but decrypting is still unknown (to me). However, there are many ways to compare these things.

  1. Using compare methods like so:

    <?php
      $db_pass = $P$BX5675uhhghfhgfhfhfgftut/0;
      $my_pass = "mypass";
      if ($db_pass === md5($my_pass)) {
        // password is matched
      } else {
        // password didn't match
      }
    
  2. Only for WordPress users. If you have access to your PHPMyAdmin, focus you have because you paste that hashing here: $P$BX5675uhhghfhgfhfhfgftut/0, WordPress user_pass is not only MD5 format it also uses utf8_mb4_cli charset so what to do?

    That's why I use another Approach if I forget my WordPress password I use

    I install other WordPress with new password :P, and I then go to PHPMyAdmin and copy that hashing from the database and paste that hashing to my current PHPMyAdmin password ( which I forget )

    EASY is use this :

    1. password = "ARJUNsingh@123"
    2. password_hasing = " $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1 "
    3. Replace your $P$BX5675uhhghfhgfhfhfgftut/0 with my $P$BDSdKx2nglM.5UErwjQGeVtVWvjEvD1

I USE THIS APPROACH FOR MY SELF WHEN I DESIGN THEMES AND PLUGINS

WORDPRESS USE THIS

https://developer.wordpress.org/reference/functions/wp_hash_password/

How to store printStackTrace into a string

You can use the ExceptionUtils.getStackTrace(Throwable t); from Apache Commons 3 class org.apache.commons.lang3.exception.ExceptionUtils.

http://commons.apache.org/proper/commons-lang/

ExceptionUtils.getStackTrace(Throwable t)

Code example:

try {

  // your code here

} catch(Exception e) {
  String s = ExceptionUtils.getStackTrace(e);
}

"Could not get any response" response when using postman with subdomain

In my case it was a misconfigured subnet. Only one of the 2 subnets in the ELB worked.

I figured this out by doing a nslookup and trying to curl the returned IPs directly. Only one worked. Postman just kept using the misconfigured one.

How to send a POST request from node.js Express?

I use superagent, which is simliar to jQuery.

Here is the docs

And the demo like:

var sa = require('superagent');
sa.post('url')
  .send({key: value})
  .end(function(err, res) {
    //TODO
  });

Replace all elements of Python NumPy Array that are greater than some value

Since you actually want a different array which is arr where arr < 255, and 255 otherwise, this can be done simply:

result = np.minimum(arr, 255)

More generally, for a lower and/or upper bound:

result = np.clip(arr, 0, 255)

If you just want to access the values over 255, or something more complicated, @mtitan8's answer is more general, but np.clip and np.minimum (or np.maximum) are nicer and much faster for your case:

In [292]: timeit np.minimum(a, 255)
100000 loops, best of 3: 19.6 µs per loop

In [293]: %%timeit
   .....: c = np.copy(a)
   .....: c[a>255] = 255
   .....: 
10000 loops, best of 3: 86.6 µs per loop

If you want to do it in-place (i.e., modify arr instead of creating result) you can use the out parameter of np.minimum:

np.minimum(arr, 255, out=arr)

or

np.clip(arr, 0, 255, arr)

(the out= name is optional since the arguments in the same order as the function's definition.)

For in-place modification, the boolean indexing speeds up a lot (without having to make and then modify the copy separately), but is still not as fast as minimum:

In [328]: %%timeit
   .....: a = np.random.randint(0, 300, (100,100))
   .....: np.minimum(a, 255, a)
   .....: 
100000 loops, best of 3: 303 µs per loop

In [329]: %%timeit
   .....: a = np.random.randint(0, 300, (100,100))
   .....: a[a>255] = 255
   .....: 
100000 loops, best of 3: 356 µs per loop

For comparison, if you wanted to restrict your values with a minimum as well as a maximum, without clip you would have to do this twice, with something like

np.minimum(a, 255, a)
np.maximum(a, 0, a)

or,

a[a>255] = 255
a[a<0] = 0

Excel VBA Loop on columns

Yes, let's use Select as an example

sample code: Columns("A").select

How to loop through Columns:

Method 1: (You can use index to replace the Excel Address)

For i = 1 to 100
    Columns(i).Select
next i

Method 2: (Using the address)

For i = 1 To 100
 Columns(Columns(i).Address).Select
Next i

EDIT: Strip the Column for OP

columnString = Replace(Split(Columns(27).Address, ":")(0), "$", "")

e.g. you want to get the 27th Column --> AA, you can get it this way

installing cPickle with python 3.5

cPickle comes with the standard library… in python 2.x. You are on python 3.x, so if you want cPickle, you can do this:

>>> import _pickle as cPickle

However, in 3.x, it's easier just to use pickle.

No need to install anything. If something requires cPickle in python 3.x, then that's probably a bug.

How to keep a git branch in sync with master

You are thinking in the right direction. Merge master with mobiledevicesupport continuously and merge mobiledevicesupport with master when mobiledevicesupport is stable. Each developer will have his own branch and can merge to and from either on master or mobiledevicesupport depending on their role.

Find and replace words/lines in a file

Any decent text editor has a search&replace facility that supports regular expressions.

If however, you have reason to reinvent the wheel in Java, you can do:

Path path = Paths.get("test.txt");
Charset charset = StandardCharsets.UTF_8;

String content = new String(Files.readAllBytes(path), charset);
content = content.replaceAll("foo", "bar");
Files.write(path, content.getBytes(charset));

This only works for Java 7 or newer. If you are stuck on an older Java, you can do:

String content = IOUtils.toString(new FileInputStream(myfile), myencoding);
content = content.replaceAll(myPattern, myReplacement);
IOUtils.write(content, new FileOutputStream(myfile), myencoding);

In this case, you'll need to add error handling and close the streams after you are done with them.

IOUtils is documented at http://commons.apache.org/proper/commons-io/javadocs/api-release/org/apache/commons/io/IOUtils.html

Undefined Symbols for architecture x86_64: Compiling problems

There's no mystery here, the linker is telling you that you haven't defined the missing symbols, and you haven't.

Similarity::Similarity() or Similarity::~Similarity() are just missing and you have defined the others incorrectly,

void Similarity::readData(Scanner& inStream){
}

not

void readData(Scanner& inStream){
}

etc. etc.

The second one is a function called readData, only the first is the readData method of the Similarity class.

To be clear about this, in Similarity.h

void readData(Scanner& inStream);

but in Similarity.cpp

void Similarity::readData(Scanner& inStream){
}

How can I add an item to a ListBox in C# and WinForms?

ListBoxItem is a WPF class, NOT a WinForms class.

For WPF, use ListBoxItem.

For WinForms, the item is a Object type, so use one of these:
1. Provide your own ToString() method for the Object type.
2. Use databinding with DisplayMemeber and ValueMember (see Kelsey's answer)

What does Visual Studio mean by normalize inconsistent line endings?

Line endings also called newline, end of line (EOL) or line break is a control character or sequence of control characters in a character encoding specification (e.g. ASCII or EBCDIC) that is used to signify the end of a line of text and the start of a new one. Some text editors set/implement this special character when you press the Enter key.

The Carriage Return, Line Feed characters are ASCII representations for the end of a line (EOL). They will end the current line of a string, and start a new one.

However, at the operating system level, they are treated differently:

  • The Carriage Return ("CR") character (ASCII 13\0x0D, \r): Moves the cursor to the beginning of the line without advancing to the next line. This character is used as the new line character in Commodore and Early Macintosh operating systems (Mac OS 9 and earlier).

  • The Line Feed ("LF") character (ASCII 10\0x0A, \n): Moves the cursor down to the next line without returning to the beginning of the line. This character is used as the new line character in Unix based systems (Linux, macOS X, Android, etc).

  • The Carriage Return Line Feed ("CRLF") character (0x0D0A, \r\n): This is actually two ASCII characters and is a combination of the CR and LF characters. It moves the cursor both down to the next line and to the beginning of that line. This character is used as the new line character in most other non-Unix operating systems, including Microsoft Windows and Symbian OS.

Normalizing inconsistent line endings in Visual Studio means selecting one character type to be used for all your files. It could be:

  • The Carriage Return Line Feed ("CRLF") character
  • The Line Feed ("LF") character
  • The Carriage Return ("CR") character

However, you can set this in a better way using .gitattributes file in your root directory to avoid conflicts when you move your files from one Operating system to the other.

Simply create a new file called .gitattributes in the root directory of your application:

touch .gitattributes

And add the following in it:

# Enforce Unix newlines
* text=auto eol=lf

This enforces the Unix line feed line ending character.

Note: If this is an already existing project, simply run this command to update the files for the application using the newly defined line ending as specified in the .gitattributes.

git rm --cached -r .
git reset --hard

That's all.

I hope this helps

How to delete a folder and all contents using a bat file in windows?

@RD /S /Q "D:\PHP_Projects\testproject\Release\testfolder"

Explanation:

Removes (deletes) a directory.

RMDIR [/S] [/Q] [drive:]path RD [/S] [/Q] [drive:]path

/S      Removes all directories and files in the specified directory
        in addition to the directory itself.  Used to remove a directory
        tree.

/Q      Quiet mode, do not ask if ok to remove a directory tree with /S

Highcharts - redraw() vs. new Highcharts.chart

@RobinL as mentioned in previous comments, you can use chart.series[n].setData(). First you need to make sure you’ve assigned a chart instance to the chart variable, that way it adopts all the properties and methods you need to access and manipulate the chart.

I’ve also used the second parameter of setData() and had it false, to prevent automatic rendering of the chart. This was because I have multiple data series, so I’ll rather update each of them, with render=false, and then running chart.redraw(). This multiplied performance (I’m having 10,000-100,000 data points and refreshing the data set every 50 milliseconds).

How to add Tomcat Server in eclipse

Right Click on the server tab, go for NEW-> Server. then choose recent version of tomcat server. Click on next, and then give path for your tomcat server.(You can download tomcat server from this link https://tomcat.apache.org/download-80.cgi#8.5.32). Click on finish.

You can start your server now..!!

Compare string with all values in list

If you only want to know if any item of d is contained in paid[j], as you literally say:

if any(x in paid[j] for x in d): ...

If you also want to know which items of d are contained in paid[j]:

contained = [x for x in d if x in paid[j]]

contained will be an empty list if no items of d are contained in paid[j].

There are other solutions yet if what you want is yet another alternative, e.g., get the first item of d contained in paid[j] (and None if no item is so contained):

firstone = next((x for x in d if x in paid[j]), None)

BTW, since in a comment you mention sentences and words, maybe you don't necessarily want a string check (which is what all of my examples are doing), because they can't consider word boundaries -- e.g., each example will say that 'cat' is in 'obfuscate' (because, 'obfuscate' contains 'cat' as a substring). To allow checks on word boundaries, rather than simple substring checks, you might productively use regular expressions... but I suggest you open a separate question on that, if that's what you require -- all of the code snippets in this answer, depending on your exact requirements, will work equally well if you change the predicate x in paid[j] into some more sophisticated predicate such as somere.search(paid[j]) for an appropriate RE object somere. (Python 2.6 or better -- slight differences in 2.5 and earlier).

If your intention is something else again, such as getting one or all of the indices in d of the items satisfying your constrain, there are easy solutions for those different problems, too... but, if what you actually require is so far away from what you said, I'd better stop guessing and hope you clarify;-).

How do I import a Swift file from another Swift file?

Instead of requiring explicit imports, the Swift compiler implicitly searches for .swiftmodule files of dependency Swift libraries.

Xcode can build swift modules for you, or refer to the railsware blog for command line instructions for swiftc.

How to access custom attributes from event object in React?

<div className='btn' onClick={(e) =>
     console.log(e.currentTarget.attributes['tag'].value)}
     tag='bold'>
    <i className='fa fa-bold' />
</div>

so e.currentTarget.attributes['tag'].value works for me

moment.js, how to get day of week number

If you are specifically looking for the 1-7 approach...

This is the ISO weekday number. moment.js has also taken this into account. Use isoWeekday()

_x000D_
_x000D_
console.log(moment().isoWeekday()); // returns 1-7 where 1 is Monday and 7 is Sunday
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Seeing as I wrote this answer on a Tuesday, today this gives me a 2.

How to set the color of "placeholder" text?

For giving placeholder a color just use these lines of code:

::-webkit-input-placeholder { color: red; }
::-moz-placeholder {color: red; }
:-ms-input-placeholder { color: red; } 
:-o-input-placeholder { color: red; } 

Oracle DB: How can I write query ignoring case?

You can use the upper() function in your query, and to increase performance you can use a function-base index

 CREATE INDEX upper_index_name ON table(upper(name))

Git error: "Please make sure you have the correct access rights and the repository exists"

Like other answers, use https instead of ssh was the solution.

I post an answer to give a concrete example of a possible solution. I solved this issue with bitbucket when I changed remote url to HTTPS with this command line:

git remote set-url origin <bitbucket_URL>

After that, I could push the content to the repository with this command:

git push -u origin --all

And then I could also use Sourcetree

Check if a Postgres JSON array contains a string

As of PostgreSQL 9.4, you can use the ? operator:

select info->>'name' from rabbits where (info->'food')::jsonb ? 'carrots';

You can even index the ? query on the "food" key if you switch to the jsonb type instead:

alter table rabbits alter info type jsonb using info::jsonb;
create index on rabbits using gin ((info->'food'));
select info->>'name' from rabbits where info->'food' ? 'carrots';

Of course, you probably don't have time for that as a full-time rabbit keeper.

Update: Here's a demonstration of the performance improvements on a table of 1,000,000 rabbits where each rabbit likes two foods and 10% of them like carrots:

d=# -- Postgres 9.3 solution
d=# explain analyze select info->>'name' from rabbits where exists (
d(# select 1 from json_array_elements(info->'food') as food
d(#   where food::text = '"carrots"'
d(# );
 Execution time: 3084.927 ms

d=# -- Postgres 9.4+ solution
d=# explain analyze select info->'name' from rabbits where (info->'food')::jsonb ? 'carrots';
 Execution time: 1255.501 ms

d=# alter table rabbits alter info type jsonb using info::jsonb;
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
 Execution time: 465.919 ms

d=# create index on rabbits using gin ((info->'food'));
d=# explain analyze select info->'name' from rabbits where info->'food' ? 'carrots';
 Execution time: 256.478 ms

Can't install via pip because of egg_info error

For me reinstalling and then upgrading the pip worked.

  1. Reinstall pip by using below command or following link How do I install pip on macOS or OS X?

    curl https://bootstrap.pypa.io/get-pip.py -o - | python

  2. Upgrade pip after it's installed

    pip install -U pip

How to reload apache configuration for a site without restarting apache?

If you are using Ubuntu server, you can use systemctl

systemctl reload apache2

Failed to load resource: the server responded with a status of 404 (Not Found) css

you have defined the public dir in app root/public

app.use(express.static(__dirname + '/public')); 

so you have to use:

./css/main.css

Get only part of an Array in Java?

public static int[] range(int[] array, int start, int end){
        int returner[] = new int[end-start];
        for(int x = 0; x <= end-start-1; x++){
            returner[x] = array[x+start];
        }
        return returner;
    }

this is a way to do the same thing as Array.copyOfRange but without importing anything

What is the difference between RTP or RTSP in a streaming server?

You are getting something wrong... RTSP is a realtime streaming protocol. Meaning, you can stream whatever you want in real time. So you can use it to stream LIVE content (no matter what it is, video, audio, text, presentation...). RTP is a transport protocol which is used to transport media data which is negotiated over RTSP.

You use RTSP to control media transmission over RTP. You use it to setup, play, pause, teardown the stream...

So, if you want your server to just start streaming when the URL is requested, you can implement some sort of RTP-only server. But if you want more control and if you are streaming live video, you must use RTSP, because it transmits SDP and other important decoding data.

Read the documents I linked here, they are a good starting point.

About "*.d.ts" in TypeScript

This answer assumes you have some JavaScript that you don't want to convert to TypeScript, but you want to benefit from type checking with minimal changes to your .js. A .d.ts file is very much like a C or C++ header file. Its purpose is to define an interface. Here is an example:

mashString.d.ts

/** Makes a string harder to read. */
declare function mashString(
    /** The string to obscure */
    str: string
):string;
export = mashString;

mashString.js

// @ts-check
/** @type {import("./mashString")} */
module.exports = (str) => [...str].reverse().join("");

main.js

// @ts-check
const mashString = require("./mashString");
console.log(mashString("12345"));

The relationship here is: mashString.d.ts defines an interface, mashString.js implements the interface and main.js uses the interface.

To get the type checking to work you add // @ts-check to your .js files. But this only checks that main.js uses the interface correctly. To also ensure that mashString.js implements it correctly we add /** @type {import("./mashString")} */ before the export.

You can create your initial .d.ts files using tsc -allowJs main.js -d then edit them as required manually to improve the type checking and documentation.

In most cases the implementation and interface have the same name, here mashString. But you can have alternative implementations. For example we could rename mashString.js to reverse.js and have an alternative encryptString.js.

What's the difference between a method and a function?

If you feel like reading here is "My introduction to OO methods"

The idea behind Object Oriented paradigm is to "threat" the software is composed of .. well "objects". Objects in real world have properties, for instance if you have an Employee, the employee has a name, an employee id, a position, he belongs to a department etc. etc.

The object also know how to deal with its attributes and perform some operations on them. Let say if we want to know what an employee is doing right now we would ask him.

employe whatAreYouDoing.

That "whatAreYouDoing" is a "message" sent to the object. The object knows how to answer to that questions, it is said it has a "method" to resolve the question.

So, the way objects have to expose its behavior are called methods. Methods thus are the artifact object have to "do" something.

Other possible methods are

employee whatIsYourName
employee whatIsYourDepartmentsName

etc.

Functions in the other hand are ways a programming language has to compute some data, for instance you might have the function addValues( 8 , 8 ) that returns 16

// pseudo-code
function addValues( int x, int y )  return x + y 
// call it 
result = addValues( 8,8 )
print result // output is 16...

Since first popular programming languages ( such as fortran, c, pascal ) didn't cover the OO paradigm, they only call to these artifacts "functions".

for instance the previous function in C would be:

int addValues( int x, int y ) 
{
   return x + y;
}

It is not "natural" to say an object has a "function" to perform some action, because functions are more related to mathematical stuff while an Employee has little mathematic on it, but you can have methods that do exactly the same as functions, for instance in Java this would be the equivalent addValues function.

public static int addValues( int x, int y ) {
    return x + y;
}

Looks familiar? That´s because Java have its roots on C++ and C++ on C.

At the end is just a concept, in implementation they might look the same, but in the OO documentation these are called method.

Here´s an example of the previously Employee object in Java.

public class Employee {

    Department department;
    String name;

    public String whatsYourName(){
        return this.name;
    }
    public String whatsYourDeparmentsName(){
         return this.department.name();
    }
    public String whatAreYouDoing(){
        return "nothing";
    } 
    // Ignore the following, only set here for completness
    public Employee( String name ) {
        this.name = name;
    }

}

// Usage sample.
Employee employee = new Employee( "John" ); // Creates an employee called John

// If I want to display what is this employee doing I could use its methods.
// to know it.
String name = employee.whatIsYourName():
String doingWhat = employee.whatAreYouDoint();

// Print the info to the console.

 System.out.printf("Employee %s is doing: %s", name, doingWhat );

Output:
Employee John is doing nothing.

The difference then, is on the "domain" where it is applied.

AppleScript have the idea of "natural language" matphor , that at some point OO had. For instance Smalltalk. I hope it may be reasonable easier for you to understand methods in objects after reading this.

NOTE: The code is not to be compiled, just to serve as an example. Feel free to modify the post and add Python example.

What is the difference between npm install and npm run build?

The main difference is ::

npm install is a npm cli-command which does the predefined thing i.e, as written by Churro, to install dependencies specified inside package.json

npm run command-name or npm run-script command-name ( ex. npm run build ) is also a cli-command predefined to run your custom scripts with the name specified in place of "command-name". So, in this case npm run build is a custom script command with the name "build" and will do anything specified inside it (for instance echo 'hello world' given in below example package.json).

Ponits to note::

  1. One more thing, npm build and npm run build are two different things, npm run build will do custom work written inside package.json and npm build is a pre-defined script (not available to use directly)

  2. You cannot specify some thing inside custom build script (npm run build) script and expect npm build to do the same. Try following thing to verify in your package.json:

    { "name": "demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "build":"echo 'hello build'" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": {}, "dependencies": {} }

and run npm run build and npm build one by one and you will see the difference. For more about commands kindly follow npm documentation.

Cheers!!

Fix footer to bottom of page

For your footer:

#footer {
    position: fixed;
    height: 50px;
    background-color: red;
    bottom: 0px;
    left: 0px;
    right: 0px;
    margin-bottom: 0px;
}

For your body:

body {
    margin-bottom:50px;
}

_x000D_
_x000D_
#footer {_x000D_
  background-color: red;_x000D_
  position: fixed;_x000D_
  bottom: 0px;_x000D_
  left: 0px;_x000D_
  right: 0px;_x000D_
  height: 50px;_x000D_
  margin-bottom: 0px;_x000D_
}_x000D_
_x000D_
div {_x000D_
  margin: 20px 20px;_x000D_
}_x000D_
_x000D_
body {_x000D_
  margin-bottom: 50px;_x000D_
}
_x000D_
<div>_x000D_
  Although most pages on my site have enough content to push the footer to the bottom of the page for most people. I would like to know it's always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom:_x000D_
  0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it's container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright_x000D_
  bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site have enough content to push the footer to the_x000D_
  bottom of the page for most people. I would like to know it's always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally_x000D_
  pushes the footer out of it's container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts_x000D_
  at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site have enough content to push the footer to the bottom of the page for most people. I would like to know it's always_x000D_
  fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it's container to fix to the bottom using_x000D_
  some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and_x000D_
  see what the current code is to amend. Although most pages on my site have enough content to push the footer to the bottom of the page for most people. I would like to know it's always fixed to the bottom regardless of screen size from now on anyway._x000D_
  I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it's container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for_x000D_
  the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site_x000D_
  have enough content to push the footer to the bottom of the page for most people. I would like to know it's always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc._x000D_
  Never seems to work very well, occasionally pushes the footer out of it's container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside_x000D_
  of a div anyway. I removed my attempts at getting it to stick so people can have a look at it right now and see what the current code is to amend. Although most pages on my site have enough content to push the footer to the bottom of the page for most_x000D_
  people. I would like to know it's always fixed to the bottom regardless of screen size from now on anyway. I've tried a number of ways such as bottom: 0x; position:absolute: etc. Never seems to work very well, occasionally pushes the footer out of it's_x000D_
  container to fix to the bottom using some of those examples right there. Included is the HTML and CSS for the two parts of the footer (footer & copyright bar). They're both inside of a div anyway. I removed my attempts at getting it to stick so people_x000D_
  can have a look at it right now and see what the current code is to amend._x000D_
</div>_x000D_
<div id="footer">_x000D_
  This is footer_x000D_
</div>
_x000D_
_x000D_
_x000D_

jsFiddle Demo

return value after a promise

The best way to do this would be to use the promise returning function as it is, like this

lookupValue(file).then(function(res) {
    // Write the code which depends on the `res.val`, here
});

The function which invokes an asynchronous function cannot wait till the async function returns a value. Because, it just invokes the async function and executes the rest of the code in it. So, when an async function returns a value, it will not be received by the same function which invoked it.

So, the general idea is to write the code which depends on the return value of an async function, in the async function itself.

How to extend an existing JavaScript array with another array, without creating a new array

Update 2018: A better answer is a newer one of mine: a.push(...b). Don't upvote this one anymore, as it never really answered the question, but it was a 2015 hack around first-hit-on-Google :)


For those that simply searched for "JavaScript array extend" and got here, you can very well use Array.concat.

var a = [1, 2, 3];
a = a.concat([5, 4, 3]);

Concat will return a copy the new array, as thread starter didn't want. But you might not care (certainly for most kind of uses this will be fine).


There's also some nice ECMAScript 6 sugar for this in the form of the spread operator:

const a = [1, 2, 3];
const b = [...a, 5, 4, 3];

(It also copies.)

Calculating Covariance with Python and Numpy

When a and b are 1-dimensional sequences, numpy.cov(a,b)[0][1] is equivalent to your cov(a,b).

The 2x2 array returned by np.cov(a,b) has elements equal to

cov(a,a)  cov(a,b)

cov(a,b)  cov(b,b)

(where, again, cov is the function you defined above.)

How to save S3 object to a file using boto3

# Preface: File is json with contents: {'name': 'Android', 'status': 'ERROR'}

import boto3
import io

s3 = boto3.resource('s3')

obj = s3.Object('my-bucket', 'key-to-file.json')
data = io.BytesIO()
obj.download_fileobj(data)

# object is now a bytes string, Converting it to a dict:
new_dict = json.loads(data.getvalue().decode("utf-8"))

print(new_dict['status']) 
# Should print "Error"

Calculate correlation for more than two variables?

You might want to look at Quick-R, which has a lot of nice little tutorials on how you can do basic statistics in R. For example on correlations:

http://www.statmethods.net/stats/correlations.html

Function overloading in Javascript - Best practices

check this out. It is very cool. http://ejohn.org/blog/javascript-method-overloading/ Trick Javascript to allow you to do calls like this:

var users = new Users();
users.find(); // Finds all
users.find("John"); // Finds users by name
users.find("John", "Resig"); // Finds users by first and last name

Android new Bottom Navigation bar or BottomNavigationView

I think this is also be useful.

Snippet

public class MainActivity : AppCompatActivity, BottomNavigationBar.Listeners.IOnTabSelectedListener
{
    private BottomBar _bottomBar;

    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.MainActivity);

        _bottomBar = BottomBar.Attach(this, bundle);
        _bottomBar.SetItems(
            new BottomBarTab(Resource.Drawable.ic_recents, "Recents"),
            new BottomBarTab(Resource.Drawable.ic_favorites, "Favorites"),
            new BottomBarTab(Resource.Drawable.ic_nearby, "Nearby")
        );
        _bottomBar.SetOnItemSelectedListener(this);
        _bottomBar.HideShadow();
        _bottomBar.UseDarkTheme(true);
        _bottomBar.SetTypeFace("Roboto-Regular.ttf");

        var badge = _bottomBar.MakeBadgeForTabAt(1, Color.ParseColor("#f02d4c"), 1);
        badge.AutoShowAfterUnSelection = true;
    }

    public void OnItemSelected(int position)
    {

    }

    protected override void OnSaveInstanceState(Bundle outState)
    {
        base.OnSaveInstanceState(outState);

        // Necessary to restore the BottomBar's state, otherwise we would
        // lose the current tab on orientation change.
        _bottomBar.OnSaveInstanceState(outState);
    }
}

Links

https://github.com/pocheshire/BottomNavigationBar

It's https://github.com/roughike/BottomBar ported to C# for Xamarin developers

Not able to start Genymotion device

First of All, Make Sure to Enable Virtualization Technology under BIOS settings.

#ifdef in C#

#if DEBUG
bool bypassCheck=TRUE_OR_FALSE;//i will decide depending on what i am debugging
#else
bool bypassCheck = false; //NEVER bypass it
#endif

Make sure you have the checkbox to define DEBUG checked in your build properties.

How do you embed binary data in XML?

I had this problem just last week. I had to serialize a PDF file and send it, inside an XML file, to a server.

If you're using .NET, you can convert a binary file directly to a base64 string and stick it inside an XML element.

string base64 = Convert.ToBase64String(File.ReadAllBytes(fileName));

Or, there is a method built right into the XmlWriter object. In my particular case, I had to include Microsoft's datatype namespace:

StringBuilder sb = new StringBuilder();
System.Xml.XmlWriter xw = XmlWriter.Create(sb);
xw.WriteStartElement("doc");
xw.WriteStartElement("serialized_binary");
xw.WriteAttributeString("types", "dt", "urn:schemas-microsoft-com:datatypes", "bin.base64");
byte[] b = File.ReadAllBytes(fileName);
xw.WriteBase64(b, 0, b.Length);
xw.WriteEndElement();
xw.WriteEndElement();
string abc = sb.ToString();

The string abc looks something that looks like this:

<?xml version="1.0" encoding="utf-16"?>
<doc>
    <serialized_binary types:dt="bin.base64" xmlns:types="urn:schemas-microsoft-com:datatypes">
        JVBERi0xLjMKJaqrrK0KNCAwIG9iago8PCAvVHlwZSAvSW5mbw...(plus lots more)
    </serialized_binary>
</doc>

Unresolved external symbol in object files

I believe most of the points regarding the causes and remedies have been covered by all contributors in this thread. I just want to point out for my 'unresolved external' problem, it was caused by a datatype defined as macro that gets substituted differently than expected, which results in that incorrect type being supplied to the function in question, and since the function with type is never defined, it couldn't have been resolved. In particular, under C/C++ -> Language, there is an attribute called 'Treat WChar_t As Built in Type, which should have been defined as 'No (/Zc:wchar_t-)' but did not in my case.

change array size

This worked well for me to create a dynamic array from a class array.

var s = 0;
var songWriters = new SongWriterDetails[1];
foreach (var contributor in Contributors)
{
    Array.Resize(ref songWriters, s++);
    songWriters[s] = new SongWriterDetails();
    songWriters[s].DisplayName = contributor.Name;
    songWriters[s].PartyId = contributor.Id;
    s++;
}

Angular error: "Can't bind to 'ngModel' since it isn't a known property of 'input'"

Try adding

ngModel in module level

The code is same as the above

Apply function to all elements of collection through LINQ

You can try something like

var foo = (from fooItems in context.footable select fooItems.fooID + 1);

Returns a list of id's +1, you can do the same with using a function to whatever you have in the select clause.

Update: As suggested from Jon Skeet this is a better version of the snippet of code I just posted:

var foo = context.footable.Select(foo => foo.fooID + 1);

ASP.NET Temporary files cleanup

Just an update on more current OS's (Vista, Win7, etc.) - the temp file path has changed may be different based on several variables. The items below are not definitive, however, they are a few I have encountered:

"temp" environment variable setting - then it would be:

%temp%\Temporary ASP.NET Files

Permissions and what application/process (VS, IIS, IIS Express) is running the .Net compiler. Accessing the C:\WINDOWS\Microsoft.NET\Framework folders requires elevated permissions and if you are not developing under an account with sufficient permissions then this folder might be used:

c:\Users\[youruserid]\AppData\Local\Temp\Temporary ASP.NET Files

There are also cases where the temp folder can be set via config for a machine or site specific using this:

<compilation tempDirectory="d:\MyTempPlace" />

I even have a funky setup at work where we don't run Admin by default, plus the IT guys have login scripts that set %temp% and I get temp files in 3 different locations depending on what is compiling things! And I'm still not certain about how these paths get picked....sigh.

Still, dthrasher is correct, you can just delete these and VS and IIS will just recompile them as needed.

Print the address or pointer for value in C

I have been in this position, especially with new hardware. I suggest you write a little hex dump routine of your own. You will be able to see the data, and the addresses they are at, shown all together. It's good practice and a confidence builder.

How to debug a referenced dll (having pdb)

Another point to keep in mind, be sure the referenced dlls are not installed in the GAC. After testing, I installed my dlls into the GAC to do system level testing. Later, when I had to debug my code again, I couldn't step into the referenced assemblies until I deleted them from the GAC.

What is the purpose of the return statement?

In python, we start defining a function with "def" and generally, but not necessarily, end the function with "return".

A function of variable x is denoted as f(x). What this function does? Suppose, this function adds 2 to x. So, f(x)=x+2

Now, the code of this function will be:

def A_function (x):
    return x + 2

After defining the function, you can use that for any variable and get result. Such as:

print A_function (2)
>>> 4

We could just write the code slightly differently, such as:

def A_function (x):
    y = x + 2
    return y
print A_function (2)

That would also give "4".

Now, we can even use this code:

def A_function (x):
    x = x + 2
    return x
print A_function (2)

That would also give 4. See, that the "x" beside return actually means (x+2), not x of "A_function(x)".

I guess from this simple example, you would understand the meaning of return command.

Iterating over all the keys of a map

Here's some easy way to get slice of the map-keys.

// Return keys of the given map
func Keys(m map[string]interface{}) (keys []string) {
    for k := range m {
        keys = append(keys, k)
    }
    return keys
}

// use `Keys` func
func main() {
    m := map[string]interface{}{
        "foo": 1,
        "bar": true,
        "baz": "baz",
    }
    fmt.Println(Keys(m)) // [foo bar baz]
}

how to make a jquery "$.post" request synchronous

From the Jquery docs: you specify the async option to be false to get a synchronous Ajax request. Then your callback can set some data before your mother function proceeds.

Here's what your code would look like if changed as suggested:

beforecreate: function(node,targetNode,type,to) {
    jQuery.ajax({
         url:    url,
         success: function(result) {
                      if(result.isOk == false)
                          alert(result.message);
                  },
         async:   false
    });          
}

this is because $.ajax is the only request type that you can set the asynchronousity for

How to slice an array in Bash

There is also a convenient shortcut to get all elements of the array starting with specified index. For example "${A[@]:1}" would be the "tail" of the array, that is the array without its first element.

version=4.7.1
A=( ${version//\./ } )
echo "${A[@]}"    # 4 7 1
B=( "${A[@]:1}" )
echo "${B[@]}"    # 7 1

how to set image from url for imageView

Using Glide library:

Glide.with(context)
  .load(new File(url)
  .diskCacheStrategy(DiskCacheStrategy.ALL)
  .into(imageView);

How to stop Python closing immediately when executed in Microsoft Windows

In Python 3, add the following to the end of your code:

input('Press ENTER to exit')

This will cause the program to wait for user input, with pressing ENTER causing the program to finish.

You can double click on your script.py file in Windows conveniently this way.

How can I pass an Integer class correctly by reference?

There are two problems:

  1. Integer is pass by value, not by reference. Changing the reference inside a method won't be reflected into the passed-in reference in the calling method.
  2. Integer is immutable. There's no such method like Integer#set(i). You could otherwise just make use of it.

To get it to work, you need to reassign the return value of the inc() method.

integer = inc(integer);

To learn a bit more about passing by value, here's another example:

public static void main(String... args) {
    String[] strings = new String[] { "foo", "bar" };
    changeReference(strings);
    System.out.println(Arrays.toString(strings)); // still [foo, bar]
    changeValue(strings);
    System.out.println(Arrays.toString(strings)); // [foo, foo]
}
public static void changeReference(String[] strings) {
    strings = new String[] { "foo", "foo" };
}
public static void changeValue(String[] strings) {
    strings[1] = "foo";
}

Add st, nd, rd and th (ordinal) suffix to a number

_x000D_
_x000D_
<p>31<sup>st</sup> March 2015</p>
_x000D_
_x000D_
_x000D_

You can use

1<sup>st</sup> 2<sup>nd</sup> 3<sup>rd</sup> 4<sup>th</sup>

for positioning the suffix

How to simulate a click by using x,y coordinates in JavaScript?

Yes, you can simulate a mouse click by creating an event and dispatching it:

function click(x,y){
    var ev = document.createEvent("MouseEvent");
    var el = document.elementFromPoint(x,y);
    ev.initMouseEvent(
        "click",
        true /* bubble */, true /* cancelable */,
        window, null,
        x, y, 0, 0, /* coordinates */
        false, false, false, false, /* modifier keys */
        0 /*left*/, null
    );
    el.dispatchEvent(ev);
}

Beware of using the click method on an element -- it is widely implemented but not standard and will fail in e.g. PhantomJS. I assume jQuery's implemention of .click() does the right thing but have not confirmed.

Bind event to right mouse click

The function returns too early. I've added a comment to the code below:

$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
        $('.alert').fadeToggle(); // this line never gets called
    });
});

Try swapping the return false; with the next line.

Using Tempdata in ASP.NET MVC - Best practice

Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek method. I would recommend reading this cool article:

MVC Tempdata , Peek and Keep confusion

How to limit depth for recursive file list?

Checkout the -maxdepth flag of find

find . -maxdepth 1 -type d -exec ls -ld "{}" \;

Here I used 1 as max level depth, -type d means find only directories, which then ls -ld lists contents of, in long format.

How to insert current_timestamp into Postgres via python

from datetime import datetime as dt

then use this in your code:

cur.execute('INSERT INTO my_table (dt_col) VALUES (%s)', (dt.now(),))

Converting Varchar Value to Integer/Decimal Value in SQL Server

You are getting arithmetic overflow. this means you are trying to make a conversion impossible to be made. This error is thrown when you try to make a conversion and the destiny data type is not enough to convert the origin data. For example:

If you try to convert 100.52 to decimal(4,2) you will get this error. The number 100.52 requires 5 positions and 2 of them are decimal.

Try to change the decimal precision to something like 16,2 or higher. Try with few records first then use it to all your select.

JSON Parse File Path

Since it is in the directory data/, You need to do:

file path is '../../data/file.json'

$.getJSON('../../data/file.json', function(data) {         
    alert(data);
});

Pure JS:

   var request = new XMLHttpRequest();
   request.open("GET", "../../data/file.json", false);
   request.send(null)
   var my_JSON_object = JSON.parse(request.responseText);
   alert (my_JSON_object.result[0]);

Threads vs Processes in Linux

Threads -- > Threads shares a memory space,it is an abstraction of the CPU,it is lightweight. Processes --> Processes have their own memory space,it is an abstraction of a computer. To parallelise task you need to abstract a CPU. However the advantages of using a process over a thread is security,stability while a thread uses lesser memory than process and offers lesser latency. An example in terms of web would be chrome and firefox. In case of Chrome each tab is a new process hence memory usage of chrome is higher than firefox ,while the security and stability provided is better than firefox. The security here provided by chrome is better,since each tab is a new process different tab cannot snoop into the memory space of a given process.

Launch an app from within another (iPhone)

Swift 3 quick and paste version of @villy393 answer for :

if UIApplication.shared.canOpenURL(openURL) {
    UIApplication.shared.openURL(openURL)
} else if UIApplication.shared.canOpenURL(installUrl) 
    UIApplication.shared.openURL(installUrl)
}

Clear android application user data

To clear Application Data Please Try this way.

    public void clearApplicationData() {
    File cache = getCacheDir();
    File appDir = new File(cache.getParent());
    if (appDir.exists()) {
        String[] children = appDir.list();
        for (String s : children) {
            if (!s.equals("lib")) {
                deleteDir(new File(appDir, s));Log.i("TAG", "**************** File /data/data/APP_PACKAGE/" + s + " DELETED *******************");
            }
        }
    }
}

public static boolean deleteDir(File dir) {
    if (dir != null &amp;&amp; dir.isDirectory()) {
        String[] children = dir.list();
        for (int i = 0; i < children.length; i++) {
            boolean success = deleteDir(new File(dir, children[i]));
            if (!success) {
                return false;
            }
        }
    }

    return dir.delete();
}

Quantile-Quantile Plot using SciPy

Using qqplot of statsmodels.api is another option:

Very basic example:

import numpy as np
import statsmodels.api as sm
import pylab

test = np.random.normal(0,1, 1000)

sm.qqplot(test, line='45')
pylab.show()

Result:

enter image description here

Documentation and more example are here

JavaScript math, round to two decimal places

Fastest Way - faster than toFixed():

TWO DECIMALS

x      = .123456
result = Math.round(x * 100) / 100  // result .12

THREE DECIMALS

x      = .123456
result = Math.round(x * 1000) / 1000      // result .123

Auto-fit TextView for Android

After i tried Android official Autosizing TextView, i found if your Android version is prior to Android 8.0 (API level 26), you need use android.support.v7.widget.AppCompatTextView, and make sure your support library version is above 26.0.0. Example:

<android.support.v7.widget.AppCompatTextView
    android:layout_width="130dp"
    android:layout_height="32dp"
    android:maxLines="1"
    app:autoSizeMaxTextSize="22sp"
    app:autoSizeMinTextSize="12sp"
    app:autoSizeStepGranularity="2sp"
    app:autoSizeTextType="uniform" />

update:

According to @android-developer's reply, i check the AppCompatActivity source code, and found these two lines in onCreate

final AppCompatDelegate delegate = getDelegate(); delegate.installViewFactory();

and in AppCompatDelegateImpl's createView

    if (mAppCompatViewInflater == null) {
        mAppCompatViewInflater = new AppCompatViewInflater();
    }

it use AppCompatViewInflater inflater view, when AppCompatViewInflater createView it will use AppCompatTextView for "TextView".

public final View createView(){
    ...
    View view = null;
    switch (name) {
        case "TextView":
            view = new AppCompatTextView(context, attrs);
            break;
        case "ImageView":
            view = new AppCompatImageView(context, attrs);
            break;
        case "Button":
            view = new AppCompatButton(context, attrs);
            break;
    ...
}

In my project i don't use AppCompatActivity, so i need use <android.support.v7.widget.AppCompatTextView> in xml.

Create normal zip file programmatically

You can now use the ZipArchive class (System.IO.Compression.ZipArchive), available from .NET 4.5

You have to add System.IO.Compression as a reference.

Example: Generating a zip of PDF files

using (var fileStream = new FileStream(@"C:\temp\temp.zip", FileMode.CreateNew))
{
    using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
    {
        foreach (var creditNumber in creditNumbers)
        {
            var pdfBytes = GeneratePdf(creditNumber);
            var fileName = "credit_" + creditNumber + ".pdf";
            var zipArchiveEntry = archive.CreateEntry(fileName, CompressionLevel.Fastest);
            using (var zipStream = zipArchiveEntry.Open())
                zipStream.Write(pdfBytes, 0, pdfBytes.Length);
            }
        }
    }
}

Using an array from Observable Object with ngFor and Async Pipe Angular 2

If you don't have an array but you are trying to use your observable like an array even though it's a stream of objects, this won't work natively. I show how to fix this below assuming you only care about adding objects to the observable, not deleting them.

If you are trying to use an observable whose source is of type BehaviorSubject, change it to ReplaySubject then in your component subscribe to it like this:

Component

this.messages$ = this.chatService.messages$.pipe(scan((acc, val) => [...acc, val], []));

Html

<div class="message-list" *ngFor="let item of messages$ | async">

How do I convert a list of ascii values to a string in python?

Same basic solution as others, but I personally prefer to use map instead of the list comprehension:


>>> L = [104, 101, 108, 108, 111, 44, 32, 119, 111, 114, 108, 100]
>>> ''.join(map(chr,L))
'hello, world'

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

How can I position my jQuery dialog to center?

To fix center position, I use:

open : function() {
    var t = $(this).parent(), w = window;
    t.offset({
        top: (w.height() / 2) - (t.height() / 2),
        left: (w.width() / 2) - (t.width() / 2)
    });
}

How to return a table from a Stored Procedure?

It's VERY important to include:

 SET NOCOUNT ON;

into SP, In First line, if you do INSERT in SP, the END SELECT can't return values.

THEN, in vb60 you can:

SET RS = CN.EXECUTE(SQL)

OR:

RS.OPEN CN, RS, SQL

standard size for html newsletter template

Short answer: 400-800 pixels.

What I have read is that HTML newsletter width should be as narrow as possible without being too narrow. For instance, 400-500 pixels for a one column layout is a lower limit. Any less may look too weird.

Today's widescreen monitors allow for more horizontal pixels and most web email clients will either be of the two-column variety (Gmail) or 3-pane layout where the content window bellow the inbox list (Hotmail and Yahoo). In either case, you can be okay with 800 pixels if you're targeting the 1280 wide audience. An older or less technical audience may have older, square monitors.

There is the problem of Outlook having a three-column layout. That limits the width of your email even more. With them, you may want to go even narrower.

I just recently created a template that required an ad banner that is 730 pixels wide. It was near in the wide range, but not so much that most people could not double-click the email an open a new window in Outlook (the web email users should be okay for the most part).

Hope this advice helps.

PHP - auto refreshing page

use this code ,it will automatically refresh in 5 seconds, you can change time in refresh

<?php $url1=$_SERVER['REQUEST_URI']; header("Refresh: 5; URL=$url1"); ?>

How can I enable or disable the GPS programmatically on Android?

Instead of using intent Settings.ACTION_LOCATION_SOURCE_SETTINGS you can directly able to show pop up in your app like Google Map & on Gps on click of ok button their is no need to redirect to setting simply you need to use my code as

Note : This line of code automatic open the dialog box if Location is not on. This piece of line is used in Google Map also

 public class MainActivity extends AppCompatActivity
    implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener {


LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
PendingResult<LocationSettingsResult> result;
final static int REQUEST_LOCATION = 199;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addApi(LocationServices.API)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this).build();
    mGoogleApiClient.connect();

}

@Override
public void onConnected(Bundle bundle) {

    mLocationRequest = LocationRequest.create();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(30 * 1000);
    mLocationRequest.setFastestInterval(5 * 1000);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(mLocationRequest);
    builder.setAlwaysShow(true);

    result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());

    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            //final LocationSettingsStates state = result.getLocationSettingsStates();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    // All location settings are satisfied. The client can initialize location
                    // requests here.
                    //...
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    // Location settings are not satisfied. But could be fixed by showing the user
                    // a dialog.
                    try {
                        // Show the dialog by calling startResolutionForResult(),
                        // and check the result in onActivityResult().
                        status.startResolutionForResult(
                                MainActivity.this,
                                REQUEST_LOCATION);
                    } catch (SendIntentException e) {
                        // Ignore the error.
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    // Location settings are not satisfied. However, we have no way to fix the
                    // settings so we won't show the dialog.
                    //...
                    break;
            }
        }
    });

}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    Log.d("onActivityResult()", Integer.toString(resultCode));

    //final LocationSettingsStates states = LocationSettingsStates.fromIntent(data);
    switch (requestCode)
    {
        case REQUEST_LOCATION:
            switch (resultCode)
            {
                case Activity.RESULT_OK:
                {
                    // All required changes were successfully made
                    Toast.makeText(MainActivity.this, "Location enabled by user!", Toast.LENGTH_LONG).show();
                    break;
                }
                case Activity.RESULT_CANCELED:
                {
                    // The user was asked to change settings, but chose not to
                    Toast.makeText(MainActivity.this, "Location not enabled, user cancelled.", Toast.LENGTH_LONG).show();
                    break;
                }
                default:
                {
                    break;
                }
            }
            break;
    }
}

@Override
public void onConnectionSuspended(int i) {

}

@Override
public void onConnectionFailed(ConnectionResult connectionResult) {

}
} 

Note : This line of code automatic open the dialog box if Location is not on. This piece of line is used in Google Map also

How to use session in JSP pages to get information?

You can directly use (String)session.getAttribute("username"); inside scriptlet tag ie <% %>.

What is the best (idiomatic) way to check the type of a Python variable?

built-in types in Python have built in names:

>>> s = "hallo"
>>> type(s) is str
True
>>> s = {}
>>> type(s) is dict
True

btw note the is operator. However, type checking (if you want to call it that) is usually done by wrapping a type-specific test in a try-except clause, as it's not so much the type of the variable that's important, but whether you can do a certain something with it or not.

Use String.split() with multiple delimiters

Try this code:

var string = 'AA.BB-CC-DD.zip';
array = string.split(/[,.]/);

Php multiple delimiters in explode

You can take the first string, replace all the @ with vs using str_replace, then explode on vs or vice versa.

How to convert MySQL time to UNIX timestamp using PHP?

Instead of strtotime you should use DateTime with PHP. You can also regard the timezone this way:

$dt = DateTime::createFromFormat('Y-m-d H:i:s', $mysqltime, new DateTimeZone('Europe/Berlin'));
$unix_timestamp = $dt->getTimestamp();

$mysqltime is of type MySQL Datetime, e. g. 2018-02-26 07:53:00.

Python - 'ascii' codec can't decode byte

Always encode from unicode to bytes.
In this direction, you get to choose the encoding.

>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print _
??

The other way is to decode from bytes to unicode.
In this direction, you have to know what the encoding is.

>>> bytes = '\xe4\xbd\xa0\xe5\xa5\xbd'
>>> print bytes
??
>>> bytes.decode('utf-8')
u'\u4f60\u597d'
>>> print _
??

This point can't be stressed enough. If you want to avoid playing unicode "whack-a-mole", it's important to understand what's happening at the data level. Here it is explained another way:

  • A unicode object is decoded already, you never want to call decode on it.
  • A bytestring object is encoded already, you never want to call encode on it.

Now, on seeing .encode on a byte string, Python 2 first tries to implicitly convert it to text (a unicode object). Similarly, on seeing .decode on a unicode string, Python 2 implicitly tries to convert it to bytes (a str object).

These implicit conversions are why you can get UnicodeDecodeError when you've called encode. It's because encoding usually accepts a parameter of type unicode; when receiving a str parameter, there's an implicit decoding into an object of type unicode before re-encoding it with another encoding. This conversion chooses a default 'ascii' decoder, giving you the decoding error inside an encoder.

In fact, in Python 3 the methods str.decode and bytes.encode don't even exist. Their removal was a [controversial] attempt to avoid this common confusion.

...or whatever coding sys.getdefaultencoding() mentions; usually this is 'ascii'

Cross-reference (named anchor) in markdown

Late to the party, but I think this addition might be useful for people working with rmarkdown. In rmarkdown there is built-in support for references to headers in your document.

Any header defined by

# Header

can be referenced by

get me back to that [header](#header)

The following is a minimal standalone .rmd file that shows this behavior. It can be knitted to .pdf and .html.

---
title: "references in rmarkdown"
output:
  html_document: default
  pdf_document: default
---

# Header

Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. Write some more text. 

Go back to that [header](#header).

Test if remote TCP port is open from a shell script

While an old question, I've just dealt with a variant of it, but none of the solutions here were applicable, so I found another, and am adding it for posterity. Yes, I know the OP said they were aware of this option and it didn't suit them, but for anyone following afterwards it might prove useful.

In my case, I want to test for the availability of a local apt-cacher-ng service from a docker build. That means absolutely nothing can be installed prior to the test. No nc, nmap, expect, telnet or python. perl however is present, along with the core libraries, so I used this:

perl -MIO::Socket::INET -e 'exit(! defined( IO::Socket::INET->new("172.17.42.1:3142")))'

AmazonS3 putObject with InputStream length example

Just passing the file object to the putobject method worked for me. If you are getting a stream, try writing it to a temp file before passing it on to S3.

amazonS3.putObject(bucketName, id,fileObject);

I am using Aws SDK v1.11.414

The answer at https://stackoverflow.com/a/35904801/2373449 helped me

How can I determine if a date is between two dates in Java?

Here's how to find whether today is between 2 months:

private boolean isTodayBetween(int from, int to) {
    if (from < 0 || to < 0 || from > Calendar.DECEMBER || to > Calendar.DECEMBER) {
        throw new IllegalArgumentException("Invalid month provided: from = " + from + " to = " + to);
    }
    Date now = new Date();
    GregorianCalendar cal = new GregorianCalendar();
    cal.setTime(now);
    int thisMonth = cal.get(Calendar.MONTH);
    if (from > to) {
        to = to + Calendar.DECEMBER;
        thisMonth = thisMonth + Calendar.DECEMBER;
    }
    if (thisMonth >= from && thisMonth <= to) {
        return true;
    }
    return false;
}

and call it like:

isTodayBetween(Calendar.OCTOBER, Calendar.MARCH)

How to add fonts to create-react-app based projects?

There are two options:

Using Imports

This is the suggested option. It ensures your fonts go through the build pipeline, get hashes during compilation so that browser caching works correctly, and that you get compilation errors if the files are missing.

As described in “Adding Images, Fonts, and Files”, you need to have a CSS file imported from JS. For example, by default src/index.js imports src/index.css:

import './index.css';

A CSS file like this goes through the build pipeline, and can reference fonts and images. For example, if you put a font in src/fonts/MyFont.woff, your index.css might include this:

@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(./fonts/MyFont.woff) format('woff');
}

Notice how we’re using a relative path starting with ./. This is a special notation that helps the build pipeline (powered by Webpack) discover this file.

Normally this should be enough.

Using public Folder

If for some reason you prefer not to use the build pipeline, and instead do it the “classic way”, you can use the public folder and put your fonts there.

The downside of this approach is that the files don’t get hashes when you compile for production so you’ll have to update their names every time you change them, or browsers will cache the old versions.

If you want to do it this way, put the fonts somewhere into the public folder, for example, into public/fonts/MyFont.woff. If you follow this approach, you should put CSS files into public folder as well and not import them from JS because mixing these approaches is going to be very confusing. So, if you still want to do it, you’d have a file like public/index.css. You would have to manually add <link> to this stylesheet from public/index.html:

<link rel="stylesheet" href="%PUBLIC_URL%/index.css">

And inside of it, you would use the regular CSS notation:

@font-face {
  font-family: 'MyFont';
  src: local('MyFont'), url(fonts/MyFont.woff) format('woff');
}

Notice how I’m using fonts/MyFont.woff as the path. This is because index.css is in the public folder so it will be served from the public path (usually it’s the server root, but if you deploy to GitHub Pages and set your homepage field to http://myuser.github.io/myproject, it will be served from /myproject). However fonts are also in the public folder, so they will be served from fonts relatively (either http://mywebsite.com/fonts or http://myuser.github.io/myproject/fonts). Therefore we use the relative path.

Note that since we’re avoiding the build pipeline in this example, it doesn’t verify that the file actually exists. This is why I don’t recommend this approach. Another problem is that our index.css file doesn’t get minified and doesn’t get a hash. So it’s going to be slower for the end users, and you risk the browsers caching old versions of the file.

 Which Way to Use?

Go with the first method (“Using Imports”). I only described the second one since that’s what you attempted to do (judging by your comment), but it has many problems and should only be the last resort when you’re working around some issue.

What is the best alternative IDE to Visual Studio

If you are looking to try Java, I believe NetBeans is a very, very good IDE. However, for .NET, sure there are alternative IDEs but I don't think it makes much sense to use them unless you are developing on an Open Source platform, in which case SharpDevelop is a good choice and is reasonably mature.

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

In Dart, if/else and switch are statements not expressions. They don't return a value so you can't pass them to constructor params. If you have a lot of conditional logic in your build method, then it is a good practice to try and simplify it. For example, you can move self-contained logic to methods, and use if/else statements to initialize local variables which you can later use.

Using a method and if/else

Widget _buildChild() {
  if (condition) {
    return ...
  }
  return ...
}

Widget build(BuildContext context) {
  return new Container(child: _buildChild());
}

Using an if/else

Widget build(BuildContext context) {
  Widget child;
  if (condition) {
    child = ...
  } else {
    child = ...
  }
  return new Container(child: child);
}

Sublime 3 - Set Key map for function Goto Definition

To set go to definition to alt + d. From the Menu Preferences > Key Bindings-User. And then add the following JSON.

[
    { "keys": ["alt+d"], "command": "goto_definition" }
]

How do I limit the number of rows returned by an Oracle query after ordering?

An analytic solution with only one nested query:

SELECT * FROM
(
   SELECT t.*, Row_Number() OVER (ORDER BY name) MyRow FROM sometable t
) 
WHERE MyRow BETWEEN 10 AND 20;

Rank() could be substituted for Row_Number() but might return more records than you are expecting if there are duplicate values for name.

Disabled href tag

Tips 1: Using CSS pointer-events: none;

Tips 2: Using JavaScript javascript:void(0) (This is a best practice)

<a href="javascript:void(0)"></a>

Tips 1: Using Jquery $('selector').attr("disabled","disabled");

PowerShell Remoting giving "Access is Denied" error

Had similar problems recently. Would suggest you carefully check if the user you're connecting with has proper authorizations on the remote machine.

You can review permissions using the following command.

Set-PSSessionConfiguration -ShowSecurityDescriptorUI -Name Microsoft.PowerShell

Found this tip here (updated link, thanks "unbob"):

https://devblogs.microsoft.com/scripting/configure-remote-security-settings-for-windows-powershell/

It fixed it for me.

Mongoose's find method with $or condition does not work properly

According to mongoDB documentation: "...That is, for MongoDB to use indexes to evaluate an $or expression, all the clauses in the $or expression must be supported by indexes."

So add indexes for your other fields and it will work. I had a similar problem and this solved it.

You can read more here: https://docs.mongodb.com/manual/reference/operator/query/or/

How to exit an if clause

You can emulate goto's functionality with exceptions:

try:
    # blah, blah ...
    # raise MyFunkyException as soon as you want out
except MyFunkyException:
    pass

Disclaimer: I only mean to bring to your attention the possibility of doing things this way, while in no way do I endorse it as reasonable under normal circumstances. As I mentioned in a comment on the question, structuring code so as to avoid Byzantine conditionals in the first place is preferable by far. :-)

What's the best way to calculate the size of a directory in .NET?

I've been fiddling with VS2008 and LINQ up until recently and this compact and short method works great for me (example is in VB.NET; requires LINQ / .NET FW 3.5+ of course):

Dim size As Int64 = (From strFile In My.Computer.FileSystem.GetFiles(strFolder, _
              FileIO.SearchOption.SearchAllSubDirectories) _
              Select New System.IO.FileInfo(strFile).Length).Sum()

Its short, it searches sub-directories and is simple to understand if you know LINQ syntax. You could even specify wildcards to search for specific files using the third parameter of the .GetFiles function.

I'm not a C# expert but you can add the My namespace on C# this way.

I think this way of obtaining a folder size is not only shorter and more modern than the way described on Hao's link, it basically uses the same loop-of-FileInfo method described there in the end.

What is Join() in jQuery?

A practical example using a jQuery example might be

 var today = new Date();
 $('#'+[today.getMonth()+1, today.getDate(), today.getFullYear()].join("_")).whatever();

I do that in a calendar tool that I am using, this way on the page load, I can do certain things with today's date.

Angular 2: How to call a function after get a response from subscribe http.post

Update your get_categories() method to return the total (wrapped in an observable):

// Note that .subscribe() is gone and I've added a return.
get_categories(number) {
  return this.http.post( url, body, {headers: headers, withCredentials:true})
    .map(response => response.json());
}

In search_categories(), you can subscribe the observable returned by get_categories() (or you could keep transforming it by chaining more RxJS operators):

// send_categories() is now called after get_categories().
search_categories() {
  this.get_categories(1)
    // The .subscribe() method accepts 3 callbacks
    .subscribe(
      // The 1st callback handles the data emitted by the observable.
      // In your case, it's the JSON data extracted from the response.
      // That's where you'll find your total property.
      (jsonData) => {
        this.send_categories(jsonData.total);
      },
      // The 2nd callback handles errors.
      (err) => console.error(err),
      // The 3rd callback handles the "complete" event.
      () => console.log("observable complete")
    );
}

Note that you only subscribe ONCE, at the end.

Like I said in the comments, the .subscribe() method of any observable accepts 3 callbacks like this:

obs.subscribe(
  nextCallback,
  errorCallback,
  completeCallback
);

They must be passed in this order. You don't have to pass all three. Many times only the nextCallback is implemented:

obs.subscribe(nextCallback);

How to write text in ipython notebook?

Adding to Matt's answer above (as I don't have comment privileges yet), one mouse-free workflow would be:

Esc then m then Enter so that you gain focus again and can start typing.

Without the last Enter you would still be in Escape mode and would otherwise have to use your mouse to activate text input in the cell.

Another way would be to add a new cell, type out your markdown in "Code" mode and then change to markdown once you're done typing everything you need, thus obviating the need to refocus.

You can then move on to your next cells. :)

How do I find the date a video (.AVI .MP4) was actually recorded?

Actually you can find very easy the day a video was created, right-click, property but remember it will only give the details of any copy date of the video but if you do click where it says DETAILS JUST there is the information you need, the original date that the archive was created on. Note that most modern devices will produce this information when you take pictures and videos but others will not.

How to tune Tomcat 5.5 JVM Memory settings without using the configuration program

Not sure that it will be applicable solution for you. But the only way for monitoring tomcat memory settings as well as number of connections etc. that actually works for us is Lambda Probe.

It shows most of informations that we need for Tomcat tunning. We tested it with Tomcat 5.5 and 6.0 and it works fine despite beta status and date of last update in end of 2006.

Cannot import XSSF in Apache POI

1) imported all the JARS from POI folder 2) Imported all the JARS from ooxml folder which a subdirectory of POI folder 3) Imported all the JARS from lib folder which is a subdirectory of POI folder

String fileName = "C:/File raw.xlsx";
File file = new File(fileName);
FileInputStream fileInputStream;
Workbook workbook = null;
Sheet sheet;
Iterator<Row> rowIterator;
try {
        fileInputStream = new FileInputStream(file);
        String fileExtension = fileName.substring(fileName.indexOf("."));
        System.out.println(fileExtension);
        if(fileExtension.equals(".xls")){
        workbook  = new HSSFWorkbook(new POIFSFileSystem(fileInputStream));
        }
        else if(fileExtension.equals(".xlsx")){
        workbook  = new XSSFWorkbook(fileInputStream);
        }
        else {
        System.out.println("Wrong File Type");
        } 
        FormulaEvaluator evaluator workbook.getCreationHelper().createFormulaEvaluator();
        sheet = workbook.getSheetAt(0);
        rowIterator = sheet.iterator();
        while(rowIterator.hasNext()){
        Row row = rowIterator.next();
        Iterator<Cell> cellIterator = row.cellIterator();
        while (cellIterator.hasNext()){
        Cell cell = cellIterator.next();
        //Check the cell type after evaluating formulae
       //If it is formula cell, it will be evaluated otherwise no change will happen
        switch (evaluator.evaluateInCell(cell).getCellType()){
        case Cell.CELL_TYPE_NUMERIC:
        System.out.print(cell.getNumericCellValue() + " ");
        break;
        case Cell.CELL_TYPE_STRING:
        System.out.print(cell.getStringCellValue() + " ");
        break;
        case Cell.CELL_TYPE_FORMULA:
        Not again
        break;
        case Cell.CELL_TYPE_BLANK:
        break;
        }
}
 System.out.println("\n");
}
//System.out.println(sheet);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e){
e.printStackTrace();
}?

Changing navigation bar color in Swift

In Swift 4

You can change the color of navigation bar. Just use this below code snippet in viewDidLoad()

Navigation Bar color

self.navigationController?.navigationBar.barTintColor = UIColor.white

Navigation Bar Text Color

self.navigationController?.navigationBar.titleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.purple]

For iOS 11 Large Title Navigation Bar, you need to use largeTitleTextAttributes property

self.navigationController?.navigationBar.largeTitleTextAttributes = [NSAttributedStringKey.foregroundColor: UIColor.purple]

How do I increase the RAM and set up host-only networking in Vagrant?

You can easily increase your VM's RAM by modifying the memory property of config.vm.provider section in your vagrant file.

config.vm.provider "virtualbox" do |vb|
 vb.memory = "4096"
end

This allocates about 4GB of RAM to your VM. You can change this according to your requirement. For example, following setting would allocate 2GB of RAM to your VM.

config.vm.provider "virtualbox" do |vb|
 vb.memory = "2048"
end

Try removing the config.vm.customize ["modifyvm", :id, "--memory", 1024] in your file, and adding the above code.

For the network configuration, try modifying the config.vm.network :hostonly, "199.188.44.20" in your file toconfig.vm.network "private_network", ip: "199.188.44.20"

How to access global js variable in AngularJS directive

I have tried these methods and find that they dont work for my needs. In my case, I needed to inject json rendered server side into the main template of the page, so when it loads and angular inits, the data is already there and doesnt have to be retrieved (large dataset).

The easiest solution that I have found is to do the following:

In your angular code outside of the app, module and controller definitions add in a global javascript value - this definition MUST come before the angular stuff is defined.

Example:

'use strict';

//my data variable that I need access to.
var data = null;

angular.module('sample', [])

Then in your controller:

.controller('SampleApp', function ($scope, $location) {

$scope.availableList = [];

$scope.init = function () {
    $scope.availableList = data;
}

Finally, you have to init everything (order matters):

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="/path/to/your/angular/js/sample.js"></script>
  <script type="text/javascript">
      data = <?= json_encode($cproducts); ?>
  </script>

Finally initialize your controller and init function.

  <div ng-app="samplerrelations" ng-controller="SamplerApp" ng-init="init();">

By doing this you will now have access to whatever data you stuffed into the global variable.

Why Doesn't C# Allow Static Methods to Implement an Interface?

To give an example where I am missing either static implementation of interface methods or what Mark Brackett introduced as the "so-called type method":

When reading from a database storage, we have a generic DataTable class that handles reading from a table of any structure. All table specific information is put in one class per table that also holds data for one row from the DB and which must implement an IDataRow interface. Included in the IDataRow is a description of the structure of the table to read from the database. The DataTable must ask for the datastructure from the IDataRow before reading from the DB. Currently this looks like:

interface IDataRow {
  string GetDataSTructre();  // How to read data from the DB
  void Read(IDBDataRow);     // How to populate this datarow from DB data
}

public class DataTable<T> : List<T> where T : IDataRow {

  public string GetDataStructure()
    // Desired: Static or Type method:
    // return (T.GetDataStructure());
    // Required: Instantiate a new class:
    return (new T().GetDataStructure());
  }

}

The GetDataStructure is only required once for each table to read, the overhead for instantiating one more instance is minimal. However, it would be nice in this case here.

JetBrains / IntelliJ keyboard shortcut to collapse all methods

@precastic's answer above is, imo, the right idea.

Worth noting that in IDEA 2018.2 (and surely other nearby versions) there are default keyboard shortcuts for this: (showing Mac, see Code > Folding > Expand All to Level for your system):

Cmd+Option+Keypad *, 1 - expand all to level 1
Cmd+Option+Keypad *, 2 - expand all to level 2
...
Cmd+Option+Keypad *, 5 - expand all to level 5

Note: these are "second stroke" shortcuts. First press Cmd+Option+*, then release, then hit the number you want.

How to remove selected commit log entries from a Git repository while keeping their changes?

git-rebase(1) does exactly that.

$ git rebase -i HEAD~5

git awsome-ness [git rebase --interactive] contains an example.

  1. Don't use git-rebase on public (remote) commits.
  2. Make sure your working directory is clean (commit or stash your current changes).
  3. Run the above command. It launches your $EDITOR.
  4. Replace pick before C and D by squash. It will meld C and D into B. If you want to delete a commit then just delete its line.

If you are lost, type:

$ git rebase --abort  

How to stop and restart memcached server?

This worked for me:

brew services stop memcached

Only get hash value using md5sum (without filename)

Well, I had the same problem today, but trying to get file md5 hash when running the find command. I got the most voted question and wrapped it in a function called md5 to run in find command. The mission for me was calculate hash for all files in an folder and output it as hash:filename.

md5() { md5sum $1 | awk '{ printf "%s",$1 }'; }
export -f md5
find -type f -exec bash -c 'md5 "$0"' {} \; -exec echo -n ':' \; -print

So, I'd got some pieces from here and also from find -exec a shell function?

How to install maven on redhat linux

Sometimes you may get "Exception in thread "main" java.lang.NoClassDefFoundError: org/codehaus/classworlds/Launcher" even after setting M2_HOME and PATH parameters correctly.

This exception is because your JDK/Java version need to be updated/installed.

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

Please be advised:

JSONP supports only the GET request method.

*Send request by firefox:*

$.ajax({
   type: 'POST',//<<===
   contentType: 'application/json',
   url: url,
   dataType: "json"//<<=============
    ...
});

Above request send by OPTIONS(while ==>type: 'POST')!!!!

$.ajax({
    type: 'POST',//<<===
    contentType: 'application/json',
    url: url,
    dataType: "jsonp"//<<==============
    ...
});

But above request send by GET(while ==>type: 'POST')!!!!

When you are in "cross-domain communication" , pay attention and be careful.

Accessing Redux state in an action creator?

I agree with @Bloomca. Passing the value needed from the store into the dispatch function as an argument seems simpler than exporting the store. I made an example here:

import React from "react";
import {connect} from "react-redux";
import * as actions from '../actions';

class App extends React.Component {

  handleClick(){
    const data = this.props.someStateObject.data;
    this.props.someDispatchFunction(data);
  }

  render(){
    return (
      <div>       
      <div onClick={ this.handleClick.bind(this)}>Click Me!</div>      
      </div>
    );
  }
}


const mapStateToProps = (state) => {
  return { someStateObject: state.someStateObject };
};

const mapDispatchToProps = (dispatch) => {
  return {
    someDispatchFunction:(data) => { dispatch(actions.someDispatchFunction(data))},

  };
}


export default connect(mapStateToProps, mapDispatchToProps)(App);

Maven: Failed to read artifact descriptor

I solved this issue by deleting in the repository folders where this error was shown everything except the .jar and .pom files.

Given URL is not permitted by the application configuration

Settings -> Advanced, add url to "Valid OAuth redirect URIs". This works for me.

Difference Between Schema / Database in MySQL

in MySQL schema is synonym of database. Its quite confusing for beginner people who jump to MySQL and very first day find the word schema, so guys nothing to worry as both are same.

When you are starting MySQL for the first time you need to create a database (like any other database system) to work with so you can CREATE SCHEMA which is nothing but CREATE DATABASE

In some other database system schema represents a part of database or a collection of Tables, and collection of schema is a database.

Firebase Permission Denied

  1. Open firebase, select database on the left hand side.
  2. Now on the right hand side, select [Realtime database] from the drown and change the rules to:
{
  "rules": {
    ".read": true,
    ".write": true
  }
}