Programs & Examples On #Finddialog

Using Chrome's Element Inspector in Print Preview Mode?

As of Chrome 48+, you can access the print preview via the following steps:

  1. Open dev tools – Ctrl/Cmd + Shift + I or right click on the page and choose 'Inspect'.

  2. Hit Esc to open the additional drawer.

  3. If 'Rendering' isn't already being show, click the 3 dot kebab and choose 'rendering'.

  4. Check the 'Emulate print media' checkbox.

From there Chrome will show you a print version of your page and you can inspect element and troubleshoot like you would the browser version.

Image of Chrome 49+ Print Preview option in Dev Tools

How do I exit from the text window in Git?

On windows, simply pressing 'q' on the keyboard quits this screen. I got it when I was reading help using '!help' or simply 'help' and 'enter', from the DOS prompt.

Happy Coding :-)

Quick Sort Vs Merge Sort

See Quicksort on wikipedia:

Typically, quicksort is significantly faster in practice than other T(nlogn) algorithms, because its inner loop can be efficiently implemented on most architectures, and in most real-world data, it is possible to make design choices which minimize the probability of requiring quadratic time.

Note that the very low memory requirement is a big plus as well.

How do I use a char as the case in a switch-case?

Here's an example:

public class Main {

    public static void main(String[] args) {

        double val1 = 100;
        double val2 = 10;
        char operation = 'd';
        double result = 0;

        switch (operation) {

            case 'a':
                result = val1 + val2; break;

            case 's':
                result = val1 - val2; break;
            case 'd':
                if (val2 != 0)
                    result = val1 / val2; break;
            case 'm':
                result = val1 * val2; break;

            default: System.out.println("Not a defined operation");


        }

        System.out.println(result);
    }
}

Unable to begin a distributed transaction

My last adventure with MSDTC and this error today turned out to be a DNS issue. You're on the right track asking if the machines are on the same domain, EBarr. Terrific list for this issue, by the way!

My situation: I needed a server in a child domain to be able to run distributed transactions against a server in the parent domain through a firewall. I've used linked servers quite a bit over the years, so I had all the usual settings in SQL for a linked server and in MSDTC that Ian documented so nicely above. I set up MSDTC with a range of TCP ports (5000-5200) to use on both servers, and arranged for a firewall hole between the boxes for ports 1433 and 5000-5200. That should have worked. The linked server tested OK and I could query the remote SQL server via the linked server nicely, but I couldn't get it to allow a distributed transaction. I could even see a connection on the QA server from the DEV server, but something wasn't making the trip back.

I could PING the DEV server from QA using a FQDN like: PING DEVSQL.dev.domain.com

I could not PING the DEV server with just the machine name: PING DEVSQL

The DEVSQL server was supposed to be a member of both domains, but the name wasn't resolving in the parent domain's DNS... something had happened to the machine account for DEVSQL in the parent domain. Once we added DEVSQL to the DNS for the parent domain, and "PING DEVSQL" worked from the remote QA server, this issue was resolved for us.

I hope this helps!

HTTP 400 (bad request) for logical error, not malformed request syntax

Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.

Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)

Thank You, Vish

Rails: FATAL - Peer authentication failed for user (PG::Error)

I was facing same problem on Ubuntu machine so I removed this error by following some steps. Switch to postgres user

$ sudo su - postgres

it will ask for password and by default password is postgres

After switch the user to postgres, open psql console

$ psql

so check the version of postgres if multiple versions are available

psql=# select VERSION();

PostgreSQL 9.1.13 on x86_64-unk....         # so version is 9.1

Now Open postgres user

vim /etc/postgresql/9.1/main/pg_hba.conf

9.1 is version return form upper command

and replace

local   all             postgres                                peer

to

local   all             postgres                                md5

Restart the service

sudo service postgresql restart

I write steps on my blog also

http://tarungarg402.blogspot.in/2014/10/set-up-postgresql-on-ubuntu.html

No input file specified

Run ulimit -n 2048

And restart php/php-fpm

NoSQL Use Case Scenarios or WHEN to use NoSQL

I think Nosql is "more suitable" in these scenarios at least (more supplementary is welcome)

  1. Easy to scale horizontally by just adding more nodes.

  2. Query on large data set

    Imagine tons of tweets posted on twitter every day. In RDMS, there could be tables with millions (or billions?) of rows, and you don't want to do query on those tables directly, not even mentioning, most of time, table joins are also needed for complex queries.

  3. Disk I/O bottleneck

    If a website needs to send results to different users based on users' real-time info, we are probably talking about tens or hundreds of thousands of SQL read/write requests per second. Then disk i/o will be a serious bottleneck.

Adding a right click menu to an item

If you are using Visual Studio, there is a GUI solution as well:

  1. From Toolbox add a ContextMenuStrip
  2. Select the context menu and add the right click items
  3. For each item set the click events to the corresponding functions
  4. Select the form / button / image / etc (any item) that the right click menu will be connected
  5. Set its ContextMenuStrip property to the menu you have created.

Find the smallest positive integer that does not occur in a given sequence

For the space complexity of O(1) and time complexity of O(N) and if the array can be modified then it could be as follows:

public int getFirstSmallestPositiveNumber(int[] arr) {
    // set positions of non-positive or out of range elements as free (use 0 as marker)
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] <= 0 || arr[i] > arr.length) {
            arr[i] = 0;
        }
    }

    //iterate through the whole array again mapping elements [1,n] to positions [0, n-1]
    for (int i = 0; i < arr.length; i++) {
        int prev = arr[i];
        // while elements are not on their correct positions keep putting them there
        while (prev > 0 && arr[prev - 1] != prev) {
            int next = arr[prev - 1];
            arr[prev - 1] = prev;
            prev = next;
        }
    }

    // now, the first unmapped position is the smallest element
    for (int i = 0; i < arr.length; i++) {
        if (arr[i] != i + 1) {
            return i + 1;
        }
    }
    return arr.length + 1;
}

@Test
public void testGetFirstSmallestPositiveNumber() {
    int[][] arrays = new int[][]{{1,-1,-5,-3,3,4,2,8},
      {5, 4, 3, 2, 1}, 
      {0, 3, -2, -1, 1}};

    for (int i = 0; i < arrays.length; i++) {
        System.out.println(getFirstSmallestPositiveNumber(arrays[i]));
    }
}  

Output:

5

6

2

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

You can input the following command on Linux:

find ./ -name "*." | xargs svn add

matplotlib savefig() plots different from show()

savefig specifies the DPI for the saved figure (The default is 100 if it's not specified in your .matplotlibrc, have a look at the dpi kwarg to savefig). It doesn't inheret it from the DPI of the original figure.

The DPI affects the relative size of the text and width of the stroke on lines, etc. If you want things to look identical, then pass fig.dpi to fig.savefig.

E.g.

import matplotlib.pyplot as plt

fig = plt.figure()
plt.plot(range(10))
fig.savefig('temp.png', dpi=fig.dpi)

Getting value of selected item in list box as string

If you are using ListBox in your application and you want to return the selected value of ListBox and display it in a Label or any thing else then use this code, it will help you

 private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
    {
         label1.Text  = listBox1.SelectedItem.ToString();
    }

how do I change text in a label with swift?

Swift uses the same cocoa-touch API. You can call all the same methods, but they will use Swift's syntax. In this example you can do something like this:

self.simpleLabel.text = "message"

Note the setText method isn't available. Setting the label's text with = will automatically call the setter in swift.

this.getClass().getClassLoader().getResource("...") and NullPointerException

When you use

this.getClass().getResource("myFile.ext")

getResource will try to find the resource relative to the package. If you use:

this.getClass().getResource("/myFile.ext")

getResource will treat it as an absolute path and simply call the classloader like you would have if you'd done.

this.getClass().getClassLoader().getResource("myFile.ext")

The reason you can't use a leading / in the ClassLoader path is because all ClassLoader paths are absolute and so / is not a valid first character in the path.

Test if a property is available on a dynamic variable

I think there is no way to find out whether a dynamic variable has a certain member without trying to access it, unless you re-implemented the way dynamic binding is handled in the C# compiler. Which would probably include a lot of guessing, because it is implementation-defined, according to the C# specification.

So you should actually try to access the member and catch an exception, if it fails:

dynamic myVariable = GetDataThatLooksVerySimilarButNotTheSame();

try
{
    var x = myVariable.MyProperty;
    // do stuff with x
}
catch (RuntimeBinderException)
{
    //  MyProperty doesn't exist
} 

Setting button text via javascript

Set the text of the button by setting the innerHTML

var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');
b.innerHTML = 'test value';

var wrapper = document.getElementById('divWrapper');
wrapper.appendChild(b);

http://jsfiddle.net/jUVpE/

file_put_contents(meta/services.json): failed to open stream: Permission denied

None of the above solution can be useful for me, because I didn't have access by SSH to run the commands to clear cache or giving the recursive permission, so I fixed the issue by removing this file and the issue fixed.

You can delete the bootstrap/cache/config.php file.

How to place object files in separate subdirectory

You can specify the -o $@ option to your compile command to force the output of the compile command to take on the name of the target. For example, if you have:

  • sources: cpp/class.cpp and cpp/driver.cpp
  • headers: headers/class.h

...and you want to place the object files in:

  • objects: obj/class.o obj/driver.o

...then you can compile cpp/class.cpp and cpp/driver.cpp separately into obj/class.o and obj/driver.o, and then link, with the following Makefile:

CC=c++
FLAGS=-std=gnu++11

INCS=-I./headers
SRC=./cpp
OBJ=./obj
EXE=./exe

${OBJ}/class.o:    ${SRC}/class.cpp
                   ${CC} ${FLAGS} ${INCS} -c $< -o $@

${OBJ}/driver.o:    ${SRC}/driver.cpp ${SRC}/class.cpp
                    ${CC} ${FLAGS} ${INCS} -c $< -o $@

driver: ${OBJ}/driver.o ${OBJ}/class.o
        ${CC} ${FLAGS} ${OBJ}/driver.o ${OBJ}/class.o -o ${EXE}/driver

How to display multiple notifications in android

Use the following method in your code.

Method call :-

notificationManager.notify(getCurrentNotificationId(getApplicationContext()), notification);

Method:-

  *Returns a unique notification id.
         */

        public static int getCurrentNotificationId(Context iContext){

            NOTIFICATION_ID_UPPER_LIMIT = 30000; // Arbitrary number.

            NOTIFICATION_ID_LOWER_LIMIT = 0;
            SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(iContext);
        int previousTokenId= sharedPreferences.getInt("currentNotificationTokenId", 0);

        int currentTokenId= previousTokenId+1;

        SharedPreferences.Editor editor= sharedPreferences.edit();

        if(currentTokenId<NOTIFICATION_ID_UPPER_LIMIT) {

            editor.putInt("currentNotificationTokenId", currentTokenId); // }
        }else{
            //If reaches the limit reset to lower limit..
            editor.putInt("currentNotificationTokenId", NOTIFICATION_ID_LOWER_LIMIT);
        }

        editor.commit();

        return currentTokenId;
    }

Make new column in Panda dataframe by adding values from other columns

Can do using loc

In [37]:  df = pd.DataFrame({"A":[1,2,3],"B":[4,6,9]})

In [38]: df
Out[38]:
   A  B
0  1  4
1  2  6
2  3  9

In [39]: df['C']=df.loc[:,['A','B']].sum(axis=1)

In [40]: df
Out[40]:
   A  B   C
0  1  4   5
1  2  6   8
2  3  9  12

How do you count the elements of an array in java

There is no built-in functionality for this. This count is in its whole user-specific. Maintain a counter or whatever.

Preventing iframe caching in browser

Have you installed Fiddler2?

It will let you see exactly what is being requested, what is being sent back, etc. It doesn't sound plausible that the browser would really hit its cache for different URLs.

Spring .properties file: get element as an Array

Here is an example of how you can do it in Spring 4.0+

application.properties content:

some.key=yes,no,cancel

Java Code:

@Autowire
private Environment env;

...

String[] springRocks = env.getProperty("some.key", String[].class);

Adding devices to team provisioning profile

Note that testers are no longer added via UUID in the new Apple TestFlight.

Test Flight builds now require an App Store Distribution Provisioning Profile. The portal does not allow UUIDs to be added to this type of provisioning profile.

Instead, add "Internal Testers" via iTunes Connect:

Internal testers are iTunes Connect users with the Admin or Technical role. They can be added in Users and Roles.

After adding a user, be sure to click on their name and flip the "Internal Tester" switch.

Internal Tester Toggle Switch

Then, go to App > Prerelease > Internal Testers and invite them to the build.

How to bind DataTable to Datagrid

In cs file

DataTable employeeData = CreateDataTable();
gridEmployees.DataContext = employeeData.DefaultView;

In xaml file

<DataGrid Name="gridEmployees" ItemsSource="{Binding}">

Does Visual Studio have code coverage for unit tests?

Toni's answer is very useful, but I thought a quick start for total beginners to test coverage assessment (like I am).

As already mentioned, Visual Studio Professional and Community Editions do not have built-in test coverage support. However, it can be obtained quite easily. I will write step-by-step configuration for use with NUnit tests within Visual Studion 2015 Professional.

  1. Install OpenCover NUGet component using NuGet interface

  2. Get OpenCoverUI extension. This can be installed directly from Visual Studio by using Tools -> Extensions and Updates

  3. Configure OpenCoverUI to use the appropriate executables, by accessing Tools -> Options -> OpenCover.UI Options -> General

NUnit Path: must point to the `nunit-console.exe file. This can be found only within NUnit 2.xx version, which can be downloaded from here.

OpenCover Path: this should point to the installed package, usually <solution path>\packages\OpenCover.4.6.519\tools\OpenCover.Console.exe

  1. Install ReportGenerator NUGet package

  2. Access OpenCover Test Explorer from OpenCover menu. Try discovering tests from there. If it fails, check Output windows for more details.

  3. Check OpenCover Results (within OpenCover menu) for more details. It will output details such as Code Coverage in a tree based view. You can also highlight code that is or is not covered (small icon in the top-left).

NOTE: as mentioned, OpenCoverUI does not support latest major version of NUnit (3.xx). However, if nothing specific to this version is used within tests, it will work with no problems, regardless of having installed NUnit 3.xx version.

This covers the quick start. As already mentioned in the comments, for more advanced configuration and automation check this article.

How to Customize the time format for Python logging?

From the official documentation regarding the Formatter class:

The constructor takes two optional arguments: a message format string and a date format string.

So change

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

to

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

Pass C# ASP.NET array to Javascript array

For array of objects:

var array= JSON.parse('@Newtonsoft.Json.JsonConvert.SerializeObject(numbers)'.replace(/&quot;/g, "\""));

For array of int:

 var array= JSON.parse('@Newtonsoft.Json.JsonConvert.SerializeObject(numbers)');

How to do a FULL OUTER JOIN in MySQL?

Answer:

SELECT * FROM t1 FULL OUTER JOIN t2 ON t1.id = t2.id;

Can be recreated as follows:

 SELECT t1.*, t2.* 
 FROM (SELECT * FROM t1 UNION SELECT name FROM t2) tmp
 LEFT JOIN t1 ON t1.id = tmp.id
 LEFT JOIN t2 ON t2.id = tmp.id;

Using a UNION or UNION ALL answer does not cover the edge case where the base tables have duplicated entries.

Explanation:

There is an edge case that a UNION or UNION ALL cannot cover. We cannot test this on mysql as it doesn't support FULL OUTER JOINs, but we can illustrate this on a database that does support it:

 WITH cte_t1 AS
 (
       SELECT 1 AS id1
       UNION ALL SELECT 2
       UNION ALL SELECT 5
       UNION ALL SELECT 6
       UNION ALL SELECT 6
 ),
cte_t2 AS
(
      SELECT 3 AS id2
      UNION ALL SELECT 4
      UNION ALL SELECT 5
      UNION ALL SELECT 6
      UNION ALL SELECT 6
)
SELECT  *  FROM  cte_t1 t1 FULL OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2;

This gives us this answer:

id1  id2
1  NULL
2  NULL
NULL  3
NULL  4
5  5
6  6
6  6
6  6
6  6

The UNION solution:

SELECT  * FROM  cte_t1 t1 LEFT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2
UNION    
SELECT  * FROM cte_t1 t1 RIGHT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2

Gives an incorrect answer:

 id1  id2
NULL  3
NULL  4
1  NULL
2  NULL
5  5
6  6

The UNION ALL solution:

SELECT  * FROM cte_t1 t1 LEFT OUTER join cte_t2 t2 ON t1.id1 = t2.id2
UNION ALL
SELECT  * FROM  cte_t1 t1 RIGHT OUTER JOIN cte_t2 t2 ON t1.id1 = t2.id2

Is also incorrect.

id1  id2
1  NULL
2  NULL
5  5
6  6
6  6
6  6
6  6
NULL  3
NULL  4
5  5
6  6
6  6
6  6
6  6

Whereas this query:

SELECT t1.*, t2.*
FROM (SELECT * FROM t1 UNION SELECT name FROM t2) tmp 
LEFT JOIN t1 ON t1.id = tmp.id 
LEFT JOIN t2 ON t2.id = tmp.id;

Gives the following:

id1  id2
1  NULL
2  NULL
NULL  3
NULL  4
5  5
6  6
6  6
6  6
6  6

The order is different, but otherwise matches the correct answer.

In Python, how do I iterate over a dictionary in sorted key order?

>>> import heapq
>>> d = {"c": 2, "b": 9, "a": 4, "d": 8}
>>> def iter_sorted(d):
        keys = list(d)
        heapq.heapify(keys) # Transforms to heap in O(N) time
        while keys:
            k = heapq.heappop(keys) # takes O(log n) time
            yield (k, d[k])


>>> i = iter_sorted(d)
>>> for x in i:
        print x


('a', 4)
('b', 9)
('c', 2)
('d', 8)

This method still has an O(N log N) sort, however, after a short linear heapify, it yields the items in sorted order as it goes, making it theoretically more efficient when you do not always need the whole list.

How can I force input to uppercase in an ASP.NET textbox?

  <telerik:RadTextBox ID="txtCityName" runat="server" MaxLength="50" Width="200px"
                            Style="text-transform: uppercase;">

nginx- duplicate default server error

If you're on Digital Ocean this means you need to go to /etc/nginx/sites-enabled/ and then REMOVE using rm -R digitalocean and default

It fixed it for me!

Pic of Console on Windows 10 using Bitvise

How to check Elasticsearch cluster health?

You can check elasticsearch cluster health by using (CURL) and Cluster API provieded by elasticsearch:

$ curl -XGET 'localhost:9200/_cluster/health?pretty'

This will give you the status and other related data you need.

{
 "cluster_name" : "xxxxxxxx",
 "status" : "green",
 "timed_out" : false,
 "number_of_nodes" : 2,
 "number_of_data_nodes" : 2,
 "active_primary_shards" : 15,
 "active_shards" : 12,
 "relocating_shards" : 0,
 "initializing_shards" : 0,
 "unassigned_shards" : 0,
 "delayed_unassigned_shards" : 0,
 "number_of_pending_tasks" : 0,
 "number_of_in_flight_fetch" : 0
}

SQL Server after update trigger

try this solution.

       DECLARE @Id INT
       DECLARE @field VARCHAR(50)

       SELECT @Id= INSERTED.CustomerId       
       FROM INSERTED

       IF UPDATE(Name)
       BEGIN
              SET @field = 'Updated Name'
       END

       IF UPDATE(Country)
       BEGIN
              SET @field = 'Updated Country'
       END

       INSERT INTO CustomerLogs
       VALUES(@Id, @field)

       // OR
       -- If you wish to update existing table records.
       UPDATE YOUR_TABLE SET [FIELD]=[VALUE] WHERE {CONDITION}

I didn't checked this with older version of sql server but this will work with sql server 2012.

ImportError: No module named BeautifulSoup

if you got two version of python, maybe my situation could help you

this is my situation

1-> mac osx

2-> i have two version python , (1) system default version 2.7 (2) manually installed version 3.6

3-> i have install the beautifulsoup4 with sudo pip install beautifulsoup4

4-> i run the python file with python3 /XXX/XX/XX.py

so this situation 3 and 4 are the key part, i have install beautifulsoup4 with "pip" but this module was installed for python verison 2.7, and i run the python file with "python3". so you should install beautifulsoup4 for the python 3.6;

with the sudo pip3 install beautifulsoup4 you can install the module for the python 3.6

How to capitalize the first letter of word in a string using Java?

String sentence = "ToDAY   WeAthEr   GREat";    
public static String upperCaseWords(String sentence) {
        String words[] = sentence.replaceAll("\\s+", " ").trim().split(" ");
        String newSentence = "";
        for (String word : words) {
            for (int i = 0; i < word.length(); i++)
                newSentence = newSentence + ((i == 0) ? word.substring(i, i + 1).toUpperCase(): 
                    (i != word.length() - 1) ? word.substring(i, i + 1).toLowerCase() : word.substring(i, i + 1).toLowerCase().toLowerCase() + " ");
        }

        return newSentence;
    }
//Today Weather Great

Selecting option by text content with jQuery

Replace this:

var cat = $.jqURL.get('category');
var $dd = $('#cbCategory');
var $options = $('option', $dd);
$options.each(function() {
if ($(this).text() == cat)
    $(this).select(); // This is where my problem is
});

With this:

$('#cbCategory').val(cat);

Calling val() on a select list will automatically select the option with that value, if any.

Font.createFont(..) set color and size (java.awt.Font)

Because font doesn't have color, you need a panel to make a backgound color and give the foreground color for both JLabel (if you use JLabel) and JPanel to make font color, like example below :

JLabel lblusr = new JLabel("User name : ");
lblusr.setForeground(Color.YELLOW);

JPanel usrPanel = new JPanel();
Color maroon = new Color (128, 0, 0);
usrPanel.setBackground(maroon);
usrPanel.setOpaque(true);
usrPanel.setForeground(Color.YELLOW);
usrPanel.add(lblusr);

The background color of label is maroon with yellow font color.

How to calculate rolling / moving average using NumPy / SciPy?

NumPy's lack of a particular domain-specific function is perhaps due to the Core Team's discipline and fidelity to NumPy's prime directive: provide an N-dimensional array type, as well as functions for creating, and indexing those arrays. Like many foundational objectives, this one is not small, and NumPy does it brilliantly.

The (much) larger SciPy contains a much larger collection of domain-specific libraries (called subpackages by SciPy devs)--for instance, numerical optimization (optimize), signal processsing (signal), and integral calculus (integrate).

My guess is that the function you are after is in at least one of the SciPy subpackages (scipy.signal perhaps); however, i would look first in the collection of SciPy scikits, identify the relevant scikit(s) and look for the function of interest there.

Scikits are independently developed packages based on NumPy/SciPy and directed to a particular technical discipline (e.g., scikits-image, scikits-learn, etc.) Several of these were (in particular, the awesome OpenOpt for numerical optimization) were highly regarded, mature projects long before choosing to reside under the relatively new scikits rubric. The Scikits homepage liked to above lists about 30 such scikits, though at least several of those are no longer under active development.

Following this advice would lead you to scikits-timeseries; however, that package is no longer under active development; In effect, Pandas has become, AFAIK, the de facto NumPy-based time series library.

Pandas has several functions that can be used to calculate a moving average; the simplest of these is probably rolling_mean, which you use like so:

>>> # the recommended syntax to import pandas
>>> import pandas as PD
>>> import numpy as NP

>>> # prepare some fake data:
>>> # the date-time indices:
>>> t = PD.date_range('1/1/2010', '12/31/2012', freq='D')

>>> # the data:
>>> x = NP.arange(0, t.shape[0])

>>> # combine the data & index into a Pandas 'Series' object
>>> D = PD.Series(x, t)

Now, just call the function rolling_mean passing in the Series object and a window size, which in my example below is 10 days.

>>> d_mva = PD.rolling_mean(D, 10)

>>> # d_mva is the same size as the original Series
>>> d_mva.shape
    (1096,)

>>> # though obviously the first w values are NaN where w is the window size
>>> d_mva[:3]
    2010-01-01         NaN
    2010-01-02         NaN
    2010-01-03         NaN

verify that it worked--e.g., compared values 10 - 15 in the original series versus the new Series smoothed with rolling mean

>>> D[10:15]
     2010-01-11    2.041076
     2010-01-12    2.041076
     2010-01-13    2.720585
     2010-01-14    2.720585
     2010-01-15    3.656987
     Freq: D

>>> d_mva[10:20]
      2010-01-11    3.131125
      2010-01-12    3.035232
      2010-01-13    2.923144
      2010-01-14    2.811055
      2010-01-15    2.785824
      Freq: D

The function rolling_mean, along with about a dozen or so other function are informally grouped in the Pandas documentation under the rubric moving window functions; a second, related group of functions in Pandas is referred to as exponentially-weighted functions (e.g., ewma, which calculates exponentially moving weighted average). The fact that this second group is not included in the first (moving window functions) is perhaps because the exponentially-weighted transforms don't rely on a fixed-length window

How to fix 'fs: re-evaluating native module sources is not supported' - graceful-fs

Solved this bug with reinstall gulp

npm uninstall gulp
npm install gulp

Cannot read property length of undefined

The id of the input seems is not WallSearch. Maybe you're confusing that name and id. They are two different properties. name is used to define the name by which the value is posted, while id is the unique identification of the element inside the DOM.

Other possibility is that you have two elements with the same id. The browser will pick any of these (probably the last, maybe the first) and return an element that doesn't support the value property.

How does the ARM architecture differ from x86?

The ARM architecture was originally designed for Acorn personal computers (See Acorn Archimedes, circa 1987, and RiscPC), which were just as much keyboard-based personal computers as were x86 based IBM PC models. Only later ARM implementations were primarily targeted at the mobile and embedded market segment.

Originally, simple RISC CPUs of roughly equivalent performance could be designed by much smaller engineering teams (see Berkeley RISC) than those working on the x86 development at Intel.

But, nowadays, the fastest ARM chips have very complex multi-issue out-of-order instruction dispatch units designed by large engineering teams, and x86 cores may have something like a RISC core fed by an instruction translation unit.

So, any current differences between the two architectures are more related to the specific market needs of the product niches that the development teams are targeting. (Random opinion: ARM probably makes more in license fees from embedded applications that tend to be far more power and cost constrained. And Intel needs to maintain a performance edge in PCs and servers for their profit margins. Thus you see differing implementation optimizations.)

Combining "LIKE" and "IN" for SQL Server

Effectively, the IN statement creates a series of OR statements... so

SELECT * FROM table WHERE column IN (1, 2, 3)

Is effectively

SELECT * FROM table WHERE column = 1 OR column = 2 OR column = 3

And sadly, that is the route you'll have to take with your LIKE statements

SELECT * FROM table
WHERE column LIKE 'Text%' OR column LIKE 'Hello%' OR column LIKE 'That%'

Java: Instanceof and Generics

The error message says it all. At runtime, the type is gone, there is no way to check for it.

You could catch it by making a factory for your object like this:

 public static <T> MyObject<T> createMyObject(Class<T> type) {
    return new MyObject<T>(type);
 }

And then in the object's constructor store that type, so variable so that your method could look like this:

        if (arg0 != null && !(this.type.isAssignableFrom(arg0.getClass()))
        {
            return -1;
        }

How to compare two tags with git?

As @Nakilon said, their is a comparing tool built in github if that's what you use.

To use it, append the url of the repo with "/compare".

Convert AM/PM time to 24 hours format?

Convert a string to a DateTime, you could try

    DateTime timeValue = Convert.ToDateTime("01:00 PM");
    Console.WriteLine(timeValue.ToString("HH:mm"));

Stretch and scale CSS background

An additional tip for SolidSmile's cheat is to scale (the proportionate re-sizing) by setting a width and using auto for height.

Ex:

#background {
    width: 500px;
    height: auto;
    position: absolute; 
    left: 0px; 
    top: 0px; 
    z-index: 0;
}

simple vba code gives me run time error 91 object variable or with block not set

Also you are trying to set value2 using Set keyword, which is not required. You can directly use rng.value2 = 1

below test code for ref.

Sub test()
    Dim rng As Range
    Set rng = Range("A1")
    rng.Value2 = 1
End Sub

How to overcome "datetime.datetime not JSON serializable"?

This library superjson can do it. And you can easily custom json serializer for your own Python Object by following this instruction https://superjson.readthedocs.io/index.html#extend.

The general concept is:

your code need to locate the right serialization / deserialization method based on the python object. Usually, the full classname is a good identifier.

And then your ser / deser method should be able to transform your object to a regular Json serializable object, a combination of generic python type, dict, list, string, int, float. And implement your deser method reversely.

HTTP Request in Swift with POST method

For anyone looking for a clean way to encode a POST request in Swift 5.

You don’t need to deal with manually adding percent encoding. Use URLComponents to create a GET request URL. Then use query property of that URL to get properly percent escaped query string.

let url = URL(string: "https://example.com")!
var components = URLComponents(url: url, resolvingAgainstBaseURL: false)!

components.queryItems = [
    URLQueryItem(name: "key1", value: "NeedToEscape=And&"),
    URLQueryItem(name: "key2", value: "vålüé")
]

let query = components.url!.query

The query will be a properly escaped string:

key1=NeedToEscape%3DAnd%26&key2=v%C3%A5l%C3%BC%C3%A9

Now you can create a request and use the query as HTTPBody:

var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = Data(query.utf8)

Now you can send the request.

Counter in foreach loop in C#

The sequence being iterated in a foreach loop might not support indexing or know such a concept it just needs to implement a method called GetEnumerator that returns an object that as a minimum has the interface of IEnumerator though implmenting it is not required. If you know that what you iterate does support indexing and you need the index then I suggest to use a for loop instead.

An example class that can be used in foreach:

    class Foo {

        public iterator GetEnumerator() {
            return new iterator();
        }

        public class iterator {
            public Bar Current {
                get{magic}
            }

            public bool MoveNext() {
                incantation
            }
        }
    }

How to select an item in a ListView programmatically?

if (listView1.Items.Count > 0)
{
    listView1.FocusedItem = listView1.Items[0];
    listView1.Items[0].Selected = true;
    listView1.Select();
}

Why is Visual Studio 2013 very slow?

Visual Studio 2013 has a package server running, and it was spending up to 2 million K of memory.

I put it to low priority and affinity with only one CPU, and Visual Studio ran much more smoothly.

OpenCV resize fails on large image with "error: (-215) ssize.area() > 0 in function cv::resize"

I know this is a very old thread but I had the same problem which was due spaces in the images names.

e.g.

Image name: "hello o.jpg"

weirdly, by removing the spaces the function worked just fine.

Image name: "hello_o.jpg"

How to change the color of a CheckBox?

Add buttonTint in your xml

<CheckBox
      android:id="@+id/chk_remember_signup"
      android:layout_width="wrap_content"
      android:layout_height="wrap_content"
      android:buttonTint="@android:color/white"
      android:text="@string/hint_chk_remember_me" />

Jquery show/hide table rows

http://sandbox.phpcode.eu/g/corrected-b5fe953c76d4b82f7e63f1cef1bc506e.php

<span id="black_only">Show only black</span><br>
<span id="white_only">Show only white</span><br>
<span id="all">Show all of them</span>
<style>
.black{background-color:black;}
#white{background-color:white;}
</style>
<table class="someclass" border="0" cellpadding="0" cellspacing="0" summary="bla bla bla">
<caption>bla bla bla</caption>
<thead>
  <tr class="black">
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
    <th>Header Text</th>
  </tr>
</thead>
<tbody>
  <tr id="white">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
  <tr class="black" style="background-color:black;">
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
    <td>Some Text</td>
</tr>
</tbody>
<script>
$(function(){
   $("#black_only").click(function(){
    $("#white").hide();
    $(".black").show();

   });
   $("#white_only").click(function(){
    $(".black").hide();
    $("#white").show();

   });
   $("#all").click(function(){
    $("#white").show();
    $(".black").show();

   });

});
</script>

How do I capture all of my compiler's output to a file?

Assume you want to hilight warning and error from build ouput:

make |& grep -E "warning|error"

How do I filter date range in DataTables?

Here is my solution, there is no way to use momemt.js.Here is DataTable with Two DatePickers for DateRange (To and From) Filter.

$.fn.dataTable.ext.search.push(
  function (settings, data, dataIndex) {
    var min = $('#min').datepicker("getDate");
    var max = $('#max').datepicker("getDate");
    var startDate = new Date(data[4]);
    if (min == null && max == null) { return true; }
    if (min == null && startDate <= max) { return true; }
    if (max == null && startDate >= min) { return true; }
    if (startDate <= max && startDate >= min) { return true; }
    return false;
  }
);
  

    

Find location of a removable SD card

Here is the method I use to find a removable SD card. It's complex, and probably overkill for some situations, but it works on a wide variety of Android versions and device manufacturers that I've tested over the last few years. I don't know of any devices since API level 15 on which it doesn't find the SD card, if there is one mounted. It won't return false positives in most cases, especially if you give it the name of a known file to look for.

Please let me know if you run into any cases where it doesn't work.

import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Locale;
import java.util.regex.Pattern;

public class SDCard {
    private static final String TAG = "SDCard";

    /** In some scenarios we can expect to find a specified file or folder on SD cards designed
     * to work with this app. If so, set KNOWNFILE to that filename. It will make our job easier.
     * Set it to null otherwise. */
    private static final String KNOWNFILE = null;

    /** Common paths for microSD card. **/
    private static String[] commonPaths = {
            // Some of these taken from
            // https://stackoverflow.com/questions/13976982/removable-storage-external-sdcard-path-by-manufacturers
            // These are roughly in order such that the earlier ones, if they exist, are more sure
            // to be removable storage than the later ones.
            "/mnt/Removable/MicroSD",
            "/storage/removable/sdcard1", // !< Sony Xperia Z1
            "/Removable/MicroSD", // Asus ZenPad C
            "/removable/microsd",
            "/external_sd", // Samsung
            "/_ExternalSD", // some LGs
            "/storage/extSdCard", // later Samsung
            "/storage/extsdcard", // Main filesystem is case-sensitive; FAT isn't.
            "/mnt/extsd", // some Chinese tablets, e.g. Zeki
            "/storage/sdcard1", // If this exists it's more likely than sdcard0 to be removable.
            "/mnt/extSdCard",
            "/mnt/sdcard/external_sd",
            "/mnt/external_sd",
            "/storage/external_SD",
            "/storage/ext_sd", // HTC One Max
            "/mnt/sdcard/_ExternalSD",
            "/mnt/sdcard-ext",

            "/sdcard2", // HTC One M8s
            "/sdcard1", // Sony Xperia Z
            "/mnt/media_rw/sdcard1",   // 4.4.2 on CyanogenMod S3
            "/mnt/sdcard", // This can be built-in storage (non-removable).
            "/sdcard",
            "/storage/sdcard0",
            "/emmc",
            "/mnt/emmc",
            "/sdcard/sd",
            "/mnt/sdcard/bpemmctest",
            "/mnt/external1",
            "/data/sdext4",
            "/data/sdext3",
            "/data/sdext2",
            "/data/sdext",
            "/storage/microsd" //ASUS ZenFone 2

            // If we ever decide to support USB OTG storage, the following paths could be helpful:
            // An LG Nexus 5 apparently uses usb://1002/UsbStorage/ as a URI to access an SD
            // card over OTG cable. Other models, like Galaxy S5, use /storage/UsbDriveA
            //        "/mnt/usb_storage",
            //        "/mnt/UsbDriveA",
            //        "/mnt/UsbDriveB",
    };

    /** Find path to removable SD card. */
    public static File findSdCardPath(Context context) {
        String[] mountFields;
        BufferedReader bufferedReader = null;
        String lineRead = null;

        /** Possible SD card paths */
        LinkedHashSet<File> candidatePaths = new LinkedHashSet<>();

        /** Build a list of candidate paths, roughly in order of preference. That way if
         * we can't definitively detect removable storage, we at least can pick a more likely
         * candidate. */

        // Could do: use getExternalStorageState(File path), with and without an argument, when
        // available. With an argument is available since API level 21.
        // This may not be necessary, since we also check whether a directory exists and has contents,
        // which would fail if the external storage state is neither MOUNTED nor MOUNTED_READ_ONLY.

        // I moved hard-coded paths toward the end, but we need to make sure we put the ones in
        // backwards order that are returned by the OS. And make sure the iterators respect
        // the order!
        // This is because when multiple "external" storage paths are returned, it's always (in
        // experience, but not guaranteed by documentation) with internal/emulated storage
        // first, removable storage second.

        // Add value of environment variables as candidates, if set:
        // EXTERNAL_STORAGE, SECONDARY_STORAGE, EXTERNAL_SDCARD_STORAGE
        // But note they are *not* necessarily *removable* storage! Especially EXTERNAL_STORAGE.
        // And they are not documented (API) features. Typically useful only for old versions of Android.

        String val = System.getenv("SECONDARY_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);
        val = System.getenv("EXTERNAL_SDCARD_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);

        // Get listing of mounted devices with their properties.
        ArrayList<File> mountedPaths = new ArrayList<>();
        try {
            // Note: Despite restricting some access to /proc (http://stackoverflow.com/a/38728738/423105),
            // Android 7.0 does *not* block access to /proc/mounts, according to our test on George's Alcatel A30 GSM.
            bufferedReader = new BufferedReader(new FileReader("/proc/mounts"));

            // Iterate over each line of the mounts listing.
            while ((lineRead = bufferedReader.readLine()) != null) {
                Log.d(TAG, "\nMounts line: " + lineRead);
                mountFields = lineRead.split(" ");

                // columns: device, mountpoint, fs type, options... Example:
                // /dev/block/vold/179:97 /storage/sdcard1 vfat rw,dirsync,nosuid,nodev,noexec,relatime,uid=1000,gid=1015,fmask=0002,dmask=0002,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0
                String device = mountFields[0], path = mountFields[1], fsType = mountFields[2];

                // The device, path, and fs type must conform to expected patterns.
                if (!(devicePattern.matcher(device).matches() &&
                        pathPattern.matcher(path).matches() &&
                        fsTypePattern.matcher(fsType).matches()) ||
                        // mtdblock is internal, I'm told.
                        device.contains("mtdblock") ||
                        // Check for disqualifying patterns in the path.
                        pathAntiPattern.matcher(path).matches()) {
                    // If this mounts line fails our tests, skip it.
                    continue;
                }

                // TODO maybe: check options to make sure it's mounted RW?
                // The answer at http://stackoverflow.com/a/13648873/423105 does.
                // But it hasn't seemed to be necessary so far in my testing.

                // This line met the criteria so far, so add it to candidate list.
                addPath(path, null, mountedPaths);
            }
        } catch (IOException ignored) {
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ignored) {
                }
            }
        }

        // Append the paths from mount table to candidate list, in reverse order.
        if (!mountedPaths.isEmpty()) {
            // See https://stackoverflow.com/a/5374346/423105 on why the following is necessary.
            // Basically, .toArray() needs its parameter to know what type of array to return.
            File[] mountedPathsArray = mountedPaths.toArray(new File[mountedPaths.size()]);
            addAncestors(candidatePaths, mountedPathsArray);
        }

        // Add hard-coded known common paths to candidate list:
        addStrings(candidatePaths, commonPaths);

        // If the above doesn't work we could try the following other options, but in my experience they
        // haven't added anything helpful yet.

        // getExternalFilesDir() and getExternalStorageDirectory() typically something app-specific like
        //   /storage/sdcard1/Android/data/com.mybackuparchives.android/files
        // so we want the great-great-grandparent folder.

        // This may be non-removable.
        Log.d(TAG, "Environment.getExternalStorageDirectory():");
        addPath(null, ancestor(Environment.getExternalStorageDirectory()), candidatePaths);

        // Context.getExternalFilesDirs() is only available from API level 19. You can use
        // ContextCompat.getExternalFilesDirs() on earlier APIs, but it only returns one dir anyway.
        Log.d(TAG, "context.getExternalFilesDir(null):");
        addPath(null, ancestor(context.getExternalFilesDir(null)), candidatePaths);

        // "Returns absolute paths to application-specific directories on all external storage
        // devices where the application can place persistent files it owns."
        // We might be able to use these to deduce a higher-level folder that isn't app-specific.
        // Also, we apparently have to call getExternalFilesDir[s](), at least in KITKAT+, in order to ensure that the
        // "external files" directory exists and is available.
        Log.d(TAG, "ContextCompat.getExternalFilesDirs(context, null):");
        addAncestors(candidatePaths, ContextCompat.getExternalFilesDirs(context, null));
        // Very similar results:
        Log.d(TAG, "ContextCompat.getExternalCacheDirs(context):");
        addAncestors(candidatePaths, ContextCompat.getExternalCacheDirs(context));

        // TODO maybe: use getExternalStorageState(File path), with and without an argument, when
        // available. With an argument is available since API level 21.
        // This may not be necessary, since we also check whether a directory exists,
        // which would fail if the external storage state is neither MOUNTED nor MOUNTED_READ_ONLY.

        // A "public" external storage directory. But in my experience it doesn't add anything helpful.
        // Note that you can't pass null, or you'll get an NPE.
        final File publicDirectory = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
        // Take the parent, because we tend to get a path like /pathTo/sdCard/Music.
        addPath(null, publicDirectory.getParentFile(), candidatePaths);
        // EXTERNAL_STORAGE: may not be removable.
        val = System.getenv("EXTERNAL_STORAGE");
        if (!TextUtils.isEmpty(val)) addPath(val, null, candidatePaths);

        if (candidatePaths.isEmpty()) {
            Log.w(TAG, "No removable microSD card found.");
            return null;
        } else {
            Log.i(TAG, "\nFound potential removable storage locations: " + candidatePaths);
        }

        // Accept or eliminate candidate paths if we can determine whether they're removable storage.
        // In Lollipop and later, we can check isExternalStorageRemovable() status on each candidate.
        if (Build.VERSION.SDK_INT >= 21) {
            Iterator<File> itf = candidatePaths.iterator();
            while (itf.hasNext()) {
                File dir = itf.next();
                // handle illegalArgumentException if the path is not a valid storage device.
                try {
                    if (Environment.isExternalStorageRemovable(dir)
                        // && containsKnownFile(dir)
                            ) {
                        Log.i(TAG, dir.getPath() + " is removable external storage");
                        return dir;
                    } else if (Environment.isExternalStorageEmulated(dir)) {
                        Log.d(TAG, "Removing emulated external storage dir " + dir);
                        itf.remove();
                    }
                } catch (IllegalArgumentException e) {
                    Log.d(TAG, "isRemovable(" + dir.getPath() + "): not a valid storage device.", e);
                }
            }
        }

        // Continue trying to accept or eliminate candidate paths based on whether they're removable storage.
        // On pre-Lollipop, we only have singular externalStorage. Check whether it's removable.
        if (Build.VERSION.SDK_INT >= 9) {
            File externalStorage = Environment.getExternalStorageDirectory();
            Log.d(TAG, String.format(Locale.ROOT, "findSDCardPath: getExternalStorageDirectory = %s", externalStorage.getPath()));
            if (Environment.isExternalStorageRemovable()) {
                // Make sure this is a candidate.
                // TODO: Does this contains() work? Should we be canonicalizing paths before comparing?
                if (candidatePaths.contains(externalStorage)
                    // && containsKnownFile(externalStorage)
                        ) {
                    Log.d(TAG, "Using externalStorage dir " + externalStorage);
                    return externalStorage;
                }
            } else if (Build.VERSION.SDK_INT >= 11 && Environment.isExternalStorageEmulated()) {
                Log.d(TAG, "Removing emulated external storage dir " + externalStorage);
                candidatePaths.remove(externalStorage);
            }
        }

        // If any directory contains our special test file, consider that the microSD card.
        if (KNOWNFILE != null) {
            for (File dir : candidatePaths) {
                Log.d(TAG, String.format(Locale.ROOT, "findSdCardPath: Looking for known file in candidate path, %s", dir));
                if (containsKnownFile(dir)) return dir;
            }
        }

        // If we don't find the known file, still try taking the first candidate.
        if (!candidatePaths.isEmpty()) {
            Log.d(TAG, "No definitive path to SD card; taking the first realistic candidate.");
            return candidatePaths.iterator().next();
        }

        // If no reasonable path was found, give up.
        return null;
    }

    /** Add each path to the collection. */
    private static void addStrings(LinkedHashSet<File> candidatePaths, String[] newPaths) {
        for (String path : newPaths) {
            addPath(path, null, candidatePaths);
        }
    }

    /** Add ancestor of each File to the collection. */
    private static void addAncestors(LinkedHashSet<File> candidatePaths, File[] files) {
        for (int i = files.length - 1; i >= 0; i--) {
            addPath(null, ancestor(files[i]), candidatePaths);
        }
    }

    /**
     * Add a new candidate directory path to our list, if it's not obviously wrong.
     * Supply path as either String or File object.
     * @param strNew path of directory to add (or null)
     * @param fileNew directory to add (or null)
     */
    private static void addPath(String strNew, File fileNew, Collection<File> paths) {
        // If one of the arguments is null, fill it in from the other.
        if (strNew == null) {
            if (fileNew == null) return;
            strNew = fileNew.getPath();
        } else if (fileNew == null) {
            fileNew = new File(strNew);
        }

        if (!paths.contains(fileNew) &&
                // Check for paths known not to be removable SD card.
                // The antipattern check can be redundant, depending on where this is called from.
                !pathAntiPattern.matcher(strNew).matches()) {

            // Eliminate candidate if not a directory or not fully accessible.
            if (fileNew.exists() && fileNew.isDirectory() && fileNew.canExecute()) {
                Log.d(TAG, "  Adding candidate path " + strNew);
                paths.add(fileNew);
            } else {
                Log.d(TAG, String.format(Locale.ROOT, "  Invalid path %s: exists: %b isDir: %b canExec: %b canRead: %b",
                        strNew, fileNew.exists(), fileNew.isDirectory(), fileNew.canExecute(), fileNew.canRead()));
            }
        }
    }

    private static final String ANDROID_DIR = File.separator + "Android";

    private static File ancestor(File dir) {
        // getExternalFilesDir() and getExternalStorageDirectory() typically something app-specific like
        //   /storage/sdcard1/Android/data/com.mybackuparchives.android/files
        // so we want the great-great-grandparent folder.
        if (dir == null) {
            return null;
        } else {
            String path = dir.getAbsolutePath();
            int i = path.indexOf(ANDROID_DIR);
            if (i == -1) {
                return dir;
            } else {
                return new File(path.substring(0, i));
            }
        }
    }

    /** Returns true iff dir contains the special test file.
     * Assumes that dir exists and is a directory. (Is this a necessary assumption?) */
    private static boolean containsKnownFile(File dir) {
        if (KNOWNFILE == null) return false;

        File knownFile = new File(dir, KNOWNFILE);
        return knownFile.exists();
    }

    private static Pattern
            /** Pattern that SD card device should match */
            devicePattern = Pattern.compile("/dev/(block/.*vold.*|fuse)|/mnt/.*"),
    /** Pattern that SD card mount path should match */
    pathPattern = Pattern.compile("/(mnt|storage|external_sd|extsd|_ExternalSD|Removable|.*MicroSD).*",
            Pattern.CASE_INSENSITIVE),
    /** Pattern that the mount path should not match.
     * 'emulated' indicates an internal storage location, so skip it.
     * 'asec' is an encrypted package file, decrypted and mounted as a directory. */
    pathAntiPattern = Pattern.compile(".*(/secure|/asec|/emulated).*"),
    /** These are expected fs types, including vfat. tmpfs is not OK.
     * fuse can be removable SD card (as on Moto E or Asus ZenPad), or can be internal (Huawei G610). */
    fsTypePattern = Pattern.compile(".*(fat|msdos|ntfs|ext[34]|fuse|sdcard|esdfs).*");
}

P.S.

  • Don't forget <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> in the manifest. And at API level 23 and higher, make sure to use checkSelfPermission / requestPermissions.
  • Set KNOWNFILE="myappfile" if there's a file or folder you expect to find on the SD card. That makes detection more accurate.
  • Obviously you'll want to cache the value of findSdCardPath(), rather than recomputing it every time you need it.
  • There's a bunch of logging (Log.d()) in the above code. It helps diagnose any cases where the right path isn't found. Comment it out if you don't want logging.

jsPDF multi page PDF with HTML renderer

You can use html2canvas plugin and jsPDF both. Process order: html to png & png to pdf

Example code:

jQuery('#part1').html2canvas({
    onrendered: function( canvas ) {
        var img1 = canvas.toDataURL('image/png');
    }
});
jQuery('#part2').html2canvas({
    onrendered: function( canvas ) {
        var img2 = canvas.toDataURL('image/png');
    }
});
jQuery('#part3').html2canvas({
    onrendered: function( canvas ) {
        var img3 = canvas.toDataURL('image/png');
    }
});
var doc = new jsPDF('p', 'mm');
doc.addImage( img1, 'PNG', 0, 0, 210, 297); // A4 sizes
doc.addImage( img2, 'PNG', 0, 90, 210, 297); // img1 and img2 on first page

doc.addPage();
doc.addImage( img3, 'PNG', 0, 0, 210, 297); // img3 on second page
doc.save("file.pdf");

PHP: HTML: send HTML select option attribute in POST

You will have to use JavaScript. The browser will only send the value of the selected option (so its not PHP's fault).

What your JS should do is hook into the form's submit event and create a hidden field with the value of the selected option's stud_name value. This hidden field will then get sent to the server.

That being said ... you shouldn't relay on the client to provide the correct data. You already know what stud_name should be for a given value on the server (since you are outputting it). So just apply the same logic when you are processing the form.

Getting today's date in YYYY-MM-DD in Python?

You can use strftime:

>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'

Additionally, for anyone also looking for a zero-padded Hour, Minute, and Second at the end: (Comment by Gabriel Staples)

>>> datetime.today().strftime('%Y-%m-%d-%H:%M:%S')
'2021-01-26-16:50:03'

Any way to exit bash script, but not quitting the terminal

Also make sure to return with expected return value. Else if you use exit when you will encounter an exit it will exit from your base shell since source does not create another process (instance).

printf() formatting for hex

The "0x" counts towards the eight character count. You need "%#010x".

Note that # does not append the 0x to 0 - the result will be 0000000000 - so you probably actually should just use "0x%08x" anyway.

Maven: best way of linking custom external JAR to my project?

The Maven manual says to do this:

mvn install:install-file -Dfile=non-maven-proj.jar -DgroupId=some.group -DartifactId=non-maven-proj -Dversion=1 -Dpackaging=jar

Calculate difference between two datetimes in MySQL

USE TIMESTAMPDIFF MySQL function. For example, you can use:

SELECT TIMESTAMPDIFF(SECOND, '2012-06-06 13:13:55', '2012-06-06 15:20:18')

In your case, the third parameter of TIMSTAMPDIFF function would be the current login time (NOW()). Second parameter would be the last login time, which is already in the database.

how to check if string value is in the Enum list?

I've got a handy extension method that uses TryParse, as IsDefined is case-sensitive.

public static bool IsParsable<T>(this string value) where T : struct
{
    return Enum.TryParse<T>(value, true, out _);
}

Removing duplicates from a SQL query (not just "use distinct")

If I understand you correctly, you want a list of all pictures with the same name (and their different ids) such that their name occurs more than once in the table. I think this will do the trick:

SELECT U.NAME, P.PIC_ID
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND U.Name IN (
SELECT U.Name 
FROM USERS U, PICTURES P, POSTINGS P1
WHERE U.EMAIL_ID = P1.EMAIL_ID AND P1.PIC_ID = P.PIC_ID AND P.CAPTION LIKE '%car%';
GROUP BY U.Name HAVING COUNT(U.Name) > 1)

I haven't executed it, so there may be a syntax error or two there.

Python equivalent for HashMap

You need a dict:

my_dict = {'cheese': 'cake'}

Example code (from the docs):

>>> a = dict(one=1, two=2, three=3)
>>> b = {'one': 1, 'two': 2, 'three': 3}
>>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3]))
>>> d = dict([('two', 2), ('one', 1), ('three', 3)])
>>> e = dict({'three': 3, 'one': 1, 'two': 2})
>>> a == b == c == d == e
True

You can read more about dictionaries here.

How to close the command line window after running a batch file?

Your code is absolutely fine. It just needs "exit 0" for a cleaner exit.

 tncserver.exe C:\Work -p4 -b57600 -r -cFE -tTNC426B
 exit 0

What are the retransmission rules for TCP?

What exactly are the rules for requesting retransmission of lost data?

The receiver does not request the retransmission. The sender waits for an ACK for the byte-range sent to the client and when not received, resends the packets, after a particular interval. This is ARQ (Automatic Repeat reQuest). There are several ways in which this is implemented.

Stop-and-wait ARQ
Go-Back-N ARQ
Selective Repeat ARQ

are detailed in the RFC 3366.

At what time frequency are the retransmission requests performed?

The retransmissions-times and the number of attempts isn't enforced by the standard. It is implemented differently by different operating systems, but the methodology is fixed. (One of the ways to fingerprint OSs perhaps?)

The timeouts are measured in terms of the RTT (Round Trip Time) times. But this isn't needed very often due to Fast-retransmit which kicks in when 3 Duplicate ACKs are received.

Is there an upper bound on the number?

Yes there is. After a certain number of retries, the host is considered to be "down" and the sender gives up and tears down the TCP connection.

Is there functionality for the client to indicate to the server to forget about the whole TCP segment for which part went missing when the IP packet went missing?

The whole point is reliable communication. If you wanted the client to forget about some part, you wouldn't be using TCP in the first place. (UDP perhaps?)

ASP.NET Core return JSON with status code

The easiest way I came up with is :

var result = new Item { Id = 123, Name = "Hero" };

return new JsonResult(result)
{
    StatusCode = StatusCodes.Status201Created // Status code here 
};

Convert a secure string to plain text

You may also use PSCredential.GetNetworkCredential() :

$SecurePassword = Get-Content C:\Users\tmarsh\Documents\securePassword.txt | ConvertTo-SecureString
$UnsecurePassword = (New-Object PSCredential "user",$SecurePassword).GetNetworkCredential().Password

How do servlets work? Instantiation, sessions, shared variables and multithreading

ServletContext

When the servlet container (like Apache Tomcat) starts up, it will deploy and load all its web applications. When a web application is loaded, the servlet container creates the ServletContext once and keeps it in the server's memory. The web app's web.xml and all of included web-fragment.xml files is parsed, and each <servlet>, <filter> and <listener> found (or each class annotated with @WebServlet, @WebFilter and @WebListener respectively) is instantiated once and kept in the server's memory as well. For each instantiated filter, its init() method is invoked with a new FilterConfig.

When a Servlet has a <servlet><load-on-startup> or @WebServlet(loadOnStartup) value greater than 0, then its init() method is also invoked during startup with a new ServletConfig. Those servlets are initialized in the same order specified by that value (1 is 1st, 2 is 2nd, etc). If the same value is specified for more than one servlet, then each of those servlets is loaded in the same order as they appear in the web.xml, web-fragment.xml, or @WebServlet classloading. In the event the "load-on-startup" value is absent, the init() method will be invoked whenever the HTTP request hits that servlet for the very first time.

When the servlet container is finished with all of the above described initialization steps, then the ServletContextListener#contextInitialized() will be invoked.

When the servlet container shuts down, it unloads all web applications, invokes the destroy() method of all its initialized servlets and filters, and all ServletContext, Servlet, Filter and Listener instances are trashed. Finally the ServletContextListener#contextDestroyed() will be invoked.

HttpServletRequest and HttpServletResponse

The servlet container is attached to a web server that listens for HTTP requests on a certain port number (port 8080 is usually used during development and port 80 in production). When a client (e.g. user with a web browser, or programmatically using URLConnection) sends an HTTP request, the servlet container creates new HttpServletRequest and HttpServletResponse objects and passes them through any defined Filter in the chain and, eventually, the Servlet instance.

In the case of filters, the doFilter() method is invoked. When the servlet container's code calls chain.doFilter(request, response), the request and response continue on to the next filter, or hit the servlet if there are no remaining filters.

In the case of servlets, the service() method is invoked. By default, this method determines which one of the doXxx() methods to invoke based off of request.getMethod(). If the determined method is absent from the servlet, then an HTTP 405 error is returned in the response.

The request object provides access to all of the information about the HTTP request, such as its URL, headers, query string and body. The response object provides the ability to control and send the HTTP response the way you want by, for instance, allowing you to set the headers and the body (usually with generated HTML content from a JSP file). When the HTTP response is committed and finished, both the request and response objects are recycled and made available for reuse.

HttpSession

When a client visits the webapp for the first time and/or the HttpSession is obtained for the first time via request.getSession(), the servlet container creates a new HttpSession object, generates a long and unique ID (which you can get by session.getId()), and stores it in the server's memory. The servlet container also sets a Cookie in the Set-Cookie header of the HTTP response with JSESSIONID as its name and the unique session ID as its value.

As per the HTTP cookie specification (a contract any decent web browser and web server must adhere to), the client (the web browser) is required to send this cookie back in subsequent requests in the Cookie header for as long as the cookie is valid (i.e. the unique ID must refer to an unexpired session and the domain and path are correct). Using your browser's built-in HTTP traffic monitor, you can verify that the cookie is valid (press F12 in Chrome / Firefox 23+ / IE9+, and check the Net/Network tab). The servlet container will check the Cookie header of every incoming HTTP request for the presence of the cookie with the name JSESSIONID and use its value (the session ID) to get the associated HttpSession from server's memory.

The HttpSession stays alive until it has been idle (i.e. not used in a request) for more than the timeout value specified in <session-timeout>, a setting in web.xml. The timeout value defaults to 30 minutes. So, when the client doesn't visit the web app for longer than the time specified, the servlet container trashes the session. Every subsequent request, even with the cookie specified, will not have access to the same session anymore; the servlet container will create a new session.

On the client side, the session cookie stays alive for as long as the browser instance is running. So, if the client closes the browser instance (all tabs/windows), then the session is trashed on the client's side. In a new browser instance, the cookie associated with the session wouldn't exist, so it would no longer be sent. This causes an entirely new HttpSession to be created, with an entirely new session cookie being used.

In a nutshell

  • The ServletContext lives for as long as the web app lives. It is shared among all requests in all sessions.
  • The HttpSession lives for as long as the client is interacting with the web app with the same browser instance, and the session hasn't timed out at the server side. It is shared among all requests in the same session.
  • The HttpServletRequest and HttpServletResponse live from the time the servlet receives an HTTP request from the client, until the complete response (the web page) has arrived. It is not shared elsewhere.
  • All Servlet, Filter and Listener instances live as long as the web app lives. They are shared among all requests in all sessions.
  • Any attribute that is defined in ServletContext, HttpServletRequest and HttpSession will live as long as the object in question lives. The object itself represents the "scope" in bean management frameworks such as JSF, CDI, Spring, etc. Those frameworks store their scoped beans as an attribute of its closest matching scope.

Thread Safety

That said, your major concern is possibly thread safety. You should now know that servlets and filters are shared among all requests. That's the nice thing about Java, it's multithreaded and different threads (read: HTTP requests) can make use of the same instance. It would otherwise be too expensive to recreate, init() and destroy() them for every single request.

You should also realize that you should never assign any request or session scoped data as an instance variable of a servlet or filter. It will be shared among all other requests in other sessions. That's not thread-safe! The below example illustrates this:

public class ExampleServlet extends HttpServlet {

    private Object thisIsNOTThreadSafe;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object thisIsThreadSafe;

        thisIsNOTThreadSafe = request.getParameter("foo"); // BAD!! Shared among all requests!
        thisIsThreadSafe = request.getParameter("foo"); // OK, this is thread safe.
    } 
}

See also:

JQuery get data from JSON array

You need to iterate both the groups and the items. $.each() takes a collection as first parameter and data.response.venue.tips.groups.items.text tries to point to a string. Both groups and items are arrays.

Verbose version:

$.getJSON(url, function (data) {

    // Iterate the groups first.
    $.each(data.response.venue.tips.groups, function (index, value) {

        // Get the items
        var items = this.items; // Here 'this' points to a 'group' in 'groups'

        // Iterate through items.
        $.each(items, function () {
            console.log(this.text); // Here 'this' points to an 'item' in 'items'
        });
    });
});

Or more simply:

$.getJSON(url, function (data) {
    $.each(data.response.venue.tips.groups, function (index, value) {
        $.each(this.items, function () {
            console.log(this.text);
        });
    });
});

In the JSON you specified, the last one would be:

$.getJSON(url, function (data) {
    // Get the 'items' from the first group.
    var items = data.response.venue.tips.groups[0].items;

    // Find the last index and the last item.
    var lastIndex = items.length - 1;
    var lastItem = items[lastIndex];

    console.log("User: " + lastItem.user.firstName + " " + lastItem.user.lastName);
    console.log("Date: " + lastItem.createdAt);
    console.log("Text: " + lastItem.text);
});

This would give you:

User: Damir P.
Date: 1314168377
Text: ajd da vidimo hocu li znati ponoviti

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

As everyone informed it's IDE bug, I tried in Eclipse and STS. In both the cases, it is failing.

As a workaround, I have fixed by modifying the pom.xml file like below.

I have added these two maven dependencies junit-jupiter-engine and junit-platform-launcher.

pom.xml

<!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine -->
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit-jupiter.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- https://mvnrepository.com/artifact/org.junit.platform/junit-platform launcher -->
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-launcher</artifactId>
        <version>${junit-platform.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>

Also please make sure to add the version of both the maven dependencies in the properties tag.

<properties>
    <java.version>1.8</java.version>
    <junit-jupiter.version>5.2.0</junit-jupiter.version>
    <junit-platform.version>1.2.0</junit-platform.version>
</properties>

JSON and escaping characters

hmm, well here's a workaround anyway:

function JSON_stringify(s, emit_unicode)
{
   var json = JSON.stringify(s);
   return emit_unicode ? json : json.replace(/[\u007f-\uffff]/g,
      function(c) { 
        return '\\u'+('0000'+c.charCodeAt(0).toString(16)).slice(-4);
      }
   );
}

test case:

js>s='15\u00f8C 3\u0111';
15°C 3?
js>JSON_stringify(s, true)
"15°C 3?"
js>JSON_stringify(s, false)
"15\u00f8C 3\u0111"

Get element by id - Angular2

A different approach, i.e: You could just do it 'the Angular way' and use ngModel and skip document.getElementById('loginInput').value = '123'; altogether. Instead:

<input type="text" [(ngModel)]="username"/>
<input type="text" [(ngModel)]="password"/>

and in your component you give these values:

username: 'whatever'
password: 'whatever'

this will preset the username and password upon navigating to page.

jQuery posting valid json in request body

An actual JSON request would look like this:

data: '{"command":"on"}',

Where you're sending an actual JSON string. For a more general solution, use JSON.stringify() to serialize an object to JSON, like this:

data: JSON.stringify({ "command": "on" }),

To support older browsers that don't have the JSON object, use json2.js which will add it in.


What's currently happening is since you have processData: false, it's basically sending this: ({"command":"on"}).toString() which is [object Object]...what you see in your request.

How do I convert between ISO-8859-1 and UTF-8 in Java?

Here is an easy way with String output (I created a method to do this):

public static String (String input){
    String output = "";
    try {
        /* From ISO-8859-1 to UTF-8 */
        output = new String(input.getBytes("ISO-8859-1"), "UTF-8");
        /* From UTF-8 to ISO-8859-1 */
        output = new String(input.getBytes("UTF-8"), "ISO-8859-1");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return output;
}
// Example
input = "Música";
output = "Música";

Get first element in PHP stdObject

Update PHP 7.4

Curly brace access syntax is deprecated since PHP 7.4

Update 2019

Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.

Simply iterate its using {}

Example:

$videos{0}->id

This way your object is not destroyed and you can easily iterate through object.

For PHP 5.6 and below use this

$videos{0}['id']

Both array() and the stdClass objects can be accessed using the current() key() next() prev() reset() end() functions.

So, if your object looks like

object(stdClass)#19 (3) {
  [0]=>
  object(stdClass)#20 (22) {
    ["id"]=>
    string(1) "123"
  etc...

Then you can just do;

$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object

If you need the key for some reason, you can do;

reset($obj); //Ensure that we're at the first element
$key = key($obj);

Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4


2022 Update:
After PHP 7.4, using current(), end(), etc functions on objects is deprecated.

In newer versions of PHP, use the ArrayIterator class:

$objIterator = new ArrayIterator($obj);

$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object

$key = $objIterator->key(); // and gets the key

How to Alter Constraint

No. We cannot alter the constraint, only thing we can do is drop and recreate it

ALTER TABLE [TABLENAME] DROP CONSTRAINT [CONSTRAINTNAME]

Foreign Key Constraint

Alter Table Table1 Add Constraint [CONSTRAINTNAME] Foreign Key (Column) References Table2 (Column) On Update Cascade On Delete Cascade

Primary Key constraint

Alter Table Table add constraint [Primary Key] Primary key(Column1,Column2,.....)

Getting the parent div of element

The property pDoc.parentElement or pDoc.parentNode will get you the parent element.

Getting random numbers in Java

The first solution is to use the java.util.Random class:

import java.util.Random;

Random rand = new Random();

// Obtain a number between [0 - 49].
int n = rand.nextInt(50);

// Add 1 to the result to get a number from the required range
// (i.e., [1 - 50]).
n += 1;

Another solution is using Math.random():

double random = Math.random() * 49 + 1;

or

int random = (int)(Math.random() * 50 + 1);

Difference between "include" and "require" in php

You find the differences explained in the detailed PHP manual on the page of require:

require is identical to include except upon failure it will also produce a fatal E_COMPILE_ERROR level error. In other words, it will halt the script whereas include only emits a warning (E_WARNING) which allows the script to continue.

See @efritz's answer for an example

Select distinct rows from datatable in Linq

We can get the distinct similar to the example shown below

 //example
           var  distinctValues =  DetailedBreakDown_Table.AsEnumerable().Select(r => new
            {
                InvestmentVehicleID = r.Field<string>("InvestmentVehicleID"),
                Universe = r.Field<string>("Universe"),
                AsOfDate = _imqDate,
                Ticker = "",
                Cusip = "",
                PortfolioDate = r.Field<DateTime>("PortfolioDate")

            } ).Distinct();

failed to find target with hash string 'android-22'

I had similar issue. I updated android studio build tools and my project didn't find "android-22". I looked in android sdk manager and it was installed.

To fix this issue I uninstalled "android-22" and installed again.

Firing events on CSS class changes in jQuery

Whenever you change a class in your script, you could use a trigger to raise your own event.

$(this).addClass('someClass');
$(mySelector).trigger('cssClassChanged')
....
$(otherSelector).bind('cssClassChanged', data, function(){ do stuff });

but otherwise, no, there's no baked-in way to fire an event when a class changes. change() only fires after focus leaves an input whose input has been altered.

_x000D_
_x000D_
$(function() {_x000D_
  var button = $('.clickme')_x000D_
      , box = $('.box')_x000D_
  ;_x000D_
  _x000D_
  button.on('click', function() { _x000D_
    box.removeClass('box');_x000D_
    $(document).trigger('buttonClick');_x000D_
  });_x000D_
            _x000D_
  $(document).on('buttonClick', function() {_x000D_
    box.text('Clicked!');_x000D_
  });_x000D_
});
_x000D_
.box { background-color: red; }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<div class="box">Hi</div>_x000D_
<button class="clickme">Click me</button>
_x000D_
_x000D_
_x000D_

More info on jQuery Triggers

How do I rename both a Git local and remote branch name?

  • Rename your local branch.

If you are on the branch you want to rename:

git branch -m new-name

if you stay on a different branch at the current time:

git branch -m old-name new-name
  • Delete the old-name remote branch and push the new-name local branch.

Stay on the target branch and:

git push origin :old-name new-name
  • Reset the upstream branch for the new-name local branch.

Switch to the target branch and then:

git push origin -u new-name

using scp in terminal

I would open another terminal on your laptop and do the scp from there, since you already know how to set that connection up.

scp username@remotecomputer:/path/to/file/you/want/to/copy where/to/put/file/on/laptop

The username@remotecomputer is the same string you used with ssh initially.

Regular Expression for matching parentheses

For any special characters you should use '\'. So, for matching parentheses - /\(/

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

Javascript Date: next month

You'll probably find you're setting the date to Feb 31, 2009 (if today is Jan 31) and Javascript automagically rolls that into the early part of March.

Check the day of the month, I'd expect it to be 1, 2 or 3. If it's not the same as before you added a month, roll back by one day until the month changes again.

That way, the day "last day of Jan" becomes "last day of Feb".

EDIT:

Ronald, based on your comments to other answers, you might want to steer clear of edge-case behavior such as "what happens when I try to make Feb 30" or "what happens when I try to make 2009/13/07 (yyyy/mm/dd)" (that last one might still be a problem even for my solution, so you should test it).

Instead, I would explicitly code for the possibilities. Since you don't care about the day of the month (you just want the year and month to be correct for next month), something like this should suffice:

var now = new Date();
if (now.getMonth() == 11) {
    var current = new Date(now.getFullYear() + 1, 0, 1);
} else {
    var current = new Date(now.getFullYear(), now.getMonth() + 1, 1);
}

That gives you Jan 1 the following year for any day in December and the first day of the following month for any other day. More code, I know, but I've long since grown tired of coding tricks for efficiency, preferring readability unless there's a clear requirement to do otherwise.

How to detect Adblock on my website?

ads.js

var e=document.createElement('div');e.id='GjyTonmtkfKD';e.style.display='none';document.body.appendChild(e);

html file

<div id="GPlTKAacLIdW">Our website is made possible by displaying online advertisements to our visitors.<br>Please consider supporting us by disabling your ad blocker.</div><script src="/ads.js" type="text/javascript"></script><script type="text/javascript">if(!document.getElementById('GjyTonmtkfKD')){ document.getElementById('GPlTKAacLIdW').style.display='block'; }</script>

This is also shown on https://www.detectadblock.com/

Sql Server equivalent of a COUNTIF aggregate function

How about

SELECT id, COUNT(IF status=42 THEN 1 ENDIF) AS cnt
FROM table
GROUP BY table

Shorter than CASE :)

Works because COUNT() doesn't count null values, and IF/CASE return null when condition is not met and there is no ELSE.

I think it's better than using SUM().

WPF: Setting the Width (and Height) as a Percentage Value

The way to stretch it to the same size as the parent container is to use the attribute:

 <Textbox HorizontalAlignment="Stretch" ...

That will make the Textbox element stretch horizontally and fill all the parent space horizontally (actually it depends on the parent panel you're using but should work for most cases).

Percentages can only be used with grid cell values so another option is to create a grid and put your textbox in one of the cells with the appropriate percentage.

How to deserialize a list using GSON or another JSON library in Java?

With Gson, you'd just need to do something like:

List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());

You might also need to provide a no-arg constructor on the Video class you're deserializing to.

QString to char* conversion

It is a viable way to use std::vector as an intermediate container:

QString dataSrc("FooBar");
QString databa = dataSrc.toUtf8();
std::vector<char> data(databa.begin(), databa.end());
char* pDataChar = data.data();

How to get a value from the last inserted row?

Here is how I solved it, based on the answers here:

Connection conn = ConnectToDB(); //ConnectToDB establishes a connection to the database.
String sql = "INSERT INTO \"TableName\"" +
        "(\"Column1\", \"Column2\",\"Column3\",\"Column4\")" +
        "VALUES ('value1',value2, 'value3', 'value4') RETURNING 
         \"TableName\".\"TableId\"";
PreparedStatement prpState = conn.prepareStatement(sql);
ResultSet rs = prpState.executeQuery();
if(rs.next()){
      System.out.println(rs.getInt(1));
        }

No Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator

If you are using LOMBOK. Create a file lombok.config if you don't have one and add this line.

lombok.anyconstructor.addconstructorproperties=true

HTML5 Video autoplay on iPhone

Here is the little hack to overcome all the struggles you have for video autoplay in a website:

  1. Check video is playing or not.
  2. Trigger video play on event like body click or touch.

Note: Some browsers don't let videos to autoplay unless the user interacts with the device.

So scripts to check whether video is playing is:

Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function () {
    return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
}});

And then you can simply autoplay the video by attaching event listeners to the body:

$('body').on('click touchstart', function () {
        const videoElement = document.getElementById('home_video');
        if (videoElement.playing) {
            // video is already playing so do nothing
        }
        else {
            // video is not playing
            // so play video now
            videoElement.play();
        }
});

Note: autoplay attribute is very basic which needs to be added to the video tag already other than these scripts.

You can see the working example with code here at this link:

How to autoplay video when the device is in low power mode / data saving mode / safari browser issue

Traversing text in Insert mode

You seem to misuse vim, but that's likely due to not being very familiar with it.

The right way is to press Esc, go where you want to do a small correction, fix it, go back and keep editing. It is effective because Vim has much more movements than usual character forward/backward/up/down. After you learn more of them, this will happen to be more productive.

Here's a couple of use-cases:

  • You accidentally typed "accifentally". No problem, the sequence EscFfrdA will correct the mistake and bring you back to where you were editing. The Ff movement will move your cursor backwards to the first encountered "f" character. Compare that with Ctrl+DeldEnd, which does virtually the same in a casual editor, but takes more keystrokes and makes you move your hand out of the alphanumeric area of the keyboard.
  • You accidentally typed "you accidentally typed", but want to correct it to "you intentionally typed". Then Esc2bcw will erase the word you want to fix and bring you to insert mode, so you can immediately retype it. To get back to editing, just press A instead of End, so you don't have to move your hand to reach the End key.
  • You accidentally typed "mouse" instead of "mice". No problem - the good old Ctrl+w will delete the previous word without leaving insert mode. And it happens to be much faster to erase a small word than to fix errors within it. I'm so used to it that I had closed the browser page when I was typing this message...!
  • Repetition count is largely underused. Before making a movement, you can type a number; and the movement will be repeated this number of times. For example, 15h will bring your cursor 15 characters back and 4j will move your cursor 4 lines down. Start using them and you'll get used to it soon. If you made a mistake ten characters back from your cursor, you'll find out that pressing the key 10 times is much slower than the iterative approach to moving the cursor. So you can instead quickly type the keys 12h (as a rough of guess how many characters back that you need to move your cursor), and immediately move forward twice with ll to quickly correct the error.

But, if you still want to do small text traversals without leaving insert mode, follow rson's advice and use Ctrl+O. Taking the first example that I mentioned above, Ctrl+OFf will move you to a previous "f" character and leave you in insert mode.

How can get the text of a div tag using only javascript (no jQuery)

You'll probably want to try textContent instead of innerHTML.

Given innerHTML will return DOM content as a String and not exclusively the "text" in the div. It's fine if you know that your div contains only text but not suitable if every use case. For those cases, you'll probably have to use textContent instead of innerHTML

For example, considering the following markup:

<div id="test">
  Some <span class="foo">sample</span> text.
</div>

You'll get the following result:

var node = document.getElementById('test'),

htmlContent = node.innerHTML,
// htmlContent = "Some <span class="foo">sample</span> text."

textContent = node.textContent;
// textContent = "Some sample text."

See MDN for more details:

What is a elegant way in Ruby to tell if a variable is a Hash or an Array?

You can just do:

@some_var.class == Hash

or also something like:

@some_var.is_a?(Hash)

It's worth noting that the "is_a?" method is true if the class is anywhere in the objects ancestry tree. for instance:

@some_var.is_a?(Object)  # => true

the above is true if @some_var is an instance of a hash or other class that stems from Object. So, if you want a strict match on the class type, using the == or instance_of? method is probably what you're looking for.

Add marker to Google Map on Click

After much further research, i managed to find a solution.

google.maps.event.addListener(map, 'click', function(event) {
   placeMarker(event.latLng);
});

function placeMarker(location) {
    var marker = new google.maps.Marker({
        position: location, 
        map: map
    });
}

Why can't a text column have a default value in MySQL?

Windows MySQL v5 throws an error but Linux and other versions only raise a warning. This needs to be fixed. WTF?

Also see an attempt to fix this as bug #19498 in the MySQL Bugtracker:

Bryce Nesbitt on April 4 2008 4:36pm:
On MS Windows the "no DEFAULT" rule is an error, while on other platforms it is often a warning. While not a bug, it's possible to get trapped by this if you write code on a lenient platform, and later run it on a strict platform:

Personally, I do view this as a bug. Searching for "BLOB/TEXT column can't have a default value" returns about 2,940 results on Google. Most of them are reports of incompatibilities when trying to install DB scripts that worked on one system but not others.

I am running into the same problem now on a webapp I'm modifying for one of my clients, originally deployed on Linux MySQL v5.0.83-log. I'm running Windows MySQL v5.1.41. Even trying to use the latest version of phpMyAdmin to extract the database, it doesn't report a default for the text column in question. Yet, when I try running an insert on Windows (that works fine on the Linux deployment) I receive an error of no default on ABC column. I try to recreate the table locally with the obvious default (based on a select of unique values for that column) and end up receiving the oh-so-useful BLOB/TEXT column can't have a default value.

Again, not maintaining basic compatability across platforms is unacceptable and is a bug.


How to disable strict mode in MySQL 5 (Windows):

  • Edit /my.ini and look for line

    sql-mode="STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"
    
  • Replace it with

    sql_mode='MYSQL40'
    
  • Restart the MySQL service (assuming that it is mysql5)

    net stop mysql5
    net start mysql5
    

If you have root/admin access you might be able to execute

mysql_query("SET @@global.sql_mode='MYSQL40'");

how to draw a rectangle in HTML or CSS?

I do the following in my eBay listings:

<p style="border:solid thick darkblue; border-radius: 1em; 
          border-width:3px; padding-left:9px; padding-top:6px; 
          padding-bottom:6px; margin:2px; width:980px;">

This produces a box border with rounded corners.You can play with the variables.

Creating Duplicate Table From Existing Table

Use this query to create the new table with the values from existing table

CREATE TABLE New_Table_name AS SELECT * FROM Existing_table_Name; 

Now you can get all the values from existing table into newly created table.

How to use JQuery with ReactJS

Earlier,I was facing problem in using jquery with React js,so I did following steps to make it working-

  1. npm install jquery --save

  2. Then, import $ from "jquery";

    See here

How to reload a page using Angularjs?

You can also try this, after injecting $window service.

$window.location.reload();

How can I add new dimensions to a Numpy array?

There is no structure in numpy that allows you to append more data later.

Instead, numpy puts all of your data into a contiguous chunk of numbers (basically; a C array), and any resize requires allocating a new chunk of memory to hold it. Numpy's speed comes from being able to keep all the data in a numpy array in the same chunk of memory; e.g. mathematical operations can be parallelized for speed and you get less cache misses.

So you will have two kinds of solutions:

  1. Pre-allocate the memory for the numpy array and fill in the values, like in JoshAdel's answer, or
  2. Keep your data in a normal python list until it's actually needed to put them all together (see below)

images = []
for i in range(100):
    new_image = # pull image from somewhere
    images.append(new_image)
images = np.stack(images, axis=3)

Note that there is no need to expand the dimensions of the individual image arrays first, nor do you need to know how many images you expect ahead of time.

How do you append to a file?

You probably want to pass "a" as the mode argument. See the docs for open().

with open("foo", "a") as f:
    f.write("cool beans...")

There are other permutations of the mode argument for updating (+), truncating (w) and binary (b) mode but starting with just "a" is your best bet.

React - changing an uncontrolled input

Simple solution to resolve this problem is to set an empty value by default :

<input name='myInput' value={this.state.myInput || ''} onChange={this.handleChange} />

writing integer values to a file using out.write()

write() only takes a single string argument, so you could do this:

outf.write(str(num))

or

outf.write('{}'.format(num))  # more "modern"
outf.write('%d' % num)        # deprecated mostly

Also note that write will not append a newline to your output so if you need it you'll have to supply it yourself.

Aside:

Using string formatting would give you more control over your output, so for instance you could write (both of these are equivalent):

num = 7
outf.write('{:03d}\n'.format(num))

num = 12
outf.write('%03d\n' % num)          

to get three spaces, with leading zeros for your integer value followed by a newline:

007
012

format() will be around for a long while, so it's worth learning/knowing.

How should I store GUID in MySQL tables?

My DBA asked me when I asked about the best way to store GUIDs for my objects why I needed to store 16 bytes when I could do the same thing in 4 bytes with an Integer. Since he put that challenge out there to me I thought now was a good time to mention it. That being said...

You can store a guid as a CHAR(16) binary if you want to make the most optimal use of storage space.

Make more than one chart in same IPython Notebook cell

Something like this:

import matplotlib.pyplot as plt
... code for plot 1 ...
plt.show()
... code for plot 2...
plt.show()

Note that this will also work if you are using the seaborn package for plotting:

import matplotlib.pyplot as plt
import seaborn as sns
sns.barplot(... code for plot 1 ...) # plot 1
plt.show()
sns.barplot(... code for plot 2 ...) # plot 2
plt.show()

Make multiple-select to adjust its height to fit options without scroll bar

Old, but this will do what you're after without need for jquery. The hidden overflow gets rid of the scrollbar, and the javascript makes it the right size.

<select multiple='multiple' id='select' style='overflow:hidden'>
<option value='foo'>foo</option>
<option value='bar'>bar</option>
<option value='abc'>abc</option>
<option value='def'>def</option>
<option value='xyz'>xyz</option>
</select>

And just a tiny amount of javascript

var select = document.getElementById('select');
select.size = select.length;

Trigger change event of dropdown

For some reason, the other jQuery solutions provided here worked when running the script from console, however, it did not work for me when triggered from Chrome Bookmarklets.

Luckily, this Vanilla JS solution (the triggerChangeEvent function) did work:

_x000D_
_x000D_
/**_x000D_
  * Trigger a `change` event on given drop down option element._x000D_
  * WARNING: only works if not already selected._x000D_
  * @see https://stackoverflow.com/questions/902212/trigger-change-event-of-dropdown/58579258#58579258_x000D_
  */_x000D_
function triggerChangeEvent(option) {_x000D_
  // set selected property_x000D_
  option.selected = true;_x000D_
  _x000D_
  // raise event on parent <select> element_x000D_
  if ("createEvent" in document) {_x000D_
    var evt = document.createEvent("HTMLEvents");_x000D_
    evt.initEvent("change", false, true);_x000D_
    option.parentNode.dispatchEvent(evt);_x000D_
  }_x000D_
  else {_x000D_
    option.parentNode.fireEvent("onchange");_x000D_
  }_x000D_
}_x000D_
_x000D_
// ################################################_x000D_
// Setup our test case_x000D_
// ################################################_x000D_
_x000D_
(function setup() {_x000D_
  const sel = document.querySelector('#fruit');_x000D_
  sel.onchange = () => {_x000D_
    document.querySelector('#result').textContent = sel.value;_x000D_
  };_x000D_
})();_x000D_
_x000D_
function runTest() {_x000D_
  const sel = document.querySelector('#selector').value;_x000D_
  const optionEl = document.querySelector(sel);_x000D_
  triggerChangeEvent(optionEl);_x000D_
}
_x000D_
<select id="fruit">_x000D_
  <option value="">(select a fruit)</option>_x000D_
  <option value="apple">Apple</option>_x000D_
  <option value="banana">Banana</option>_x000D_
  <option value="pineapple">Pineapple</option>_x000D_
</select>_x000D_
_x000D_
<p>_x000D_
  You have selected: <b id="result"></b>_x000D_
</p>_x000D_
<p>_x000D_
  <input id="selector" placeholder="selector" value="option[value='banana']">_x000D_
  <button onclick="runTest()">Trigger select!</button>_x000D_
</p>
_x000D_
_x000D_
_x000D_

ORA-00918: column ambiguously defined in SELECT *

You can also see this error when selecting for a union where corresponding columns can be null.

select * from (select D.dept_no, D.nullable_comment
                  from dept D
       union
               select R.dept_no, NULL
                 from redundant_dept R
)

This apparently confuses the parser, a solution is to assign a column alias to the always null column.

select * from (select D.dept_no, D.comment
                  from dept D
       union
               select R.dept_no, NULL "nullable_comment"
                 from redundant_dept R
)

The alias does not have to be the same as the corresponding column, but the column heading in the result is driven by the first query from among the union members, so it's probably a good practice.

What does {0} mean when found in a string in C#?

This is what we called Composite Formatting of the .NET Framework to convert the value of an object to its text representation and embed that representation in a string. The resulting string is written to the output stream.

The overloaded Console.WriteLine Method (String, Object)Writes the text representation of the specified object, followed by the current line terminator, to the standard output stream using the specified format information.

How can I create an error 404 in PHP?

Try this:

<?php
header("HTTP/1.0 404 Not Found");
?>

Check if string begins with something?

A little more reusable function:

beginsWith = function(needle, haystack){
    return (haystack.substr(0, needle.length) == needle);
}

How do I call one constructor from another in Java?

Yes, it is possible:

public class Foo {
    private int x;

    public Foo() {
        this(1);
    }

    public Foo(int x) {
        this.x = x;
    }
}

To chain to a particular superclass constructor instead of one in the same class, use super instead of this. Note that you can only chain to one constructor, and it has to be the first statement in your constructor body.

See also this related question, which is about C# but where the same principles apply.

clear form values after submission ajax

$("#cform")[0].reset();

or in plain javascript:

document.getElementById("cform").reset();

Google Recaptcha v3 example demo

We use recaptcha-V3 only to see site traffic quality, and used it as non blocking. Since recaptcha-V3 doesn't require to show on site and can be used as hidden but you have to show recaptcha privacy etc links (as recommended)

Script Tag in Head

<script src="https://www.google.com/recaptcha/api.js?onload=ReCaptchaCallbackV3&render='SITE KEY' async defer></script>

Note: "async defer" make sure its non blocking which is our specific requirement

JS Code:

<script>
    ReCaptchaCallbackV3 = function() {
        grecaptcha.ready(function() {
            grecaptcha.execute("SITE KEY").then(function(token) {
                $.ajax({
                    type: "POST",
                    url: `https://api.${window.appInfo.siteDomain}/v1/recaptcha/score`,
                    data: {
                        "token" : token,
                    },
                    success: function(data) {
                        if(data.response.success) {
                            window.recaptchaScore = data.response.score;
                            console.log('user score ' + data.response.score)
                        }
                    },
                    error: function() {
                        console.log('error while getting google recaptcha score!')
                    }
                });

            });
        });
    };
</script> 

HTML/Css Code:

there is no html code since our requirement is just to get score and don't want to show recaptcha badge.

Backend - Laravel Code:

Route:

Route::post('/recaptcha/score', 'Api\\ReCaptcha\\RecaptchaScore@index');


Class:

class RecaptchaScore extends Controller
{
    public function index(Request $request)
    {
        $score = null;

        $response = (new Client())->request('post', 'https://www.google.com/recaptcha/api/siteverify', [
            'form_params' => [
                'response' => $request->get('token'),
                'secret' => 'SECRET HERE',
            ],
        ]);

        $score = json_decode($response->getBody()->getContents(), true);

        if (!$score['success']) {
            Log::warning('Google ReCaptcha Score', [
                'class' => __CLASS__,
                'message' => json_encode($score['error-codes']),
            ]);
        }

        return [
            'response' => $score,
        ];
    }
} 

we get back score and save in variable which we later user when submit form.

Reference: https://developers.google.com/recaptcha/docs/v3 https://developers.google.com/recaptcha/

Requests (Caused by SSLError("Can't connect to HTTPS URL because the SSL module is not available.") Error in PyCharm requesting website

I don't have Anaconda so the steps I took are:

  • brew uninstall python3
  • brew install python3
    • got an error message stating,Your Xcode (10.2) is too outdated. Please update to Xcode 11.3 (or delete it). Xcode can be updated from the App Store.**So, I deleted Xcode since no update would show, then I reinstalled it.
    • ran xcode-select --install after. If you don't.. you'll get an error: The following formula python cannot be installed as binary package and must be built from source. Install the Command Line Tools: xcode-select --install
  • ran brew install python3 and it completed successfully.

Used this script just to see if it works

import requests
r = requests.get('https://www.office.com')
print(r)

Ran the script python3 and python3.7 and output was <Response [200]> instead of SSLError.

MVC Redirect to View from jQuery with parameters

i used to do like this

inside view

<script type="text/javascript">

//will replace the '_transactionIds_' and '_payeeId_' 
var _addInvoiceUrl = '@(Html.Raw( Url.Action("PayableInvoiceMainEditor", "Payables", new { warehouseTransactionIds ="_transactionIds_",payeeId = "_payeeId_", payeeType="Vendor" })))';

on javascript file

var url = _addInvoiceUrl.replace('_transactionIds_', warehouseTransactionIds).replace('_payeeId_', payeeId);
        window.location.href = url;

in this way i can able to pass the parameter values on demand..

by using @Html.Raw, url will not get amp; for parameters

How to get the currently logged in user's user id in Django?

This is how I usually get current logged in user and their id in my templates.

<p>Your Username is : {{user|default: Unknown}} </p>
<p>Your User Id is  : {{user.id|default: Unknown}} </p>

Cron and virtualenv

You should be able to do this by using the python in your virtual environment:

/home/my/virtual/bin/python /home/my/project/manage.py command arg

EDIT: If your django project isn't in the PYTHONPATH, then you'll need to switch to the right directory:

cd /home/my/project && /home/my/virtual/bin/python ...

You can also try to log the failure from cron:

cd /home/my/project && /home/my/virtual/bin/python /home/my/project/manage.py > /tmp/cronlog.txt 2>&1

Another thing to try is to make the same change in your manage.py script at the very top:

#!/home/my/virtual/bin/python

Converting from longitude\latitude to Cartesian coordinates

You can do it this way on Java.

public List<Double> convertGpsToECEF(double lat, double longi, float alt) {

    double a=6378.1;
    double b=6356.8;
    double N;
    double e= 1-(Math.pow(b, 2)/Math.pow(a, 2));
    N= a/(Math.sqrt(1.0-(e*Math.pow(Math.sin(Math.toRadians(lat)), 2))));
    double cosLatRad=Math.cos(Math.toRadians(lat));
    double cosLongiRad=Math.cos(Math.toRadians(longi));
    double sinLatRad=Math.sin(Math.toRadians(lat));
    double sinLongiRad=Math.sin(Math.toRadians(longi));
    double x =(N+0.001*alt)*cosLatRad*cosLongiRad;
    double y =(N+0.001*alt)*cosLatRad*sinLongiRad;
    double z =((Math.pow(b, 2)/Math.pow(a, 2))*N+0.001*alt)*sinLatRad;

    List<Double> ecef= new ArrayList<>();
    ecef.add(x);
    ecef.add(y);
    ecef.add(z);

    return ecef;


}

Basic Python client socket example

Here is a pretty simple socket program. This is about as simple as sockets get.

for the client program(CPU 1)

import socket

s = socket.socket()
host = '111.111.0.11' # needs to be in quote
port = 1247
s.connect((host, port))
print s.recv(1024)
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print "the message has been sent"

You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.

For the server program(CPU 2)

import socket

s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
    c, addr = s.accept()
    print("Connection accepted from " + repr(addr[1]))

    c.send("Server approved connection\n")
    print repr(addr[1]) + ": " + c.recv(1026)
    c.close()

Run the server program and then the client one.

Python Serial: How to use the read or readline function to read more than 1 character at a time

Serial sends data 8 bits at a time, that translates to 1 byte and 1 byte means 1 character.

You need to implement your own method that can read characters into a buffer until some sentinel is reached. The convention is to send a message like 12431\n indicating one line.

So what you need to do is to implement a buffer that will store X number of characters and as soon as you reach that \n, perform your operation on the line and proceed to read the next line into the buffer.

Note you will have to take care of buffer overflow cases i.e. when a line is received that is longer than your buffer etc...

EDIT

import serial

ser = serial.Serial(
    port='COM5',\
    baudrate=9600,\
    parity=serial.PARITY_NONE,\
    stopbits=serial.STOPBITS_ONE,\
    bytesize=serial.EIGHTBITS,\
        timeout=0)

print("connected to: " + ser.portstr)

#this will store the line
line = []

while True:
    for c in ser.read():
        line.append(c)
        if c == '\n':
            print("Line: " + ''.join(line))
            line = []
            break

ser.close()

Returning from a void function

The only reason to have a return in a void function would be to exit early due to some conditional statement:

void foo(int y)
{
    if(y == 0) return;

    // do stuff with y
}

As unwind said: when the code ends, it ends. No need for an explicit return at the end.

How to fix 'android.os.NetworkOnMainThreadException'?

These answers need to be updated to use more contemporary way to connect to servers on Internet and to process asynchronous tasks in general, e.g. you can find examples where Tasks are used in Google Drive API sample. The same should be used in this case. I'll use OP's original code to demonstrate this approach.

First, you'll need to define an off-main thread executor and you need to do it only once:

        private val mExecutor: Executor = Executors.newSingleThreadExecutor()

Then process your logic in that executor, which will be running off main thread

        Tasks.call (mExecutor, Callable<String> {

                val url = URL(urlToRssFeed)
                val factory = SAXParserFactory.newInstance()
                val parser = factory.newSAXParser()
                val xmlreader = parser.getXMLReader()
                val theRSSHandler = RssHandler()
                xmlreader.setContentHandler(theRSSHandler)
                val is = InputSource(url.openStream())
                xmlreader.parse(is)
                theRSSHandler.getFeed()
                // complete processing and return String or other object
                // e.g. you could return Boolean indicating a success or failure
                return@Callable someResult
        }).continueWith{
            // it.result here is what your asynchronous task has returned
            processResult(it.result)
        }

continueWith clause will be executed after your asynchronous task is completed and you will have an access to a value that has been returned by the task through it.result.

How does the stack work in assembly language?

I think primarily you're getting confused between a program's stack and any old stack.

A Stack

Is an abstract data structure which consists of information in a Last In First Out system. You put arbitrary objects onto the stack and then you take them off again, much like an in/out tray, the top item is always the one that is taken off and you always put on to the top.

A Programs Stack

Is a stack, it's a section of memory that is used during execution, it generally has a static size per program and frequently used to store function parameters. You push the parameters onto the stack when you call a function and the function either address the stack directly or pops off the variables from the stack.

A programs stack isn't generally hardware (though it's kept in memory so it can be argued as such), but the Stack Pointer which points to a current area of the Stack is generally a CPU register. This makes it a bit more flexible than a LIFO stack as you can change the point at which the stack is addressing.

You should read and make sure you understand the wikipedia article as it gives a good description of the Hardware Stack which is what you are dealing with.

There is also this tutorial which explains the stack in terms of the old 16bit registers but could be helpful and another one specifically about the stack.

From Nils Pipenbrinck:

It's worthy of note that some processors do not implement all of the instructions for accessing and manipulating the stack (push, pop, stack pointer, etc) but the x86 does because of it's frequency of use. In these situations if you wanted a stack you would have to implement it yourself (some MIPS and some ARM processors are created without stacks).

For example, in MIPs a push instruction would be implemented like:

addi $sp, $sp, -4  # Decrement stack pointer by 4  
sw   $t0, ($sp)   # Save $t0 to stack  

and a Pop instruction would look like:

lw   $t0, ($sp)   # Copy from stack to $t0  
addi $sp, $sp, 4   # Increment stack pointer by 4  

width:auto for <input> fields

Because input's width is controlled by it's size attribute, this is how I initialize an input width according to its content:

<input type="text" class="form-list-item-name" [size]="myInput.value.length" #myInput>

Postgresql query between date ranges

SELECT user_id 
FROM user_logs 
WHERE login_date BETWEEN '2014-02-01' AND '2014-03-01'

Between keyword works exceptionally for a date. it assumes the time is at 00:00:00 (i.e. midnight) for dates.

Best way to get all selected checkboxes VALUES in jQuery

You want the :checkbox:checked selector and map to create an array of the values:

var checkedValues = $('input:checkbox:checked').map(function() {
    return this.value;
}).get();

If your checkboxes have a shared class it would be faster to use that instead, eg. $('.mycheckboxes:checked'), or for a common name $('input[name="Foo"]:checked')

- Update -

If you don't need IE support then you can now make the map() call more succinct by using an arrow function:

var checkedValues = $('input:checkbox:checked').map((i, el) => el.value).get();

CORS with POSTMAN

Generally, Postman used for debugging and used in the development phase. But in case you want to block it even from postman try this.

    const referrer_domain = "[enter-the-domain-name-of-the-referrer]"
    //check for the referrer domain
    app.all('/*', function(req, res, next) {
      if(req.headers.referer.indexOf(referrer_domain) == -1){
        res.send('Invalid Request')
      }

      next();
    });

How to host material icons offline?

Added this to the web config and the error went away

<system.webServer>
    <staticContent>
      <remove fileExtension=".woff" /> 
      <mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
      <remove fileExtension=".woff2" /> 
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
    </staticContent>

VBA module that runs other modules

As long as the macros in question are in the same workbook and you verify the names exist, you can call those macros from any other module by name, not by module.

So if in Module1 you had two macros Macro1 and Macro2 and in Module2 you had Macro3 and Macro 4, then in another macro you could call them all:

Sub MasterMacro()
    Call Macro1
    Call Macro2
    Call Macro3
    Call Macro4
End Sub

Read input numbers separated by spaces

You'll want to:

  • Read in an entire line from the console
  • Tokenize the line, splitting along spaces.
  • Place those split pieces into an array or list
  • Step through that array/list, performing your prime/perfect/etc tests.

What has your class covered along these lines so far?

Detect page change on DataTable

You may use fnDrawCallback or fnInfoCallback to detect changes, when next is clicked both of them are fired.

But beware, page changes are not the only source that can fire those callbacks.

How do I print a datetime in the local timezone?

As of python 3.2, using only standard library functions:

u_tm = datetime.datetime.utcfromtimestamp(0)
l_tm = datetime.datetime.fromtimestamp(0)
l_tz = datetime.timezone(l_tm - u_tm)

t = datetime.datetime(2009, 7, 10, 18, 44, 59, 193982, tzinfo=l_tz)
str(t)
'2009-07-10 18:44:59.193982-07:00'

Just need to use l_tm - u_tm or u_tm - l_tm depending whether you want to show as + or - hours from UTC. I am in MST, which is where the -07 comes from. Smarter code should be able to figure out which way to subtract.

And only need to calculate the local timezone once. That is not going to change. At least until you switch from/to Daylight time.

How do I create a simple Qt console application in C++?

Don't forget to add the

CONFIG += console 

flag in the qmake .pro file.

For the rest is just using some of Qt classes. One way I use it is to spawn processes cross-platform.

Python - How do you run a .py file?

On windows platform, you have 2 choices:

  1. In a command line terminal, type

    c:\python23\python xxxx.py

  2. Open the python editor IDLE from the menu, and open xxxx.py, then press F5 to run it.

For your posted code, the error is at this line:

def main(url, out_folder="C:\asdf\"):

It should be:

def main(url, out_folder="C:\\asdf\\"):

Why is there an unexplainable gap between these inline-block div elements?

You need to add

#container
{
    display:inline-block;
    position:relative;
    background:rgb(255,100,0);
    margin:0px;
    width:40%;
    height:100px;
    margin-right:-4px;
}

because whenever you write display:inline-block it takes an additional margin-right:4px. So, you need to remove it.

Expression must be a modifiable L-value

lvalue means "left value" -- it should be assignable. You cannot change the value of text since it is an array, not a pointer.

Either declare it as char pointer (in this case it's better to declare it as const char*):

const char *text;
if(number == 2) 
    text = "awesome"; 
else 
    text = "you fail";

Or use strcpy:

char text[60];
if(number == 2) 
    strcpy(text, "awesome"); 
else 
    strcpy(text, "you fail");

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

All you need to do is run the below script. Then, remove/re-install the module that you want to use.

npm install --save @types/react-redux

.autocomplete is not a function Error

I faced the same problem and try to solve, but unfortunately it wouldn't work anymore ! If you are facing the same problem and can't find the solution, it may help you.

If you configure jquery/jquery-ui globally in webpack, you need to import autocomplete like this

import { autocomplete } from 'webpack-jquery-ui';

And you must include jquery-ui.css in the head section of html, i don't understand why its not working without it!

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

Hope your problem will be solved.

And make sure you include/install the following three

  1. jquery-ui-css
  2. jquery-ui
  3. jquery

Run an Ansible task only when the variable contains a specific string

use this

when: "{{ 'value' in variable1}}"

instead of

when: "'value' in {{variable1}}"

Also for string comparison you can use

when: "{{ variable1 == 'value' }}"

Pandas: create two new columns in a dataframe with values calculated from a pre-existing column

I'd just use zip:

In [1]: from pandas import *

In [2]: def calculate(x):
   ...:     return x*2, x*3
   ...: 

In [3]: df = DataFrame({'a': [1,2,3], 'b': [2,3,4]})

In [4]: df
Out[4]: 
   a  b
0  1  2
1  2  3
2  3  4

In [5]: df["A1"], df["A2"] = zip(*df["a"].map(calculate))

In [6]: df
Out[6]: 
   a  b  A1  A2
0  1  2   2   3
1  2  3   4   6
2  3  4   6   9

Disable same origin policy in Chrome

FOR MAC USER ONLY

open -n -a /Applications/Google\ Chrome.app --args --user-data-dir="/tmp/someFolderName" --disable-web-security

JavaFX Application Icon

Full program for starters :) This program sets icon for StackOverflowIcon.

import javafx.application.Application;
import javafx.scene.Scene;
import javafx.scene.image.Image;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;

public class StackoverflowIcon extends Application {

    @Override
    public void start(Stage stage) {
        StackPane root = new StackPane();
        // set icon
        stage.getIcons().add(new Image("/path/to/stackoverflow.jpg"));
        stage.setTitle("Wow!! Stackoverflow Icon");
        stage.setScene(new Scene(root, 300, 250));
        stage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

Output Screnshot

JavaFX Screenshot

Updated for JavaFX 8

No need to change the code. It still works fine. Tested and verified in Java 1.8(1.8.0_45). Path can be set to local or remote both are supported.

stage.getIcons().add(new Image("/path/to/javaicon.png"));

OR

stage.getIcons().add(new Image("https://example.com/javaicon.png"));

enter image description here

Hope it helps. Thanks!!

Converting string to integer

The function you need is CInt.

ie CInt(PrinterLabel)

See Type Conversion Functions (Visual Basic) on MSDN

Edit: Be aware that CInt and its relatives behave differently in VB.net and VBScript. For example, in VB.net, CInt casts to a 32-bit integer, but in VBScript, CInt casts to a 16-bit integer. Be on the lookout for potential overflows!

How to get a unique computer identifier in Java (like disk ID or motherboard ID)?

Not Knowing all of your requirements. For example, are you trying to uniquely identify a computer from all of the computers in the world, or are you just trying to uniquely identify a computer from a set of users of your application. Also, can you create files on the system?

If you are able to create a file. You could create a file and use the creation time of the file as your unique id. If you create it in user space then it would uniquely identify a user of your application on a particular machine. If you created it somewhere global then it could uniquely identify the machine.

Again, as most things, How fast is fast enough.. or in this case, how unique is unique enough.

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

Another possible solution is:

const link = document.createElement('a');
link.target = '_blank';
link.href = 'https://www.google.es';
link.setAttribute('visibility', 'hidden');
link.click();

Extract a page from a pdf as a jpeg

The pdf2image library can be used.

You can install it simply using,

pip install pdf2image

Once installed you can use following code to get images.

from pdf2image import convert_from_path
pages = convert_from_path('pdf_file', 500)

Saving pages in jpeg format

for page in pages:
    page.save('out.jpg', 'JPEG')

Edit: the Github repo pdf2image also mentions that it uses pdftoppm and that it requires other installations:

pdftoppm is the piece of software that does the actual magic. It is distributed as part of a greater package called poppler. Windows users will have to install poppler for Windows. Mac users will have to install poppler for Mac. Linux users will have pdftoppm pre-installed with the distro (Tested on Ubuntu and Archlinux) if it's not, run sudo apt install poppler-utils.

You can install the latest version under Windows using anaconda by doing:

conda install -c conda-forge poppler

note: Windows versions upto 0.67 are available at http://blog.alivate.com.au/poppler-windows/ but note that 0.68 was released in Aug 2018 so you'll not be getting the latest features or bug fixes.

Could not instantiate mail function. Why this error occurring

Try using SMTP to send email:-

$mail->IsSMTP();
$mail->Host = "smtp.example.com";

// optional
// used only when SMTP requires authentication  
$mail->SMTPAuth = true;
$mail->Username = 'smtp_username';
$mail->Password = 'smtp_password';

Duplicating a MySQL table, indices, and data

To create table structure only use this below code :

CREATE TABLE new_table LIKE current_table; 

To copy data from table to another use this below code :

INSERT INTO new_table SELECT * FROM current_table;

How to prevent robots from automatically filling up a form?

I have a simple approach to stopping spammers which is 100% effective, at least in my experience, and avoids the use of reCAPTCHA and similar approaches. I went from close to 100 spams per day on one of my sites' html forms to zero for the last 5 years once I implemented this approach.

It works by taking advantage of the e-mail ALIAS capabilities of most html form handling scripts (I use FormMail.pl), along with a graphic submission "code", which is easily created in the most simple of graphics programs. One such graphic includes the code M19P17nH and the prompt "Please enter the code at left".

This particular example uses a random sequence of letters and numbers, but I tend to use non-English versions of words familiar to my visitors (e.g. "pnofrtay"). Note that the prompt for the form field is built into the graphic, rather than appearing on the form. Thus, to a robot, that form field presents no clue as to its purpose.

The only real trick here is to make sure that your form html assigns this code to the "recipient" variable. Then, in your mail program, make sure that each such code you use is set as an e-mail alias, which points to whatever e-mail addresses you want to use. Since there is no prompt of any kind on the form for a robot to read and no e-mail addresses, it has no idea what to put in the blank form field. If it puts nothing in the form field or anything except acceptable codes, the form submission fails with a "bad recipient" error. You can use a different graphic on different forms, although it isn't really necessary in my experience.

Of course, a human being can solve this problem in a flash, without all the problems associated with reCAPTCHA and similar, more elegant, schemes. If a human spammer does respond to the recipient failure and programs the image code into the robot, you can change it easily, once you realize that the robot has been hard-coded to respond. In five years of using this approach, I've never had a spam from any of the forms on which I use it nor have I ever had a complaint from any human user of the forms. I'm certain that this could be beaten with OCR capability in the robot, but I've never had it happen on any of my sites which use html forms. I have also used "spam traps" (hidden "come hither" html code which points to my anti-spam policies) to good effect, but they were only about 90% effective.

How to Display Multiple Google Maps per page with API V3

Taken from These examples - guide , implementation .

  1. set your <div>'s with the appropriate id
  2. include the Google Map options with foundation calling.
  3. include foundation and rem js lib .

Example -

index.html -

<div class="row">
   <div class="large-6 medium-6 ">
      <div id="map_canvas" class="google-maps">
      </div>
   </div>
   <br>
   <div class="large-6 medium-6 ">
      <div id="map_canvas_2" class="google-maps"></div>
   </div>
</div>
<script src="/js/foundation.js"></script>
<script src="/js/google_maps_options.js"></script>
<script src="/js/rem.js"></script>
<script>
   jQuery(function(){
       setTimeout(initializeGoogleMap,700);
   });
</script>

google_maps_options.js -

function initializeGoogleMap()
{
    $(document).foundation();
    var latlng = new google.maps.LatLng(28.561287,-81.444465);
    var latlng2 = new google.maps.LatLng(28.507561,-81.482359);

    var myOptions =
    {
        zoom: 13,
        center: latlng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    var myOptions2 =
    {
        zoom: 13,
        center: latlng2,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };


    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);

    var map2 = new google.maps.Map(document.getElementById("map_canvas_2"), myOptions2);


    var myMarker = new google.maps.Marker(
    {
        position: latlng,
        map: map,
        title:"Barnett Park"
   });

    var myMarker2 = new google.maps.Marker(
    {
        position: latlng2,
        map: map2,
        title:"Bill Fredrick Park at Turkey Lake"
    });


}

Qt c++ aggregate 'std::stringstream ss' has incomplete type and cannot be defined

You probably have a forward declaration of the class, but haven't included the header:

#include <sstream>

//...
QString Stats_Manager::convertInt(int num)
{
    std::stringstream ss;   // <-- also note namespace qualification
    ss << num;
    return ss.str();
}

Twitter Bootstrap vs jQuery UI?

Having used both, Twitter's Bootstrap is a superior technology set. Here are some differences,

  • Widgets: jQuery UI wins here. The date widget it provides is immensely useful, and Twitter Bootstrap provides nothing of the sort.
  • Scaffolding: Bootstrap wins here. Twitter's grid both fluid and fixed are top notch. jQuery UI doesn't even provide this direction leaving page layout up to the end user.
  • Out of the box professionalism: Bootstrap using CSS3 is leagues ahead, jQuery UI looks dated by comparison.
  • Icons: I'll go tie on this one. Bootstrap has nicer icons imho than jQuery UI, but I don't like the terms one bit, Glyphicons Halflings are normally not available for free, but an arrangement between Bootstrap and the Glyphicons creators have made this possible at no cost to you as developers. As a thank you, we ask you to include an optional link back to Glyphicons whenever practical.
  • Images & Thumbnails: goes to Bootstrap, jQuery UI doesn't even help here.

Other notes,

  • It's important to understand how these two technologies compete in the spheres too. There is a lot of overlap, but if you want simple scaffolding and fixed/fluid creation Bootstrap isn't another technology, it's the best technology. If you want any single widget, jQuery UI probably isn't even in the top three. Today, jQuery UI is mainly just a toy for consistency and proof of concept for a client-side widget creation using a unified framework.

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

I find this quite tricky, but there is some information on it here at the MatPlotLib FAQ. It is rather cumbersome, and requires finding out about what space individual elements (ticklabels) take up...

Update: The page states that the tight_layout() function is the easiest way to go, which attempts to automatically correct spacing.

Otherwise, it shows ways to acquire the sizes of various elements (eg. labels) so you can then correct the spacings/positions of your axes elements. Here is an example from the above FAQ page, which determines the width of a very wide y-axis label, and adjusts the axis width accordingly:

import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(range(10))
ax.set_yticks((2,5,7))
labels = ax.set_yticklabels(('really, really, really', 'long', 'labels'))

def on_draw(event):
   bboxes = []
   for label in labels:
       bbox = label.get_window_extent()
       # the figure transform goes from relative coords->pixels and we
       # want the inverse of that
       bboxi = bbox.inverse_transformed(fig.transFigure)
       bboxes.append(bboxi)

   # this is the bbox that bounds all the bboxes, again in relative
   # figure coords
   bbox = mtransforms.Bbox.union(bboxes)
   if fig.subplotpars.left < bbox.width:
       # we need to move it over
       fig.subplots_adjust(left=1.1*bbox.width) # pad a little
       fig.canvas.draw()
   return False

fig.canvas.mpl_connect('draw_event', on_draw)

plt.show()

How does "cat << EOF" work in bash?

Using tee instead of cat

Not exactly as an answer to the original question, but I wanted to share this anyway: I had the need to create a config file in a directory that required root rights.

The following does not work for that case:

$ sudo cat <<EOF >/etc/somedir/foo.conf
# my config file
foo=bar
EOF

because the redirection is handled outside of the sudo context.

I ended up using this instead:

$ sudo tee <<EOF /etc/somedir/foo.conf >/dev/null
# my config file
foo=bar
EOF

In CSS what is the difference between "." and "#" when declaring a set of styles?

The dot(.) signifies a class name while the hash (#) signifies an element with a specific id attribute. The class will apply to any element decorated with that particular class, while the # style will only apply to the element with that particular id.

Class name:

<style>
   .class { ... }
</style>

<div class="class"></div>
<span class="class></span>
<a href="..." class="class">...</a>

Named element:

<style>
   #name { ... }
</style>

<div id="name"></div>

How to check if a variable is null or empty string or all whitespace in JavaScript?

When checking for white space the c# method uses the Unicode standard. White space includes spaces, tabs, carriage returns and many other non-printing character codes. So you are better of using:

function isNullOrWhiteSpace(str){
    return str == null || str.replace(/\s/g, '').length < 1;
}

How do I split a string into an array of characters?

You can use the regular expression /(?!$)/:

"overpopulation".split(/(?!$)/)

The negative look-ahead assertion (?!$) will match right in front of every character.

How do I define global variables in CoffeeScript?

To me it seems @atomicules has the simplest answer, but I think it can be simplified a little more. You need to put an @ before anything you want to be global, so that it compiles to this.anything and this refers to the global object.

so...

@bawbag = (x, y) ->
    z = (x * y)

bawbag(5, 10)

compiles to...

this.bawbag = function(x, y) {
  var z;
  return z = x * y;
};
bawbag(5, 10);

and works inside and outside of the wrapper given by node.js

(function() {
    this.bawbag = function(x, y) {
      var z;
      return z = x * y;
    };
    console.log(bawbag(5,13)) // works here
}).call(this);

console.log(bawbag(5,11)) // works here

How to select data of a table from another database in SQL Server?

In SQL Server 2012 and above, you don't need to create a link. You can execute directly

SELECT * FROM [TARGET_DATABASE].dbo.[TABLE] AS _TARGET

I don't know whether previous versions of SQL Server work as well

How do I install a custom font on an HTML site

For the best possible browser support, your CSS code should look like this :

@font-face {
  font-family: 'MyWebFont';
  src: url('webfont.eot'); /* IE9 Compat Modes */
  src: url('webfont.eot?#iefix') format('embedded-opentype'), /* IE6-IE8 */
       url('webfont.woff2') format('woff2'), /* Super Modern Browsers */
       url('webfont.woff') format('woff'), /* Pretty Modern Browsers */
       url('webfont.ttf')  format('truetype'), /* Safari, Android, iOS */
       url('webfont.svg#svgFontName') format('svg'); /* Legacy iOS */
}

body {
  font-family: 'MyWebFont', Fallback, sans-serif;
}

For more info, see the article Using @font-face at CSS-tricks.com.

Why is Event.target not Element in Typescript?

Using typescript, I use a custom interface that only applies to my function. Example use case.

  handleChange(event: { target: HTMLInputElement; }) {
    this.setState({ value: event.target.value });
  }

In this case, the handleChange will receive an object with target field that is of type HTMLInputElement.

Later in my code I can use

<input type='text' value={this.state.value} onChange={this.handleChange} />

A cleaner approach would be to put the interface to a separate file.

interface HandleNameChangeInterface {
  target: HTMLInputElement;
}

then later use the following function definition:

  handleChange(event: HandleNameChangeInterface) {
    this.setState({ value: event.target.value });
  }

In my usecase, it's expressly defined that the only caller to handleChange is an HTML element type of input text.

How to create a library project in Android Studio and an application project that uses the library project

To create a library:

File > New Module

select Android Library

Lib

To use the library add it as a dependancy:

File > Project Structure > Modules > Dependencies

dep

Then add the module (android library) as a module dependency.

add module

Run your project. It will work.

"RangeError: Maximum call stack size exceeded" Why?

Here it fails at Array.apply(null, new Array(1000000)) and not the .map call.

All functions arguments must fit on callstack(at least pointers of each argument), so in this they are too many arguments for the callstack.

You need to the understand what is call stack.

Stack is a LIFO data structure, which is like an array that only supports push and pop methods.

Let me explain how it works by a simple example:

function a(var1, var2) {
    var3 = 3;
    b(5, 6);
    c(var1, var2);
}
function b(var5, var6) {
    c(7, 8);
}
function c(var7, var8) {
}

When here function a is called, it will call b and c. When b and c are called, the local variables of a are not accessible there because of scoping roles of Javascript, but the Javascript engine must remember the local variables and arguments, so it will push them into the callstack. Let's say you are implementing a JavaScript engine with the Javascript language like Narcissus.

We implement the callStack as array:

var callStack = [];

Everytime a function called we push the local variables into the stack:

callStack.push(currentLocalVaraibles);

Once the function call is finished(like in a, we have called b, b is finished executing and we must return to a), we get back the local variables by poping the stack:

currentLocalVaraibles = callStack.pop();

So when in a we want to call c again, push the local variables in the stack. Now as you know, compilers to be efficient define some limits. Here when you are doing Array.apply(null, new Array(1000000)), your currentLocalVariables object will be huge because it will have 1000000 variables inside. Since .apply will pass each of the given array element as an argument to the function. Once pushed to the call stack this will exceed the memory limit of call stack and it will throw that error.

Same error happens on infinite recursion(function a() { a() }) as too many times, stuff has been pushed to the call stack.

Note that I'm not a compiler engineer and this is just a simplified representation of what's going on. It really is more complex than this. Generally what is pushed to callstack is called stack frame which contains the arguments, local variables and the function address.

Init array of structs in Go

Adding this just as an addition to @jimt's excellent answer:

one common way to define it all at initialization time is using an anonymous struct:

var opts = []struct {
    shortnm      byte
    longnm, help string
    needArg      bool
}{
    {'a', "multiple", "Usage for a", false},
    {
        shortnm: 'b',
        longnm:  "b-option",
        needArg: false,
        help:    "Usage for b",
    },
}

This is commonly used for testing as well to define few test cases and loop through them.

CSS Border Not Working

Have you tried using Firebug to inspect the rendered HTML, and to see exactly what css is being applied to the various elements? That should pick up css errors like the ones mentioned above, and you can see what styles are being inherited and from where - it is an invaluable too in any css debugging.

How to check syslog in Bash on Linux?

On Fedora 19, it looks like the answer is /var/log/messages. Although check /etc/rsyslog.conf if it has been changed.

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to make div follow scrolling smoothly with jQuery?

This one is same on facebook:

_x000D_
_x000D_
<script>_x000D_
var valX = $(window).scrollTop();_x000D_
function syncScroll(target){_x000D_
 var valY = $(window).scrollTop();_x000D_
 var difYX = valY - valX;_x000D_
 var targetX = $(target).scrollTop();_x000D_
 if(valY > valX){_x000D_
  $(target).scrollTop(difYX);_x000D_
 }_x000D_
 if(difYX <= 0){_x000D_
  $(target).scrollTop(-20);_x000D_
 }_x000D_
}_x000D_
_x000D_
$(window).scroll(function(){_x000D_
 syncScroll('#demo');_x000D_
})_x000D_
</script>
_x000D_
body{_x000D_
  margin:0;_x000D_
  padding:0;_x000D_
  height:100%;_x000D_
}_x000D_
#demo{_x000D_
  position:fixed;_x000D_
  height:100vh;_x000D_
  overflow:hidden;_x000D_
  width:40%;_x000D_
}_x000D_
#content{_x000D_
  position:relative;_x000D_
  float:right;_x000D_
  width:60%;_x000D_
  color:red; _x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
_x000D_
<body>_x000D_
  <div id="demo">_x000D_
    <ul>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
    <ul>_x000D_
  </div>_x000D_
  <div id="content">_x000D_
    <ul>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</p>_x000D_
      </li>_x000D_
      <li>_x000D_
        <p>_x000D_
"Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur? Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?"_x000D_
        </p>_x000D_
      </li>  _x000D_
      <li>_x000D_
        <p>_x000D_
"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"_x000D_
        </p>_x000D_
      </li>_x000D_
    <ul>_x000D_
   </div>   _x000D_
</body
_x000D_
_x000D_
_x000D_

Html.DropdownListFor selected value not being set

You should forget the class

SelectList

Use this in your Controller:

var customerTypes = new[] 
{ 
    new SelectListItem(){Value = "all", Text= "All"},
    new SelectListItem(){Value = "business", Text= "Business"},
    new SelectListItem(){Value = "private", Text= "Private"},
};

Select the value:

var selectedCustomerType = customerTypes.FirstOrDefault(d => d.Value == "private");
if (selectedCustomerType != null)
    selectedCustomerType.Selected = true;

Add the list to the ViewData:

ViewBag.CustomerTypes = customerTypes;

Use this in your View:

@Html.DropDownList("SectionType", (SelectListItem[])ViewBag.CustomerTypes)

-

More information at: http://www.asp.net/mvc/overview/older-versions/working-with-the-dropdownlist-box-and-jquery/using-the-dropdownlist-helper-with-aspnet-mvc

Tuple unpacking in for loops

Short answer, unpacking tuples from a list in a for loop works. enumerate() creates a tuple using the current index and the entire current item, such as (0, ('bob', 3))

I created some test code to demonstrate this:

    list = [('bob', 3), ('alice', 0), ('john', 5), ('chris', 4), ('alex', 2)]

    print("Displaying Enumerated List")
    for name, num in enumerate(list):
        print("{0}: {1}".format(name, num))

    print("Display Normal Iteration though List")
    for name, num in list:
        print("{0}: {1}".format(name, num))

The simplicity of Tuple unpacking is probably one of my favourite things about Python :D

setAttribute('display','none') not working

Try this:

setAttribute("hidden", true);

Get an image extension from an uploaded file in Laravel

The Laravel way

Try this:

$foo = \File::extension($filename);

Parsing JSON with Unix tools

One interesting tool that hasn't be covered in the existing answers is using gron written in Go which has a tagline that says Make JSON greppable! which is exactly what it does.

So essentially gron breaks down your JSON into discrete assignments see the absolute 'path' to it. The primary advantage of it over other tools like jq would be to allow searching for the value without knowing how nested the record to search is present at, without breaking the original JSON structure

e.g., I want to search for the 'twitter_username' field from the following link, I just do

% gron 'https://api.github.com/users/lambda' | fgrep 'twitter_username'
json.twitter_username = "unlambda";
% gron 'https://api.github.com/users/lambda' | fgrep 'twitter_username' | gron -u
{
  "twitter_username": "unlambda"
}

As simple as that. Note how the gron -u (short for ungron) reconstructs the JSON back from the search path. The need for fgrep is just to filter your search to the paths needed and not let the search expression be evaluated as a regex, but as a fixed string (which is essentially grep -F)

Another example to search for a string to see where in the nested structure the record is under

% echo '{"foo":{"bar":{"zoo":{"moo":"fine"}}}}' | gron | fgrep "fine"
json.foo.bar.zoo.moo = "fine";

It also supports streaming JSON with its -s command line flag, where you can continuously gron the input stream for a matching record. Also gron has zero runtime dependencies. You can download a binary for Linux, Mac, Windows or FreeBSD and run it.

More usage examples and trips can be found at the official Github page - Advanced Usage

As for why you one can use gron over other JSON parsing tools, see from author's note from the project page.

Why shouldn't I just use jq?

jq is awesome, and a lot more powerful than gron, but with that power comes complexity. gron aims to make it easier to use the tools you already know, like grep and sed.

setValue:forUndefinedKey: this class is not key value coding-compliant for the key

You're probably setting a value for a key in the alertView, which is not allowed. The key is in this case LoginScreen. I don't see any call to setValue(), so I assume it's somewhere else in the code.

SQL Server AS statement aliased column within WHERE statement

I am not sure why you cannot use "lat" but, if you must you can rename the columns in a derived table.

select latitude from (SELECT lat AS latitude FROM poi_table) p where latitude < 500

How to maximize the browser window in Selenium WebDriver (Selenium 2) using C#?

There is a function that you can use to maximize the window in Python which is window_maximize(). And this is how I'm using it.Hope this helps -

from selenium import selenium
sel = selenium('localhost', 4444, '*firefox', 'http://10.77.21.67/')
sel.start()
sel.open('/')
sel.wait_for_page_to_load(60000)
#sel.window_focus()
sel.window_maximize()
png = sel.capture_screenshot_to_string()
f = open('screenshot.png', 'wb')
f.write(png.decode('base64'))
f.close()
sel.stop()

Setting default value for TypeScript object passed as argument

Here is something to try, using interface and destructuring with default values. Please note that "lastName" is optional.

interface IName {
  firstName: string
  lastName?: string
}

function sayName(params: IName) {
  const { firstName, lastName = "Smith" } = params
  const fullName = `${firstName} ${lastName}`

  console.log("FullName-> ", fullName)
}

sayName({ firstName: "Bob" })

I can't install python-ldap

In Ubuntu it looks like this :

 $ sudo apt-get install python-dev libldap2-dev libsasl2-dev libssl-dev
 $ sudo pip install python-ldap

Application.WorksheetFunction.Match method

You are getting this error because the value cannot be found in the range. String or integer doesn't matter. Best thing to do in my experience is to do a check first to see if the value exists.

I used CountIf below, but there is lots of different ways to check existence of a value in a range.

Public Sub test()

Dim rng As Range
Dim aNumber As Long

aNumber = 666

Set rng = Sheet5.Range("B16:B615")

    If Application.WorksheetFunction.CountIf(rng, aNumber) > 0 Then

        rowNum = Application.WorksheetFunction.Match(aNumber, rng, 0)

    Else
        MsgBox aNumber & " does not exist in range " & rng.Address
    End If

End Sub

ALTERNATIVE WAY

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Long

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    If Not IsError(Application.Match(aNumber, rng, 0)) Then
        rowNum = Application.Match(aNumber, rng, 0)
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

OR

Public Sub test()
    Dim rng As Range
    Dim aNumber As Variant
    Dim rowNum As Variant

    aNumber = "2gg"

    Set rng = Sheet5.Range("B1:B20")

    rowNum = Application.Match(aNumber, rng, 0)

    If Not IsError(rowNum) Then
        MsgBox rowNum
    Else
        MsgBox "error"
    End If
End Sub

Kafka consumer list

Kafka stores all the information in zookeeper. You can see all the topic related information under brokers->topics. If you wish to get all the topics programmatically you can do that using Zookeeper API.

It is explained in detail in below links Tutorialspoint, Zookeeper Programmer guide

Visual Studio: LINK : fatal error LNK1181: cannot open input file

I solved it with the following:

Go to View-> Property Pages -> Configuration Properties -> Linker -> Input

Under additional dependencies add the thelibrary.lib. Don't use any quotations.

jQuery .load() call doesn't execute JavaScript in loaded HTML file

A other version of John Pick's solution just before, this works fine for me :

jQuery.ajax({
   ....
   success: function(data, textStatus, jqXHR) {
       jQuery(selecteur).html(jqXHR.responseText);
       var reponse = jQuery(jqXHR.responseText);
       var reponseScript = reponse.filter("script");
       jQuery.each(reponseScript, function(idx, val) { eval(val.text); } );
   }
   ...
});